diff --git a/changelog.d/update-policyengine-6.20.4.changed.md b/changelog.d/update-policyengine-6.20.4.changed.md new file mode 100644 index 000000000..38b97469a --- /dev/null +++ b/changelog.d/update-policyengine-6.20.4.changed.md @@ -0,0 +1 @@ +Updated policyengine.py from 6.20.0 to 6.20.4 in the simulation runtime. 6.20.4 ranks households with equal incomes in the order of their rows when it calculates the Gini coefficient and the top 10% and top 1% income shares, so the same rows give the same values on every host. numpy's default sort, used before, puts equal values in an order that depends on the CPU, so the same UK report could give different top shares on different hosts: in one check of 20 UK values they moved by up to 9.8e-5 relative. The update also brings in .py 6.20.1 to 6.20.3: policyengine-uk 2.179.2 (from 2.174.1), policyengine-core 3.34.10 (from 3.33.3) and newly certified UK national and local-area datasets, so UK results change. A UK national report's data version becomes `uk-frs-calibration-attempt-20261122T100732Z-b891aa69`, and the UK datasets' revisions are Hugging Face commit hashes instead of tag names. policyengine-us and the US data are unchanged, but policyengine-core's reform and caching fixes apply to US simulations too. API v1 sends its own .py version with each request, so its reports move to 6.20.4 only when API v1 raises its own pin. diff --git a/projects/policyengine-simulation-executor/pyproject.toml b/projects/policyengine-simulation-executor/pyproject.toml index 0e0ec2102..c67e88502 100644 --- a/projects/policyengine-simulation-executor/pyproject.toml +++ b/projects/policyengine-simulation-executor/pyproject.toml @@ -24,7 +24,7 @@ dependencies = [ "policyengine-stage12-persistence", # PolicyEngine.py's models extra is the only selector for core, country # models, and the SPM calculator. Do not duplicate those versions here. - "policyengine[models]==6.20.0", + "policyengine[models]==6.20.4", "tables>=3.10.2", # 1.6.4 is the first release whose containers reload Secret values when # they restore from a memory snapshot. Every app deployed or run from this @@ -58,7 +58,7 @@ packages = ["src/policyengine_simulation_executor"] # certified datasets and writes their receipt. [dependency-groups] modal-simulation-image = [ - "policyengine[models]==6.20.0", + "policyengine[models]==6.20.4", "fastapi>=0.115.0", "tables>=3.10.2", "policyengine-observability[fastapi,google,otlp-grpc]>=3.0.7,<4", diff --git a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py index 646b288a9..63883a549 100644 --- a/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py +++ b/projects/policyengine-simulation-executor/src/policyengine_simulation_executor/stage12_runtime/aggregation.py @@ -52,8 +52,9 @@ def reported_data_version( on the regional dataset, and a UK-wide or nation report on the local-area dataset (``is_local_area_report``), which stands for API v1's local-area breakdown run. Until policyengine.py 6.20.0 the default dataset's revision - was the release's data version; since then the US one is a Hugging Face - commit, while the release keeps its version name. + was the release's data version. Since then the US one is a Hugging Face + commit, and since 6.20.1 the UK national and local-area ones are too, while + each release keeps its version name. """ from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle get_country_release_bundle, diff --git a/projects/policyengine-simulation-executor/tests/test_inequality_row_order.py b/projects/policyengine-simulation-executor/tests/test_inequality_row_order.py new file mode 100644 index 000000000..70956a0d0 --- /dev/null +++ b/projects/policyengine-simulation-executor/tests/test_inequality_row_order.py @@ -0,0 +1,215 @@ +"""The UK inequality output ranks households with equal incomes in row order. + +A UK report's Gini coefficient and top 10% and top 1% income shares come from +.py's ``calculate_uk_inequality``, which the UK ``economic_impact_analysis`` +calls for the baseline and the reform, and reach the result through +``build_inequality``. A household counts towards a top share only once its +cumulative weight share passes the cutoff, so when households with the same +income sit at a cutoff, the order they are ranked in decides which of them +count. The Gini's floating-point sums depend on that order too. + +Stage 12 stores each entity's rows sorted by ``_id``, and API v1's +calculation keeps the dataset's order, which for the UK national dataset is the +same. These tests rebuild a UK dataset from stored frames as Stage 12's +aggregation does (``_dataset_from_frames`` and ``PrecomputedSimulation``) and +check that households with equal incomes are ranked in row order, so the same +rows give the same values on every host. Until .py sorted incomes with a stable +sort (PolicyEngine/policyengine.py#777), it used numpy's default sort, which +puts equal values in a different order on different CPUs. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import TYPE_CHECKING, NamedTuple + +import numpy as np +import pandas as pd +import pytest +from policyengine.outputs.inequality import calculate_uk_inequality +from policyengine_simulation_executor.simulation_output_inequality import ( + build_inequality, +) +from policyengine_simulation_executor.simulation_runtime import _country_module +from policyengine_simulation_executor.stage12_runtime.aggregation import ( + PrecomputedSimulation, + _dataset_from_frames, +) + +if TYPE_CHECKING: + from collections.abc import Sequence + +INCOME_VARIABLE = "equiv_hbai_household_net_income" + +# One poorer household and twenty copies of a richer one: ten copies weigh 1 +# and ten weigh 3. The total weight is 110, so the top 10% cutoff (a +# cumulative weight above 99) and the top 1% cutoff (above 108.9) both fall +# among the copies. Twenty copies, because numpy's default sort has left +# smaller groups of equal values in row order on some CPUs. +POORER_INCOME = 10_000.0 +POORER_WEIGHT = 70.0 +RICHER_INCOME = 50_000.0 +LIGHT_COPY_WEIGHT = 1.0 +HEAVY_COPY_WEIGHT = 3.0 +COPIES_PER_WEIGHT = 10 +TOTAL_INCOME = POORER_INCOME * POORER_WEIGHT + RICHER_INCOME * COPIES_PER_WEIGHT * ( + LIGHT_COPY_WEIGHT + HEAVY_COPY_WEIGHT +) + +# Seeded households at a few income levels, so many households share each +# income and the cutoffs fall inside groups of equal incomes. +SEEDED_HOUSEHOLD_COUNT = 200 +SEEDED_INCOME_LEVELS = np.arange(1, 9) * 10_000.0 + + +class InequalityValues(NamedTuple): + """The three values the inequality output reports for one simulation.""" + + gini: float + top_10_pct_share: float + top_1_pct_share: float + + +@pytest.fixture(scope="module") +def uk_model_version(): + """Return the installed UK model version, loaded once for this module.""" + return _country_module("uk").model + + +def _uk_frames( + incomes: Sequence[float], + weights: Sequence[float], + household_ids: Sequence[int], +) -> dict[str, pd.DataFrame]: + """Return stored UK frames with one person and benefit unit per household.""" + household_id_column = list(household_ids) + return { + "person": pd.DataFrame( + { + "person_id": household_id_column, + "person_household_id": household_id_column, + "person_benunit_id": household_id_column, + "person_weight": list(weights), + } + ), + "benunit": pd.DataFrame( + {"benunit_id": household_id_column, "benunit_weight": list(weights)} + ), + "household": pd.DataFrame( + { + "household_id": household_id_column, + "household_weight": list(weights), + INCOME_VARIABLE: list(incomes), + } + ), + } + + +def _service_inequality( + frames: dict[str, pd.DataFrame], uk_model_version: object +) -> InequalityValues: + """Return the inequality output the service reports for these stored frames. + + Rebuilds the dataset and the stand-in simulation as Stage 12's aggregation + does, runs the calculation the UK ``economic_impact_analysis`` runs for + each simulation, and reads the baseline values ``build_inequality`` + reports. + """ + dataset = _dataset_from_frames(frames, country="uk", year=2026) + simulation = PrecomputedSimulation( + dataset=dataset, tax_benefit_model_version=uk_model_version + ) + simulation.output_dataset = dataset + inequality = calculate_uk_inequality(simulation) + output = build_inequality( + SimpleNamespace(baseline_inequality=inequality, reform_inequality=inequality) + ) + return InequalityValues( + gini=output.gini.baseline, + top_10_pct_share=output.top_10_pct_share.baseline, + top_1_pct_share=output.top_1_pct_share.baseline, + ) + + +@pytest.mark.parametrize( + ( + "first_copy_weight", + "second_copy_weight", + "top_10_copy_weight", + "top_1_copy_weight", + ), + [ + # Light copies first: the cumulative weight passes 99 at the seventh + # heavy copy (101), so four heavy copies (weight 12) are in the top + # 10%, and the last heavy copy (weight 3) is the top 1%. + pytest.param(LIGHT_COPY_WEIGHT, HEAVY_COPY_WEIGHT, 12.0, 3.0, id="light-first"), + # Heavy copies first: the last heavy copy (100) and the ten light + # copies (weight 13) are in the top 10%, and the last two light copies + # (109 and 110, weight 2) are the top 1%. + pytest.param(HEAVY_COPY_WEIGHT, LIGHT_COPY_WEIGHT, 13.0, 2.0, id="heavy-first"), + ], +) +def test_top_income_shares_count_tied_households_in_row_order( + uk_model_version: object, + first_copy_weight: float, + second_copy_weight: float, + top_10_copy_weight: float, + top_1_copy_weight: float, +) -> None: + copy_count = 2 * COPIES_PER_WEIGHT + frames = _uk_frames( + incomes=[POORER_INCOME] + [RICHER_INCOME] * copy_count, + weights=[POORER_WEIGHT] + + [first_copy_weight] * COPIES_PER_WEIGHT + + [second_copy_weight] * COPIES_PER_WEIGHT, + household_ids=range(1, copy_count + 2), + ) + + reported = _service_inequality(frames, uk_model_version) + + assert reported.top_10_pct_share == pytest.approx( + top_10_copy_weight * RICHER_INCOME / TOTAL_INCOME, rel=1e-12 + ) + assert reported.top_1_pct_share == pytest.approx( + top_1_copy_weight * RICHER_INCOME / TOTAL_INCOME, rel=1e-12 + ) + + +@pytest.mark.parametrize("seed", range(10)) +def test_rows_in_id_order_give_the_values_of_rows_ranked_in_row_order( + uk_model_version: object, seed: int +) -> None: + random_generator = np.random.default_rng(seed) + frames = _uk_frames( + incomes=random_generator.choice( + SEEDED_INCOME_LEVELS, size=SEEDED_HOUSEHOLD_COUNT + ).tolist(), + weights=random_generator.uniform( + 0.5, 50.0, size=SEEDED_HOUSEHOLD_COUNT + ).tolist(), + household_ids=range(1, SEEDED_HOUSEHOLD_COUNT + 1), + ) + # The same households listed by income, with equal incomes kept in + # household_id order: what ranking the rows in row order gives. + ranked_households = frames["household"].sort_values(INCOME_VARIABLE, kind="stable") + ranked_frames = _uk_frames( + incomes=ranked_households[INCOME_VARIABLE].tolist(), + weights=ranked_households["household_weight"].tolist(), + household_ids=ranked_households["household_id"].tolist(), + ) + + reported = _service_inequality(frames, uk_model_version) + ranked_in_row_order = _service_inequality(ranked_frames, uk_model_version) + + # The Gini is summed over the ranked households only, so it is exactly the + # same. Each share divides by the total income summed in the order the + # rows are given, which differs between the two lists in the last bits; a + # different ranking of tied households at a cutoff moves a share by about + # 1e-4 relative or more. + assert reported.gini == ranked_in_row_order.gini + assert reported.top_10_pct_share == pytest.approx( + ranked_in_row_order.top_10_pct_share, rel=1e-12 + ) + assert reported.top_1_pct_share == pytest.approx( + ranked_in_row_order.top_1_pct_share, rel=1e-12 + ) diff --git a/projects/policyengine-simulation-executor/tests/test_uk_local_authority_metadata.py b/projects/policyengine-simulation-executor/tests/test_uk_local_authority_metadata.py index 853a3f6da..3e245f93b 100644 --- a/projects/policyengine-simulation-executor/tests/test_uk_local_authority_metadata.py +++ b/projects/policyengine-simulation-executor/tests/test_uk_local_authority_metadata.py @@ -638,7 +638,9 @@ def test_the_installed_bundle_routes_area_regions_to_the_dense_dataset() -> None assert uk_area_regions_routed() is True assert uk_area_regions_routed() is area_regions_routed_to_local_release() assert isinstance(revision, str) - assert revision.startswith("microcosm-uk-2024-25-dense-") + # Since .py 6.20.1 the UK release pins each file in Microcosm's build + # folders to the Hugging Face commit that published it. + assert re.fullmatch(r"[0-9a-f]{40}", revision) assert revision == get_release_manifest("uk").datasets[name].revision diff --git a/projects/policyengine-simulation-executor/uv.lock b/projects/policyengine-simulation-executor/uv.lock index 887d914e8..c8be4780b 100644 --- a/projects/policyengine-simulation-executor/uv.lock +++ b/projects/policyengine-simulation-executor/uv.lock @@ -1769,7 +1769,7 @@ wheels = [ [[package]] name = "policyengine" -version = "6.20.0" +version = "6.20.4" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "h5py" }, @@ -1781,9 +1781,9 @@ dependencies = [ { name = "pydantic" }, { name = "requests" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/14/e8/4373c716f428ed885392ff1776dc1be1f9e9a3a6f7608afcc1f39d683546/policyengine-6.20.0.tar.gz", hash = "sha256:65dad563d92c17485c5943b2bb8114d8f16cd49c977acbce6412cd8b8bcfadfd", size = 1863269, upload-time = "2026-11-16T16:21:45.756Z" } +sdist = { url = "https://files.pythonhosted.org/packages/32/77/e2970d5839f497d6fefd06aeef99774859ca2f30bb5ee1691dfb458a7e2c/policyengine-6.20.4.tar.gz", hash = "sha256:4f253587872230fd55e8c045622ccd913ada304c1ead9b60dbc33cf4315685cf", size = 1868173, upload-time = "2026-12-01T01:43:30.923Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/64/b6/9ebed9a78c755c25893a20c924bc6952100bc3376608511fbcdb065145c3/policyengine-6.20.0-py3-none-any.whl", hash = "sha256:cc2da1b7448ae229294090318140bfe39440e8899415b8e465459c7e89bb7135", size = 774390, upload-time = "2026-11-16T16:21:43.414Z" }, + { url = "https://files.pythonhosted.org/packages/fc/92/02d046bf927873476ebf3e54e3efd23acd7270b221bca00d972f69086312/policyengine-6.20.4-py3-none-any.whl", hash = "sha256:0b93ec55feab0edfde61dcf27ecb81c68e1f7a271bd328a0ddf0e92f54933301", size = 775042, upload-time = "2026-12-01T01:43:28.788Z" }, ] [package.optional-dependencies] @@ -1796,7 +1796,7 @@ models = [ [[package]] name = "policyengine-core" -version = "3.33.3" +version = "3.34.10" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "dpath" }, @@ -1816,9 +1816,9 @@ dependencies = [ { name = "standard-imghdr" }, { name = "wheel" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/17/af/e8449e8a488468e5ce28b6b9066a2372e05bc7971ad9a441eb4e6efbb740/policyengine_core-3.33.3.tar.gz", hash = "sha256:7da78ae9cc7b1d6833dc30651a0a4775edd2d5e205a73bbafcc0b15c988c880e", size = 693203, upload-time = "2026-10-12T20:53:17.299Z" } +sdist = { url = "https://files.pythonhosted.org/packages/39/15/8526adf38be5c96324f458886a2622704daec39b7e487899a7e922e299eb/policyengine_core-3.34.10.tar.gz", hash = "sha256:d232ddc415c3fa65bad31c0be25ff0f2c5826a5ae4cae10a47e6cd0a2102931d", size = 779988, upload-time = "2026-11-08T01:59:34.917Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/c8/d6/253cc99d853e36996f264138f4f8a2c662047da3eda8e37ddf39959397fc/policyengine_core-3.33.3-py3-none-any.whl", hash = "sha256:5847d9938412095fe9848c2ce535838a7dc8fac9238d8fd9e6c9d0a0648e0888", size = 301905, upload-time = "2026-10-12T20:53:15.706Z" }, + { url = "https://files.pythonhosted.org/packages/ef/2e/b92cc4271bd5d02cc7830201316514cef91128861074cc5e06d6ac3c3dd2/policyengine_core-3.34.10-py3-none-any.whl", hash = "sha256:5045ed5e4d157eefab22bd285c8ba09e107f5c3a5a61e380fc2a85163259982a", size = 311145, upload-time = "2026-11-08T01:59:32.984Z" }, ] [[package]] @@ -1982,7 +1982,7 @@ requires-dist = [ { name = "openapi-python-client", marker = "extra == 'build'", specifier = ">=0.21.6" }, { name = "opentelemetry-instrumentation-fastapi", specifier = ">=0.65b0,<0.66" }, { name = "opentelemetry-instrumentation-sqlalchemy", specifier = ">=0.65b0,<0.66" }, - { name = "policyengine", extras = ["models"], specifier = "==6.20.0" }, + { name = "policyengine", extras = ["models"], specifier = "==6.20.4" }, { name = "policyengine-fastapi", editable = "../../libs/policyengine-fastapi" }, { name = "policyengine-observability", extras = ["fastapi", "google", "otlp-grpc"], specifier = ">=3.0.7,<4" }, { name = "policyengine-simulation-contract", extras = ["modal"], editable = "../../libs/policyengine-simulation-contract" }, @@ -2012,7 +2012,7 @@ modal-simulation-image = [ { name = "fastapi", specifier = ">=0.115.0" }, { name = "google-cloud-storage", specifier = ">=2" }, { name = "huggingface-hub", specifier = ">=1,<2" }, - { name = "policyengine", extras = ["models"], specifier = "==6.20.0" }, + { name = "policyengine", extras = ["models"], specifier = "==6.20.4" }, { name = "policyengine-observability", extras = ["fastapi", "google", "otlp-grpc"], specifier = ">=3.0.7,<4" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.2,<4" }, { name = "pyarrow", specifier = ">=20,<24" }, @@ -2131,7 +2131,7 @@ provides-extras = ["test", "build"] [[package]] name = "policyengine-uk" -version = "2.174.1" +version = "2.179.2" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "microdf-python" }, @@ -2139,9 +2139,9 @@ dependencies = [ { name = "pydantic" }, { name = "tables" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/be/3a/fbf290895263fd4f8394f76fe1694e90e2c7b8b51a5a18f45f9bda16a4e2/policyengine_uk-2.174.1.tar.gz", hash = "sha256:c8302686c4d7c6fa92fb87febe1ad8130b7a0dd7987d5b14104384bd171f2245", size = 4434552, upload-time = "2026-11-04T07:36:05.319Z" } +sdist = { url = "https://files.pythonhosted.org/packages/69/45/9bfc794973d685c5da6c09d3b84b2445ffbfc16fc28bfd96772f8457aee0/policyengine_uk-2.179.2.tar.gz", hash = "sha256:56a99e8e3a48d2ebf5ee5f4383e5b5671b3c3b3b84f668cabc7b560f83bfd44e", size = 5294795, upload-time = "2026-11-18T15:41:54.502Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/35/ed/5ea303be2fd38da4e5f9b9a3fd012a5f9454fd5ef66a1df26c3267fb57a8/policyengine_uk-2.174.1-py3-none-any.whl", hash = "sha256:1d4d17c74bd5b853a148e9c44b080490dd0393725fe18b2b82ec55eecdb9bb58", size = 6313656, upload-time = "2026-11-04T07:36:02.964Z" }, + { url = "https://files.pythonhosted.org/packages/c6/55/84a5f328cff944fae92dc64d49ca139fe51b0f06b0217063ff87e3ea9779/policyengine_uk-2.179.2-py3-none-any.whl", hash = "sha256:a1da93b521408fd4aee7e85f6550d33fb392f0291bcab0eaba631533e3cc0836", size = 7416601, upload-time = "2026-11-18T15:41:51.547Z" }, ] [[package]]