From 1f506fa2513f504bae0a0979a96207f016d1d2ce Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 9 Nov 2026 11:51:11 -0500 Subject: [PATCH 1/5] Fold the review follow-ups from #1417, #1109 and #1416 ITL differential check (#1417): - Name the engine variables the cells read (TAX, TOTAL_INCOME, IS_SP_AGE, AGE) and hold them, and each bound cell's mask, to the contract's policyengine bindings: a structural test of the counting keys, a differential against the build's own binding interpreter on people at every edge, and twelve binding edits that each turn exactly their family red. - Refuse --current-income-for-annual-measures unless --diagnostics or --references names the in-sample basis. - Cite the vendored band counts in the tolerance note; keep 5% and 10%. - Import UK_HMRC_ITL_UK_GEOGRAPHY_ID instead of repeating K02000001. Fiscal refresh (#1109): the estate_income exclusion also covers a run whose raw base becomes the reference. Target materialization (#1416): the docstring limits the plain-row period refusal to a row declaring a period other than the calibration period. Co-Authored-By: Claude Opus 5.5 --- changelog.d/1417-review-followups.fixed.md | 1 + .../microcosm/build/target_materialization.py | 4 +- .../build/uk_runtime/itl_differential.py | 44 +- .../uk/test_uk_itl_differential.py | 533 +++++++++++++++--- tools/build_us_fiscal_refresh_release.py | 3 +- tools/check_uk_itl_projections.py | 24 +- 6 files changed, 523 insertions(+), 86 deletions(-) create mode 100644 changelog.d/1417-review-followups.fixed.md diff --git a/changelog.d/1417-review-followups.fixed.md b/changelog.d/1417-review-followups.fixed.md new file mode 100644 index 0000000000..34d6a2d24d --- /dev/null +++ b/changelog.d/1417-review-followups.fixed.md @@ -0,0 +1 @@ +Follow-ups from the reviews of microcosm#1417, #1109 and #1416. `tools/check_uk_itl_projections.py` refuses `--current-income-for-annual-measures` unless `--diagnostics` or `--references` names the in-sample basis: this tree's target references say what a build of this tree binds, not what a file built before the annual income descriptors bound, so on that basis every band and area cell of such a file read `in` at the default `--year`. `uk_runtime.itl_differential` names the engine variables its cells read (`TAX`, `TOTAL_INCOME`, `IS_SP_AGE`, `AGE`), and new engine-free tests hold them, and each bound cell's mask, to the contract's `policyengine` bindings of the three bound families through the build's own binding interpreter, so an edit to a binding's filter, band variable or band reading fails until the check follows it. The note on `NATIONAL_TOLERANCE` cites the vendored band counts (at the calendar-2025 window five of the eleven bands hold under 400,000 taxpayers, and the top three hold fewer than the smallest area cell) in place of a claim that national cells sum over millions; the tolerances stay 5% and 10%. The check imports `UK_HMRC_ITL_UK_GEOGRAPHY_ID` instead of repeating it. The US fiscal refresh's reviewed `estate_income` exclusion also asks for re-adjudication when the flag is absent and the raw base becomes the reference, and the `materialize_target_bindings` docstring limits the plain-row period refusal to a row that declares a period other than the calibration period. diff --git a/packages/microcosm-build/src/microcosm/build/target_materialization.py b/packages/microcosm-build/src/microcosm/build/target_materialization.py index 1298de5e3f..28e4e47fb9 100644 --- a/packages/microcosm-build/src/microcosm/build/target_materialization.py +++ b/packages/microcosm-build/src/microcosm/build/target_materialization.py @@ -716,8 +716,8 @@ def materialize_target_bindings( A provider binding reads its columns as the frame holds them, so a period it declares must be one its value reads hold. A declared period that any one read misses refuses the run: for a provider row on any - frame with a period model, for a plain row on a frame with period - metadata. + frame with a period model, and for a plain row that declares any period + but the calibration period, on a frame with period metadata. """ provider_registry = {**default_provider_registry(), **(providers or {})} diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py index dd159750a2..4da48d5c51 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py @@ -47,18 +47,36 @@ import numpy as np from microcosm.build.ledger_targets import CALENDAR_YEAR_WINDOW_WEIGHTS -from microcosm.build.uk_runtime.hmrc_uprating import ITL_BANDS +from microcosm.build.uk_runtime.hmrc_uprating import ( + ITL_BANDS, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, +) from microcosm.calibrate.geography_constants import UK_REGION_TIER +#: The engine variables a cell reads, as the contract's ``policyengine`` +#: bindings of the ``BOUND_BY`` targets name them: every cell counts people +#: whose ``TAX`` is above zero, a band reads ``TOTAL_INCOME``, the counts of +#: and below State Pension age read ``IS_SP_AGE`` and the count aged 65 and +#: over reads ``AGE``. ``resolved_people`` reads them; a test holds them, and +#: the cells' masks, to the bindings. TAX = "income_tax_before_winter_fuel_payment_charge_annual" TOTAL_INCOME = "total_income_after_loss_relief_annual" - -#: Largest relative miss a cell may show: national cells are sums over -#: millions of weighted taxpayers, a region's over a twelfth of them. +IS_SP_AGE = "is_SP_age" +AGE = "age" + +#: Largest relative miss a cell may show: ``REGIONAL_TOLERANCE`` for each +#: Table 2.2 area, ``NATIONAL_TOLERANCE`` for every other cell (Table 2.5's +#: bands and all-band count, Table 2.1's United Kingdom counts, the count +#: below State Pension age and the residents' sums). Geography, not size, +#: decides which: at the calendar-2025 window of the vendored rows, five of +#: the eleven bands hold under 400,000 taxpayers (342,750 at £150,000 to +#: £200,000, 372,500 at £200,000 to £500,000, 65,500 at £500,000 to £1m, +#: 20,750 at £1m to £2m and 10,750 at £2m and over), and the top three hold +#: fewer than the smallest area cell (Northern Ireland's State Pension age +#: count, 198,750). NATIONAL_TOLERANCE = 0.05 REGIONAL_TOLERANCE = 0.10 -UNITED_KINGDOM = "K02000001" #: The ``key`` of the sum over the twelve region-tier areas. RESIDENTS = "residents" AGE_MEASURES = ("state_pension_age", "age_65_and_over") @@ -102,7 +120,7 @@ def key(self) -> str: if self.band is not None: lower, upper = self.band return f"{lower}+" if upper is None else f"{lower}-{upper}" - return self.area or UNITED_KINGDOM + return self.area or UK_HMRC_ITL_UK_GEOGRAPHY_ID @property def sort_key(self) -> tuple[Any, ...]: @@ -178,9 +196,9 @@ def _read_by_cells(row: Mapping[str, Any]) -> bool: measure = str(row.get("measure_id")) geography = str((row.get("geography") or {}).get("id")) if table == "2.5": - return measure == _TABLE_2_5_COUNT and geography == UNITED_KINGDOM + return measure == _TABLE_2_5_COUNT and geography == UK_HMRC_ITL_UK_GEOGRAPHY_ID if table == "2.1": - return measure in AGE_MEASURES and geography == UNITED_KINGDOM + return measure in AGE_MEASURES and geography == UK_HMRC_ITL_UK_GEOGRAPHY_ID return ( table == "2.2" and measure in AGE_MEASURES and geography in _REGION_TIER_CODES ) @@ -333,16 +351,16 @@ def need(key): cell( "2.5", BAND_COUNT, - need(("2.5", _TABLE_2_5_COUNT, UNITED_KINGDOM, band)), + need(("2.5", _TABLE_2_5_COUNT, UK_HMRC_ITL_UK_GEOGRAPHY_ID, band)), band=band, ) for band in ITL_BANDS ] - all_taxpayers = need(("2.5", _TABLE_2_5_COUNT, UNITED_KINGDOM, None)) + all_taxpayers = need(("2.5", _TABLE_2_5_COUNT, UK_HMRC_ITL_UK_GEOGRAPHY_ID, None)) all_cell = _summed(cell("2.5", ALL_TAXPAYERS, all_taxpayers), cells) cells.append(all_cell) for measure in AGE_MEASURES: - national = window.get(("2.1", measure, UNITED_KINGDOM, None)) + national = window.get(("2.1", measure, UK_HMRC_ITL_UK_GEOGRAPHY_ID, None)) areas = [ window.get(("2.2", measure, code, None)) for _level, code in UK_REGION_TIER ] @@ -577,7 +595,7 @@ def resolved_people(resolver: Any) -> ITLPeople: weight=_person(resolver, "household_weight").astype(float), taxpayer=_person(resolver, TAX).astype(float) > 0, total_income=_person(resolver, TOTAL_INCOME).astype(float), - state_pension_age=_person(resolver, "is_SP_age").astype(bool), - age=_person(resolver, "age").astype(float), + state_pension_age=_person(resolver, IS_SP_AGE).astype(bool), + age=_person(resolver, AGE).astype(float), area=np.array([by_name.get(name, "") for name in region]), ) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py index 3aa7a3c522..b64e38f789 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py @@ -8,37 +8,52 @@ within tolerance exactly when its relative miss is no larger than the tolerance fixed before any file is read. The in-sample flags read the targets by the names the contract's references and a run's diagnostics give -them, so Table 2.2's areas, bound since microcosm#1069, are in sample. +them, so Table 2.2's areas, bound since microcosm#1069, are in sample. Each +bound cell counts exactly the people the build's own reading of its contract +binding counts (its filters and its band), so an edit to a binding's filter +or band variable fails these tests until the check follows it. """ from __future__ import annotations +import copy import importlib.util +import itertools import json import math from fractions import Fraction from importlib.resources import files +from types import SimpleNamespace import numpy as np import pytest from hypothesis import given, settings from hypothesis import strategies as st -from microcosm.build.uk_runtime.hmrc_uprating import ITL_BANDS +from microcosm.build.target_materialization import ( + WHOLE_PENCE_UPPER_CLOSED, + _prepared_column_values, +) +from microcosm.build.uk_runtime.hmrc_uprating import ( + ITL_BANDS, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, +) from microcosm.build.uk_runtime.itl_differential import ( + AGE, AGE_MEASURES, ALL_TAXPAYERS, BAND_COUNT, BELOW_STATE_PENSION_AGE, BOUND_BY, + IS_SP_AGE, NATIONAL_TOLERANCE, REGIONAL_TOLERANCE, RESIDENTS, TAX, TOTAL_INCOME, - UNITED_KINGDOM, ITLPeople, calendar_window, + cell_mask, differential, expected_cells, itl_band_key, @@ -48,7 +63,10 @@ table_of, ) from microcosm.build.uk_runtime.ledger_fact_vendoring import load_vendored_resource -from microcosm.calibrate.geography_constants import UK_REGION_TIER +from microcosm.calibrate.geography_constants import ( + UK_REGION_TIER, + UK_REGION_TIER_ENUM, +) from test_support.paths import paths_for AREAS = tuple(code for _level, code in UK_REGION_TIER) @@ -80,7 +98,11 @@ def _rows(*, ages=True, value=1_000.0): scale = 1.0 + (year - 2023) / 10 rows.append( _row( - "2.5", "total_taxpayer_count", UNITED_KINGDOM, year, 40 * value * scale + "2.5", + "total_taxpayer_count", + UK_HMRC_ITL_UK_GEOGRAPHY_ID, + year, + 40 * value * scale, ) ) for index, band in enumerate(ITL_BANDS): @@ -88,7 +110,7 @@ def _rows(*, ages=True, value=1_000.0): _row( "2.5", "total_taxpayer_count", - UNITED_KINGDOM, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, year, (index + 1) * value * scale, band, @@ -97,7 +119,13 @@ def _rows(*, ages=True, value=1_000.0): if ages: for measure in ("state_pension_age", "age_65_and_over"): rows.append( - _row("2.1", measure, UNITED_KINGDOM, year, 13 * value * scale) + _row( + "2.1", + measure, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, + year, + 13 * value * scale, + ) ) for index, area in enumerate(AREAS): rows.append( @@ -111,8 +139,8 @@ def _rows(*, ages=True, value=1_000.0): @given(then=_counts, now=_counts) def test_the_window_weights_the_two_tax_years(then, now) -> None: rows = [ - _row("2.1", "state_pension_age", UNITED_KINGDOM, 2024, then), - _row("2.1", "state_pension_age", UNITED_KINGDOM, 2025, now), + _row("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2024, then), + _row("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, now), ] ((value, sources),) = calendar_window(rows, year=2025).values() assert value == math.fsum((0.25 * then, 0.75 * now)) @@ -132,7 +160,7 @@ def test_a_duplicate_or_half_window_is_refused() -> None: rows = _rows() with pytest.raises(ValueError, match="two rows"): calendar_window([*rows, rows[0]], year=2024) - lonely = _row("2.1", "males", UNITED_KINGDOM, 2025, 1.0) + lonely = _row("2.1", "males", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, 1.0) with pytest.raises(ValueError, match="window at 2025 needs"): calendar_window([*rows, lonely], year=2025) @@ -180,10 +208,12 @@ def test_the_derived_cells_are_their_components() -> None: (cell.table, cell.measure, cell.key): cell for cell in expected_cells(_rows(), year=2025) } - all_taxpayers = cells[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)].expected - state_pension_age = cells[("2.1", "state_pension_age", UNITED_KINGDOM)].expected + all_taxpayers = cells[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)].expected + state_pension_age = cells[ + ("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID) + ].expected assert ( - cells[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)].expected + cells[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)].expected == all_taxpayers - state_pension_age ) for measure in ("state_pension_age", "age_65_and_over"): @@ -240,10 +270,10 @@ def test_a_family_is_in_sample_cell_by_cell() -> None: assert flags[key] is (band != left_out_band) for area in AREAS: assert flags[("2.2", "state_pension_age", area)] is (area != left_out_area) - assert not flags[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)] + assert not flags[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] assert not flags[("2.2", "state_pension_age", RESIDENTS)] - assert not flags[("2.1", "state_pension_age", UNITED_KINGDOM)] - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)] + assert not flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)] + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] every = { *(f"{band_family}.{itl_band_key(b)}" for b in ITL_BANDS), @@ -286,10 +316,10 @@ def test_a_sum_is_in_sample_only_when_its_parts_count_everyone_it_counts() -> No everyone_in_a_part = ITLPeople(**_person()) flags = _flags(differential(cells, everyone_in_a_part)) for key in ( - ("2.5", ALL_TAXPAYERS, UNITED_KINGDOM), + ("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID), ("2.2", "state_pension_age", RESIDENTS), - ("2.1", "state_pension_age", UNITED_KINGDOM), - ("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM), + ("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID), + ("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID), ): assert flags[key]["in_sample"], key assert flags[key]["outside_parts"] == 0.0, key @@ -306,19 +336,33 @@ def merged(*people): _person(), _person(total_income=[10_000.0], weight=[2.5]) ) flags = _flags(differential(cells, below_the_first_edge)) - assert not flags[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)]["in_sample"] - assert flags[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)]["outside_parts"] == 2.5 - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)]["in_sample"] - assert flags[("2.1", "state_pension_age", UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] + assert ( + flags[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["outside_parts"] + == 2.5 + ) + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] + assert flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] in_no_area = merged(_person(), _person(area=[""], weight=[4.0])) flags = _flags(differential(cells, in_no_area)) - assert not flags[("2.1", "state_pension_age", UNITED_KINGDOM)]["in_sample"] - assert flags[("2.1", "state_pension_age", UNITED_KINGDOM)]["outside_parts"] == 4.0 - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] + assert ( + flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "outside_parts" + ] + == 4.0 + ) + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] # The residents' count is exactly its areas', whoever else the file holds. assert flags[("2.2", "state_pension_age", RESIDENTS)]["in_sample"] - assert flags[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)]["in_sample"] + assert flags[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] def test_a_family_is_in_sample_only_when_every_cell_is() -> None: @@ -358,7 +402,7 @@ def test_rows_of_another_geography_are_not_read() -> None: _row("2.5", "total_taxpayer_count", AREAS[0], 2025, 1.0), _row("2.5", "total_taxpayer_count", AREAS[0], 2025, 1.0, (15_000, 17_500)), _row("2.1", "state_pension_age", AREAS[0], 2025, 1.0), - _row("2.2", "state_pension_age", UNITED_KINGDOM, 2025, 1.0), + _row("2.2", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, 1.0), _row("2.2", "age_65_and_over", "E06000001", 2025, 1.0), ] assert expected_cells([*_rows(), *elsewhere], year=2025) == expected_cells( @@ -367,9 +411,9 @@ def test_rows_of_another_geography_are_not_read() -> None: def test_table_of_names_the_table_or_none() -> None: - assert table_of(_row("2.5", "total_taxpayer_count", UNITED_KINGDOM, 2025, 1)) == ( - "2.5" - ) + assert table_of( + _row("2.5", "total_taxpayer_count", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, 1) + ) == ("2.5") assert table_of(_row("2.2", "males", AREAS[0], 2025, 1)) == "2.2" assert table_of({"layout": {"record_set_id": "hmrc.spi.table_3_6"}}) == "3.6" assert table_of({"layout": {"record_set_id": "ons.mid_year_2025"}}) is None @@ -379,7 +423,14 @@ def test_table_of_names_the_table_or_none() -> None: def test_a_band_outside_itl_bands_is_refused() -> None: rows = _rows(ages=False) rows += [ - _row("2.5", "total_taxpayer_count", UNITED_KINGDOM, year, 1.0, (15_000, 17_500)) + _row( + "2.5", + "total_taxpayer_count", + UK_HMRC_ITL_UK_GEOGRAPHY_ID, + year, + 1.0, + (15_000, 17_500), + ) for year in (2024, 2025) ] with pytest.raises(ValueError, match=r"bands \['\(15000, 17500\)'\]"): @@ -390,8 +441,8 @@ def test_rows_no_cell_reads_do_not_refuse_the_window() -> None: """A measure the check does not read may carry one tax year only.""" lonely = [ - _row("2.1", "males", UNITED_KINGDOM, 2025, 1.0), - _row("2.5", "total_income_amount", UNITED_KINGDOM, 2025, 1.0), + _row("2.1", "males", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, 1.0), + _row("2.5", "total_income_amount", UK_HMRC_ITL_UK_GEOGRAPHY_ID, 2025, 1.0), ] assert expected_cells([*_rows(), *lonely], year=2025) == expected_cells( _rows(), year=2025 @@ -471,7 +522,9 @@ def test_the_bands_and_the_areas_partition_their_totals(people) -> None: bands = [ model_count(cell, people) for key, cell in cells.items() if key[1] == BAND_COUNT ] - total = model_count(cells[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)], people) + total = model_count( + cells[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)], people + ) assert math.fsum([*bands, below_first_edge]) == pytest.approx( total, rel=1e-12, abs=1e-9 ) @@ -479,8 +532,12 @@ def test_the_bands_and_the_areas_partition_their_totals(people) -> None: areas = [model_count(cells[("2.2", measure, area)], people) for area in AREAS] residents = model_count(cells[("2.2", measure, RESIDENTS)], people) assert math.fsum(areas) == pytest.approx(residents, rel=1e-12, abs=1e-9) - spa = model_count(cells[("2.1", "state_pension_age", UNITED_KINGDOM)], people) - below = model_count(cells[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)], people) + spa = model_count( + cells[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)], people + ) + below = model_count( + cells[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)], people + ) assert math.fsum([spa, below]) == pytest.approx(total, rel=1e-12, abs=1e-9) @@ -500,18 +557,18 @@ def test_a_sum_in_sample_is_fixed_by_bound_parts(people, every_band) -> None: ) rows = _flags(report) model = {key: row["model"] for key, row in rows.items()} - total = rows[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)] + total = rows[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] if total["in_sample"]: assert every_band band_models = [m for (t, ms, _k), m in model.items() if ms == BAND_COUNT] assert math.fsum(band_models) == pytest.approx( total["model"], rel=1e-12, abs=1e-9 ) - spa = rows[("2.1", "state_pension_age", UNITED_KINGDOM)] + spa = rows[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)] if spa["in_sample"]: areas = [model[("2.2", "state_pension_age", area)] for area in AREAS] assert math.fsum(areas) == pytest.approx(spa["model"], rel=1e-12, abs=1e-9) - below = rows[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)] + below = rows[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] if below["in_sample"]: assert total["in_sample"] and spa["in_sample"] families: dict[str, list] = {} @@ -548,7 +605,7 @@ def test_the_verdict_is_the_tolerance(model, expected) -> None: _row( "2.5", "total_taxpayer_count", - UNITED_KINGDOM, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, year, expected, (20_000, 30_000), @@ -588,12 +645,47 @@ def test_the_vendored_table_2_5_rows_give_every_band_at_calendar_2025() -> None: (cell.table, cell.measure, cell.key): cell for cell in expected_cells(rows, year=2025) } - total = cells[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)] + total = cells[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] # Table 2.5's all-band count: 38.6m in 2024-25 and 39.8m in 2025-26. assert total.expected == pytest.approx(0.25 * 38_600_000 + 0.75 * 39_800_000) assert sum(1 for key in cells if key[1] == BAND_COUNT) == len(ITL_BANDS) +def test_the_tolerance_note_cites_the_vendored_counts() -> None: + """The counts the note on ``NATIONAL_TOLERANCE`` cites, from the vendored + rows at the calendar-2025 window: five of the eleven bands hold under + 400,000 taxpayers, and the top three hold fewer than the smallest area + cell, Northern Ireland's State Pension age count. Every band takes the + national tolerance all the same: geography, not size, decides.""" + + rows = load_vendored_resource("hmrc_itl_taxpayer_counts.json")["rows"] + cells = expected_cells(rows, year=2025) + bands = [cell for cell in cells if cell.measure == BAND_COUNT] + assert len(bands) == len(ITL_BANDS) + assert {cell.key: cell.expected for cell in bands if cell.expected < 400_000} == { + "150000-200000": 342_750.0, + "200000-500000": 372_500.0, + "500000-1000000": 65_500.0, + "1000000-2000000": 20_750.0, + "2000000+": 10_750.0, + } + smallest = min( + (cell for cell in cells if cell.tolerance == REGIONAL_TOLERANCE), + key=lambda cell: cell.expected, + ) + assert (smallest.measure, smallest.key, smallest.expected) == ( + "state_pension_age", + "N92000002", + 198_750.0, + ) + assert [cell.key for cell in bands if cell.expected < smallest.expected] == [ + "500000-1000000", + "1000000-2000000", + "2000000+", + ] + assert {cell.tolerance for cell in bands} == {NATIONAL_TOLERANCE} + + # The tool ------------------------------------------------------------------ @@ -693,14 +785,18 @@ def _consistent_rows(): _row( "2.5", "total_taxpayer_count", - UNITED_KINGDOM, + UK_HMRC_ITL_UK_GEOGRAPHY_ID, year, (index + 1) * 1_000.0, band, ) ) total = math.fsum((index + 1) * 1_000.0 for index in range(len(ITL_BANDS))) - rows.append(_row("2.5", "total_taxpayer_count", UNITED_KINGDOM, year, total)) + rows.append( + _row( + "2.5", "total_taxpayer_count", UK_HMRC_ITL_UK_GEOGRAPHY_ID, year, total + ) + ) return rows @@ -714,8 +810,8 @@ def _band_people(weight): "household_weight": weight, TAX: np.ones(size), TOTAL_INCOME: edges, - "is_SP_age": np.zeros(size, dtype=bool), - "age": np.full(size, 40.0), + IS_SP_AGE: np.zeros(size, dtype=bool), + AGE: np.full(size, 40.0), "region": np.array(["LONDON"] * size), } ) @@ -889,6 +985,236 @@ def test_the_bound_cells_expect_what_the_build_compiles() -> None: ) +# Whom the contract's bindings count ------------------------------------------- + + +def _contract(): + """The contract's targets by id.""" + + return { + row["target_id"]: row + for row in _resource("uk_population_targets.json")["targets"] + } + + +#: The keys of a ``policyengine`` binding that decide whom its rows count and +#: what each person counts for. +_COUNTING_KEYS = ( + "kind", + "value_variable", + "value_expression", + "value_reduction", + "from_entity", + "map_to", + "filters", + "household_conditions", + "groupby_variable", + "band_semantics", +) + + +def test_the_check_reads_what_the_contract_binds() -> None: + """The three families ``BOUND_BY`` reads count as the check counts. Each + counts ``person_count`` at person grain, mapped to the household (the + check gives each person its household's weight), and only people whose + ``TAX`` is above zero. The bands group on ``TOTAL_INCOME`` and read + ``[lower, upper)``: no ``band_semantics``. The age families add + ``IS_SP_AGE`` true and ``AGE`` at least 65, and band nothing. A binding + that changes any of these, or gains a provider ``kind``, a value + expression or reduction, or a household condition, fails here.""" + + taxpayer = {"variable": TAX, "operator": ">", "value": 0} + counted = { + "value_variable": "person_count", + "from_entity": "person", + "map_to": "household", + } + expected = { + ("2.5", BAND_COUNT): { + **counted, + "filters": [taxpayer], + "groupby_variable": TOTAL_INCOME, + }, + ("2.2", "state_pension_age"): { + **counted, + "filters": [taxpayer, {"variable": IS_SP_AGE, "equals": True}], + }, + ("2.2", "age_65_and_over"): { + **counted, + "filters": [taxpayer, {"variable": AGE, "operator": ">=", "value": 65}], + }, + } + assert set(expected) == set(BOUND_BY) + contract = _contract() + for family, target in BOUND_BY.items(): + binding = contract[target]["bindings"]["policyengine"] + read = {key: binding[key] for key in _COUNTING_KEYS if key in binding} + assert read == expected[family], target + + +def _edge_people(): + """Engine columns for people at every edge the bindings read, and each + person's household region: tax either side of zero, total income either + side of each band edge, either State Pension age flag and ages either + side of 65, in each of the twelve region-tier areas and in none.""" + + edges = [float(lower) for lower, _upper in ITL_BANDS] + incomes = sorted( + { + 0.0, + 5_000_000.0, + *(edge + step for edge in edges for step in (-0.01, 0.0, 0.01)), + } + ) + grid = itertools.product( + (*UK_REGION_TIER_ENUM.values(), "UNKNOWN"), + (-1.0, 0.0, 0.01, 1.0), + incomes, + (False, True), + (64.0, 64.99, 65.0, 65.01, 90.0), + ) + region, tax, income, sp_age, age = ( + np.array(column) for column in zip(*grid, strict=True) + ) + return {TAX: tax, TOTAL_INCOME: income, IS_SP_AGE: sp_age, AGE: age}, region + + +def _readings(contract): + """Each bound cell (a Table 2.5 band or a Table 2.2 area) on + ``_edge_people``, with what each person counts for in it: the check's + reading, and the build's reading of the cell's binding in ``contract`` + through the plain-column interpreter that materializes these + prepared-column targets (None when it cannot read the binding from the + check's columns, or bands what the check does not). The reference's + geography predicate is not part of the binding, so the check's own area + stands in for it on both sides.""" + + engine, region = _edge_people() + size = len(region) + people = resolved_people( + _Resolver({**engine, "household_weight": np.ones(size), "region": region}) + ) + adapter = SimpleNamespace( + tables={"person": {**engine, "person_count": np.ones(size)}} + ) + for cell in expected_cells(_rows(), year=2025): + if cell.reference is None: + continue + target = BOUND_BY[(cell.table, cell.measure)] + binding = contract[target]["bindings"]["policyengine"] + build = None + if bool(binding.get("groupby_variable")) == (cell.band is not None): + band = None + if cell.band is not None: + lower, upper = cell.band + band = (float(lower), math.inf if upper is None else float(upper)) + try: + counted = _prepared_column_values(adapter, "person", binding, band=band) + except (KeyError, TypeError, ValueError): + pass + else: + build = np.asarray(counted, dtype=float) + if cell.area is not None: + build = np.where(people.area == cell.area, build, 0.0) + yield cell, cell_mask(cell, people).astype(float), build + + +def test_each_bound_cell_counts_whom_its_binding_counts() -> None: + """Two readings of each bound family agree: on people at every edge, each + Table 2.5 band and Table 2.2 area counts, person by person, what the + build's interpreter counts for the cell's contract binding, and each + counts someone and leaves someone out.""" + + readings = list(_readings(_contract())) + assert len(readings) == len(ITL_BANDS) + len(AGE_MEASURES) * len(AREAS) + for cell, check, build in readings: + assert build is not None, cell.reference + assert np.array_equal(check, build), cell.reference + assert 0 < check.sum() < len(check), cell.reference + + +_BAND_TARGET = BOUND_BY[("2.5", BAND_COUNT)] +_STATE_PENSION_AGE_TARGET = BOUND_BY[("2.2", "state_pension_age")] +_AGED_65_AND_OVER_TARGET = BOUND_BY[("2.2", "age_65_and_over")] + +#: Edits a later change could make to a binding, by name: the binding's +#: target and the edit. +_BINDING_EDITS = { + "taxpayers-from-zero": ( + _BAND_TARGET, + lambda binding: binding["filters"][0].update(operator=">="), + ), + "another-tax-variable": ( + _STATE_PENSION_AGE_TARGET, + lambda binding: binding["filters"][0].update(variable="income_tax"), + ), + "bands-on-tax": ( + _BAND_TARGET, + lambda binding: binding.update(groupby_variable=TAX), + ), + "bands-on-another-variable": ( + _BAND_TARGET, + lambda binding: binding.update(groupby_variable="total_income"), + ), + "no-band-variable": ( + _BAND_TARGET, + lambda binding: binding.pop("groupby_variable"), + ), + "bands-in-whole-pence": ( + _BAND_TARGET, + lambda binding: binding.update(band_semantics=WHOLE_PENCE_UPPER_CLOSED), + ), + "below-state-pension-age": ( + _STATE_PENSION_AGE_TARGET, + lambda binding: binding["filters"][1].update(equals=False), + ), + "another-state-pension-age-flag": ( + _STATE_PENSION_AGE_TARGET, + lambda binding: binding["filters"][1].update(variable="is_female"), + ), + "aged-66-and-over": ( + _AGED_65_AND_OVER_TARGET, + lambda binding: binding["filters"][1].update(value=66), + ), + "aged-over-65": ( + _AGED_65_AND_OVER_TARGET, + lambda binding: binding["filters"][1].update(operator=">"), + ), + "any-age": ( + _AGED_65_AND_OVER_TARGET, + lambda binding: binding["filters"].pop(), + ), + "an-added-filter": ( + _STATE_PENSION_AGE_TARGET, + lambda binding: binding["filters"].append( + {"variable": AGE, "operator": ">=", "value": 70} + ), + ), +} + + +@pytest.mark.parametrize("edit", sorted(_BINDING_EDITS)) +def test_an_edited_binding_turns_its_family_red(edit) -> None: + """The differential reads the bindings themselves, not a copy of them: + an edit to a filter, the band variable or the band reading makes every + cell of that binding's family, and no other cell, read differently from + the check.""" + + target, change = _BINDING_EDITS[edit] + contract = copy.deepcopy(_contract()) + change(contract[target]["bindings"]["policyengine"]) + red = { + cell.reference + for cell, check, build in _readings(contract) + if build is None or not np.array_equal(check, build) + } + assert red == { + cell.reference + for cell in expected_cells(_rows(), year=2025) + if cell.reference is not None and BOUND_BY[(cell.table, cell.measure)] == target + } + + def _diagnostics(tmp_path, *, left_out=frozenset()): """A run's calibration_diagnostics.json as a UK build writes its target rows: each bound reference at 2025, a reference in ``left_out`` with no @@ -962,11 +1288,15 @@ def report(people, **left_out): abroad = _person(area=[""], total_income=[20_000.0], weight=[3.0]) flags = _flags(report(_area_people(abroad))) for measure in AGE_MEASURES: - assert not flags[("2.1", measure, UNITED_KINGDOM)]["in_sample"] - assert flags[("2.1", measure, UNITED_KINGDOM)]["outside_parts"] == 3.0 + assert not flags[("2.1", measure, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] + assert ( + flags[("2.1", measure, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["outside_parts"] == 3.0 + ) assert flags[("2.2", measure, RESIDENTS)]["in_sample"] - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)]["in_sample"] - assert flags[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] + assert flags[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] area = AREAS[6] target = BOUND_BY[("2.2", "state_pension_age")] @@ -974,8 +1304,12 @@ def report(people, **left_out): flags = _flags(left) assert not flags[("2.2", "state_pension_age", area)]["in_sample"] assert not flags[("2.2", "state_pension_age", RESIDENTS)]["in_sample"] - assert not flags[("2.1", "state_pension_age", UNITED_KINGDOM)]["in_sample"] - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] assert all( flags[("2.2", "state_pension_age", other)]["in_sample"] for other in AREAS @@ -983,7 +1317,7 @@ def report(people, **left_out): ) assert left["families"]["2.2:age_65_and_over"]["in_sample"] assert not left["families"]["2.2:state_pension_age"]["in_sample"] - assert flags[("2.1", "age_65_and_over", UNITED_KINGDOM)]["in_sample"] + assert flags[("2.1", "age_65_and_over", UK_HMRC_ITL_UK_GEOGRAPHY_ID)]["in_sample"] def test_resolved_people_reads_the_area_from_the_household_region() -> None: @@ -996,8 +1330,8 @@ def test_resolved_people_reads_the_area_from_the_household_region() -> None: "household_weight": np.array([1.0, 2.0, 3.0]), TAX: np.array([1.0, 0.0, 5.0]), TOTAL_INCOME: np.array([20_000.0, 5_000.0, 60_000.0]), - "is_SP_age": np.array([True, False, False]), - "age": np.array([70.0, 30.0, 50.0]), + IS_SP_AGE: np.array([True, False, False]), + AGE: np.array([70.0, 30.0, 50.0]), "region": np.array(["Region.LONDON", "WALES", "UNKNOWN"]), } ) @@ -1020,13 +1354,17 @@ def test_without_table_2_2_the_united_kingdom_counts_have_no_parts() -> None: cells = expected_cells(rows, year=2025, bound_targets=set(BOUND_BY.values())) by_key = {(cell.table, cell.measure, cell.key): cell for cell in cells} for measure in AGE_MEASURES: - national = by_key[("2.1", measure, UNITED_KINGDOM)] + national = by_key[("2.1", measure, UK_HMRC_ITL_UK_GEOGRAPHY_ID)] assert national.parts == () assert not national.in_sample - assert not by_key[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)].in_sample - assert by_key[("2.5", ALL_TAXPAYERS, UNITED_KINGDOM)].in_sample + assert not by_key[ + ("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID) + ].in_sample + assert by_key[("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID)].in_sample flags = _flags(differential(cells, ITLPeople(**_person()))) - assert not flags[("2.1", "state_pension_age", UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] def test_a_sum_given_without_one_of_its_parts_is_out_of_sample() -> None: @@ -1039,19 +1377,23 @@ def test_a_sum_given_without_one_of_its_parts_is_out_of_sample() -> None: } cells = expected_cells(_rows(), year=2025, bound_targets=bound) people = ITLPeople(**_person()) - total = ("2.5", ALL_TAXPAYERS, UNITED_KINGDOM) + total = ("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID) assert _flags(differential(cells, people))[total]["in_sample"] without = [cell for cell in cells if cell.band != ITL_BANDS[3]] flags = _flags(differential(without, people)) assert not flags[total]["in_sample"] - assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM)]["in_sample"] + assert not flags[("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID)][ + "in_sample" + ] def test_the_cells_read_the_bindings_at_their_edges() -> None: - """Each mask is its binding at the edges: a band holds its lower edge and - not its upper; 65 is in the count aged 65 and over and 64.9 is not; only - taxpayers count; State Pension age is the engine's flag, not an age; the - residents are the twelve areas and no other code.""" + """Each mask is its binding at the edges, pinned by hand: a band holds its + lower edge and not its upper; 65 is in the count aged 65 and over and + 64.9 is not; only taxpayers count; State Pension age is the engine's + flag, not an age; the residents are the twelve areas and no other code. + ``test_each_bound_cell_counts_whom_its_binding_counts`` reads the + bindings themselves.""" people = ITLPeople( weight=np.array([1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]), @@ -1076,10 +1418,13 @@ def count(*key): assert count("2.5", BAND_COUNT, "12570-15000") == 1.0 assert count("2.5", BAND_COUNT, "15000-20000") == 2.0 assert count("2.5", BAND_COUNT, "20000-30000") == 8.0 + 32.0 + 64.0 - assert count("2.5", ALL_TAXPAYERS, UNITED_KINGDOM) == 111.0 - assert count("2.1", "age_65_and_over", UNITED_KINGDOM) == 1.0 + 4.0 + 32.0 + 64.0 - assert count("2.1", "state_pension_age", UNITED_KINGDOM) == 8.0 + 64.0 - assert count("2.1", BELOW_STATE_PENSION_AGE, UNITED_KINGDOM) == 39.0 + assert count("2.5", ALL_TAXPAYERS, UK_HMRC_ITL_UK_GEOGRAPHY_ID) == 111.0 + assert ( + count("2.1", "age_65_and_over", UK_HMRC_ITL_UK_GEOGRAPHY_ID) + == 1.0 + 4.0 + 32.0 + 64.0 + ) + assert count("2.1", "state_pension_age", UK_HMRC_ITL_UK_GEOGRAPHY_ID) == 8.0 + 64.0 + assert count("2.1", BELOW_STATE_PENSION_AGE, UK_HMRC_ITL_UK_GEOGRAPHY_ID) == 39.0 assert count("2.2", "age_65_and_over", AREAS[0]) == 1.0 + 4.0 assert count("2.2", "state_pension_age", AREAS[1]) == 8.0 assert count("2.2", "state_pension_age", RESIDENTS) == 8.0 @@ -1284,3 +1629,53 @@ def test_the_basis_reports_rows_bound_without_a_weight( assert receipt["in_sample_basis"] == f"target references {references} at 2025" assert not any(cell["in_sample"] for cell in receipt["cells"]) assert "run_estimates" not in receipt + + +def test_the_current_income_route_needs_a_basis( + tool, tmp_path, monkeypatch, capsys +) -> None: + """``--current-income-for-annual-measures`` reads a file built before the + annual income descriptors, whose calibration this tree's references do + not describe: on their basis every band would read in sample. Without + ``--diagnostics`` or ``--references`` the tool refuses the option before + it reads anything; with either it passes the reason on. Without the + option, this tree's references stay the default basis.""" + + reasons = [] + weight = np.array([(index + 1) * 1_000.0 for index in range(len(ITL_BANDS))]) + + def resolver(*args, reason=None, **kwargs): + reasons.append(reason) + return _band_people(weight) + + monkeypatch.setattr(tool, "measure_resolver", resolver) + h5 = tmp_path / "incumbent.h5" + h5.write_bytes(b"not read") + rows = tmp_path / "rows.json" + rows.write_text(json.dumps({"rows": _consistent_rows()})) + out = tmp_path / "report.json" + argv = ["--h5", str(h5), "--out", str(out), "--itl-rows", str(rows)] + incumbent = [*argv, "--current-income-for-annual-measures", "incumbent"] + + with pytest.raises(SystemExit) as refused: + tool.main(incumbent) + assert refused.value.code == 2 + assert "needs --diagnostics or --references" in capsys.readouterr().err + assert reasons == [] and not out.exists() + + assert tool.main(argv) == 0 + receipt = json.loads(out.read_text()) + assert receipt["in_sample_basis"] == "target references of this tree at 2025" + assert all(cell["in_sample"] for cell in receipt["cells"]) + + references = tmp_path / "target_references.json" + references.write_text(json.dumps({"target_references": []})) + assert tool.main([*incumbent, "--references", str(references)]) == 0 + receipt = json.loads(out.read_text()) + assert receipt["in_sample_basis"] == f"target references {references} at 2025" + assert not any(cell["in_sample"] for cell in receipt["cells"]) + diagnostics = tmp_path / "calibration_diagnostics.json" + diagnostics.write_text(json.dumps({"targets": []})) + assert tool.main([*incumbent, "--diagnostics", str(diagnostics)]) == 0 + assert not any(cell["in_sample"] for cell in json.loads(out.read_text())["cells"]) + assert reasons == [None, "incumbent", "incumbent"] diff --git a/tools/build_us_fiscal_refresh_release.py b/tools/build_us_fiscal_refresh_release.py index 85ce3a94b7..a4fa912cb0 100644 --- a/tools/build_us_fiscal_refresh_release.py +++ b/tools/build_us_fiscal_refresh_release.py @@ -8034,7 +8034,8 @@ def _ecps_parity_gate( "(PolicyEngine/microcosm#299 Build H). That math holds only for the " "$98.434B reference. The build applies this entry for any reference, " "so re-adjudicate it if --export-input-mass-reference-h5 names a file " - "with a different level." + "with a different level, or if the flag is absent and the raw base " + "becomes the reference." ), "non_sch_d_capital_gains": ( "Identified by SOI Table 1.4 capital gain distributions reported on " diff --git a/tools/check_uk_itl_projections.py b/tools/check_uk_itl_projections.py index ec923d6253..a662ce0079 100644 --- a/tools/check_uk_itl_projections.py +++ b/tools/check_uk_itl_projections.py @@ -27,6 +27,14 @@ --h5 --out [--diagnostics ] \ [--itl-rows ] [--strict] +``--current-income-for-annual-measures`` reads a file built before the annual +income descriptors existed (the incumbent). This tree's references say what a +build of this tree binds, not what that file's calibration bound: they bind +every band and area at 2025, so at the default ``--year`` every band and area +cell of such a file would read ``in``. The tool refuses the option unless +``--diagnostics`` or ``--references`` names the basis; a references file that +lists no reference marks every cell out of sample. + ``--itl-rows`` replaces the vendored ``hmrc_itl_taxpayer_counts.json`` with a vendored-format JSON or a JSONL of Chronicle consumer facts. The report holds aggregates only; keep it on the private lane with the run all the same. @@ -228,10 +236,24 @@ def main(argv: list[str] | None = None) -> int: parser.add_argument( "--current-income-for-annual-measures", metavar="REASON", - help="For a file without annual income descriptors (the incumbent).", + help="For a file without annual income descriptors (the incumbent). " + "Needs --diagnostics or --references: this tree's target references " + "say what a build of this tree binds, not what that file bound.", ) parser.add_argument("--strict", action="store_true", help="Exit 1 on any miss.") args = parser.parse_args(argv) + if ( + args.current_income_for_annual_measures is not None + and args.diagnostics is None + and args.references is None + ): + parser.error( + "--current-income-for-annual-measures needs --diagnostics or " + "--references: this tree's target references say what a build of " + "this tree binds, not what a file built before the annual income " + "descriptors bound. A references file that lists no reference marks " + "every cell out of sample." + ) rows, rows_source = load_rows(args.itl_rows) if args.diagnostics is not None: From 39b8a930df347e8e377dc274d3f61bf8cd9c3176 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 9 Nov 2026 13:53:54 -0500 Subject: [PATCH 2/5] Run the ITL binding differential through the build's materialization Review of 1f506fa25 (should-fix): the differential handed the build the check's own band edges, so a band_upper_bound or band_period_factor on the band binding left every test green. The differential now builds real TargetSpecs for the 35 bound references (stamped by the Ledger compile's _ledger_metadata from each reference's vendored fact, under _reference_metadata), puts the edge people on a real Frame and runs materialize_target_bindings on a UKFrameTargetAdapter, so the build reads each band from the spec and scopes each area by its geography predicate. People 0.4p below each band edge make a whole-pence reading visible. The structural test now holds every binding key but notes and metric_name, and three edits join the mutation list: a capped top band (the top band alone turns red), monthly band edges and a provider kind. Nits: the tolerance-note test reads the note from the module source and derives its numbers from the rows; the tool refuses an empty --current-income-for-annual-measures reason and records the reason in the receipt; "is above zero" reads "exceeds zero". Co-Authored-By: Claude Opus 5.5 --- changelog.d/1417-review-followups.fixed.md | 2 +- .../build/uk_runtime/itl_differential.py | 7 +- .../uk/test_uk_itl_differential.py | 390 +++++++++++++----- tools/check_uk_itl_projections.py | 19 +- 4 files changed, 296 insertions(+), 122 deletions(-) diff --git a/changelog.d/1417-review-followups.fixed.md b/changelog.d/1417-review-followups.fixed.md index 34d6a2d24d..b66d5d1d8c 100644 --- a/changelog.d/1417-review-followups.fixed.md +++ b/changelog.d/1417-review-followups.fixed.md @@ -1 +1 @@ -Follow-ups from the reviews of microcosm#1417, #1109 and #1416. `tools/check_uk_itl_projections.py` refuses `--current-income-for-annual-measures` unless `--diagnostics` or `--references` names the in-sample basis: this tree's target references say what a build of this tree binds, not what a file built before the annual income descriptors bound, so on that basis every band and area cell of such a file read `in` at the default `--year`. `uk_runtime.itl_differential` names the engine variables its cells read (`TAX`, `TOTAL_INCOME`, `IS_SP_AGE`, `AGE`), and new engine-free tests hold them, and each bound cell's mask, to the contract's `policyengine` bindings of the three bound families through the build's own binding interpreter, so an edit to a binding's filter, band variable or band reading fails until the check follows it. The note on `NATIONAL_TOLERANCE` cites the vendored band counts (at the calendar-2025 window five of the eleven bands hold under 400,000 taxpayers, and the top three hold fewer than the smallest area cell) in place of a claim that national cells sum over millions; the tolerances stay 5% and 10%. The check imports `UK_HMRC_ITL_UK_GEOGRAPHY_ID` instead of repeating it. The US fiscal refresh's reviewed `estate_income` exclusion also asks for re-adjudication when the flag is absent and the raw base becomes the reference, and the `materialize_target_bindings` docstring limits the plain-row period refusal to a row that declares a period other than the calibration period. +Follow-ups from the reviews of microcosm#1417, #1109 and #1416. `tools/check_uk_itl_projections.py` refuses `--current-income-for-annual-measures` unless `--diagnostics` or `--references` names the in-sample basis: this tree's target references say what a build of this tree binds, not what a file built before the annual income descriptors bound, so on that basis every band and area cell of such a file read `in` at the default `--year`. It also refuses an empty reason, which turned the current-income route off, and the receipt records the reason. `uk_runtime.itl_differential` names the engine variables its cells read (`TAX`, `TOTAL_INCOME`, `IS_SP_AGE`, `AGE`). New engine-free tests hold the contract's three bound `policyengine` bindings to what the check reads, every key but `notes` and `metric_name`, and run the build's own `materialize_target_bindings` on a `UKFrameTargetAdapter` against the check's masks for all 35 bound cells, band edges from the compiled spec and area geography included. An edit to a binding's filter, band variable or band reading (whole pence, an upper bound, a period factor) therefore fails until the check follows it. The note on `NATIONAL_TOLERANCE` cites the vendored band counts (at the calendar-2025 window five of the eleven bands hold under 400,000 taxpayers, and the top three hold fewer than the smallest area cell) in place of a claim that national cells sum over millions, and a test reads the note against the rows; the tolerances stay 5% and 10%. The check imports `UK_HMRC_ITL_UK_GEOGRAPHY_ID` instead of repeating it. The US fiscal refresh's reviewed `estate_income` exclusion also asks for re-adjudication when the flag is absent and the raw base becomes the reference, and the `materialize_target_bindings` docstring limits the plain-row period refusal to a row that declares a period other than the calibration period. diff --git a/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py b/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py index 4da48d5c51..8c64d2e2bb 100644 --- a/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py +++ b/packages/microcosm-build/src/microcosm/build/uk_runtime/itl_differential.py @@ -55,10 +55,11 @@ #: The engine variables a cell reads, as the contract's ``policyengine`` #: bindings of the ``BOUND_BY`` targets name them: every cell counts people -#: whose ``TAX`` is above zero, a band reads ``TOTAL_INCOME``, the counts of +#: whose ``TAX`` exceeds zero, a band reads ``TOTAL_INCOME``, the counts of #: and below State Pension age read ``IS_SP_AGE`` and the count aged 65 and -#: over reads ``AGE``. ``resolved_people`` reads them; a test holds them, and -#: the cells' masks, to the bindings. +#: over reads ``AGE``. ``resolved_people`` reads them. The tests hold them to +#: the bindings, and each bound cell's mask to what the build materializes +#: for its target. TAX = "income_tax_before_winter_fuel_payment_charge_annual" TOTAL_INCOME = "total_income_after_loss_relief_annual" IS_SP_AGE = "is_SP_age" diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py index b64e38f789..2d166483f2 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py @@ -9,9 +9,12 @@ tolerance fixed before any file is read. The in-sample flags read the targets by the names the contract's references and a run's diagnostics give them, so Table 2.2's areas, bound since microcosm#1069, are in sample. Each -bound cell counts exactly the people the build's own reading of its contract -binding counts (its filters and its band), so an edit to a binding's filter -or band variable fails these tests until the check follows it. +bound cell counts exactly the people the build's own materialization of its +target counts: the binding's filters, the band the build reads from the +compiled spec, and the reference's geography. So an edit to a binding's +filter, band variable or band reading fails these tests until the check +follows it, and an edit to any other key that counts fails the test that +holds the bindings to what the check reads. """ from __future__ import annotations @@ -21,19 +24,28 @@ import itertools import json import math +import re from fractions import Fraction from importlib.resources import files -from types import SimpleNamespace +from pathlib import Path import numpy as np +import pandas as pd import pytest from hypothesis import given, settings from hypothesis import strategies as st +from microcosm.build.country_spec import load_country_spec +from microcosm.build.ledger_targets import ( + CALENDAR_YEAR_WINDOW_WEIGHTS, + _ledger_metadata, + _reference_metadata, +) from microcosm.build.target_materialization import ( WHOLE_PENCE_UPPER_CLOSED, - _prepared_column_values, + materialize_target_bindings, ) +from microcosm.build.uk_runtime import itl_differential from microcosm.build.uk_runtime.hmrc_uprating import ( ITL_BANDS, UK_HMRC_ITL_UK_GEOGRAPHY_ID, @@ -63,10 +75,14 @@ table_of, ) from microcosm.build.uk_runtime.ledger_fact_vendoring import load_vendored_resource +from microcosm.build.uk_runtime.ledger_targets import UKFrameTargetAdapter +from microcosm.calibrate import TargetRegistry, TargetSpec from microcosm.calibrate.geography_constants import ( + UK_GEOGRAPHY_ID_TO_LABEL, UK_REGION_TIER, UK_REGION_TIER_ENUM, ) +from microcosm.frame import EntitySchema, Frame, WeightKind, Weights from test_support.paths import paths_for AREAS = tuple(code for _level, code in UK_REGION_TIER) @@ -651,38 +667,77 @@ def test_the_vendored_table_2_5_rows_give_every_band_at_calendar_2025() -> None: assert sum(1 for key in cells if key[1] == BAND_COUNT) == len(ITL_BANDS) -def test_the_tolerance_note_cites_the_vendored_counts() -> None: - """The counts the note on ``NATIONAL_TOLERANCE`` cites, from the vendored - rows at the calendar-2025 window: five of the eleven bands hold under - 400,000 taxpayers, and the top three hold fewer than the smallest area - cell, Northern Ireland's State Pension age count. Every band takes the - national tolerance all the same: geography, not size, decides.""" +#: Numbers as the tolerance note spells them. +_NUMBER_WORDS = ( + "zero", + "one", + "two", + "three", + "four", + "five", + "six", + "seven", + "eight", + "nine", + "ten", + "eleven", + "twelve", +) +_MEASURE_WORDS = { + "state_pension_age": "State Pension age", + "age_65_and_over": "aged 65 and over", +} + + +def _tolerance_note() -> str: + """The ``#:`` note above ``NATIONAL_TOLERANCE`` in the module's source, + as one line.""" + + lines = Path(itl_differential.__file__).read_text(encoding="utf-8").splitlines() + end = next( + index + for index, line in enumerate(lines) + if line.startswith("NATIONAL_TOLERANCE = ") + ) + start = end + while lines[start - 1].startswith("#:"): + start -= 1 + return " ".join(line.removeprefix("#:").strip() for line in lines[start:end]) + +def test_the_tolerance_note_cites_the_vendored_counts() -> None: + """The note on ``NATIONAL_TOLERANCE`` says what the vendored rows give at + the calendar-2025 window, and this test reads the note: how many bands + hold under 400,000 taxpayers and, in band order, each one's count; how + many of the top bands hold fewer than the smallest area cell; and that + cell's area, measure and count. A change to the rows fails here until + the note follows it. Every band takes the national tolerance all the + same: geography, not size, decides.""" + + note = _tolerance_note() rows = load_vendored_resource("hmrc_itl_taxpayer_counts.json")["rows"] cells = expected_cells(rows, year=2025) bands = [cell for cell in cells if cell.measure == BAND_COUNT] - assert len(bands) == len(ITL_BANDS) - assert {cell.key: cell.expected for cell in bands if cell.expected < 400_000} == { - "150000-200000": 342_750.0, - "200000-500000": 372_500.0, - "500000-1000000": 65_500.0, - "1000000-2000000": 20_750.0, - "2000000+": 10_750.0, - } + assert [cell.band for cell in bands] == list(ITL_BANDS) + under = [cell.expected for cell in bands if cell.expected < 400_000] + assert ( + f"{_NUMBER_WORDS[len(under)]} of the {_NUMBER_WORDS[len(bands)]} bands " + "hold under 400,000 taxpayers" + ) in note + assert re.findall(r"([\d,]+) at £", note) == [f"{count:,.0f}" for count in under] smallest = min( (cell for cell in cells if cell.tolerance == REGIONAL_TOLERANCE), key=lambda cell: cell.expected, ) - assert (smallest.measure, smallest.key, smallest.expected) == ( - "state_pension_age", - "N92000002", - 198_750.0, - ) - assert [cell.key for cell in bands if cell.expected < smallest.expected] == [ - "500000-1000000", - "1000000-2000000", - "2000000+", - ] + fewer = [cell for cell in bands if cell.expected < smallest.expected] + assert fewer == bands[len(bands) - len(fewer) :] + assert ( + f"the top {_NUMBER_WORDS[len(fewer)]} hold fewer than the smallest area cell" + ) in note + assert ( + f"({UK_GEOGRAPHY_ID_TO_LABEL[smallest.key]}'s " + f"{_MEASURE_WORDS[smallest.measure]} count, {smallest.expected:,.0f})" + ) in note assert {cell.tolerance for cell in bands} == {NATIONAL_TOLERANCE} @@ -997,31 +1052,26 @@ def _contract(): } -#: The keys of a ``policyengine`` binding that decide whom its rows count and -#: what each person counts for. -_COUNTING_KEYS = ( - "kind", - "value_variable", - "value_expression", - "value_reduction", - "from_entity", - "map_to", - "filters", - "household_conditions", - "groupby_variable", - "band_semantics", -) +#: The keys of a ``policyengine`` binding that change no count: ``notes`` +#: documents the row, and ``metric_name`` names a counterfactual binding's +#: column, which these plain bindings do not have. +_INERT_KEYS = frozenset({"metric_name", "notes"}) def test_the_check_reads_what_the_contract_binds() -> None: - """The three families ``BOUND_BY`` reads count as the check counts. Each - counts ``person_count`` at person grain, mapped to the household (the - check gives each person its household's weight), and only people whose - ``TAX`` is above zero. The bands group on ``TOTAL_INCOME`` and read - ``[lower, upper)``: no ``band_semantics``. The age families add - ``IS_SP_AGE`` true and ``AGE`` at least 65, and band nothing. A binding - that changes any of these, or gains a provider ``kind``, a value - expression or reduction, or a household condition, fails here.""" + """The three families ``BOUND_BY`` reads bind exactly what the check + counts: ``person_count`` at person grain, mapped to the household (the + check gives each person its household's weight), of people whose ``TAX`` + exceeds zero. The bands group on ``TOTAL_INCOME`` along the + ``total_income`` filter dimension and declare no band semantics, upper + bound or period factor, so the build reads each band as ``[lower, + upper)`` between the vendored lower edges. The age families add + ``IS_SP_AGE`` true or ``AGE`` at least 65, and band nothing. Every key + but ``notes`` and ``metric_name`` is held, so a binding that gains or + changes any other key fails here. That covers the keys whose effect the + differential below cannot see on these rows: ``band_filter_dimension`` + beside a single band-like filter, ``measurement_period`` on a frame + without period metadata, and ``require_matching_fact_period``.""" taxpayer = {"variable": TAX, "operator": ">", "value": 0} counted = { @@ -1034,6 +1084,7 @@ def test_the_check_reads_what_the_contract_binds() -> None: **counted, "filters": [taxpayer], "groupby_variable": TOTAL_INCOME, + "band_filter_dimension": "total_income", }, ("2.2", "state_pension_age"): { **counted, @@ -1048,23 +1099,22 @@ def test_the_check_reads_what_the_contract_binds() -> None: contract = _contract() for family, target in BOUND_BY.items(): binding = contract[target]["bindings"]["policyengine"] - read = {key: binding[key] for key in _COUNTING_KEYS if key in binding} - assert read == expected[family], target + held = {key: value for key, value in binding.items() if key not in _INERT_KEYS} + assert held == expected[family], target def _edge_people(): """Engine columns for people at every edge the bindings read, and each - person's household region: tax either side of zero, total income either - side of each band edge, either State Pension age flag and ages either - side of 65, in each of the twelve region-tier areas and in none.""" + person's household region: tax either side of zero; total income at each + band edge, a penny either side of it and 0.4p below it (where a reading + in whole pence moves a person across the edge); either State Pension age + flag; ages either side of 65; in each of the twelve region-tier areas + and in none.""" edges = [float(lower) for lower, _upper in ITL_BANDS] + steps = (-0.01, -0.004, 0.0, 0.01) incomes = sorted( - { - 0.0, - 5_000_000.0, - *(edge + step for edge in edges for step in (-0.01, 0.0, 0.01)), - } + {0.0, 5_000_000.0, *(edge + step for edge in edges for step in steps)} ) grid = itertools.product( (*UK_REGION_TIER_ENUM.values(), "UNKNOWN"), @@ -1079,51 +1129,117 @@ def _edge_people(): return {TAX: tax, TOTAL_INCOME: income, IS_SP_AGE: sp_age, AGE: age}, region +def _edge_frame(engine, region): + """The edge people as a frame, each in a household of their own.""" + + ids = np.arange(len(region), dtype="int64") + return Frame( + { + "person": pd.DataFrame( + {"person_id": ids, "person_household_id": ids, **engine} + ), + "household": pd.DataFrame({"household_id": ids, "region": region}), + }, + EntitySchema(group_entities=("household",)), + {"household": Weights(np.ones(len(ids)), WeightKind.DESIGN)}, + ) + + +def _window_facts(rows, reference): + """The vendored facts ``reference`` selects in the calendar-2025 window: + its geography, measure and dimension values, at each tax year the + window weights.""" + + selector = reference.ledger_selector + wanted = { + key: str(value) + for key, value in (selector.get("dimension_values") or {}).items() + } + years = {2025 + offset for offset in CALENDAR_YEAR_WINDOW_WEIGHTS} + return [ + row + for row in rows + if row["geography"]["id"] == selector["geography_id"] + and row["measure_id"] == selector["source_measure_id"] + and row["period"]["value"] in years + and all( + str(row["dimensions"].get(key)) == value for key, value in wanted.items() + ) + ] + + +def _bound_registry(): + """The compiled spec of each bound reference, stamped as the Ledger + compile stamps it: the compile's Ledger metadata of a fact the reference + selects (the fact's dimensions give the band's edges, as + ``ledger_filter_total_income_lower_bound``), under the compile's + metadata of the reference (its contract target and geography predicate + among it). The window's facts carry the same dimensions, so either one + stamps the spec.""" + + rows = load_vendored_resource("hmrc_itl_taxpayer_counts.json")["rows"] + specs = [] + for reference in load_country_spec("uk").target_references: + if reference.metadata.get("contract_target_id") not in BOUND_BY.values(): + continue + facts = _window_facts(rows, reference) + assert len(facts) == len(CALENDAR_YEAR_WINDOW_WEIGHTS), reference.name + assert all(fact["dimensions"] == facts[0]["dimensions"] for fact in facts), ( + reference.name + ) + metadata = { + **_ledger_metadata(facts[0], fact_key=facts[0]["source_record_id"]), + **_reference_metadata(reference), + } + specs.append( + TargetSpec( + name=reference.name, + entity=reference.entity, + measure=reference.measure, + value=1.0, + period=reference.period, + source="vendored", + metadata=metadata, + ) + ) + return TargetRegistry(specs, country="uk") + + def _readings(contract): """Each bound cell (a Table 2.5 band or a Table 2.2 area) on ``_edge_people``, with what each person counts for in it: the check's - reading, and the build's reading of the cell's binding in ``contract`` - through the plain-column interpreter that materializes these - prepared-column targets (None when it cannot read the binding from the - check's columns, or bands what the check does not). The reference's - geography predicate is not part of the binding, so the check's own area - stands in for it on both sides.""" + reading, and what ``materialize_target_bindings`` writes for the cell's + reference from ``contract`` on a ``UKFrameTargetAdapter`` (None when it + skips the reference). The build reads each band from the compiled spec + and scopes each area by its reference's geography predicate, as a UK + calibration does.""" engine, region = _edge_people() size = len(region) people = resolved_people( _Resolver({**engine, "household_weight": np.ones(size), "region": region}) ) - adapter = SimpleNamespace( - tables={"person": {**engine, "person_count": np.ones(size)}} - ) + registry = _bound_registry() + adapter = UKFrameTargetAdapter(_edge_frame(engine, region)) + result = materialize_target_bindings(adapter, registry, contract, period=2025) + skipped = {skip.name for skip in result.skipped} + specs = {spec.name: spec for spec in registry.specs} for cell in expected_cells(_rows(), year=2025): if cell.reference is None: continue - target = BOUND_BY[(cell.table, cell.measure)] - binding = contract[target]["bindings"]["policyengine"] build = None - if bool(binding.get("groupby_variable")) == (cell.band is not None): - band = None - if cell.band is not None: - lower, upper = cell.band - band = (float(lower), math.inf if upper is None else float(upper)) - try: - counted = _prepared_column_values(adapter, "person", binding, band=band) - except (KeyError, TypeError, ValueError): - pass - else: - build = np.asarray(counted, dtype=float) - if cell.area is not None: - build = np.where(people.area == cell.area, build, 0.0) + if cell.reference not in skipped: + spec = specs[cell.reference] + build = np.asarray(adapter.column(spec.entity, spec.measure), dtype=float) yield cell, cell_mask(cell, people).astype(float), build def test_each_bound_cell_counts_whom_its_binding_counts() -> None: """Two readings of each bound family agree: on people at every edge, each Table 2.5 band and Table 2.2 area counts, person by person, what the - build's interpreter counts for the cell's contract binding, and each - counts someone and leaves someone out.""" + build's own materialization of its contract target counts, band edges + and geography included; the build skips none of them; and each counts + someone and leaves someone out.""" readings = list(_readings(_contract())) assert len(readings) == len(ITL_BANDS) + len(AGE_MEASURES) * len(AREAS) @@ -1136,83 +1252,118 @@ def test_each_bound_cell_counts_whom_its_binding_counts() -> None: _BAND_TARGET = BOUND_BY[("2.5", BAND_COUNT)] _STATE_PENSION_AGE_TARGET = BOUND_BY[("2.2", "state_pension_age")] _AGED_65_AND_OVER_TARGET = BOUND_BY[("2.2", "age_65_and_over")] +_TOP_BAND = f"{_BAND_TARGET}.{itl_band_key(ITL_BANDS[-1])}" #: Edits a later change could make to a binding, by name: the binding's -#: target and the edit. +#: target, the edit, and the references it turns red (None: every reference +#: of the target). _BINDING_EDITS = { "taxpayers-from-zero": ( _BAND_TARGET, lambda binding: binding["filters"][0].update(operator=">="), + None, ), "another-tax-variable": ( _STATE_PENSION_AGE_TARGET, lambda binding: binding["filters"][0].update(variable="income_tax"), + None, ), "bands-on-tax": ( _BAND_TARGET, lambda binding: binding.update(groupby_variable=TAX), + None, ), "bands-on-another-variable": ( _BAND_TARGET, lambda binding: binding.update(groupby_variable="total_income"), + None, ), "no-band-variable": ( _BAND_TARGET, lambda binding: binding.pop("groupby_variable"), + None, ), "bands-in-whole-pence": ( _BAND_TARGET, lambda binding: binding.update(band_semantics=WHOLE_PENCE_UPPER_CLOSED), + None, + ), + "a-capped-top-band": ( + _BAND_TARGET, + lambda binding: binding.update( + band_upper_bound=3_000_000, band_upper_bound_inclusive=False + ), + {_TOP_BAND}, + ), + "monthly-band-edges": ( + _BAND_TARGET, + lambda binding: binding.update(band_period_factor=12), + None, + ), + "a-provider-kind": ( + _BAND_TARGET, + lambda binding: binding.update(kind="parameter_gated_threshold"), + None, ), "below-state-pension-age": ( _STATE_PENSION_AGE_TARGET, lambda binding: binding["filters"][1].update(equals=False), + None, ), "another-state-pension-age-flag": ( _STATE_PENSION_AGE_TARGET, lambda binding: binding["filters"][1].update(variable="is_female"), + None, ), "aged-66-and-over": ( _AGED_65_AND_OVER_TARGET, lambda binding: binding["filters"][1].update(value=66), + None, ), "aged-over-65": ( _AGED_65_AND_OVER_TARGET, lambda binding: binding["filters"][1].update(operator=">"), + None, ), "any-age": ( _AGED_65_AND_OVER_TARGET, lambda binding: binding["filters"].pop(), + None, ), "an-added-filter": ( _STATE_PENSION_AGE_TARGET, lambda binding: binding["filters"].append( {"variable": AGE, "operator": ">=", "value": 70} ), + None, ), } @pytest.mark.parametrize("edit", sorted(_BINDING_EDITS)) -def test_an_edited_binding_turns_its_family_red(edit) -> None: - """The differential reads the bindings themselves, not a copy of them: - an edit to a filter, the band variable or the band reading makes every - cell of that binding's family, and no other cell, read differently from - the check.""" - - target, change = _BINDING_EDITS[edit] +def test_an_edited_binding_turns_its_cells_red(edit) -> None: + """The differential reads the bindings themselves, through the build: an + edit to a filter, the band variable, the band reading (whole pence, an + upper bound or a period factor) or the binding's kind makes exactly the + cells it moves read differently from the check, or the build skip them. + That is every cell of the binding's family, except for an upper bound + above the top band's lower edge, which moves the top band alone.""" + + target, change, red = _BINDING_EDITS[edit] contract = copy.deepcopy(_contract()) change(contract[target]["bindings"]["policyengine"]) - red = { + if red is None: + red = { + cell.reference + for cell in expected_cells(_rows(), year=2025) + if cell.reference is not None + and BOUND_BY[(cell.table, cell.measure)] == target + } + assert { cell.reference for cell, check, build in _readings(contract) if build is None or not np.array_equal(check, build) - } - assert red == { - cell.reference - for cell in expected_cells(_rows(), year=2025) - if cell.reference is not None and BOUND_BY[(cell.table, cell.measure)] == target - } + } == red def _diagnostics(tmp_path, *, left_out=frozenset()): @@ -1393,7 +1544,7 @@ def test_the_cells_read_the_bindings_at_their_edges() -> None: 64.9 is not; only taxpayers count; State Pension age is the engine's flag, not an age; the residents are the twelve areas and no other code. ``test_each_bound_cell_counts_whom_its_binding_counts`` reads the - bindings themselves.""" + bindings themselves, through the build's materialization.""" people = ITLPeople( weight=np.array([1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]), @@ -1638,8 +1789,10 @@ def test_the_current_income_route_needs_a_basis( annual income descriptors, whose calibration this tree's references do not describe: on their basis every band would read in sample. Without ``--diagnostics`` or ``--references`` the tool refuses the option before - it reads anything; with either it passes the reason on. Without the - option, this tree's references stay the default basis.""" + it reads anything, and it refuses an empty reason, which would turn the + route off; with a basis it passes the reason on, and the receipt records + it. Without the option, this tree's references stay the default basis + and the receipt records no reason.""" reasons = [] weight = np.array([(index + 1) * 1_000.0 for index in range(len(ITL_BANDS))]) @@ -1657,22 +1810,37 @@ def resolver(*args, reason=None, **kwargs): argv = ["--h5", str(h5), "--out", str(out), "--itl-rows", str(rows)] incumbent = [*argv, "--current-income-for-annual-measures", "incumbent"] - with pytest.raises(SystemExit) as refused: - tool.main(incumbent) - assert refused.value.code == 2 - assert "needs --diagnostics or --references" in capsys.readouterr().err + references = tmp_path / "target_references.json" + references.write_text(json.dumps({"target_references": []})) + for refused_argv, message in ( + (incumbent, "needs --diagnostics or --references"), + ( + [ + *argv, + "--current-income-for-annual-measures", + " ", + "--references", + str(references), + ], + "needs a reason", + ), + ): + with pytest.raises(SystemExit) as refused: + tool.main(refused_argv) + assert refused.value.code == 2 + assert message in capsys.readouterr().err assert reasons == [] and not out.exists() assert tool.main(argv) == 0 receipt = json.loads(out.read_text()) assert receipt["in_sample_basis"] == "target references of this tree at 2025" + assert receipt["current_income_for_annual_measures"] is None assert all(cell["in_sample"] for cell in receipt["cells"]) - references = tmp_path / "target_references.json" - references.write_text(json.dumps({"target_references": []})) assert tool.main([*incumbent, "--references", str(references)]) == 0 receipt = json.loads(out.read_text()) assert receipt["in_sample_basis"] == f"target references {references} at 2025" + assert receipt["current_income_for_annual_measures"] == "incumbent" assert not any(cell["in_sample"] for cell in receipt["cells"]) diagnostics = tmp_path / "calibration_diagnostics.json" diagnostics.write_text(json.dumps({"targets": []})) diff --git a/tools/check_uk_itl_projections.py b/tools/check_uk_itl_projections.py index a662ce0079..9fc3d3d41b 100644 --- a/tools/check_uk_itl_projections.py +++ b/tools/check_uk_itl_projections.py @@ -33,7 +33,9 @@ every band and area at 2025, so at the default ``--year`` every band and area cell of such a file would read ``in``. The tool refuses the option unless ``--diagnostics`` or ``--references`` names the basis; a references file that -lists no reference marks every cell out of sample. +lists no reference marks every cell out of sample. It refuses an empty reason +too, since the resolver takes the route only with one, and the receipt +records the reason (``current_income_for_annual_measures``). ``--itl-rows`` replaces the vendored ``hmrc_itl_taxpayer_counts.json`` with a vendored-format JSON or a JSONL of Chronicle consumer facts. The report holds @@ -242,11 +244,13 @@ def main(argv: list[str] | None = None) -> int: ) parser.add_argument("--strict", action="store_true", help="Exit 1 on any miss.") args = parser.parse_args(argv) - if ( - args.current_income_for_annual_measures is not None - and args.diagnostics is None - and args.references is None - ): + reason = args.current_income_for_annual_measures + if reason is not None and not reason.strip(): + parser.error( + "--current-income-for-annual-measures needs a reason: the resolver " + "takes the current-income route only with one." + ) + if reason is not None and args.diagnostics is None and args.references is None: parser.error( "--current-income-for-annual-measures needs --diagnostics or " "--references: this tree's target references say what a build of " @@ -275,7 +279,7 @@ def main(argv: list[str] | None = None) -> int: args.h5, year=args.year, scratch=args.out.parent / f"scratch-{args.out.stem}", - reason=args.current_income_for_annual_measures, + reason=reason, ) report = differential(cells, resolved_people(resolver)) if args.diagnostics is not None: @@ -286,6 +290,7 @@ def main(argv: list[str] | None = None) -> int: "year": args.year, "itl_rows": rows_source, "in_sample_basis": in_sample_basis, + "current_income_for_annual_measures": reason, **report, } args.out.parent.mkdir(parents=True, exist_ok=True) From 9d1e62c5b9f77054844ad865086a5c327c187eeb Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Mon, 9 Nov 2026 14:36:01 -0500 Subject: [PATCH 3/5] Stamp the ITL harness specs from the compile's representative fact The review of 39b8a930d found that the harness stamped each bound spec from the window's first fact (2024-25), while the Ledger compile stamps it from _value_representative_fact, the window's latest fact (2025-26). The structural test's claim that require_matching_fact_period stays invisible held for the compile but not for the harness. The harness now picks the fact with the compile's own _value_representative_fact, keys it with _fact_key, and asserts each spec's ledger_fact_period equals its reference's period. Three latent cases pin the keys the differential cannot see on these rows (require_matching_fact_period, a declared measurement period and a band dimension beside the single band-like filter): each leaves every cell green, so the structural test alone holds them. The metric_name note names its three readers. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_itl_differential.py | 57 ++++++++++++++----- 1 file changed, 44 insertions(+), 13 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py index 2d166483f2..9015fd89c6 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py @@ -38,8 +38,10 @@ from microcosm.build.country_spec import load_country_spec from microcosm.build.ledger_targets import ( CALENDAR_YEAR_WINDOW_WEIGHTS, + _fact_key, _ledger_metadata, _reference_metadata, + _value_representative_fact, ) from microcosm.build.target_materialization import ( WHOLE_PENCE_UPPER_CLOSED, @@ -1052,9 +1054,11 @@ def _contract(): } -#: The keys of a ``policyengine`` binding that change no count: ``notes`` -#: documents the row, and ``metric_name`` names a counterfactual binding's -#: column, which these plain bindings do not have. +#: The keys of a ``policyengine`` binding that change no count. ``notes`` +#: documents the row. ``metric_name`` names it for three readers: the UK +#: local metric map keys the row's target by it, reference authoring copies +#: it into a reference's measure, and a counterfactual binding names its +#: delta column with it. None of those reads changes whom these rows count. _INERT_KEYS = frozenset({"metric_name", "notes"}) @@ -1071,7 +1075,8 @@ def test_the_check_reads_what_the_contract_binds() -> None: changes any other key fails here. That covers the keys whose effect the differential below cannot see on these rows: ``band_filter_dimension`` beside a single band-like filter, ``measurement_period`` on a frame - without period metadata, and ``require_matching_fact_period``.""" + without period metadata, and ``require_matching_fact_period``, since + each spec's fact period, 2025, matches the year the build reads it at.""" taxpayer = {"variable": TAX, "operator": ">", "value": 0} counted = { @@ -1170,12 +1175,13 @@ def _window_facts(rows, reference): def _bound_registry(): """The compiled spec of each bound reference, stamped as the Ledger - compile stamps it: the compile's Ledger metadata of a fact the reference - selects (the fact's dimensions give the band's edges, as - ``ledger_filter_total_income_lower_bound``), under the compile's - metadata of the reference (its contract target and geography predicate - among it). The window's facts carry the same dimensions, so either one - stamps the spec.""" + compile stamps it: the compile's Ledger metadata of the fact it picks to + stand for the reference's window (``_value_representative_fact``: the + latest, so the spec's ``ledger_fact_period`` is the reference's period, + 2025), under the compile's metadata of the reference (its contract + target and geography predicate among it). The window's facts share their + dimensions, which give the band's edges as + ``ledger_filter_total_income_lower_bound``, but not their period.""" rows = load_vendored_resource("hmrc_itl_taxpayer_counts.json")["rows"] specs = [] @@ -1187,10 +1193,14 @@ def _bound_registry(): assert all(fact["dimensions"] == facts[0]["dimensions"] for fact in facts), ( reference.name ) + fact = _value_representative_fact( + tuple(facts), operation=reference.value_operation + ) metadata = { - **_ledger_metadata(facts[0], fact_key=facts[0]["source_record_id"]), + **_ledger_metadata(fact, fact_key=_fact_key(fact)), **_reference_metadata(reference), } + assert metadata["ledger_fact_period"] == str(reference.period), reference.name specs.append( TargetSpec( name=reference.name, @@ -1256,7 +1266,8 @@ def test_each_bound_cell_counts_whom_its_binding_counts() -> None: #: Edits a later change could make to a binding, by name: the binding's #: target, the edit, and the references it turns red (None: every reference -#: of the target). +#: of the target; an empty set: none, for an edit the differential cannot +#: see on these rows, which the structural test holds instead). _BINDING_EDITS = { "taxpayers-from-zero": ( _BAND_TARGET, @@ -1337,6 +1348,21 @@ def test_each_bound_cell_counts_whom_its_binding_counts() -> None: ), None, ), + "latent-a-fact-period-guard": ( + _BAND_TARGET, + lambda binding: binding.update(require_matching_fact_period=True), + set(), + ), + "latent-a-declared-measurement-period": ( + _STATE_PENSION_AGE_TARGET, + lambda binding: binding.update(measurement_period=2024), + set(), + ), + "latent-another-band-dimension": ( + _BAND_TARGET, + lambda binding: binding.update(band_filter_dimension="age"), + set(), + ), } @@ -1347,7 +1373,12 @@ def test_an_edited_binding_turns_its_cells_red(edit) -> None: upper bound or a period factor) or the binding's kind makes exactly the cells it moves read differently from the check, or the build skip them. That is every cell of the binding's family, except for an upper bound - above the top band's lower edge, which moves the top band alone.""" + above the top band's lower edge, which moves the top band alone. Three + latent edits move no cell on these rows, so every cell stays green and + the structural test holds them: a fact-period guard (each spec's fact + period, 2025, matches the year the build reads it at), a declared + measurement period (the frame carries no period metadata), and a band + dimension beside the bands' single band-like filter.""" target, change, red = _BINDING_EDITS[edit] contract = copy.deepcopy(_contract()) From 3913048b64106f0ec2e37ef317714cab8ac65b36 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 13:30:48 -0500 Subject: [PATCH 4/5] Correct the ITL tests' metric_name and respelling notes (review r3) The round-3 review of 9d1e62c5b approved it with three wording nits. Two land here. The metric_name note said reference authoring copies the name into these rows' measures; it falls back to metric_name only for an unnamed reference, and all 35 of these references carry fan-out names, so only the UK local metric map reads it. The structural test's docstring said any other changed key fails; a value respelled as Python compares it (65 as 65.0, 0 as false, true as 1) passes both tests and moves no count, since _compare casts numeric thresholds with float(). The third nit lives in the PR body. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_itl_differential.py | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py index 9015fd89c6..82757d196c 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py @@ -1055,10 +1055,12 @@ def _contract(): #: The keys of a ``policyengine`` binding that change no count. ``notes`` -#: documents the row. ``metric_name`` names it for three readers: the UK -#: local metric map keys the row's target by it, reference authoring copies -#: it into a reference's measure, and a counterfactual binding names its -#: delta column with it. None of those reads changes whom these rows count. +#: documents the row. ``metric_name`` names it, and the UK local metric map +#: keys the row's target by it. Reference authoring falls back to it for an +#: unnamed reference's measure, and a counterfactual binding names its delta +#: column with it, but neither reaches these rows: their references take +#: fan-out names, and their bindings are plain. None of those reads changes +#: whom these rows count. _INERT_KEYS = frozenset({"metric_name", "notes"}) @@ -1070,13 +1072,16 @@ def test_the_check_reads_what_the_contract_binds() -> None: ``total_income`` filter dimension and declare no band semantics, upper bound or period factor, so the build reads each band as ``[lower, upper)`` between the vendored lower edges. The age families add - ``IS_SP_AGE`` true or ``AGE`` at least 65, and band nothing. Every key - but ``notes`` and ``metric_name`` is held, so a binding that gains or - changes any other key fails here. That covers the keys whose effect the - differential below cannot see on these rows: ``band_filter_dimension`` - beside a single band-like filter, ``measurement_period`` on a frame - without period metadata, and ``require_matching_fact_period``, since - each spec's fact period, 2025, matches the year the build reads it at.""" + ``IS_SP_AGE`` true or ``AGE`` at least 65, and band nothing. The test + holds every key but ``notes`` and ``metric_name``, so a binding that + gains or changes any other key fails here, unless the change only + respells a value as Python compares it (65 as 65.0, 0 as false, true as + 1). The build compares those spellings the same way, so they move no + count. The test also holds the keys whose effect the differential below + cannot see on these rows: ``band_filter_dimension`` beside a single + band-like filter, ``measurement_period`` on a frame without period + metadata, and ``require_matching_fact_period``, since each spec's fact + period, 2025, matches the year the build reads it at.""" taxpayer = {"variable": TAX, "operator": ">", "value": 0} counted = { From 305452eb73312b2682127086d37b9cc64da831fe Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 11 Nov 2026 15:06:29 -0500 Subject: [PATCH 5/5] Pair each tolerance-note count with its band; lift three deadlines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The round-4 review of 3913048b6 found that the tolerance-note test read each count but not the band the note names for it, so a note that put 65,500 on £1m to £5m stayed green. The test now reads each "count at band" pair and compares it with the count and the label spelled from ITL_BANDS, in band order. It goes red when the note moves a count to the wrong band, raises the top band's edge, misstates a count or swaps two bands' labels, and stays green on the real note. The reviewer also saw test_the_verdict_is_the_tolerance exceed hypothesis's 200 ms default deadline at host load 166 to 221. It, its neighbour test_no_residual_lands_on_a_tolerance and test_the_window_weights_the_two_tax_years now take deadline=None, as every other property test in the file already does. Co-Authored-By: Claude Opus 5.5 --- .../uk/test_uk_itl_differential.py | 43 ++++++++++++++++--- 1 file changed, 36 insertions(+), 7 deletions(-) diff --git a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py index 82757d196c..24a49fef8a 100644 --- a/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py +++ b/packages/microcosm-build/tests/engine_free/uk/test_uk_itl_differential.py @@ -154,6 +154,7 @@ def _rows(*, ages=True, value=1_000.0): return rows +@settings(deadline=None) @given(then=_counts, now=_counts) def test_the_window_weights_the_two_tax_years(then, now) -> None: rows = [ @@ -604,6 +605,7 @@ def test_a_sum_in_sample_is_fixed_by_bound_parts(people, every_band) -> None: ) +@settings(deadline=None) @given(model=st.floats(0.0, 1e8), expected=_counts) def test_the_verdict_is_the_tolerance(model, expected) -> None: people = ITLPeople( @@ -689,6 +691,30 @@ def test_the_vendored_table_2_5_rows_give_every_band_at_calendar_2025() -> None: "state_pension_age": "State Pension age", "age_65_and_over": "aged 65 and over", } +#: An amount as the tolerance note spells it: ``£150,000`` or ``£1m``. +_POUNDS = r"£\d(?:[\d,]*\d)?m?" +#: A count and the band it holds, as the tolerance note cites them. +_BAND_COUNT_PHRASE = re.compile( + rf"(\d[\d,]*\d) at ({_POUNDS} (?:to {_POUNDS}|and over))" +) + + +def _pounds(amount: float) -> str: + """``amount`` as the tolerance note spells it.""" + + if amount >= 1_000_000 and amount % 1_000_000 == 0: + return f"£{amount / 1_000_000:.0f}m" + return f"£{amount:,.0f}" + + +def _band_words(band) -> str: + """A band as the tolerance note names it: ``£150,000 to £200,000``, or + ``£2m and over`` for the open top band.""" + + lower, upper = band + if upper is None: + return f"{_pounds(lower)} and over" + return f"{_pounds(lower)} to {_pounds(upper)}" def _tolerance_note() -> str: @@ -710,23 +736,25 @@ def _tolerance_note() -> str: def test_the_tolerance_note_cites_the_vendored_counts() -> None: """The note on ``NATIONAL_TOLERANCE`` says what the vendored rows give at the calendar-2025 window, and this test reads the note: how many bands - hold under 400,000 taxpayers and, in band order, each one's count; how - many of the top bands hold fewer than the smallest area cell; and that - cell's area, measure and count. A change to the rows fails here until - the note follows it. Every band takes the national tolerance all the - same: geography, not size, decides.""" + hold under 400,000 taxpayers and, in band order, each one's count and + the band that holds it; how many of the top bands hold fewer than the + smallest area cell; and that cell's area, measure and count. A change to + the rows fails here until the note follows it. Every band takes the + national tolerance all the same: geography, not size, decides.""" note = _tolerance_note() rows = load_vendored_resource("hmrc_itl_taxpayer_counts.json")["rows"] cells = expected_cells(rows, year=2025) bands = [cell for cell in cells if cell.measure == BAND_COUNT] assert [cell.band for cell in bands] == list(ITL_BANDS) - under = [cell.expected for cell in bands if cell.expected < 400_000] + under = [cell for cell in bands if cell.expected < 400_000] assert ( f"{_NUMBER_WORDS[len(under)]} of the {_NUMBER_WORDS[len(bands)]} bands " "hold under 400,000 taxpayers" ) in note - assert re.findall(r"([\d,]+) at £", note) == [f"{count:,.0f}" for count in under] + assert _BAND_COUNT_PHRASE.findall(note) == [ + (f"{cell.expected:,.0f}", _band_words(cell.band)) for cell in under + ] smallest = min( (cell for cell in cells if cell.tolerance == REGIONAL_TOLERANCE), key=lambda cell: cell.expected, @@ -1618,6 +1646,7 @@ def count(*key): assert count("2.2", "age_65_and_over", RESIDENTS) == 1.0 + 4.0 +@settings(deadline=None) @given(model=st.floats(0.0, 1e8), expected=_counts) def test_no_residual_lands_on_a_tolerance(model, expected) -> None: """The verdict never turns on ``<`` against ``<=``: every residual is a