From dab4cda7c10d87d412cb9589bd10e81b4eb7ea30 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 18:44:14 -0400 Subject: [PATCH 01/29] Reserve Housing Benefit Working Tax Credit before childcare Apply the Schedule 5 WTC disregard separately from earnings disregards and reserve it before the childcare deduction. Add statutory examples, properties, differential checks and historical cutoff coverage. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2730.fixed.md | 1 + .../housing_benefit_wtc_disregard.yaml | 284 +++++++++++++ .../test_housing_benefit_wtc_disregard.py | 376 ++++++++++++++++++ .../housing_benefit_applicable_income.py | 9 +- ...ousing_benefit_childcare_earnings_limit.py | 17 +- .../housing_benefit_wtc_disregard.py | 73 ++++ 6 files changed, 752 insertions(+), 8 deletions(-) create mode 100644 changelog.d/2730.fixed.md create mode 100644 policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml create mode 100644 policyengine_uk/tests/test_housing_benefit_wtc_disregard.py create mode 100644 policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py diff --git a/changelog.d/2730.fixed.md b/changelog.d/2730.fixed.md new file mode 100644 index 0000000000..489f561722 --- /dev/null +++ b/changelog.d/2730.fixed.md @@ -0,0 +1 @@ +Housing Benefit reserves the Working Tax Credit income disregard before deducting childcare costs in historical tax-credit years. diff --git a/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml new file mode 100644 index 0000000000..500652ef9d --- /dev/null +++ b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml @@ -0,0 +1,284 @@ +# SI 2006/213 reg 27(1) and (2), Sch 4 para 17(1), (3), and Sch 5 +# para 56: apply the standard earnings disregard, select the additional +# earnings disregard or WTC disregard, then deduct childcare from the +# remaining earnings and tax credits. These cases supply assessed earnings, +# the standard disregard, qualifying childcare and the work condition. +# https://www.legislation.gov.uk/uksi/2006/213/regulation/27 +# https://www.legislation.gov.uk/uksi/2006/213/schedule/4/paragraph/17 +# https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56 + +- name: Reserve all of the issue 2730 WTC award before childcare + period: 2024 + absolute_error_margin: 0.02 + input: + age: 40 + employment_income: 5_200 + self_employment_income: 0 + property_income_after_finance_costs: 0 + private_pension_income: 0 + carers_allowance: 0 + carer_support_payment: 0 + esa_contrib: 0 + jsa_contrib: 0 + state_pension: 0 + maternity_allowance: 0 + statutory_sick_pay: 0 + statutory_maternity_pay: 0 + statutory_paternity_pay: 0 + iidb: 0 + sda: 0 + incapacity_benefit: 0 + spousal_maintenance_income: 0 + pension_contributions: 0 + income_tax_before_winter_fuel_payment_charge: 0 + national_insurance: 0 + tax_credits: 100 + income_support: 0 + claimant_or_partner_jsa_income: 0 + claimant_or_partner_esa_income: 0 + housing_benefit_tariff_income: 0 + housing_benefit_maintenance_disregard: 0 + housing_benefit_widowed_parents_allowance_income: 0 + housing_benefit_pension_age_regulations_apply: false + in_receipt_of_guarantee_credit: false + in_receipt_of_savings_credit_only: false + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + output: + # Sch 4 para 17: 5,200 < 1,300 + 4,160 + 889.20 = 6,349.20. + # Sch 5 para 56: disregard min(100, 17.10 * 52) = 100 WTC. + # Reg 27: limit = 5,200 - 1,300 + 100 - 100 = 3,900; + # childcare = min(4,160, 3,900) = 3,900. + housing_benefit_wtc_disregard: 100 + housing_benefit_childcare_earnings_limit: 3_900 + housing_benefit_applicable_income_childcare_element: 3_900 + housing_benefit_applicable_income_disregard: 1_300 + # Counted earnings and credits = 5,200 + 100 - 1,300 - 100 - 3,900. + housing_benefit_applicable_income: 0 + +- name: Reserve the weekly limit from a larger WTC award + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 6_000 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 2_000 + child_tax_credit: 500 + output: + # Sch 4 para 17 fails: 5,200 < 1,300 + 6,000 + 889.20. + # Sch 5 para 56 reserves 889.20, leaving WTC 1,110.80. + # Reg 27: childcare = min(6,000, 3,900 + 1,110.80 + 500). + housing_benefit_wtc_disregard: 889.20 + housing_benefit_childcare_earnings_limit: 5_510.80 + housing_benefit_applicable_income_childcare_element: 5_510.80 + +- name: Claimants without childcare still receive the WTC disregard + period: 2024 + absolute_error_margin: 0.02 + input: + age: 40 + employment_income: 500 + self_employment_income: 0 + property_income_after_finance_costs: 0 + private_pension_income: 0 + carers_allowance: 0 + carer_support_payment: 0 + esa_contrib: 0 + jsa_contrib: 0 + state_pension: 0 + maternity_allowance: 0 + statutory_sick_pay: 0 + statutory_maternity_pay: 0 + statutory_paternity_pay: 0 + iidb: 0 + sda: 0 + incapacity_benefit: 0 + spousal_maintenance_income: 0 + pension_contributions: 0 + income_tax_before_winter_fuel_payment_charge: 0 + national_insurance: 0 + tax_credits: 2_000 + income_support: 0 + claimant_or_partner_jsa_income: 0 + claimant_or_partner_esa_income: 0 + housing_benefit_tariff_income: 0 + housing_benefit_maintenance_disregard: 0 + housing_benefit_widowed_parents_allowance_income: 0 + housing_benefit_pension_age_regulations_apply: false + in_receipt_of_guarantee_credit: false + in_receipt_of_savings_credit_only: false + housing_benefit_net_earnings: 500 + housing_benefit_special_earnings_disregard: 260 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 0 + num_relevant_children_for_housing_benefit_childcare: 0 + working_tax_credit: 2_000 + child_tax_credit: 0 + output: + # Sch 4 para 17 fails: 500 < 260 + 0 + 889.20. + # Sch 5 para 56 reserves min(2,000, 889.20), with no childcare. + housing_benefit_wtc_disregard: 889.20 + housing_benefit_applicable_income_childcare_element: 0 + # Reg 27 and Sch 5 para 56: 500 + 2,000 - 260 - 889.20 = 1,350.80. + housing_benefit_applicable_income: 1_350.80 + +- name: Earnings one penny below the additional disregard threshold reserve WTC + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 6_349.19 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + output: + # Sch 4 para 17: 6,349.19 < 1,300 + 4,160 + 889.20. + # Sch 5 para 56 reserves 100; reg 27 still deducts the full 4,160. + housing_benefit_wtc_disregard: 100 + housing_benefit_applicable_income_childcare_element: 4_160 + housing_benefit_applicable_income_disregard: 1_300 + +- name: Earnings at the additional disregard threshold use earnings instead of WTC + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 6_349.20 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + output: + # Sch 4 para 17(3): equality qualifies, so 1,300 + 889.20 is + # disregarded from earnings. Sch 5 para 56 then disregards no WTC. + housing_benefit_wtc_disregard: 0 + housing_benefit_applicable_income_childcare_element: 4_160 + housing_benefit_applicable_income_disregard: 2_189.20 + +- name: WTC remains available to childcare when the work condition fails + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: false + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + output: + # Sch 5 para 56 does not apply without a Sch 4 para 17(2) work + # condition. Reg 27: min(4,160, 5,200 - 1,300 + 100) = 4,000. + housing_benefit_wtc_disregard: 0 + housing_benefit_childcare_earnings_limit: 4_000 + housing_benefit_applicable_income_childcare_element: 4_000 + +- name: CTC funds childcare after WTC has been reserved + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 500 + output: + # Sch 5 para 56 reserves only WTC. Reg 27 allows the remaining CTC: + # limit = 3,900 + (100 - 100) + 500 = 4,400; childcare = 4,160. + housing_benefit_wtc_disregard: 100 + housing_benefit_childcare_earnings_limit: 4_400 + housing_benefit_applicable_income_childcare_element: 4_160 + +- name: The coronavirus increase also raises the WTC disregard in 2020 + period: 2020 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 500 + housing_benefit_special_earnings_disregard: 260 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 0 + num_relevant_children_for_housing_benefit_childcare: 0 + working_tax_credit: 2_000 + child_tax_credit: 0 + output: + # SI 2020/371 reg 5 substitutes 37.10 for 17.10 in Sch 5 para 56: + # disregard = min(2,000, 37.10 * 52) = 1,929.20. + housing_benefit_wtc_disregard: 1_929.20 + +- name: The WTC disregard returns to its ordinary amount in 2021 + period: 2021 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 500 + housing_benefit_special_earnings_disregard: 260 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 0 + num_relevant_children_for_housing_benefit_childcare: 0 + working_tax_credit: 2_000 + child_tax_credit: 0 + output: + # SI 2020/371 reg 5 ends the substituted amount on 4 April 2021: + # Sch 5 para 56 again reserves min(2,000, 17.10 * 52) = 889.20. + housing_benefit_wtc_disregard: 889.20 + +- name: Tax credits ending prevents a WTC disregard from 2025 + period: 2025 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + output: + # HMRC: https://www.gov.uk/tax-credits-have-ended (5 April 2025). + # A synthetic award override cannot activate Sch 5 para 56 after + # tax_credits.active ends; the existing overridden-credit limit stays. + housing_benefit_wtc_disregard: 0 + housing_benefit_childcare_earnings_limit: 4_000 + housing_benefit_applicable_income_childcare_element: 4_000 diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py new file mode 100644 index 0000000000..8af8385d5f --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -0,0 +1,376 @@ +"""Housing Benefit WTC reservation against an independent statutory oracle. + +SI 2006/213 reg 27(1)-(2), Sch 4 para 17(1), (3), and Sch 5 para 56 +select the earnings or WTC disregard before childcare. Qualifying earnings, +the standard disregard, childcare and work conditions are assessed inputs. +The pension-age and Northern Ireland provisions apply the same ordering. + +For every generated family, the WTC disregard lies between zero and both +WTC and the additional disregard amount. The model never applies both the +additional earnings and WTC disregards. Childcare uses only the remaining +earnings and credits, and assessed income equals, and never falls below, +the independent scalar legal calculation. Where paragraph 56 does not +apply, the model agrees with the previous path, reproduced by a reform +that sets the new disregard to zero. + +The annual model uses 52 weeks, with the SI 2020/371 reg 5 temporary amount +in 2020 and no ongoing tax-credit awards from model year 2025. Populations +use core situations with independently supplied income components; they +never load a survey dataset or infer tax-credit awards from those incomes. +""" + +import numpy as np +import pytest +from hypothesis import HealthCheck, example, given, settings +from hypothesis import strategies as st +from policyengine_core.reforms import Reform +from policyengine_core.simulations import Simulation + +from policyengine_uk.model_api import BenUnit, Variable, YEAR +from policyengine_uk.system import system + + +TOLERANCE = 0.02 +YEARS = (2018, 2020, 2021, 2024, 2025, 2026) +REGIONS = ("LONDON", "SCOTLAND", "WALES", "NORTHERN_IRELAND") +PROPERTY_SETTINGS = settings( + max_examples=5, + derandomize=True, + deadline=None, + suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], +) + + +def case(**overrides): + result = dict( + net=5_200, + standard=1_300, + childcare=4_160, + children=1, + wtc=100, + ctc=0, + other=0, + worker=True, + pension_age=False, + region="LONDON", + ) + result.update(overrides) + return result + + +@st.composite +def families(draw): + return case( + net=draw(st.integers(0, 4_000_000)) / 100, + standard=draw(st.sampled_from([260, 520, 1_040, 1_300])), + childcare=draw(st.integers(0, 2_500_000)) / 100, + children=draw(st.integers(0, 2)), + wtc=draw(st.integers(0, 1_000_000)) / 100, + ctc=draw(st.integers(0, 1_000_000)) / 100, + other=draw(st.integers(0, 2_000_000)) / 100, + worker=draw(st.booleans()), + pension_age=draw(st.booleans()), + region=draw(st.sampled_from(REGIONS)), + ) + + +POPULATIONS = st.lists(families(), min_size=1, max_size=12) +EDGE_CASES = [ + case(), + case(net=0), + case(net=500, standard=260, childcare=0, children=0, wtc=2_000), + case(wtc=2_000, ctc=500, childcare=6_000), + case(wtc=0, ctc=2_000), + case(worker=False), + case(net=6_349.19, other=1_000), + case(net=6_349.20, other=1_000), + case(net=6_349.21, other=1_000), + case(pension_age=True), + case(children=2, childcare=25_000, wtc=10_000, ctc=10_000), + *(case(region=region) for region in REGIONS), +] + + +def legal_components(unit, year): + """Apply the regulations to scalar assessed inputs in annual pounds.""" + net = unit["net"] + standard = min(net, unit["standard"]) + cap = 15_600 if unit["children"] > 1 else 9_100 if unit["children"] else 0 + charge = min(unit["childcare"], cap) + additional_amount = 1_929.20 if year == 2020 else 889.20 + # Sch 4 para 17(3): earnings must cover the standard, qualifying + # childcare and additional amount. Compare money in statutory pence. + covers_additional = round(net * 100) >= round( + (standard + charge + additional_amount) * 100 + ) + additional = additional_amount if unit["worker"] and covers_additional else 0 + # Sch 5 para 56 applies only when para 17(1) does not apply. + reserve = ( + min(unit["wtc"], additional_amount) + if year < 2025 and unit["worker"] and not covers_additional + else 0 + ) + # Reg 27(1)-(2): childcare follows the Schedule 4/5 disregards. When + # additional earnings qualify, the full charge already fits earnings. + limit = net - standard + unit["wtc"] - reserve + unit["ctc"] + childcare = min(charge, limit) + income = max( + 0, + net + + unit["wtc"] + + unit["ctc"] + + unit["other"] + - standard + - additional + - reserve + - childcare, + ) + return dict( + childcare=childcare, + reserve=reserve, + earnings_disregard=standard + additional, + limit=limit, + income=income, + ) + + +class previous_wtc_disregard(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + + def formula(benunit, period, parameters): + return benunit.empty_array() + + +previous_wtc_disregard.__name__ = "housing_benefit_wtc_disregard" + + +class without_wtc_reservation(Reform): + def apply(self): + self.update_variable(previous_wtc_disregard) + + +def simulation(units, year, previous=False): + people, benunits, households = {}, {}, {} + for index, unit in enumerate(units): + adult = f"adult_{index}" + # Pin every ordinary-income component independently of upstream + # award/tax calculations, while the full HB income formula runs. + zero_income = { + variable: {year: 0} + for variable in ( + "self_employment_income", + "property_income_after_finance_costs", + "carers_allowance", + "carer_support_payment", + "esa_contrib", + "jsa_contrib", + "state_pension", + "maternity_allowance", + "statutory_sick_pay", + "statutory_maternity_pay", + "statutory_paternity_pay", + "iidb", + "sda", + "incapacity_benefit", + "spousal_maintenance_income", + "widowed_parents_allowance", + "pension_contributions", + "income_tax_before_winter_fuel_payment_charge", + "national_insurance", + ) + } + people[adult] = { + **zero_income, + "age": {year: 70 if unit["pension_age"] else 40}, + "is_claimant_or_partner": {year: True}, + "employment_income": {year: unit["net"]}, + "private_pension_income": {year: unit["other"]}, + "childcare_expenses": {year: unit["childcare"]}, + } + members = [adult] + for child_index in range(unit["children"]): + child = f"child_{index}_{child_index}" + members.append(child) + people[child] = { + "age": {year: 8}, + "is_claimant_or_partner": {year: False}, + "is_child_or_young_person_for_legacy_benefits": {year: True}, + } + benunits[f"family_{index}"] = { + "members": members, + "housing_benefit_net_earnings": {year: unit["net"]}, + "housing_benefit_special_earnings_disregard": { + year: min(unit["net"], unit["standard"]) + }, + "housing_benefit_permitted_work_disregard": {year: 0}, + "housing_benefit_specified_or_temporary_accommodation_disregard": {year: 0}, + "housing_benefit_on_passporting_benefit": {year: False}, + "housing_benefit_pension_age_regulations_apply": { + year: unit["pension_age"] + }, + "in_receipt_of_guarantee_credit": {year: False}, + "in_receipt_of_savings_credit_only": {year: False}, + "meets_housing_benefit_additional_earnings_disregard_conditions": { + year: unit["worker"] + }, + "working_tax_credit": {year: unit["wtc"]}, + "child_tax_credit": {year: unit["ctc"]}, + # Preserve synthetic awards even after cessation to isolate the + # active-scheme guard from the existing tax-credit formulas. + "tax_credits": {year: unit["wtc"] + unit["ctc"]}, + "income_support": {year: 0}, + "claimant_or_partner_jsa_income": {year: 0}, + "claimant_or_partner_esa_income": {year: 0}, + "housing_benefit_tariff_income": {year: 0}, + "housing_benefit_maintenance_disregard": {year: 0}, + "housing_benefit_widowed_parents_allowance_income": {year: 0}, + } + households[f"household_{index}"] = { + "members": members, + "region": {year: unit["region"]}, + } + return Simulation( + tax_benefit_system=without_wtc_reservation(system) if previous else system, + situation={"people": people, "benunits": benunits, "households": households}, + ) + + +def calculate(units, year, previous=False): + sim = simulation(units, year, previous) + return { + key: np.asarray(sim.calculate(variable, year), dtype=float) + for key, variable in { + "childcare": "housing_benefit_applicable_income_childcare_element", + "reserve": "housing_benefit_wtc_disregard", + "earnings_disregard": "housing_benefit_applicable_income_disregard", + "limit": "housing_benefit_childcare_earnings_limit", + "income": "housing_benefit_applicable_income", + }.items() + } + + +def test_issue_2730_reserves_wtc_before_childcare(): + sim = simulation([case()], 2024) + # Calculate an existing variable first: main reproduces a numeric + # failure (4,000 instead of 3,900), without needing the new variable. + assert sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[ + 0 + ] == pytest.approx(3_900, abs=TOLERANCE) + assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 + assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 0 + + +def test_lone_parent_uses_the_existing_earnings_and_work_conditions(): + sim = simulation([case()], 2024) + # Let the existing rules assess the earnings, ordinary disregard and + # work condition rather than supplying those intermediate assessments. + for variable in ( + "housing_benefit_net_earnings", + "housing_benefit_special_earnings_disregard", + "meets_housing_benefit_additional_earnings_disregard_conditions", + ): + sim.delete_arrays(variable, 2024) + sim.set_input("weekly_hours", 2024, [16, 0]) + assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 + assert ( + sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[0] + == 3_900 + ) + assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 0 + + +@pytest.mark.parametrize("region", ["LONDON", "NORTHERN_IRELAND"]) +def test_savings_credit_only_uses_the_corrected_childcare_modification(region): + sim = simulation([case(pension_age=True, region=region)], 2024) + for variable, value in { + "in_receipt_of_savings_credit_only": True, + "pension_credit_income": 10_000, + "pension_credit": 500, + "pension_credit_earnings_disregard": 1_040, + "pension_credit_war_pension_income": 0, + }.items(): + sim.set_input(variable, 2024, [value]) + # SI 2006/214 reg 27(4)(b), (5), reg 33(9); NI SR 2006/406 reg + # 25(4)(b), (5), reg 31(9): correct the childcare modification using + # the remaining WTC pool. The listed modifications do not deduct the + # WTC reserve directly from the Secretary of State's assessment. + # 10,000 + 500 - 3,900 - (1,300 - 1,040) = 6,340. + assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 + assert ( + sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[0] + == 3_900 + ) + assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 6_340 + + +@PROPERTY_SETTINGS +@given(units=POPULATIONS, year=st.sampled_from(YEARS)) +@example(units=EDGE_CASES, year=2024) +@example(units=EDGE_CASES, year=2020) +@example(units=EDGE_CASES, year=2025) +def test_assessed_income_equals_and_never_falls_below_the_regulations(units, year): + actual = calculate(units, year) + expected = [legal_components(unit, year) for unit in units] + for key, values in actual.items(): + np.testing.assert_allclose( + values, [unit[key] for unit in expected], rtol=0, atol=TOLERANCE + ) + assert np.all( + actual["income"] + TOLERANCE >= np.array([unit["income"] for unit in expected]) + ) + + +@PROPERTY_SETTINGS +@given(units=POPULATIONS, year=st.sampled_from(YEARS)) +@example(units=EDGE_CASES, year=2024) +def test_wtc_disregard_is_bounded_and_does_not_stack_with_earnings(units, year): + actual = calculate(units, year) + annual_amount = 1_929.20 if year == 2020 else 889.20 + assert np.all(actual["reserve"] >= 0) + assert np.all( + actual["reserve"] + <= np.minimum([unit["wtc"] for unit in units], annual_amount) + TOLERANCE + ) + standard = np.array([min(unit["net"], unit["standard"]) for unit in units]) + additional = actual["earnings_disregard"] - standard + assert np.all((additional <= TOLERANCE) | (actual["reserve"] <= TOLERANCE)) + + +@PROPERTY_SETTINGS +@given(units=POPULATIONS, year=st.sampled_from(YEARS)) +@example(units=EDGE_CASES, year=2024) +@example(units=EDGE_CASES, year=2025) +def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): + unchanged = [unit for unit in units if legal_components(unit, year)["reserve"] == 0] + # Always include a work-condition failure, no WTC, and sufficient + # earnings, so every population exercises the differential check. + unchanged.extend( + [case(worker=False), case(wtc=0), case(net=20_000, childcare=1_000)] + ) + actual = calculate(unchanged, year) + previous = calculate(unchanged, year, previous=True) + for variable in actual: + np.testing.assert_allclose( + actual[variable], previous[variable], rtol=0, atol=TOLERANCE + ) + + +@pytest.mark.parametrize("offset", [-0.01, 0, 0.01]) +def test_additional_earnings_threshold_includes_equality(offset): + unit = case(net=6_349.20 + offset) + actual = calculate([unit], 2024) + assert actual["reserve"][0] == (100 if offset < 0 else 0) + assert actual["earnings_disregard"][0] == pytest.approx( + 1_300 if offset < 0 else 2_189.20, abs=TOLERANCE + ) + + +@pytest.mark.parametrize("year", YEARS) +def test_wtc_disregard_honours_the_historical_amount_and_cessation(year): + unit = case(net=500, standard=260, childcare=0, children=0, wtc=2_000) + actual = calculate([unit], year) + expected = 0 if year >= 2025 else 1_929.20 if year == 2020 else 889.20 + assert actual["reserve"][0] == pytest.approx(expected, abs=TOLERANCE) + assert actual["income"][0] == pytest.approx(2_240 - expected, abs=TOLERANCE) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income.py index 49c6d82786..cdbb33b564 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income.py @@ -127,7 +127,8 @@ class housing_benefit_applicable_income(Variable): "Credit award is savings credit only, it is the Secretary of State's " "assessment of income plus the savings credit payable, less childcare " "charges and the earnings disregards. Otherwise it is the family's " - "income under the Housing Benefit rules." + "income under the Housing Benefit rules, including the separate " + "Working Tax Credit disregard before childcare." ) reference = ( "https://www.legislation.gov.uk/uksi/2006/213/regulation/25", @@ -145,6 +146,7 @@ class housing_benefit_applicable_income(Variable): "https://www.legislation.gov.uk/uksi/2006/213/regulation/2", "https://www.legislation.gov.uk/uksi/2006/213/regulation/5", "https://www.legislation.gov.uk/uksi/2006/213/regulation/40", + "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/16", "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/47", "https://www.legislation.gov.uk/uksi/2006/214/regulation/26", @@ -163,12 +165,15 @@ def formula(benunit, period, parameters): "housing_benefit_pension_age_regulations_apply", period ) disregard = benunit("housing_benefit_applicable_income_disregard", period) + # Reg 40(2), Sch 5 para 56: this comes from WTC, separately from + # the Sch 4 earnings disregard, before reg 27(1)(c) childcare. + wtc_disregard = benunit("housing_benefit_wtc_disregard", period) childcare_element = benunit( "housing_benefit_applicable_income_childcare_element", period ) income_under_general_rules = max_( 0, - income_before_deductions - disregard - childcare_element, + income_before_deductions - disregard - wtc_disregard - childcare_element, ) # SI 2006/214 reg 27 (NI: SR 2006/406 reg 25): where the award of # Pension Credit is savings credit only, the Secretary of State's diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index 8fa5661d04..b852d77929 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -15,11 +15,13 @@ def hb_childcare_earnings_limit(benunit, period, accommodation=None): "housing_benefit_specified_or_temporary_accommodation_disregard", period ) accommodation = min_(max_(accommodation, 0), max_(0, net - standard)) - # DWP BW2 W2.179–W2.182 permits the residual against any WTC/CTC in - # payment, not other income. Both amounts are benefit-unit payments. - credits = max_(benunit("working_tax_credit", period), 0) + max_( - benunit("child_tax_credit", period), 0 - ) + # Reg 40(2) and Sch 5 para 56 disregard WTC before reg 27(1)(c) + # deducts childcare. Only the remaining WTC/CTC can fund those charges. + credits = max_( + benunit("working_tax_credit", period) + - benunit("housing_benefit_wtc_disregard", period), + 0, + ) + max_(benunit("child_tax_credit", period), 0) return max_(0, net - standard - accommodation) + credits @@ -31,7 +33,8 @@ class housing_benefit_childcare_earnings_limit(Variable): label = "Housing Benefit childcare earnings and tax-credit limit" documentation = ( "Net claimant/partner earnings after the selected standard, permitted-work " - "and accommodation disregards, plus WTC/CTC payments. Unrelated income " + "and accommodation disregards, plus WTC/CTC payments after the " + "Schedule 5 paragraph 56 WTC disregard. Unrelated income " "cannot meet remaining childcare charges. The additional earnings " "disregard is conditional on earnings covering the childcare deduction " "as well as that disregard: when it applies the full capped childcare " @@ -59,6 +62,8 @@ class housing_benefit_childcare_earnings_limit(Variable): "https://www.legislation.gov.uk/nisr/2006/406/regulation/28", "https://assets.publishing.service.gov.uk/media/5a7c7cf7ed915d6969f4538d/hbgm-bw2-assessment-of-income.pdf", "https://www.legislation.gov.uk/uksi/2006/213/schedule/4/paragraph/17", + "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", + "https://www.legislation.gov.uk/uksi/2006/213/regulation/40", ) def formula(benunit, period, parameters): diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py new file mode 100644 index 0000000000..d23f2d6371 --- /dev/null +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -0,0 +1,73 @@ +from policyengine_uk.model_api import * +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( + hb_capped_childcare_charges, +) + + +class housing_benefit_wtc_disregard(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + unit = GBP + label = "Housing Benefit Working Tax Credit disregard" + documentation = ( + "Working Tax Credit disregarded before the childcare deduction when " + "the additional-disregard work conditions hold but earnings cannot " + "fund the additional earnings disregard. The amount is capped at " + "WTC received and the statutory additional amount, using its dated " + "history, including the temporary 2020 increase. The existing " + "tax-credit active parameter suppresses it from fiscal year 2025. " + "This is separate from the earnings-only disregard." + ) + reference = ( + "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", + "https://www.legislation.gov.uk/uksi/2006/213/schedule/4/paragraph/17", + "https://www.legislation.gov.uk/uksi/2006/213/regulation/40", + "https://www.legislation.gov.uk/uksi/2006/214/schedule/5/paragraph/21", + "https://www.legislation.gov.uk/nisr/2006/405/schedule/6/paragraph/58", + "https://www.legislation.gov.uk/nisr/2006/406/schedule/6/paragraph/22", + "https://www.legislation.gov.uk/uksi/2020/371/regulation/5", + "https://www.legislation.gov.uk/nisr/2020/53/regulation/5", + ) + + def formula(benunit, period, parameters): + p = parameters(period).gov.dwp + net = max_(benunit("housing_benefit_net_earnings", period), 0) + standard = benunit( + "housing_benefit_applied_standard_earnings_disregard", period + ) + accommodation = min_( + max_( + benunit( + "housing_benefit_specified_or_temporary_accommodation_disregard", + period, + ), + 0, + ), + max_(0, net - standard), + ) + additional = ( + p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR + ) + # Sch 4 para 17(3)(b) tests deductible childcare. If earnings cover + # childcare plus the positive additional amount, all capped charges + # already fit within earnings alone. Otherwise reducing the credit + # pool cannot make the test pass: a limited deduction takes at least + # all remaining earnings. Using the full charge therefore gives the + # same test without a cycle through childcare and this WTC reserve. + childcare = hb_capped_childcare_charges(benunit, period, parameters) + covers_additional = np.round(net.astype(float), 2) >= np.round( + (standard + accommodation + childcare + additional).astype(float), 2 + ) + applies = ( + p.tax_credits.active + & benunit( + "meets_housing_benefit_additional_earnings_disregard_conditions", period + ) + & ~covers_additional + ) + return where( + applies, + min_(max_(benunit("working_tax_credit", period), 0), additional), + 0, + ) From fc276e416b2ec0a8bc2c42c5652d9c8cc6632dfc Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 20:46:03 -0400 Subject: [PATCH 02/29] Read one childcare deduction in both additional-disregard tests The WTC disregard tested the full capped childcare charge, while the additional earnings disregard reads the childcare deduction. A supplied deduction, a supplied limit or a reform that replaces either could then give a benefit unit both disregards. The WTC disregard now reads that deduction whenever it differs from the model's own calculation, and keeps the cycle-free full-charge test otherwise. Tests add the accommodation disregard and supplied deductions to the oracle, which now settles paragraph 17 by trying both outcomes. They add a property that the two disregards never both apply and a differential test that supplying the calculated deduction changes nothing. Co-Authored-By: Claude Opus 5.5 --- .../housing_benefit_wtc_disregard.yaml | 77 +++ .../test_housing_benefit_wtc_disregard.py | 462 +++++++++++++++--- policyengine_uk/utils/supplied_inputs.py | 2 + .../housing_benefit_wtc_disregard.py | 123 +++-- 4 files changed, 561 insertions(+), 103 deletions(-) diff --git a/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml index 500652ef9d..85727bd4e9 100644 --- a/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml +++ b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml @@ -282,3 +282,80 @@ housing_benefit_wtc_disregard: 0 housing_benefit_childcare_earnings_limit: 4_000 housing_benefit_applicable_income_childcare_element: 4_000 + +- name: A supplied childcare deduction leaves only the additional earnings disregard + period: 2024 + absolute_error_margin: 0.02 + input: + age: 40 + employment_income: 5_200 + self_employment_income: 0 + property_income_after_finance_costs: 0 + private_pension_income: 0 + carers_allowance: 0 + carer_support_payment: 0 + esa_contrib: 0 + jsa_contrib: 0 + state_pension: 0 + maternity_allowance: 0 + statutory_sick_pay: 0 + statutory_maternity_pay: 0 + statutory_paternity_pay: 0 + iidb: 0 + sda: 0 + incapacity_benefit: 0 + spousal_maintenance_income: 0 + pension_contributions: 0 + income_tax_before_winter_fuel_payment_charge: 0 + national_insurance: 0 + tax_credits: 100 + income_support: 0 + claimant_or_partner_jsa_income: 0 + claimant_or_partner_esa_income: 0 + housing_benefit_tariff_income: 0 + housing_benefit_maintenance_disregard: 0 + housing_benefit_widowed_parents_allowance_income: 0 + housing_benefit_pension_age_regulations_apply: false + in_receipt_of_guarantee_credit: false + in_receipt_of_savings_credit_only: false + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + housing_benefit_applicable_income_childcare_element: 0 + output: + # The supplied deduction is nil, so Sch 4 para 17 applies: + # 5,200 >= 1,300 + 0 + 889.20. Sch 5 para 56 then gives no WTC disregard. + housing_benefit_applicable_income_disregard: 2_189.20 + housing_benefit_wtc_disregard: 0 + # 5,200 + 100 - 2,189.20 - 0 - 0. + housing_benefit_applicable_income: 3_110.80 + +- name: A supplied earnings and tax-credit limit sets the deduction both tests read + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + housing_benefit_childcare_earnings_limit: 1_000 + output: + # Reg 27: childcare = min(4,160, 1,000) = 1,000. + # Sch 4 para 17: 5,200 >= 1,300 + 1,000 + 889.20, so para 56 does not + # apply. + housing_benefit_applicable_income_childcare_element: 1_000 + housing_benefit_applicable_income_disregard: 2_189.20 + housing_benefit_wtc_disregard: 0 diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 8af8385d5f..e9999bb55f 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -2,32 +2,49 @@ SI 2006/213 reg 27(1)-(2), Sch 4 para 17(1), (3), and Sch 5 para 56 select the earnings or WTC disregard before childcare. Qualifying earnings, -the standard disregard, childcare and work conditions are assessed inputs. -The pension-age and Northern Ireland provisions apply the same ordering. +the standard and accommodation disregards, childcare and work conditions are +assessed inputs. The pension-age and Northern Ireland provisions apply the +same ordering. For every generated family, the WTC disregard lies between zero and both WTC and the additional disregard amount. The model never applies both the -additional earnings and WTC disregards. Childcare uses only the remaining -earnings and credits, and assessed income equals, and never falls below, -the independent scalar legal calculation. Where paragraph 56 does not -apply, the model agrees with the previous path, reproduced by a reform -that sets the new disregard to zero. +additional earnings and WTC disregards, including when a dataset, +``set_input`` or a reform supplies or replaces the childcare deduction. +Childcare uses only the remaining earnings and credits, and assessed income +equals, and never falls below, the independent scalar legal calculation. +That calculation settles paragraph 17 by trying both outcomes, rather than +assuming the full-charge shortcut the model uses. Where paragraph 56 does not +apply, the model agrees with the previous path, reproduced by a reform that +sets the new disregard to zero. Supplying the deduction the model calculates +leaves every result unchanged. The annual model uses 52 weeks, with the SI 2020/371 reg 5 temporary amount -in 2020 and no ongoing tax-credit awards from model year 2025. Populations -use core situations with independently supplied income components; they -never load a survey dataset or infer tax-credit awards from those incomes. +in 2020 and no ongoing tax-credit awards from model year 2025. Accommodation +amounts are supplied as assessed inputs, so the properties cover the earnings +test's arithmetic in every year; in law the accommodation disregard (from 5 +October 2026) and WTC (to 5 April 2025) coexist only under a reform that +keeps tax credits. Populations use core situations with independently +supplied income components; they never load a survey dataset or infer +tax-credit awards from those incomes. """ import numpy as np +import pandas as pd import pytest from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st +from policyengine_core.errors import CycleError +from policyengine_core.periods import period as period_ from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation -from policyengine_uk.model_api import BenUnit, Variable, YEAR +from policyengine_uk import Simulation as UKSimulation +from policyengine_uk.data.dataset_schema import UKSingleYearDataset +from policyengine_uk.model_api import BenUnit, Variable, YEAR, min_ from policyengine_uk.system import system +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( + hb_capped_childcare_charges, +) TOLERANCE = 0.02 @@ -39,13 +56,17 @@ deadline=None, suppress_health_check=[HealthCheck.too_slow, HealthCheck.data_too_large], ) +CHILDCARE = "housing_benefit_applicable_income_childcare_element" +LIMIT = "housing_benefit_childcare_earnings_limit" def case(**overrides): result = dict( net=5_200, standard=1_300, + accommodation=0, childcare=4_160, + supplied=None, children=1, wtc=100, ctc=0, @@ -58,23 +79,38 @@ def case(**overrides): return result +def pounds(maximum): + return st.integers(0, maximum * 100).map(lambda pence: pence / 100) + + @st.composite -def families(draw): +def families(draw, supplied=False): return case( - net=draw(st.integers(0, 4_000_000)) / 100, + net=draw(pounds(40_000)), standard=draw(st.sampled_from([260, 520, 1_040, 1_300])), - childcare=draw(st.integers(0, 2_500_000)) / 100, + accommodation=draw(st.one_of(st.just(0), pounds(6_500))), + childcare=draw(pounds(25_000)), + supplied=draw(pounds(25_000)) if supplied else None, children=draw(st.integers(0, 2)), - wtc=draw(st.integers(0, 1_000_000)) / 100, - ctc=draw(st.integers(0, 1_000_000)) / 100, - other=draw(st.integers(0, 2_000_000)) / 100, + wtc=draw(pounds(10_000)), + ctc=draw(pounds(10_000)), + other=draw(pounds(20_000)), worker=draw(st.booleans()), pension_age=draw(st.booleans()), region=draw(st.sampled_from(REGIONS)), ) -POPULATIONS = st.lists(families(), min_size=1, max_size=12) +@st.composite +def populations(draw): + # A supplied deduction is set for the whole population, as a dataset + # column or a set_input call sets it. + supplied = draw(st.booleans()) + return draw(st.lists(families(supplied), min_size=1, max_size=12)) + + +POPULATIONS = populations() +SUPPLIED_POPULATIONS = st.lists(families(supplied=True), min_size=1, max_size=12) EDGE_CASES = [ case(), case(net=0), @@ -87,33 +123,60 @@ def families(draw): case(net=6_349.21, other=1_000), case(pension_age=True), case(children=2, childcare=25_000, wtc=10_000, ctc=10_000), + case(net=2_000, standard=260, accommodation=1_000, childcare=0, wtc=1_000), + case(net=2_000, standard=260, accommodation=6_000, childcare=0, wtc=1_000), + case(net=8_000, accommodation=1_000, childcare=4_160, wtc=500), *(case(region=region) for region in REGIONS), ] +SUPPLIED_EDGE_CASES = [ + # The review's case: earnings cover the supplied nil deduction. + case(supplied=0), + case(supplied=3_900), + case(supplied=4_160), + case(net=6_349.20, supplied=4_160), + case(net=6_349.19, supplied=4_160), + case(net=2_000, standard=260, accommodation=1_000, childcare=0, supplied=0), + case(net=2_000, standard=260, accommodation=500, childcare=0, supplied=0), + case(childcare=25_000, children=2, supplied=100, wtc=5_000), + case(worker=False, supplied=0), +] def legal_components(unit, year): """Apply the regulations to scalar assessed inputs in annual pounds.""" net = unit["net"] standard = min(net, unit["standard"]) + # Sch 4 para 18 takes the earnings the other disregards leave. + accommodation = min(unit["accommodation"], net - standard) cap = 15_600 if unit["children"] > 1 else 9_100 if unit["children"] else 0 charge = min(unit["childcare"], cap) additional_amount = 1_929.20 if year == 2020 else 889.20 - # Sch 4 para 17(3): earnings must cover the standard, qualifying - # childcare and additional amount. Compare money in statutory pence. - covers_additional = round(net * 100) >= round( - (standard + charge + additional_amount) * 100 - ) - additional = additional_amount if unit["worker"] and covers_additional else 0 - # Sch 5 para 56 applies only when para 17(1) does not apply. - reserve = ( - min(unit["wtc"], additional_amount) - if year < 2025 and unit["worker"] and not covers_additional - else 0 - ) - # Reg 27(1)-(2): childcare follows the Schedule 4/5 disregards. When - # additional earnings qualify, the full charge already fits earnings. - limit = net - standard + unit["wtc"] - reserve + unit["ctc"] - childcare = min(charge, limit) + earnings = net - standard - accommodation + + def deduction(reserve): + if unit["supplied"] is not None: + return unit["supplied"] + # Reg 27(1)(c), (2): earnings, then the credits that remain after + # the Sch 5 disregards. + return min(charge, earnings + unit["wtc"] - reserve + unit["ctc"]) + + def covers(reserve): + # Sch 4 para 17(1), (3): the other disregards, the deductible + # childcare and the additional amount, compared in statutory pence. + return round(net * 100) >= round( + (standard + accommodation + deduction(reserve) + additional_amount) * 100 + ) + + # Sch 5 para 56 applies "except in a case which falls under" para 17(1). + # Try para 17(1) with every credit available; where it fails, reserve + # the WTC and check that the smaller credit pool keeps it failing. + reserve = 0 + if unit["worker"] and year < 2025 and not covers(0): + reserve = min(unit["wtc"], additional_amount) + assert not covers(reserve), "no consistent paragraph 17 outcome" + additional = additional_amount if unit["worker"] and covers(reserve) else 0 + childcare = deduction(reserve) + limit = earnings + unit["wtc"] - reserve + unit["ctc"] income = max( 0, net @@ -121,6 +184,7 @@ def legal_components(unit, year): + unit["ctc"] + unit["other"] - standard + - accommodation - additional - reserve - childcare, @@ -128,7 +192,7 @@ def legal_components(unit, year): return dict( childcare=childcare, reserve=reserve, - earnings_disregard=standard + additional, + earnings_disregard=standard + accommodation + additional, limit=limit, income=income, ) @@ -151,7 +215,9 @@ def apply(self): self.update_variable(previous_wtc_disregard) -def simulation(units, year, previous=False): +def simulation(units, year, previous=False, tax_benefit_system=None): + supplied = [unit["supplied"] is not None for unit in units] + assert all(supplied) or not any(supplied), "supply the deduction for all" people, benunits, households = {}, {}, {} for index, unit in enumerate(units): adult = f"adult_{index}" @@ -205,7 +271,9 @@ def simulation(units, year, previous=False): year: min(unit["net"], unit["standard"]) }, "housing_benefit_permitted_work_disregard": {year: 0}, - "housing_benefit_specified_or_temporary_accommodation_disregard": {year: 0}, + "housing_benefit_specified_or_temporary_accommodation_disregard": { + year: unit["accommodation"] + }, "housing_benefit_on_passporting_benefit": {year: False}, "housing_benefit_pension_age_regulations_apply": { year: unit["pension_age"] @@ -227,37 +295,58 @@ def simulation(units, year, previous=False): "housing_benefit_maintenance_disregard": {year: 0}, "housing_benefit_widowed_parents_allowance_income": {year: 0}, } + if unit["supplied"] is not None: + benunits[f"family_{index}"][CHILDCARE] = {year: unit["supplied"]} households[f"household_{index}"] = { "members": members, "region": {year: unit["region"]}, } + if tax_benefit_system is None: + tax_benefit_system = without_wtc_reservation(system) if previous else system return Simulation( - tax_benefit_system=without_wtc_reservation(system) if previous else system, + tax_benefit_system=tax_benefit_system, situation={"people": people, "benunits": benunits, "households": households}, ) -def calculate(units, year, previous=False): - sim = simulation(units, year, previous) +OUTPUTS = { + "childcare": CHILDCARE, + "reserve": "housing_benefit_wtc_disregard", + "earnings_disregard": "housing_benefit_applicable_income_disregard", + "limit": LIMIT, + "income": "housing_benefit_applicable_income", +} + + +def results(sim, year): return { key: np.asarray(sim.calculate(variable, year), dtype=float) - for key, variable in { - "childcare": "housing_benefit_applicable_income_childcare_element", - "reserve": "housing_benefit_wtc_disregard", - "earnings_disregard": "housing_benefit_applicable_income_disregard", - "limit": "housing_benefit_childcare_earnings_limit", - "income": "housing_benefit_applicable_income", - }.items() + for key, variable in OUTPUTS.items() } +def calculate(units, year, previous=False): + return results(simulation(units, year, previous), year) + + +def assert_one_additional_disregard(units, actual): + """The additional earnings disregard and a positive WTC disregard never + both apply to a benefit unit.""" + standard = np.array([min(unit["net"], unit["standard"]) for unit in units]) + net = np.array([unit["net"] for unit in units]) + accommodation = np.minimum( + [unit["accommodation"] for unit in units], net - standard + ) + additional = actual["earnings_disregard"] - standard - accommodation + both = (additional > TOLERANCE) & (actual["reserve"] > TOLERANCE) + assert not both.any(), [unit for unit, b in zip(units, both) if b] + + def test_issue_2730_reserves_wtc_before_childcare(): sim = simulation([case()], 2024) # Calculate an existing variable first: main reproduces a numeric # failure (4,000 instead of 3,900), without needing the new variable. - assert sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[ - 0 - ] == pytest.approx(3_900, abs=TOLERANCE) + assert sim.calculate(CHILDCARE, 2024)[0] == pytest.approx(3_900, abs=TOLERANCE) assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 0 @@ -274,10 +363,7 @@ def test_lone_parent_uses_the_existing_earnings_and_work_conditions(): sim.delete_arrays(variable, 2024) sim.set_input("weekly_hours", 2024, [16, 0]) assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 - assert ( - sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[0] - == 3_900 - ) + assert sim.calculate(CHILDCARE, 2024)[0] == 3_900 assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 0 @@ -298,10 +384,7 @@ def test_savings_credit_only_uses_the_corrected_childcare_modification(region): # WTC reserve directly from the Secretary of State's assessment. # 10,000 + 500 - 3,900 - (1,300 - 1,040) = 6,340. assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 100 - assert ( - sim.calculate("housing_benefit_applicable_income_childcare_element", 2024)[0] - == 3_900 - ) + assert sim.calculate(CHILDCARE, 2024)[0] == 3_900 assert sim.calculate("housing_benefit_applicable_income", 2024)[0] == 6_340 @@ -310,6 +393,7 @@ def test_savings_credit_only_uses_the_corrected_childcare_modification(region): @example(units=EDGE_CASES, year=2024) @example(units=EDGE_CASES, year=2020) @example(units=EDGE_CASES, year=2025) +@example(units=SUPPLIED_EDGE_CASES, year=2024) def test_assessed_income_equals_and_never_falls_below_the_regulations(units, year): actual = calculate(units, year) expected = [legal_components(unit, year) for unit in units] @@ -325,6 +409,7 @@ def test_assessed_income_equals_and_never_falls_below_the_regulations(units, yea @PROPERTY_SETTINGS @given(units=POPULATIONS, year=st.sampled_from(YEARS)) @example(units=EDGE_CASES, year=2024) +@example(units=SUPPLIED_EDGE_CASES, year=2020) def test_wtc_disregard_is_bounded_and_does_not_stack_with_earnings(units, year): actual = calculate(units, year) annual_amount = 1_929.20 if year == 2020 else 889.20 @@ -333,21 +418,36 @@ def test_wtc_disregard_is_bounded_and_does_not_stack_with_earnings(units, year): actual["reserve"] <= np.minimum([unit["wtc"] for unit in units], annual_amount) + TOLERANCE ) - standard = np.array([min(unit["net"], unit["standard"]) for unit in units]) - additional = actual["earnings_disregard"] - standard - assert np.all((additional <= TOLERANCE) | (actual["reserve"] <= TOLERANCE)) + assert_one_additional_disregard(units, actual) + + +@PROPERTY_SETTINGS +@given(units=SUPPLIED_POPULATIONS, year=st.sampled_from(YEARS)) +@example(units=[case(supplied=0)], year=2024) +@example(units=SUPPLIED_EDGE_CASES, year=2024) +def test_additional_earnings_and_wtc_disregards_never_both_apply(units, year): + """Earnings, WTC, the standard and accommodation disregards and a + supplied childcare deduction never give a benefit unit both additional + disregards.""" + assert_one_additional_disregard(units, calculate(units, year)) @PROPERTY_SETTINGS @given(units=POPULATIONS, year=st.sampled_from(YEARS)) @example(units=EDGE_CASES, year=2024) @example(units=EDGE_CASES, year=2025) +@example(units=SUPPLIED_EDGE_CASES, year=2024) def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): unchanged = [unit for unit in units if legal_components(unit, year)["reserve"] == 0] + supplied = units[0]["supplied"] is not None # Always include a work-condition failure, no WTC, and sufficient # earnings, so every population exercises the differential check. unchanged.extend( - [case(worker=False), case(wtc=0), case(net=20_000, childcare=1_000)] + [ + case(worker=False, supplied=0 if supplied else None), + case(wtc=0, supplied=3_000 if supplied else None), + case(net=20_000, childcare=1_000, supplied=1_000 if supplied else None), + ] ) actual = calculate(unchanged, year) previous = calculate(unchanged, year, previous=True) @@ -357,6 +457,26 @@ def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): ) +@PROPERTY_SETTINGS +@given(units=st.lists(families(), min_size=1, max_size=12), year=st.sampled_from(YEARS)) +@example(units=EDGE_CASES, year=2024) +@example(units=EDGE_CASES, year=2020) +def test_supplying_the_calculated_deduction_changes_nothing(units, year): + """The full-charge test and a test reading the supplied deduction are two + implementations of Sch 4 para 17(3)(b): supplying the deduction the + model calculates must leave every result unchanged.""" + calculated = calculate(units, year) + supplied = [ + {**unit, "supplied": float(value)} + for unit, value in zip(units, calculated["childcare"]) + ] + replayed = calculate(supplied, year) + for variable in calculated: + np.testing.assert_allclose( + replayed[variable], calculated[variable], rtol=0, atol=TOLERANCE + ) + + @pytest.mark.parametrize("offset", [-0.01, 0, 0.01]) def test_additional_earnings_threshold_includes_equality(offset): unit = case(net=6_349.20 + offset) @@ -374,3 +494,221 @@ def test_wtc_disregard_honours_the_historical_amount_and_cessation(year): expected = 0 if year >= 2025 else 1_929.20 if year == 2020 else 889.20 assert actual["reserve"][0] == pytest.approx(expected, abs=TOLERANCE) assert actual["income"][0] == pytest.approx(2_240 - expected, abs=TOLERANCE) + + +@pytest.mark.parametrize( + "accommodation,reserve,earnings_disregard", + [ + # Sch 4 para 17(3)(a): 2,000 >= 260 + 889.20, so para 17(1) applies. + (0, 0, 260 + 889.20), + # 2,000 < 260 + 1,000 + 889.20, so para 56 reserves 889.20 of WTC. + (1_000, 889.20, 260 + 1_000), + ], +) +def test_accommodation_disregard_counts_in_the_additional_earnings_test( + accommodation, reserve, earnings_disregard +): + unit = case( + net=2_000, + standard=260, + accommodation=accommodation, + childcare=0, + children=0, + wtc=1_000, + ) + actual = calculate([unit], 2024) + assert actual["reserve"][0] == pytest.approx(reserve, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx( + earnings_disregard, abs=TOLERANCE + ) + + +def test_supplied_childcare_deduction_keeps_one_additional_disregard(): + sim = simulation([case()], 2024) + sim.set_input(CHILDCARE, 2024, [0]) + actual = results(sim, 2024) + # Sch 4 para 17: 5,200 >= 1,300 + 0 + 889.20, so para 56 does not apply. + assert actual["earnings_disregard"][0] == pytest.approx(2_189.20, abs=TOLERANCE) + assert actual["reserve"][0] == 0 + # 5,200 + 100 - 2,189.20 - 0, as without the WTC disregard. + assert actual["income"][0] == pytest.approx(3_110.80, abs=TOLERANCE) + + +def test_supplied_childcare_limit_keeps_one_additional_disregard(): + sim = simulation([case()], 2024) + sim.set_input(LIMIT, 2024, [0]) + actual = results(sim, 2024) + assert actual["childcare"][0] == 0 + assert actual["earnings_disregard"][0] == pytest.approx(2_189.20, abs=TOLERANCE) + assert actual["reserve"][0] == 0 + assert actual["income"][0] == pytest.approx(3_110.80, abs=TOLERANCE) + + +@pytest.mark.usefixtures("cloned_uk_tax_benefit_system") +def test_dataset_supplied_childcare_deduction_keeps_one_additional_disregard(): + person = pd.DataFrame( + { + "person_id": [1, 2], + "person_benunit_id": [1, 1], + "person_household_id": [1, 1], + "age": [40, 8], + "childcare_expenses": [4_160.0, 0.0], + } + ) + benunit = pd.DataFrame( + { + "benunit_id": [1], + "housing_benefit_net_earnings": [5_200.0], + "housing_benefit_special_earnings_disregard": [1_300.0], + "housing_benefit_permitted_work_disregard": [0.0], + "housing_benefit_specified_or_temporary_accommodation_disregard": [0.0], + "housing_benefit_on_passporting_benefit": [False], + "meets_housing_benefit_additional_earnings_disregard_conditions": [True], + "num_relevant_children_for_housing_benefit_childcare": [1], + "working_tax_credit": [100.0], + "child_tax_credit": [0.0], + CHILDCARE: [0.0], + } + ) + household = pd.DataFrame( + { + "household_id": [1], + "region": ["LONDON"], + "tenure_type": ["RENT_PRIVATELY"], + "council_tax": [1_500.0], + "rent": [0.0], + "household_weight": [1.0], + } + ) + sim = UKSimulation( + dataset=UKSingleYearDataset( + person=person, benunit=benunit, household=household, fiscal_year=2024 + ) + ) + assert sim.calculate(CHILDCARE, 2024)[0] == 0 + assert sim.calculate( + "housing_benefit_applicable_income_disregard", 2024 + ) == pytest.approx([2_189.20], abs=TOLERANCE) + assert sim.calculate("housing_benefit_wtc_disregard", 2024)[0] == 0 + + +class neutralized_childcare(Reform): + def apply(self): + self.neutralize_variable(CHILDCARE) + + +class half_capped_childcare(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + + def formula(benunit, period, parameters): + return hb_capped_childcare_charges(benunit, period, parameters) / 2 + + +half_capped_childcare.__name__ = CHILDCARE + + +class halve_capped_childcare(Reform): + def apply(self): + self.update_variable(half_capped_childcare) + + +@pytest.mark.parametrize( + "reform,childcare,income", + [ + # Nil deduction: 5,200 + 100 - (1,300 + 889.20). + (neutralized_childcare, 0, 3_110.80), + # 2,080 deduction: 5,200 >= 1,300 + 2,080 + 889.20, so para 17(1) + # applies; 5,200 + 100 - 2,189.20 - 2,080. + (halve_capped_childcare, 2_080, 1_030.80), + ], +) +def test_reformed_childcare_deduction_keeps_one_additional_disregard( + reform, childcare, income +): + sim = simulation([case()], 2024, tax_benefit_system=reform(system)) + actual = results(sim, 2024) + assert actual["childcare"][0] == pytest.approx(childcare, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx(2_189.20, abs=TOLERANCE) + assert actual["reserve"][0] == 0 + assert actual["income"][0] == pytest.approx(income, abs=TOLERANCE) + + +class limit_reading_childcare(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + + def formula(benunit, period, parameters): + charges = hb_capped_childcare_charges(benunit, period, parameters) / 2 + return min_(charges, benunit(LIMIT, period)) + + +limit_reading_childcare.__name__ = CHILDCARE + + +class limit_reading_reform(Reform): + def apply(self): + self.update_variable(limit_reading_childcare) + + +def test_replacement_deduction_reading_the_limit_stops_with_a_cycle(): + """A replacement deduction that reads the earnings and tax-credit limit + depends on the WTC disregard, which reads that deduction: the engine + stops rather than return figures that grant both disregards. Without + active tax credits the disregard reads nothing, so the reform runs.""" + reformed = limit_reading_reform(system) + with pytest.raises(CycleError): + simulation([case()], 2024, tax_benefit_system=reformed).calculate( + "housing_benefit_applicable_income", 2024 + ) + actual = results(simulation([case()], 2025, tax_benefit_system=reformed), 2025) + assert actual["reserve"][0] == 0 + assert actual["childcare"][0] == pytest.approx(2_080, abs=TOLERANCE) + + +def test_revived_tax_credits_with_the_accommodation_disregard(): + """Under a reform that keeps tax credits, the 2027 accommodation + disregard (£77.73 a week from 5 October 2026) can leave earnings short + of the additional amount, and para 56 then reserves WTC.""" + year = 2027 + unit = case(net=2_000, standard=260, childcare=0, children=0, wtc=1_000) + people = { + "adult": { + "age": {year: 40}, + "is_claimant_or_partner": {year: True}, + "employment_income": {year: unit["net"]}, + } + } + family = { + "members": ["adult"], + "in_specified_or_temporary_accommodation": {year: True}, + "housing_benefit_net_earnings": {year: unit["net"]}, + "housing_benefit_special_earnings_disregard": {year: unit["standard"]}, + "housing_benefit_permitted_work_disregard": {year: 0}, + "housing_benefit_on_passporting_benefit": {year: False}, + "housing_benefit_pension_age_regulations_apply": {year: False}, + "meets_housing_benefit_additional_earnings_disregard_conditions": {year: True}, + "working_tax_credit": {year: unit["wtc"]}, + "child_tax_credit": {year: 0}, + } + sim = UKSimulation( + situation={ + "people": people, + "benunits": {"family": family}, + "households": {"home": {"members": ["adult"]}}, + }, + reform={"gov.dwp.tax_credits.active": {"2027": True}}, + ) + accommodation = sim.calculate( + "housing_benefit_specified_or_temporary_accommodation_disregard", year + )[0] + assert accommodation == pytest.approx(77.73 * 52, abs=TOLERANCE) + # 2,000 < 260 + min(4,041.96, 1,740) + 889.20: para 56 reserves 889.20. + assert sim.calculate("housing_benefit_wtc_disregard", year)[0] == pytest.approx( + 889.20, abs=TOLERANCE + ) + assert sim.calculate( + "housing_benefit_applicable_income_disregard", year + ) == pytest.approx([2_000], abs=TOLERANCE) diff --git a/policyengine_uk/utils/supplied_inputs.py b/policyengine_uk/utils/supplied_inputs.py index 70e7b0edf3..f742faa261 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -56,6 +56,8 @@ "extended_childcare_entitlement_term_share", "extended_childcare_entitlement_total_per_child", "gas_consumption_kwh", + "housing_benefit_applicable_income_childcare_element", + "housing_benefit_childcare_earnings_limit", "in_HE", "other_local_bus_trips", "pip_dl_category", diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index d23f2d6371..1ae1814360 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -1,7 +1,83 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.supplied_inputs import supplied_input from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( hb_capped_childcare_charges, + housing_benefit_applicable_income_childcare_element, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + housing_benefit_childcare_earnings_limit, +) + + +def hb_childcare_deduction_replaced(benunit, period): + """Whether the childcare deduction differs from the model's own + calculation: it, or the limit it reads, is supplied (by a dataset, + set_input or a scenario), neutralized, or calculated by a formula a + reform put in place of the model's.""" + system = benunit.simulation.tax_benefit_system + for model_variable in ( + housing_benefit_applicable_income_childcare_element, + housing_benefit_childcare_earnings_limit, + ): + name = model_variable.__name__ + variable = system.get_variable(name) + formula = variable.get_formula(period) + if ( + variable.is_neutralized + or formula is None + or formula.__code__ != model_variable.formula.__code__ + or supplied_input(benunit, name, period) is not None + ): + return True + return False + + +def hb_wtc_disregard(benunit, period, parameters, accommodation=None): + """WTC disregarded under Sch 5 para 56, given the full accommodation + amount (by default the annual variable).""" + p = parameters(period).gov.dwp + if not p.tax_credits.active: + return benunit.empty_array() + net = max_(benunit("housing_benefit_net_earnings", period), 0) + standard = benunit("housing_benefit_applied_standard_earnings_disregard", period) + if accommodation is None: + accommodation = benunit( + "housing_benefit_specified_or_temporary_accommodation_disregard", period + ) + accommodation = min_(max_(accommodation, 0), max_(0, net - standard)) + additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR + # Sch 4 para 17(3)(b) counts the deductible childcare, which reg + # 27(1)(c) takes from earnings and then from the credits this disregard + # reduces. With the model's own deduction, the lesser of the capped + # charge and the earnings and tax-credit limit, the whole capped charge + # gives the same answer: if earnings cover it and the additional amount, + # the whole charge fits within earnings; if not, a deduction the limit + # caps takes at least all remaining earnings, so the test fails whatever + # credits remain. That holds only for that formula. A supplied, + # neutralized or replaced deduction or limit can differ, so the test + # then reads the deduction the earnings disregard reads. A replacement + # that itself reads the limit depends on this disregard, and the engine + # stops with a circular-definition error. + if hb_childcare_deduction_replaced(benunit, period): + childcare = benunit( + "housing_benefit_applicable_income_childcare_element", period + ) + else: + childcare = hb_capped_childcare_charges(benunit, period, parameters) + covers_additional = np.round(net.astype(float), 2) >= np.round( + (standard + accommodation + childcare + additional).astype(float), 2 + ) + applies = ( + benunit( + "meets_housing_benefit_additional_earnings_disregard_conditions", period + ) + & ~covers_additional + ) + return where( + applies, + min_(max_(benunit("working_tax_credit", period), 0), additional), + 0, + ) class housing_benefit_wtc_disregard(Variable): @@ -17,7 +93,11 @@ class housing_benefit_wtc_disregard(Variable): "WTC received and the statutory additional amount, using its dated " "history, including the temporary 2020 increase. The existing " "tax-credit active parameter suppresses it from fiscal year 2025. " - "This is separate from the earnings-only disregard." + "This is separate from the earnings-only disregard. Where the " + "childcare deduction or its limit is supplied, neutralized or " + "replaced, the earnings test reads the same deduction as the " + "earnings disregard, so the two additional disregards never both " + "apply." ) reference = ( "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", @@ -31,43 +111,4 @@ class housing_benefit_wtc_disregard(Variable): ) def formula(benunit, period, parameters): - p = parameters(period).gov.dwp - net = max_(benunit("housing_benefit_net_earnings", period), 0) - standard = benunit( - "housing_benefit_applied_standard_earnings_disregard", period - ) - accommodation = min_( - max_( - benunit( - "housing_benefit_specified_or_temporary_accommodation_disregard", - period, - ), - 0, - ), - max_(0, net - standard), - ) - additional = ( - p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR - ) - # Sch 4 para 17(3)(b) tests deductible childcare. If earnings cover - # childcare plus the positive additional amount, all capped charges - # already fit within earnings alone. Otherwise reducing the credit - # pool cannot make the test pass: a limited deduction takes at least - # all remaining earnings. Using the full charge therefore gives the - # same test without a cycle through childcare and this WTC reserve. - childcare = hb_capped_childcare_charges(benunit, period, parameters) - covers_additional = np.round(net.astype(float), 2) >= np.round( - (standard + accommodation + childcare + additional).astype(float), 2 - ) - applies = ( - p.tax_credits.active - & benunit( - "meets_housing_benefit_additional_earnings_disregard_conditions", period - ) - & ~covers_additional - ) - return where( - applies, - min_(max_(benunit("working_tax_credit", period), 0), additional), - 0, - ) + return hb_wtc_disregard(benunit, period, parameters) From dd8616ad2a891df2c81cf4a22d79d97edb4ea484 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 21:21:29 -0400 Subject: [PATCH 03/29] Test the earnings decision with the disregard's own arithmetic The WTC disregard compares the same net earnings and accommodation amount as the additional earnings disregard. A cap on the accommodation amount would not change the test, since earnings already fall short where it binds. New tests cover a deduction with no formula and a negative WTC award. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 21 +++++++++++++++++++ .../housing_benefit_wtc_disregard.py | 6 ++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index e9999bb55f..a7c6a64413 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -496,6 +496,11 @@ def test_wtc_disregard_honours_the_historical_amount_and_cessation(year): assert actual["income"][0] == pytest.approx(2_240 - expected, abs=TOLERANCE) +def test_negative_wtc_gives_no_disregard(): + actual = calculate([case(net=500, standard=260, childcare=0, wtc=-100)], 2024) + assert actual["reserve"][0] == 0 + + @pytest.mark.parametrize( "accommodation,reserve,earnings_disregard", [ @@ -614,11 +619,27 @@ def apply(self): self.update_variable(half_capped_childcare) +class input_childcare(Variable): + value_type = float + entity = BenUnit + label = "Housing Benefit childcare deduction without a formula" + definition_period = YEAR + + +input_childcare.__name__ = CHILDCARE + + +class childcare_without_formula(Reform): + def apply(self): + self.replace_variable(input_childcare) + + @pytest.mark.parametrize( "reform,childcare,income", [ # Nil deduction: 5,200 + 100 - (1,300 + 889.20). (neutralized_childcare, 0, 3_110.80), + (childcare_without_formula, 0, 3_110.80), # 2,080 deduction: 5,200 >= 1,300 + 2,080 + 889.20, so para 17(1) # applies; 5,200 + 100 - 2,189.20 - 2,080. (halve_capped_childcare, 2_080, 1_030.80), diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index 1ae1814360..5e0f589f2b 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -38,13 +38,15 @@ def hb_wtc_disregard(benunit, period, parameters, accommodation=None): p = parameters(period).gov.dwp if not p.tax_credits.active: return benunit.empty_array() - net = max_(benunit("housing_benefit_net_earnings", period), 0) + net = benunit("housing_benefit_net_earnings", period) standard = benunit("housing_benefit_applied_standard_earnings_disregard", period) + # Para 18 takes only the earnings the other disregards leave, but a cap + # would not change this test: where it binds, earnings fall short of the + # additional amount anyway. if accommodation is None: accommodation = benunit( "housing_benefit_specified_or_temporary_accommodation_disregard", period ) - accommodation = min_(max_(accommodation, 0), max_(0, net - standard)) additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR # Sch 4 para 17(3)(b) counts the deductible childcare, which reg # 27(1)(c) takes from earnings and then from the credits this disregard From ba1c60ae5e410f3c2991842733a32fc1d5a22995 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Fri, 30 Oct 2026 23:46:42 -0400 Subject: [PATCH 04/29] Settle the Housing Benefit WTC disregard in each accommodation segment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #2234 settles Schedule 4 paragraph 17 separately before and after the accommodation disregard starts on 5 October 2026, but its segment income left out the WTC disregard. Paragraph 56 follows paragraph 17's outcome, so each segment now has its own WTC disregard: the childcare limit takes it, hb_segment_deductions returns it, and entitlement deducts it. The annual variable combines the segments by days. The WTC and earnings decisions now share one paragraph 17 test and one check for a supplied or replaced childcare deduction, #2234's hb_uses_annual_override. Under a reform that keeps tax credits in 2026-27, a claimant in specified accommodation with £500 of earnings and £2,000 of WTC now gets £9,600.19 rather than £9,022.21. Current-law awards do not change: tax credits end before the accommodation disregard starts. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2730.fixed.md | 2 +- .../test_housing_benefit_wtc_disregard.py | 41 ++- ..._housing_benefit_wtc_disregard_segments.py | 300 ++++++++++++++++++ policyengine_uk/utils/supplied_inputs.py | 1 + ...ing_benefit_applicable_income_disregard.py | 58 ++-- ...ousing_benefit_childcare_earnings_limit.py | 18 +- .../housing_benefit_wtc_disregard.py | 148 +++++---- .../housing_benefit_entitlement.py | 17 +- 8 files changed, 467 insertions(+), 118 deletions(-) create mode 100644 policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py diff --git a/changelog.d/2730.fixed.md b/changelog.d/2730.fixed.md index 489f561722..c79626bf3f 100644 --- a/changelog.d/2730.fixed.md +++ b/changelog.d/2730.fixed.md @@ -1 +1 @@ -Housing Benefit reserves the Working Tax Credit income disregard before deducting childcare costs in historical tax-credit years. +Housing Benefit reserves the Working Tax Credit income disregard before deducting childcare costs in historical tax-credit years, and settles it separately before and after the accommodation disregard starts under a reform that keeps tax credits. diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index a7c6a64413..7fcef89f61 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -23,7 +23,8 @@ amounts are supplied as assessed inputs, so the properties cover the earnings test's arithmetic in every year; in law the accommodation disregard (from 5 October 2026) and WTC (to 5 April 2025) coexist only under a reform that -keeps tax credits. Populations use core situations with independently +keeps tax credits. test_housing_benefit_wtc_disregard_segments.py lets the +model date that disregard. Populations use core situations with independently supplied income components; they never load a survey dataset or infer tax-credit awards from those incomes. """ @@ -58,6 +59,8 @@ ) CHILDCARE = "housing_benefit_applicable_income_childcare_element" LIMIT = "housing_benefit_childcare_earnings_limit" +ACCOMMODATION = "housing_benefit_specified_or_temporary_accommodation_disregard" +RENT = 10_400 def case(**overrides): @@ -74,6 +77,9 @@ def case(**overrides): worker=True, pension_age=False, region="LONDON", + # Used only where the model dates the accommodation disregard. + specified=False, + applicable_amount=0, ) result.update(overrides) return result @@ -142,8 +148,11 @@ def populations(draw): ] -def legal_components(unit, year): - """Apply the regulations to scalar assessed inputs in annual pounds.""" +def legal_components(unit, year, active=None): + """Apply the regulations to scalar assessed inputs in annual pounds. + Tax credits pay awards before model year 2025 unless ``active`` says + otherwise.""" + active = year < 2025 if active is None else active net = unit["net"] standard = min(net, unit["standard"]) # Sch 4 para 18 takes the earnings the other disregards leave. @@ -171,7 +180,7 @@ def covers(reserve): # Try para 17(1) with every credit available; where it fails, reserve # the WTC and check that the smaller credit pool keeps it failing. reserve = 0 - if unit["worker"] and year < 2025 and not covers(0): + if unit["worker"] and active and not covers(0): reserve = min(unit["wtc"], additional_amount) assert not covers(reserve), "no consistent paragraph 17 outcome" additional = additional_amount if unit["worker"] and covers(reserve) else 0 @@ -215,7 +224,12 @@ def apply(self): self.update_variable(previous_wtc_disregard) -def simulation(units, year, previous=False, tax_benefit_system=None): +def simulation( + units, year, previous=False, tax_benefit_system=None, dated_accommodation=False +): + """Build the population. With ``dated_accommodation`` the model dates + the accommodation disregard itself, and the population pays rent of + ``RENT``; otherwise each unit supplies its annual accommodation amount.""" supplied = [unit["supplied"] is not None for unit in units] assert all(supplied) or not any(supplied), "supply the deduction for all" people, benunits, households = {}, {}, {} @@ -271,9 +285,6 @@ def simulation(units, year, previous=False, tax_benefit_system=None): year: min(unit["net"], unit["standard"]) }, "housing_benefit_permitted_work_disregard": {year: 0}, - "housing_benefit_specified_or_temporary_accommodation_disregard": { - year: unit["accommodation"] - }, "housing_benefit_on_passporting_benefit": {year: False}, "housing_benefit_pension_age_regulations_apply": { year: unit["pension_age"] @@ -295,8 +306,20 @@ def simulation(units, year, previous=False, tax_benefit_system=None): "housing_benefit_maintenance_disregard": {year: 0}, "housing_benefit_widowed_parents_allowance_income": {year: 0}, } + family = benunits[f"family_{index}"] + if dated_accommodation: + family.update( + in_specified_or_temporary_accommodation={year: unit["specified"]}, + housing_benefit_applicable_amount={year: unit["applicable_amount"]}, + benunit_rent={year: RENT}, + LHA_eligible={year: False}, + housing_benefit_meals_deduction={year: 0}, + housing_benefit_non_dep_deductions={year: 0}, + ) + else: + family[ACCOMMODATION] = {year: unit["accommodation"]} if unit["supplied"] is not None: - benunits[f"family_{index}"][CHILDCARE] = {year: unit["supplied"]} + family[CHILDCARE] = {year: unit["supplied"]} households[f"household_{index}"] = { "members": members, "region": {year: unit["region"]}, diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py new file mode 100644 index 0000000000..1e7b376aee --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -0,0 +1,300 @@ +"""Housing Benefit WTC disregard within accommodation-disregard segments. + +SI 2026/753 reg 1(1) brings the Sch 4 para 18 accommodation disregard into +force on 5 October 2026, and SI 2026/978 reg 2(2) adds it to the amounts +para 17(3)(a) counts. The model therefore settles para 17 separately before +and after that date, and Sch 5 para 56 disregards WTC "except in a case which +falls under" para 17(1), so each segment has its own WTC disregard. In law +the two disregards coexist only under a reform that keeps tax credits after +5 April 2025. + +For every generated population in 2026-27, with or without tax credits, the +award equals the independent statutory calculation made within each +segment and combined by days, and no segment gives a benefit unit both the +additional earnings disregard and a positive WTC disregard. The annual WTC +disregard combines the segments' amounts. Where para 56 applies in no +segment, the award equals the previous path's, with the new disregard set to +zero; under current law that holds for every family. +""" + +import numpy as np +import pytest +from hypothesis import example, given +from hypothesis import strategies as st +from policyengine_core.periods import period as period_ +from policyengine_core.reforms import Reform + +from policyengine_uk.system import system +from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( + PROPERTY_SETTINGS, + RENT, + TOLERANCE, + case, + families, + legal_components, + simulation, + without_wtc_reservation, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( + hb_segment_deductions, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( + hb_accommodation_segments, +) + + +YEAR = 2026 +# 6 April to 4 October 2026, then 5 October 2026 to 5 April 2027. +SEGMENT_DAYS = (182, 183) +# Sch 4 para 18(2)(a)(ii) and (b)(ii): a single claimant or lone parent +# aged 25 or over. +FULL_ACCOMMODATION = 77.73 * 52 +# SSCBA 1992 s.130(3)(b) and SI 2006/213 reg 71. +WITHDRAWAL_RATE = 0.65 + + +class keep_tax_credits(Reform): + def apply(self): + def modify(parameters): + parameters.gov.dwp.tax_credits.active.update( + period="year:2026:2", value=True + ) + return parameters + + self.modify_parameters(modify) + + +TAX_CREDITS = keep_tax_credits(system) +SYSTEMS = {True: TAX_CREDITS, False: system} +PREVIOUS = { + True: without_wtc_reservation(TAX_CREDITS), + False: without_wtc_reservation(system), +} + + +def legal_segments(unit, active): + """The statutory components in each segment of 2026-27.""" + segments = [] + for in_force in (False, True): + applies = ( + in_force + and unit["specified"] + and unit["net"] > 0 + and not unit["pension_age"] + ) + segment = {**unit, "accommodation": FULL_ACCOMMODATION if applies else 0} + segments.append(legal_components(segment, YEAR, active)) + return segments + + +def legal_award(unit, active): + """Reg 71 within each segment, then the awards combined by days.""" + awards = [ + max( + 0, + RENT + - WITHDRAWAL_RATE * max(0, segment["income"] - unit["applicable_amount"]), + ) + for segment in legal_segments(unit, active) + ] + return sum(days * award for days, award in zip(SEGMENT_DAYS, awards)) / 365 + + +def segmented(units, active, previous=False): + systems = PREVIOUS if previous else SYSTEMS + return simulation( + units, YEAR, tax_benefit_system=systems[active], dated_accommodation=True + ) + + +def model_segments(sim): + """The earnings disregard, WTC disregard and childcare deduction the + model applies in each segment, with the capped accommodation amount.""" + benunit = sim.populations["benunit"] + year = period_(YEAR) + parameters = sim.tax_benefit_system.parameters + net = np.maximum(sim.calculate("housing_benefit_net_earnings", YEAR), 0) + standard = sim.calculate( + "housing_benefit_applied_standard_earnings_disregard", YEAR + ) + result = [] + for accommodation, share in hb_accommodation_segments(benunit, year, parameters): + disregard, reserve, childcare = hb_segment_deductions( + benunit, year, parameters, accommodation + ) + capped = np.minimum(np.maximum(accommodation, 0), np.maximum(net - standard, 0)) + result.append( + dict( + share=share, + additional=np.asarray(disregard - standard - capped, dtype=float), + reserve=np.asarray(reserve, dtype=float), + ) + ) + return result + + +def review_case(**overrides): + """A single claimant aged 40 in specified accommodation with no + childcare or other income, and a nil applicable amount.""" + return case( + **{ + "net": 500, + "standard": 260, + "childcare": 0, + "children": 0, + "wtc": 2_000, + "specified": True, + **overrides, + } + ) + + +@st.composite +def segment_families(draw, supplied=False): + return { + **draw(families(supplied)), + "specified": draw(st.booleans()), + "applicable_amount": draw(st.sampled_from([0, 2_000, 5_000])), + } + + +@st.composite +def segment_populations(draw): + supplied = draw(st.booleans()) + return draw(st.lists(segment_families(supplied), min_size=1, max_size=8)) + + +SEGMENT_EDGE_CASES = [ + review_case(), + review_case(net=2_000), + review_case(net=4_000), + review_case(net=2_000, applicable_amount=2_000), + review_case(net=8_000), + review_case(net=2_000, specified=False), + review_case(net=2_000, worker=False), + review_case(net=2_000, pension_age=True), + case(specified=True), + case(specified=True, net=8_000, wtc=500), +] +SUPPLIED_SEGMENT_EDGE_CASES = [ + {**unit, "supplied": value} + for unit, value in zip(SEGMENT_EDGE_CASES, [0, 0, 100, 0, 1_000, 0, 0, 0, 0, 3_900]) +] + + +def test_review_scenario_keeps_the_wtc_disregard_in_both_segments(): + sim = segmented([review_case()], active=True) + # 500 < 260 + 889.20 before 5 October, and 500 < 260 + 240 + 889.20 + # after it, so para 56 disregards 889.20 of WTC in both segments. + # Income before deductions is 500 + 2,000 = 2,500. + # Before: 10,400 - 0.65 * (2,500 - 260 - 889.20) = 9,521.98. + # After: 10,400 - 0.65 * (2,500 - 500 - 889.20) = 9,677.98. + # (182 * 9,521.98 + 183 * 9,677.98) / 365 = 9,600.19. + assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( + 889.20, abs=TOLERANCE + ) + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + 9_600.19, abs=TOLERANCE + ) + + +@pytest.mark.parametrize( + "net,applicable_amount,award", + [ + # Before 5 October, 2,000 >= 260 + 889.20: para 17(1) applies and + # para 56 does not, so income is 4,000 - 1,149.20 = 2,850.80 and the + # award 8,546.98. After it, 2,000 < 260 + 1,740 + 889.20: para 56 + # disregards 889.20, income is 4,000 - 2,000 - 889.20 = 1,110.80 and + # the award 9,677.98. (182 * 8,546.98 + 183 * 9,677.98) / 365. + (2_000, 0, 9_114.03), + # The same incomes against a 2,000 applicable amount: 10,400 - 0.65 + # * 850.80 = 9,846.98 before, and the full 10,400 after. + (2_000, 2_000, 10_124.25), + # Before: 6,000 - 1,149.20 = 4,850.80, award 7,246.98. After: 4,000 + # < 260 + 3,740 + 889.20, so 6,000 - 4,000 - 889.20 = 1,110.80 and + # 9,677.98. (182 * 7,246.98 + 183 * 9,677.98) / 365. + (4_000, 0, 8_465.81), + ], +) +def test_each_segment_settles_paragraph_56_with_its_own_earnings_test( + net, applicable_amount, award +): + """A WTC disregard settled once for the year, from the annual + accommodation amount, would give 9,402.23, 10,400 and 8,176.03: it + grants both additional disregards before 5 October at 2,000, and none + after it at 4,000.""" + unit = review_case(net=net, applicable_amount=applicable_amount) + sim = segmented([unit], active=True) + before, after = model_segments(sim) + assert before["reserve"][0] == 0 + assert before["additional"][0] == pytest.approx(889.20, abs=TOLERANCE) + assert after["reserve"][0] == pytest.approx(889.20, abs=TOLERANCE) + assert after["additional"][0] == pytest.approx(0, abs=TOLERANCE) + # The annual amount combines the segments: 889.20 * 183 / 365. + assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( + 445.82, abs=TOLERANCE + ) + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +def test_supplied_annual_wtc_disregard_applies_in_every_segment(): + sim = segmented([review_case(net=2_000)], active=True) + sim.set_input("housing_benefit_wtc_disregard", YEAR, [0]) + # Before: 10,400 - 0.65 * 2,850.80 = 8,546.98. After: 10,400 - 0.65 * + # (4,000 - 2,000) = 9,100. (182 * 8,546.98 + 183 * 9,100) / 365. + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + 8_824.25, abs=TOLERANCE + ) + + +@PROPERTY_SETTINGS +@given(units=segment_populations(), active=st.booleans()) +@example(units=SEGMENT_EDGE_CASES, active=True) +@example(units=SEGMENT_EDGE_CASES, active=False) +@example(units=SUPPLIED_SEGMENT_EDGE_CASES, active=True) +def test_segmented_award_equals_the_regulations_with_one_additional_disregard( + units, active +): + sim = segmented(units, active) + award = sim.calculate("housing_benefit_entitlement", YEAR) + np.testing.assert_allclose( + award, [legal_award(unit, active) for unit in units], rtol=0, atol=TOLERANCE + ) + segments = model_segments(sim) + for segment in segments: + both = (segment["additional"] > TOLERANCE) & (segment["reserve"] > TOLERANCE) + assert not both.any(), [unit for unit, b in zip(units, both) if b] + np.testing.assert_allclose( + sim.calculate("housing_benefit_wtc_disregard", YEAR), + sum(segment["share"] * segment["reserve"] for segment in segments), + rtol=0, + atol=TOLERANCE, + ) + + +@PROPERTY_SETTINGS +@given(units=segment_populations(), active=st.booleans()) +@example(units=SEGMENT_EDGE_CASES, active=True) +@example(units=SEGMENT_EDGE_CASES, active=False) +@example(units=SUPPLIED_SEGMENT_EDGE_CASES, active=False) +def test_segmented_previous_path_agrees_where_paragraph_56_does_not_apply( + units, active +): + unchanged = [ + unit + for unit in units + if all(segment["reserve"] == 0 for segment in legal_segments(unit, active)) + ] + if not active: + assert len(unchanged) == len(units) + supplied = units[0]["supplied"] is not None + unchanged.append(review_case(net=8_000, supplied=0 if supplied else None)) + current = segmented(unchanged, active).calculate( + "housing_benefit_entitlement", YEAR + ) + previous = segmented(unchanged, active, previous=True).calculate( + "housing_benefit_entitlement", YEAR + ) + np.testing.assert_allclose(current, previous, rtol=0, atol=TOLERANCE) diff --git a/policyengine_uk/utils/supplied_inputs.py b/policyengine_uk/utils/supplied_inputs.py index c6f81f512b..e4b34e1496 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -67,6 +67,7 @@ "housing_benefit_applicable_income_disregard", "housing_benefit_childcare_earnings_limit", "housing_benefit_specified_or_temporary_accommodation_disregard", + "housing_benefit_wtc_disregard", "in_HE", "other_local_bus_trips", "pip_dl_category", diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index f98756fd01..e98b991cbf 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -1,65 +1,55 @@ from policyengine_uk.model_api import * from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( hb_capped_childcare_charges, - housing_benefit_applicable_income_childcare_element, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( hb_childcare_earnings_limit, hb_standard_earnings_disregard, - housing_benefit_childcare_earnings_limit, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, hb_uses_annual_override, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( + hb_covers_additional_disregard, + hb_fixed_childcare_deduction, + hb_segment_wtc_disregard, +) def hb_segment_deductions(benunit, period, parameters, accommodation): - """Apply childcare/earnings limits to one full accommodation amount.""" + """Apply childcare/earnings limits to one full accommodation amount. + Return the earnings disregard, the WTC disregard and the childcare + deduction.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) accommodation = min_(max_(accommodation, 0), max_(net - standard, 0)) - childcare_name = "housing_benefit_applicable_income_childcare_element" - if hb_uses_annual_override( - benunit, - period, - childcare_name, - housing_benefit_applicable_income_childcare_element.formula, - ): - childcare = benunit(childcare_name, period) - else: - limit_name = "housing_benefit_childcare_earnings_limit" - if hb_uses_annual_override( - benunit, - period, - limit_name, - housing_benefit_childcare_earnings_limit.formula, - ): - childcare_limit = benunit(limit_name, period) - else: - childcare_limit = hb_childcare_earnings_limit( - benunit, period, accommodation=accommodation - ) + wtc_disregard = hb_segment_wtc_disregard(benunit, period, parameters, accommodation) + childcare = hb_fixed_childcare_deduction(benunit, period, parameters) + if childcare is None: childcare = min_( - hb_capped_childcare_charges(benunit, period, parameters), childcare_limit + hb_capped_childcare_charges(benunit, period, parameters), + hb_childcare_earnings_limit( + benunit, + period, + accommodation=accommodation, + wtc_disregard=wtc_disregard, + ), ) name = "housing_benefit_applicable_income_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_applicable_income_disregard.formula ): - return benunit(name, period), childcare + return benunit(name, period), wtc_disregard, childcare p = parameters(period).gov.dwp.housing_benefit.means_test.income_disregard - additional_amount = p.worker * WEEKS_IN_YEAR - # Compare in pence, including equality at a float32 earnings boundary. - covers_additional = np.round(net.astype(float), 2) >= np.round( - (standard + accommodation + childcare + additional_amount).astype(float), 2 - ) additional = where( benunit( "meets_housing_benefit_additional_earnings_disregard_conditions", period ) - & covers_additional, - additional_amount, + & hb_covers_additional_disregard( + benunit, period, parameters, accommodation, childcare + ), + p.worker * WEEKS_IN_YEAR, 0, ) disregard = where( @@ -67,7 +57,7 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): net, standard + accommodation + additional, ) - return disregard, childcare + return disregard, wtc_disregard, childcare class housing_benefit_applicable_income_disregard(Variable): diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index b852d77929..9b555fc27f 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -6,8 +6,12 @@ def hb_standard_earnings_disregard(benunit, period): return benunit("housing_benefit_applied_standard_earnings_disregard", period) -def hb_childcare_earnings_limit(benunit, period, accommodation=None): - """Remaining earnings and tax credits, without an additional-disregard loop.""" +def hb_childcare_earnings_limit( + benunit, period, accommodation=None, wtc_disregard=None +): + """Remaining earnings and tax credits, without an additional-disregard loop. + By default the accommodation and WTC disregards are the annual variables; + an accommodation segment passes its own.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) if accommodation is None: @@ -17,11 +21,11 @@ def hb_childcare_earnings_limit(benunit, period, accommodation=None): accommodation = min_(max_(accommodation, 0), max_(0, net - standard)) # Reg 40(2) and Sch 5 para 56 disregard WTC before reg 27(1)(c) # deducts childcare. Only the remaining WTC/CTC can fund those charges. - credits = max_( - benunit("working_tax_credit", period) - - benunit("housing_benefit_wtc_disregard", period), - 0, - ) + max_(benunit("child_tax_credit", period), 0) + if wtc_disregard is None: + wtc_disregard = benunit("housing_benefit_wtc_disregard", period) + credits = max_(benunit("working_tax_credit", period) - wtc_disregard, 0) + max_( + benunit("child_tax_credit", period), 0 + ) return max_(0, net - standard - accommodation) + credits diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index 5e0f589f2b..05cfcaec7d 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -1,80 +1,84 @@ from policyengine_uk.model_api import * -from policyengine_uk.utils.supplied_inputs import supplied_input from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( hb_capped_childcare_charges, housing_benefit_applicable_income_childcare_element, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + hb_standard_earnings_disregard, housing_benefit_childcare_earnings_limit, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( + hb_accommodation_segments, + hb_uses_annual_override, +) -def hb_childcare_deduction_replaced(benunit, period): - """Whether the childcare deduction differs from the model's own - calculation: it, or the limit it reads, is supplied (by a dataset, - set_input or a scenario), neutralized, or calculated by a formula a - reform put in place of the model's.""" - system = benunit.simulation.tax_benefit_system - for model_variable in ( - housing_benefit_applicable_income_childcare_element, - housing_benefit_childcare_earnings_limit, - ): - name = model_variable.__name__ - variable = system.get_variable(name) - formula = variable.get_formula(period) - if ( - variable.is_neutralized - or formula is None - or formula.__code__ != model_variable.formula.__code__ - or supplied_input(benunit, name, period) is not None - ): - return True - return False +def hb_fixed_childcare_deduction(benunit, period, parameters): + """The annual childcare deduction where it, or the limit it reads, is + supplied (by a dataset, set_input or a scenario), neutralized or + calculated by a formula a reform put in place of the model's. Otherwise + None: each accommodation segment calculates its own deduction.""" + childcare = housing_benefit_applicable_income_childcare_element + if hb_uses_annual_override(benunit, period, childcare.__name__, childcare.formula): + return benunit(childcare.__name__, period) + limit = housing_benefit_childcare_earnings_limit + if hb_uses_annual_override(benunit, period, limit.__name__, limit.formula): + return min_( + hb_capped_childcare_charges(benunit, period, parameters), + benunit(limit.__name__, period), + ) + return None + + +def hb_covers_additional_disregard( + benunit, period, parameters, accommodation, childcare +): + """Sch 4 para 17(1), (3): whether net earnings at least equal the other + earnings disregards, the childcare deduction and the additional amount, + compared in pence, including equality at a float32 earnings boundary. + Capping the accommodation amount at the earnings the standard disregard + leaves does not change the answer: where the cap binds, those + disregards take all the earnings, which then cannot also cover the + additional amount.""" + net = benunit("housing_benefit_net_earnings", period) + standard = hb_standard_earnings_disregard(benunit, period) + p = parameters(period).gov.dwp.housing_benefit.means_test.income_disregard + additional = p.worker * WEEKS_IN_YEAR + return np.round(net.astype(float), 2) >= np.round( + (standard + accommodation + childcare + additional).astype(float), 2 + ) -def hb_wtc_disregard(benunit, period, parameters, accommodation=None): - """WTC disregarded under Sch 5 para 56, given the full accommodation - amount (by default the annual variable).""" +def hb_wtc_disregard(benunit, period, parameters, accommodation): + """WTC disregarded under Sch 5 para 56 where the accommodation disregard + has this full annual amount.""" p = parameters(period).gov.dwp if not p.tax_credits.active: return benunit.empty_array() - net = benunit("housing_benefit_net_earnings", period) - standard = benunit("housing_benefit_applied_standard_earnings_disregard", period) - # Para 18 takes only the earnings the other disregards leave, but a cap - # would not change this test: where it binds, earnings fall short of the - # additional amount anyway. - if accommodation is None: - accommodation = benunit( - "housing_benefit_specified_or_temporary_accommodation_disregard", period - ) - additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR - # Sch 4 para 17(3)(b) counts the deductible childcare, which reg - # 27(1)(c) takes from earnings and then from the credits this disregard - # reduces. With the model's own deduction, the lesser of the capped - # charge and the earnings and tax-credit limit, the whole capped charge - # gives the same answer: if earnings cover it and the additional amount, - # the whole charge fits within earnings; if not, a deduction the limit - # caps takes at least all remaining earnings, so the test fails whatever - # credits remain. That holds only for that formula. A supplied, - # neutralized or replaced deduction or limit can differ, so the test - # then reads the deduction the earnings disregard reads. A replacement - # that itself reads the limit depends on this disregard, and the engine - # stops with a circular-definition error. - if hb_childcare_deduction_replaced(benunit, period): - childcare = benunit( - "housing_benefit_applicable_income_childcare_element", period - ) - else: + # Sch 4 para 17(3)(b) counts the childcare charges deductible under reg + # 27(1)(c), which come from the earnings left and then from the credits + # this disregard reduces, so that deduction depends on this disregard. + # Where the model calculates the deduction, the whole capped charge + # settles para 17 instead. That gives the same answer only for the + # model's formula, the lesser of the capped charge and the earnings and + # tax-credit limit: if earnings cover the whole charge and the + # additional amount, they cover any smaller deduction; if not, either + # the deduction is the whole charge, or the limit caps it and it takes + # at least all the earnings left, so para 17 fails whatever credits + # remain. Where the deduction or its limit is supplied, neutralized or + # replaced, the two can differ, so the test reads the deduction the + # earnings disregard reads. A replacement deduction that itself reads + # the limit depends on this disregard, and the engine stops with a + # circular-definition error. + childcare = hb_fixed_childcare_deduction(benunit, period, parameters) + if childcare is None: childcare = hb_capped_childcare_charges(benunit, period, parameters) - covers_additional = np.round(net.astype(float), 2) >= np.round( - (standard + accommodation + childcare + additional).astype(float), 2 - ) - applies = ( - benunit( - "meets_housing_benefit_additional_earnings_disregard_conditions", period - ) - & ~covers_additional + applies = benunit( + "meets_housing_benefit_additional_earnings_disregard_conditions", period + ) & ~hb_covers_additional_disregard( + benunit, period, parameters, accommodation, childcare ) + additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR return where( applies, min_(max_(benunit("working_tax_credit", period), 0), additional), @@ -82,6 +86,17 @@ def hb_wtc_disregard(benunit, period, parameters, accommodation=None): ) +def hb_segment_wtc_disregard(benunit, period, parameters, accommodation): + """The WTC disregard in one accommodation segment. A supplied, + neutralized or replaced annual amount applies in every segment.""" + name = "housing_benefit_wtc_disregard" + if hb_uses_annual_override( + benunit, period, name, housing_benefit_wtc_disregard.formula + ): + return benunit(name, period) + return hb_wtc_disregard(benunit, period, parameters, accommodation) + + class housing_benefit_wtc_disregard(Variable): value_type = float entity = BenUnit @@ -99,7 +114,10 @@ class housing_benefit_wtc_disregard(Variable): "childcare deduction or its limit is supplied, neutralized or " "replaced, the earnings test reads the same deduction as the " "earnings disregard, so the two additional disregards never both " - "apply." + "apply. Where the accommodation disregard starts within the fiscal " + "year, each effective-date segment has its own earnings test, as " + "the earnings disregard does; this annual amount combines the " + "segments' disregards, and entitlement deducts each segment's own." ) reference = ( "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", @@ -110,7 +128,13 @@ class housing_benefit_wtc_disregard(Variable): "https://www.legislation.gov.uk/nisr/2006/406/schedule/6/paragraph/22", "https://www.legislation.gov.uk/uksi/2020/371/regulation/5", "https://www.legislation.gov.uk/nisr/2020/53/regulation/5", + "https://www.legislation.gov.uk/uksi/2026/978/regulation/2", ) def formula(benunit, period, parameters): - return hb_wtc_disregard(benunit, period, parameters) + return sum( + hb_wtc_disregard(benunit, period, parameters, accommodation) * share + for accommodation, share in hb_accommodation_segments( + benunit, period, parameters + ) + ) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py index 84690e73aa..9bf79e518c 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py @@ -21,9 +21,10 @@ class housing_benefit_entitlement(Variable): "applies, the eligible rent is the maximum rent (LHA), which is the " "lower of the LHA rate and the rent, so the cap applies before the " "taper. When accommodation earnings disregards change within the " - "fiscal year, calculate income floors, childcare/earnings limits, " - "the income threshold, taper and zero-award floor separately in " - "each segment, then combine completed awards. Annual earnings, rent, " + "fiscal year, calculate income floors, the Working Tax Credit " + "disregard, childcare/earnings limits, the income threshold, taper " + "and zero-award floor separately in each segment, then combine " + "completed awards. Annual earnings, rent, " "ages and household status remain constant. Other parameters keep " "the model's annual convention. Supplied annual income/deductions " "and replacement formulas retain their normal override semantics. " @@ -55,6 +56,7 @@ class housing_benefit_entitlement(Variable): "https://www.legislation.gov.uk/uksi/2026/753/regulation/1", "https://www.legislation.gov.uk/uksi/2026/978/regulation/2", "https://www.legislation.gov.uk/nisr/2026/157/regulation/2", + "https://www.legislation.gov.uk/uksi/2006/213/schedule/5/paragraph/56", ) def formula(benunit, period, parameters): @@ -103,13 +105,18 @@ def formula(benunit, period, parameters): ) | benunit("housing_benefit_on_passporting_benefit", period) annual_award = benunit.empty_array() for accommodation, share in segments: - disregard, childcare = hb_segment_deductions( + disregard, wtc_disregard, childcare = hb_segment_deductions( benunit, period, parameters, accommodation ) + # Reg 40(2), Sch 5 para 56: each segment's own WTC disregard, + # as for the annual income. segment_income = where( retain_annual_income, income, - max_(0, income_before_deductions - disregard - childcare), + max_( + 0, + income_before_deductions - disregard - wtc_disregard - childcare, + ), ) taper = max_(0, segment_income - applicable_amount) * withdrawal_rate annual_award = annual_award + share * max_( From 084cb9fdc6a7bb0809168e011870fc721281402b Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 00:08:39 -0400 Subject: [PATCH 05/29] Flag any positive WTC disregard in the never-both checks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The WTC disregard is exactly nil where paragraph 56 does not apply, so the checks now count any positive amount rather than one above 2p. A pinned example gives earnings of £1,149.20, which cover the £260 standard disregard, a supplied nil deduction and the £889.20 additional amount exactly, with a 1p childcare charge and 1p of WTC. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_housing_benefit_wtc_disregard.py | 11 ++++++++++- .../test_housing_benefit_wtc_disregard_segments.py | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 7fcef89f61..4343d9df2c 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -361,7 +361,8 @@ def assert_one_additional_disregard(units, actual): [unit["accommodation"] for unit in units], net - standard ) additional = actual["earnings_disregard"] - standard - accommodation - both = (additional > TOLERANCE) & (actual["reserve"] > TOLERANCE) + # The WTC disregard is exactly nil where it does not apply. + both = (additional > TOLERANCE) & (actual["reserve"] > 0) assert not both.any(), [unit for unit, b in zip(units, both) if b] @@ -447,6 +448,14 @@ def test_wtc_disregard_is_bounded_and_does_not_stack_with_earnings(units, year): @PROPERTY_SETTINGS @given(units=SUPPLIED_POPULATIONS, year=st.sampled_from(YEARS)) @example(units=[case(supplied=0)], year=2024) +# Earnings of 1,149.20 cover the 260 standard disregard, the supplied nil +# deduction and the 889.20 additional amount exactly, but not a 1p charge. +@example( + units=[ + case(net=1_149.20, standard=260, childcare=1, children=1, wtc=0.01, supplied=0) + ], + year=2024, +) @example(units=SUPPLIED_EDGE_CASES, year=2024) def test_additional_earnings_and_wtc_disregards_never_both_apply(units, year): """Earnings, WTC, the standard and accommodation disregards and a diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index 1e7b376aee..a11a5de3da 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -264,7 +264,7 @@ def test_segmented_award_equals_the_regulations_with_one_additional_disregard( ) segments = model_segments(sim) for segment in segments: - both = (segment["additional"] > TOLERANCE) & (segment["reserve"] > TOLERANCE) + both = (segment["additional"] > TOLERANCE) & (segment["reserve"] > 0) assert not both.any(), [unit for unit, b in zip(units, both) if b] np.testing.assert_allclose( sim.calculate("housing_benefit_wtc_disregard", YEAR), From a07ed43d74290bb01adc29aaf6254ee2af79a9d5 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 00:17:09 -0400 Subject: [PATCH 06/29] Name the segment tests for what they check Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 2 +- ..._housing_benefit_wtc_disregard_segments.py | 36 ++++++++++--------- 2 files changed, 20 insertions(+), 18 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 4343d9df2c..0eee2a7132 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -135,7 +135,7 @@ def populations(draw): *(case(region=region) for region in REGIONS), ] SUPPLIED_EDGE_CASES = [ - # The review's case: earnings cover the supplied nil deduction. + # Earnings cover a supplied nil deduction and the additional amount. case(supplied=0), case(supplied=3_900), case(supplied=4_160), diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index a11a5de3da..73461aaf41 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -54,6 +54,8 @@ class keep_tax_credits(Reform): + """Keep tax credits in 2026-27, so the two disregards coexist.""" + def apply(self): def modify(parameters): parameters.gov.dwp.tax_credits.active.update( @@ -108,8 +110,8 @@ def segmented(units, active, previous=False): def model_segments(sim): - """The earnings disregard, WTC disregard and childcare deduction the - model applies in each segment, with the capped accommodation amount.""" + """Each segment's share of the year, additional earnings disregard and + WTC disregard, as the model applies them.""" benunit = sim.populations["benunit"] year = period_(YEAR) parameters = sim.tax_benefit_system.parameters @@ -119,7 +121,7 @@ def model_segments(sim): ) result = [] for accommodation, share in hb_accommodation_segments(benunit, year, parameters): - disregard, reserve, childcare = hb_segment_deductions( + disregard, reserve, _ = hb_segment_deductions( benunit, year, parameters, accommodation ) capped = np.minimum(np.maximum(accommodation, 0), np.maximum(net - standard, 0)) @@ -133,7 +135,7 @@ def model_segments(sim): return result -def review_case(**overrides): +def specified_claimant(**overrides): """A single claimant aged 40 in specified accommodation with no childcare or other income, and a nil applicable amount.""" return case( @@ -165,14 +167,14 @@ def segment_populations(draw): SEGMENT_EDGE_CASES = [ - review_case(), - review_case(net=2_000), - review_case(net=4_000), - review_case(net=2_000, applicable_amount=2_000), - review_case(net=8_000), - review_case(net=2_000, specified=False), - review_case(net=2_000, worker=False), - review_case(net=2_000, pension_age=True), + specified_claimant(), + specified_claimant(net=2_000), + specified_claimant(net=4_000), + specified_claimant(net=2_000, applicable_amount=2_000), + specified_claimant(net=8_000), + specified_claimant(net=2_000, specified=False), + specified_claimant(net=2_000, worker=False), + specified_claimant(net=2_000, pension_age=True), case(specified=True), case(specified=True, net=8_000, wtc=500), ] @@ -182,8 +184,8 @@ def segment_populations(draw): ] -def test_review_scenario_keeps_the_wtc_disregard_in_both_segments(): - sim = segmented([review_case()], active=True) +def test_wtc_disregard_applies_before_and_after_5_october(): + sim = segmented([specified_claimant()], active=True) # 500 < 260 + 889.20 before 5 October, and 500 < 260 + 240 + 889.20 # after it, so para 56 disregards 889.20 of WTC in both segments. # Income before deductions is 500 + 2,000 = 2,500. @@ -223,7 +225,7 @@ def test_each_segment_settles_paragraph_56_with_its_own_earnings_test( accommodation amount, would give 9,402.23, 10,400 and 8,176.03: it grants both additional disregards before 5 October at 2,000, and none after it at 4,000.""" - unit = review_case(net=net, applicable_amount=applicable_amount) + unit = specified_claimant(net=net, applicable_amount=applicable_amount) sim = segmented([unit], active=True) before, after = model_segments(sim) assert before["reserve"][0] == 0 @@ -240,7 +242,7 @@ def test_each_segment_settles_paragraph_56_with_its_own_earnings_test( def test_supplied_annual_wtc_disregard_applies_in_every_segment(): - sim = segmented([review_case(net=2_000)], active=True) + sim = segmented([specified_claimant(net=2_000)], active=True) sim.set_input("housing_benefit_wtc_disregard", YEAR, [0]) # Before: 10,400 - 0.65 * 2,850.80 = 8,546.98. After: 10,400 - 0.65 * # (4,000 - 2,000) = 9,100. (182 * 8,546.98 + 183 * 9,100) / 365. @@ -290,7 +292,7 @@ def test_segmented_previous_path_agrees_where_paragraph_56_does_not_apply( if not active: assert len(unchanged) == len(units) supplied = units[0]["supplied"] is not None - unchanged.append(review_case(net=8_000, supplied=0 if supplied else None)) + unchanged.append(specified_claimant(net=8_000, supplied=0 if supplied else None)) current = segmented(unchanged, active).calculate( "housing_benefit_entitlement", YEAR ) From 44825de594206d05d12fb16f6fcde4485bd33606 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 00:32:46 -0400 Subject: [PATCH 07/29] Name every amount the full-charge comparison covers Co-Authored-By: Claude Opus 5.5 --- .../applicable_income/housing_benefit_wtc_disregard.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index 05cfcaec7d..4a7782a917 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -61,11 +61,11 @@ def hb_wtc_disregard(benunit, period, parameters, accommodation): # Where the model calculates the deduction, the whole capped charge # settles para 17 instead. That gives the same answer only for the # model's formula, the lesser of the capped charge and the earnings and - # tax-credit limit: if earnings cover the whole charge and the - # additional amount, they cover any smaller deduction; if not, either - # the deduction is the whole charge, or the limit caps it and it takes - # at least all the earnings left, so para 17 fails whatever credits - # remain. Where the deduction or its limit is supplied, neutralized or + # tax-credit limit: if earnings cover the other disregards, the whole + # charge and the additional amount, they cover any smaller deduction; if + # not, either the deduction is the whole charge, or the limit caps it and + # it takes at least all the earnings left, so para 17 fails whatever + # credits remain. Where the deduction or its limit is supplied, neutralized or # replaced, the two can differ, so the test reads the deduction the # earnings disregard reads. A replacement deduction that itself reads # the limit depends on this disregard, and the engine stops with a From d1d8b3796f0b7a0bf1524dfb57feab05b88fd121 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 00:35:11 -0400 Subject: [PATCH 08/29] Cite DWP's guidance on which credits meet childcare charges Co-Authored-By: Claude Opus 5.5 --- .../housing_benefit_childcare_earnings_limit.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index 9b555fc27f..3f087fbd57 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -20,7 +20,9 @@ def hb_childcare_earnings_limit( ) accommodation = min_(max_(accommodation, 0), max_(0, net - standard)) # Reg 40(2) and Sch 5 para 56 disregard WTC before reg 27(1)(c) - # deducts childcare. Only the remaining WTC/CTC can fund those charges. + # deducts childcare. DWP BW2 W2.179-W2.182 lets WTC/CTC in payment, not + # other income, meet the charges earnings leave; only the WTC left after + # that disregard counts. Both amounts are benefit-unit payments. if wtc_disregard is None: wtc_disregard = benunit("housing_benefit_wtc_disregard", period) credits = max_(benunit("working_tax_credit", period) - wtc_disregard, 0) + max_( From ebed3303092d5a36d2975292b882909a145636a3 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 00:48:16 -0400 Subject: [PATCH 09/29] Test the pence comparison where float32 rounds earnings down MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Float32 stores £1,149.20 as £1,149.19995, so a plain float comparison would find that earnings fall short of the £260 standard disregard plus £889.20 and grant the WTC disregard instead of the additional earnings disregard. Co-Authored-By: Claude Opus 5.5 --- .../tests/test_housing_benefit_wtc_disregard.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 0eee2a7132..6ba24fa17d 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -519,6 +519,19 @@ def test_additional_earnings_threshold_includes_equality(offset): ) +@pytest.mark.parametrize("offset", [-0.01, 0, 0.01]) +def test_threshold_compares_pence_where_float32_rounds_down(offset): + """Float32 stores £1,149.20 as £1,149.19995. Sch 4 para 17(1) compares + pence, so earnings of £1,149.20 still cover the £260 standard disregard + and the £889.20 additional amount, and para 56 does not apply.""" + unit = case(net=1_149.20 + offset, standard=260, childcare=0, children=0) + actual = calculate([unit], 2024) + assert actual["reserve"][0] == (100 if offset < 0 else 0) + assert actual["earnings_disregard"][0] == pytest.approx( + 260 if offset < 0 else 1_149.20, abs=TOLERANCE + ) + + @pytest.mark.parametrize("year", YEARS) def test_wtc_disregard_honours_the_historical_amount_and_cessation(year): unit = case(net=500, standard=260, childcare=0, children=0, wtc=2_000) From 36398c81bfc911a3ba2f56ed4810090f8344560d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 01:06:09 -0400 Subject: [PATCH 10/29] Supply the childcare limit as well as the deduction in the properties MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The populations now supply the earnings and tax-credit limit as well as the deduction, and the statutory oracle caps the deduction at the charge under a supplied limit. A pinned case gives a £10,000 limit against a £4,160 charge: the deduction stays at £4,160, the additional earnings disregard applies, and paragraph 56 does not. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 85 +++++++++++++++---- ..._housing_benefit_wtc_disregard_segments.py | 25 ++++-- 2 files changed, 87 insertions(+), 23 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 6ba24fa17d..d538ce29ef 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -70,6 +70,7 @@ def case(**overrides): accommodation=0, childcare=4_160, supplied=None, + supplied_limit=None, children=1, wtc=100, ctc=0, @@ -90,13 +91,14 @@ def pounds(maximum): @st.composite -def families(draw, supplied=False): +def families(draw, supplied=False, supplied_limit=False): return case( net=draw(pounds(40_000)), standard=draw(st.sampled_from([260, 520, 1_040, 1_300])), accommodation=draw(st.one_of(st.just(0), pounds(6_500))), childcare=draw(pounds(25_000)), supplied=draw(pounds(25_000)) if supplied else None, + supplied_limit=draw(pounds(25_000)) if supplied_limit else None, children=draw(st.integers(0, 2)), wtc=draw(pounds(10_000)), ctc=draw(pounds(10_000)), @@ -109,14 +111,23 @@ def families(draw, supplied=False): @st.composite def populations(draw): - # A supplied deduction is set for the whole population, as a dataset - # column or a set_input call sets it. - supplied = draw(st.booleans()) - return draw(st.lists(families(supplied), min_size=1, max_size=12)) + # A dataset column or a set_input call supplies the deduction or its + # limit for the whole population. + supplied = draw(st.sampled_from([None, "deduction", "limit"])) + return draw( + st.lists( + families(supplied == "deduction", supplied == "limit"), + min_size=1, + max_size=12, + ) + ) POPULATIONS = populations() -SUPPLIED_POPULATIONS = st.lists(families(supplied=True), min_size=1, max_size=12) +SUPPLIED_POPULATIONS = st.one_of( + st.lists(families(supplied=True), min_size=1, max_size=12), + st.lists(families(supplied_limit=True), min_size=1, max_size=12), +) EDGE_CASES = [ case(), case(net=0), @@ -146,6 +157,17 @@ def populations(draw): case(childcare=25_000, children=2, supplied=100, wtc=5_000), case(worker=False, supplied=0), ] +SUPPLIED_LIMIT_EDGE_CASES = [ + # 8,000 >= 1,300 + 4,160 + 889.20: the deduction takes the capped + # charge, not the larger limit, and para 17(1) applies. + case(net=8_000, supplied_limit=10_000), + case(supplied_limit=0), + case(supplied_limit=4_000), + case(net=6_349.20, supplied_limit=4_160), + case(net=6_349.19, supplied_limit=9_000), + case(net=2_000, standard=260, accommodation=1_000, childcare=0, supplied_limit=0), + case(worker=False, supplied_limit=0), +] def legal_components(unit, year, active=None): @@ -167,7 +189,12 @@ def deduction(reserve): return unit["supplied"] # Reg 27(1)(c), (2): earnings, then the credits that remain after # the Sch 5 disregards. - return min(charge, earnings + unit["wtc"] - reserve + unit["ctc"]) + return min(charge, limit(reserve)) + + def limit(reserve): + if unit["supplied_limit"] is not None: + return unit["supplied_limit"] + return earnings + unit["wtc"] - reserve + unit["ctc"] def covers(reserve): # Sch 4 para 17(1), (3): the other disregards, the deductible @@ -185,7 +212,6 @@ def covers(reserve): assert not covers(reserve), "no consistent paragraph 17 outcome" additional = additional_amount if unit["worker"] and covers(reserve) else 0 childcare = deduction(reserve) - limit = earnings + unit["wtc"] - reserve + unit["ctc"] income = max( 0, net @@ -202,7 +228,7 @@ def covers(reserve): childcare=childcare, reserve=reserve, earnings_disregard=standard + accommodation + additional, - limit=limit, + limit=limit(reserve), income=income, ) @@ -230,8 +256,9 @@ def simulation( """Build the population. With ``dated_accommodation`` the model dates the accommodation disregard itself, and the population pays rent of ``RENT``; otherwise each unit supplies its annual accommodation amount.""" - supplied = [unit["supplied"] is not None for unit in units] - assert all(supplied) or not any(supplied), "supply the deduction for all" + for key in ("supplied", "supplied_limit"): + supplied = [unit[key] is not None for unit in units] + assert all(supplied) or not any(supplied), f"{key} for all or none" people, benunits, households = {}, {}, {} for index, unit in enumerate(units): adult = f"adult_{index}" @@ -320,6 +347,8 @@ def simulation( family[ACCOMMODATION] = {year: unit["accommodation"]} if unit["supplied"] is not None: family[CHILDCARE] = {year: unit["supplied"]} + if unit["supplied_limit"] is not None: + family[LIMIT] = {year: unit["supplied_limit"]} households[f"household_{index}"] = { "members": members, "region": {year: unit["region"]}, @@ -352,6 +381,14 @@ def calculate(units, year, previous=False): return results(simulation(units, year, previous), year) +def same_supply(units, amount): + """Supply ``amount`` as the population supplies its deduction or limit.""" + return { + key: None if units[0][key] is None else amount + for key in ("supplied", "supplied_limit") + } + + def assert_one_additional_disregard(units, actual): """The additional earnings disregard and a positive WTC disregard never both apply to a benefit unit.""" @@ -418,6 +455,7 @@ def test_savings_credit_only_uses_the_corrected_childcare_modification(region): @example(units=EDGE_CASES, year=2020) @example(units=EDGE_CASES, year=2025) @example(units=SUPPLIED_EDGE_CASES, year=2024) +@example(units=SUPPLIED_LIMIT_EDGE_CASES, year=2024) def test_assessed_income_equals_and_never_falls_below_the_regulations(units, year): actual = calculate(units, year) expected = [legal_components(unit, year) for unit in units] @@ -457,10 +495,11 @@ def test_wtc_disregard_is_bounded_and_does_not_stack_with_earnings(units, year): year=2024, ) @example(units=SUPPLIED_EDGE_CASES, year=2024) +@example(units=SUPPLIED_LIMIT_EDGE_CASES, year=2024) def test_additional_earnings_and_wtc_disregards_never_both_apply(units, year): """Earnings, WTC, the standard and accommodation disregards and a - supplied childcare deduction never give a benefit unit both additional - disregards.""" + supplied childcare deduction or limit never give a benefit unit both + additional disregards.""" assert_one_additional_disregard(units, calculate(units, year)) @@ -471,14 +510,13 @@ def test_additional_earnings_and_wtc_disregards_never_both_apply(units, year): @example(units=SUPPLIED_EDGE_CASES, year=2024) def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): unchanged = [unit for unit in units if legal_components(unit, year)["reserve"] == 0] - supplied = units[0]["supplied"] is not None # Always include a work-condition failure, no WTC, and sufficient # earnings, so every population exercises the differential check. unchanged.extend( [ - case(worker=False, supplied=0 if supplied else None), - case(wtc=0, supplied=3_000 if supplied else None), - case(net=20_000, childcare=1_000, supplied=1_000 if supplied else None), + case(worker=False, **same_supply(units, 0)), + case(wtc=0, **same_supply(units, 3_000)), + case(net=20_000, childcare=1_000, **same_supply(units, 1_000)), ] ) actual = calculate(unchanged, year) @@ -584,6 +622,19 @@ def test_supplied_childcare_deduction_keeps_one_additional_disregard(): assert actual["income"][0] == pytest.approx(3_110.80, abs=TOLERANCE) +def test_supplied_limit_above_the_charge_leaves_the_capped_charge(): + sim = simulation([case(net=8_000)], 2024) + sim.set_input(LIMIT, 2024, [10_000]) + actual = results(sim, 2024) + # Reg 27(1)(c), (3): the deduction stops at the 4,160 charge, and + # 8,000 >= 1,300 + 4,160 + 889.20, so para 17(1) applies and para 56 + # does not: 8,000 + 100 - 2,189.20 - 4,160. + assert actual["childcare"][0] == pytest.approx(4_160, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx(2_189.20, abs=TOLERANCE) + assert actual["reserve"][0] == 0 + assert actual["income"][0] == pytest.approx(1_750.80, abs=TOLERANCE) + + def test_supplied_childcare_limit_keeps_one_additional_disregard(): sim = simulation([case()], 2024) sim.set_input(LIMIT, 2024, [0]) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index 73461aaf41..7f673591b0 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -32,6 +32,7 @@ case, families, legal_components, + same_supply, simulation, without_wtc_reservation, ) @@ -152,9 +153,9 @@ def specified_claimant(**overrides): @st.composite -def segment_families(draw, supplied=False): +def segment_families(draw, supplied=False, supplied_limit=False): return { - **draw(families(supplied)), + **draw(families(supplied, supplied_limit)), "specified": draw(st.booleans()), "applicable_amount": draw(st.sampled_from([0, 2_000, 5_000])), } @@ -162,8 +163,14 @@ def segment_families(draw, supplied=False): @st.composite def segment_populations(draw): - supplied = draw(st.booleans()) - return draw(st.lists(segment_families(supplied), min_size=1, max_size=8)) + supplied = draw(st.sampled_from([None, "deduction", "limit"])) + return draw( + st.lists( + segment_families(supplied == "deduction", supplied == "limit"), + min_size=1, + max_size=8, + ) + ) SEGMENT_EDGE_CASES = [ @@ -182,6 +189,12 @@ def segment_populations(draw): {**unit, "supplied": value} for unit, value in zip(SEGMENT_EDGE_CASES, [0, 0, 100, 0, 1_000, 0, 0, 0, 0, 3_900]) ] +SUPPLIED_LIMIT_SEGMENT_EDGE_CASES = [ + {**unit, "supplied_limit": value} + for unit, value in zip( + SEGMENT_EDGE_CASES, [0, 10_000, 100, 0, 1_000, 0, 0, 0, 10_000, 3_900] + ) +] def test_wtc_disregard_applies_before_and_after_5_october(): @@ -256,6 +269,7 @@ def test_supplied_annual_wtc_disregard_applies_in_every_segment(): @example(units=SEGMENT_EDGE_CASES, active=True) @example(units=SEGMENT_EDGE_CASES, active=False) @example(units=SUPPLIED_SEGMENT_EDGE_CASES, active=True) +@example(units=SUPPLIED_LIMIT_SEGMENT_EDGE_CASES, active=True) def test_segmented_award_equals_the_regulations_with_one_additional_disregard( units, active ): @@ -291,8 +305,7 @@ def test_segmented_previous_path_agrees_where_paragraph_56_does_not_apply( ] if not active: assert len(unchanged) == len(units) - supplied = units[0]["supplied"] is not None - unchanged.append(specified_claimant(net=8_000, supplied=0 if supplied else None)) + unchanged.append(specified_claimant(net=8_000, **same_supply(units, 0))) current = segmented(unchanged, active).calculate( "housing_benefit_entitlement", YEAR ) From 29f52ca2cba8e2ec804b464031d357ee59d17226 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 01:39:38 -0400 Subject: [PATCH 11/29] Test the childcare limit with each segment's own WTC disregard MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After 5 October a lone parent with £8,000 of earnings, £3,000 of other income, £2,000 of WTC and a £4,160 charge has paragraph 56 disregard £889.20, so childcare can draw on only £3,768.84. The award comes to £7,266.74; a limit read with the day-weighted annual WTC disregard would give £7,394.21. Co-Authored-By: Claude Opus 5.5 --- ..._housing_benefit_wtc_disregard_segments.py | 26 +++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index 7f673591b0..c7e33fe086 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -184,15 +184,18 @@ def segment_populations(draw): specified_claimant(net=2_000, pension_age=True), case(specified=True), case(specified=True, net=8_000, wtc=500), + case(specified=True, net=8_000, wtc=2_000, other=3_000), ] SUPPLIED_SEGMENT_EDGE_CASES = [ {**unit, "supplied": value} - for unit, value in zip(SEGMENT_EDGE_CASES, [0, 0, 100, 0, 1_000, 0, 0, 0, 0, 3_900]) + for unit, value in zip( + SEGMENT_EDGE_CASES, [0, 0, 100, 0, 1_000, 0, 0, 0, 0, 3_900, 3_000] + ) ] SUPPLIED_LIMIT_SEGMENT_EDGE_CASES = [ {**unit, "supplied_limit": value} for unit, value in zip( - SEGMENT_EDGE_CASES, [0, 10_000, 100, 0, 1_000, 0, 0, 0, 10_000, 3_900] + SEGMENT_EDGE_CASES, [0, 10_000, 100, 0, 1_000, 0, 0, 0, 10_000, 3_900, 3_000] ) ] @@ -254,6 +257,25 @@ def test_each_segment_settles_paragraph_56_with_its_own_earnings_test( ) +def test_each_segment_limits_childcare_with_its_own_wtc_disregard(): + """A lone parent aged 40 in specified accommodation earns £8,000, has + £3,000 of other income and £2,000 of WTC, and pays £4,160 for + childcare. Income before deductions is £13,000.""" + unit = case(specified=True, net=8_000, wtc=2_000, other=3_000) + sim = segmented([unit], active=True) + # Before 5 October, 8,000 >= 1,300 + 4,160 + 889.20, so para 17(1) + # applies: income is 13,000 - 2,189.20 - 4,160 = 6,650.80, and the + # award 10,400 - 0.65 * 6,650.80 = 6,076.98. After it, 8,000 < 1,300 + + # 4,041.96 + 4,160 + 889.20, so para 56 disregards 889.20. Childcare + # then draws on 8,000 - 1,300 - 4,041.96 = 2,658.04 of earnings and + # 2,000 - 889.20 = 1,110.80 of WTC, 3,768.84 in all: income is 13,000 - + # 5,341.96 - 889.20 - 3,768.84 = 3,000, and the award 8,450. + # (182 * 6,076.98 + 183 * 8,450) / 365 = 7,266.74. + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + 7_266.74, abs=TOLERANCE + ) + + def test_supplied_annual_wtc_disregard_applies_in_every_segment(): sim = segmented([specified_claimant(net=2_000)], active=True) sim.set_input("housing_benefit_wtc_disregard", YEAR, [0]) From d6858f577581d7a4bfc725486383f86420abc22f Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 05:45:16 -0400 Subject: [PATCH 12/29] Keep back WTC in the childcare limit without reading the deduction The earnings and tax-credit limit now keeps back the WTC that Sch 5 para 56 disregards by testing Sch 4 para 17 with the whole capped childcare charge, so it reads neither the childcare deduction nor the housing_benefit_wtc_disregard formula. The WTC disregard and the earnings disregard then test para 17 with the deduction in force in each segment. For the model's own deduction the two tests agree, so the limit, the deduction and the disregard keep their values, and the direction runs one way: limit, deduction, WTC disregard. A reform that replaces the deduction, its limit or the WTC disregard with a formula that forwards to the model's own no longer meets a circular definition, and a replacement deduction can read the limit. A WTC disregard that an input supplies, or that a reform neutralizes, still reaches the limit and every segment. Co-Authored-By: Claude Opus 5.5 --- .../housing_benefit_wtc_disregard.yaml | 24 ++ .../test_housing_benefit_wtc_disregard.py | 276 +++++++++++++++--- ..._housing_benefit_wtc_disregard_segments.py | 130 ++++++++- ...ing_benefit_applicable_income_disregard.py | 26 +- ...ousing_benefit_childcare_earnings_limit.py | 94 +++++- ...ed_or_temporary_accommodation_disregard.py | 18 +- .../housing_benefit_wtc_disregard.py | 97 +++--- 7 files changed, 527 insertions(+), 138 deletions(-) diff --git a/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml index 85727bd4e9..5a703c6ff8 100644 --- a/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml +++ b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml @@ -359,3 +359,27 @@ housing_benefit_applicable_income_childcare_element: 1_000 housing_benefit_applicable_income_disregard: 2_189.20 housing_benefit_wtc_disregard: 0 + +- name: A supplied WTC disregard sets the WTC the childcare limit keeps back + period: 2024 + absolute_error_margin: 0.02 + input: + housing_benefit_net_earnings: 5_200 + housing_benefit_special_earnings_disregard: 1_300 + housing_benefit_permitted_work_disregard: 0 + housing_benefit_specified_or_temporary_accommodation_disregard: 0 + housing_benefit_on_passporting_benefit: false + meets_housing_benefit_additional_earnings_disregard_conditions: true + childcare_expenses: 4_160 + num_relevant_children_for_housing_benefit_childcare: 1 + working_tax_credit: 100 + child_tax_credit: 0 + housing_benefit_wtc_disregard: 50 + output: + # Reg 27(1)(c), (2): childcare draws on 5,200 - 1,300 = 3,900 of + # earnings and the 100 - 50 = 50 of WTC the supplied disregard leaves. + housing_benefit_childcare_earnings_limit: 3_950 + housing_benefit_applicable_income_childcare_element: 3_950 + # Sch 4 para 17: 5,200 < 1,300 + 3,950 + 889.20, so the additional + # earnings disregard does not apply. + housing_benefit_applicable_income_disregard: 1_300 diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index d538ce29ef..a1ea047c39 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -13,10 +13,14 @@ Childcare uses only the remaining earnings and credits, and assessed income equals, and never falls below, the independent scalar legal calculation. That calculation settles paragraph 17 by trying both outcomes, rather than -assuming the full-charge shortcut the model uses. Where paragraph 56 does not -apply, the model agrees with the previous path, reproduced by a reform that -sets the new disregard to zero. Supplying the deduction the model calculates -leaves every result unchanged. +testing the whole capped charge, as the model's earnings and tax-credit limit +does; wherever the model calculates the deduction, the WTC that limit keeps +back equals the WTC disregard, which tests the deduction in force. Where +paragraph 56 does not apply, the model agrees with the previous +path, which a reform reproduces by neutralizing the new disregard. Supplying +the deduction the model calculates leaves every result unchanged, and so +does a reform that replaces the childcare deduction, its limit or the WTC +disregard with a formula that only calls the model's own. The annual model uses 52 weeks, with the SI 2020/371 reg 5 temporary amount in 2020 and no ongoing tax-credit awards from model year 2025. Accommodation @@ -34,7 +38,6 @@ import pytest from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st -from policyengine_core.errors import CycleError from policyengine_core.periods import period as period_ from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation @@ -45,6 +48,13 @@ from policyengine_uk.system import system from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( hb_capped_childcare_charges, + housing_benefit_applicable_income_childcare_element, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + housing_benefit_childcare_earnings_limit, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( + housing_benefit_wtc_disregard, ) @@ -145,6 +155,16 @@ def populations(draw): case(net=8_000, accommodation=1_000, childcare=4_160, wtc=500), *(case(region=region) for region in REGIONS), ] +# The issue's family with and without the work condition and WTC: no WTC +# disregard can apply in the first three. +WITNESSES = [ + case(worker=False, wtc=0), + case(worker=False), + case(wtc=0), + case(), +] + + SUPPLIED_EDGE_CASES = [ # Earnings cover a supplied nil deduction and the additional amount. case(supplied=0), @@ -194,6 +214,9 @@ def deduction(reserve): def limit(reserve): if unit["supplied_limit"] is not None: return unit["supplied_limit"] + if unit["supplied"] is not None: + # A supplied deduction reads no limit, so the law sets none. + return None return earnings + unit["wtc"] - reserve + unit["ctc"] def covers(reserve): @@ -233,21 +256,43 @@ def covers(reserve): ) -class previous_wtc_disregard(Variable): - value_type = float - entity = BenUnit - definition_period = YEAR +class without_wtc_reservation(Reform): + """The previous path: no WTC disregard, and childcare draws on all WTC.""" - def formula(benunit, period, parameters): - return benunit.empty_array() + def apply(self): + self.neutralize_variable("housing_benefit_wtc_disregard") -previous_wtc_disregard.__name__ = "housing_benefit_wtc_disregard" +def forwarding_reform(original): + """A reform that replaces the variable's formula with one that only + calls the model's own.""" + class forwarded(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR -class without_wtc_reservation(Reform): - def apply(self): - self.update_variable(previous_wtc_disregard) + def formula(benunit, period, parameters): + return original.formula(benunit, period, parameters) + + forwarded.__name__ = original.__name__ + + class forward(Reform): + def apply(self): + self.update_variable(forwarded) + + return forward + + +FORWARDING_REFORMS = { + variable.__name__: forwarding_reform(variable) + for variable in ( + housing_benefit_applicable_income_childcare_element, + housing_benefit_childcare_earnings_limit, + housing_benefit_wtc_disregard, + ) +} +FORWARDED = {name: reform(system) for name, reform in FORWARDING_REFORMS.items()} def simulation( @@ -377,6 +422,20 @@ def results(sim, year): } +def assert_matches(actual, expected): + """Compare each output with the scalar calculation, skipping a limit the + law does not set.""" + for key, values in actual.items(): + wanted = [unit[key] for unit in expected] + known = np.array([value is not None for value in wanted]) + np.testing.assert_allclose( + values[known], + np.array([value for value in wanted if value is not None], dtype=float), + rtol=0, + atol=TOLERANCE, + ) + + def calculate(units, year, previous=False): return results(simulation(units, year, previous), year) @@ -459,10 +518,7 @@ def test_savings_credit_only_uses_the_corrected_childcare_modification(region): def test_assessed_income_equals_and_never_falls_below_the_regulations(units, year): actual = calculate(units, year) expected = [legal_components(unit, year) for unit in units] - for key, values in actual.items(): - np.testing.assert_allclose( - values, [unit[key] for unit in expected], rtol=0, atol=TOLERANCE - ) + assert_matches(actual, expected) assert np.all( actual["income"] + TOLERANCE >= np.array([unit["income"] for unit in expected]) ) @@ -522,6 +578,11 @@ def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): actual = calculate(unchanged, year) previous = calculate(unchanged, year, previous=True) for variable in actual: + if variable == "limit" and units[0]["supplied"] is not None: + # A supplied deduction reads no limit. The limit still keeps back + # the WTC para 56 would disregard with the whole capped charge, + # where the previous path keeps back none. + continue np.testing.assert_allclose( actual[variable], previous[variable], rtol=0, atol=TOLERANCE ) @@ -532,9 +593,9 @@ def test_previous_path_agrees_where_paragraph_56_does_not_apply(units, year): @example(units=EDGE_CASES, year=2024) @example(units=EDGE_CASES, year=2020) def test_supplying_the_calculated_deduction_changes_nothing(units, year): - """The full-charge test and a test reading the supplied deduction are two - implementations of Sch 4 para 17(3)(b): supplying the deduction the - model calculates must leave every result unchanged.""" + """A deduction a dataset or set_input supplies takes the calculated + one's place in both para 17 tests and in income, so supplying the + deduction the model calculates must leave every result unchanged.""" calculated = calculate(units, year) supplied = [ {**unit, "supplied": float(value)} @@ -547,6 +608,34 @@ def test_supplying_the_calculated_deduction_changes_nothing(units, year): ) +@PROPERTY_SETTINGS +@given(units=st.lists(families(), min_size=1, max_size=12), year=st.sampled_from(YEARS)) +@example(units=EDGE_CASES, year=2024) +@example(units=EDGE_CASES, year=2020) +@example(units=WITNESSES, year=2024) +def test_limit_keeps_back_the_wtc_disregard_in_force(units, year): + """The limit tests Sch 4 para 17 with the whole capped charge, and the + WTC disregard tests it with the deduction in force. Where the model + calculates the deduction, the two agree: the limit keeps back exactly + the WTC that the disregard takes.""" + actual = calculate(units, year) + net = np.array([unit["net"] for unit in units]) + standard = np.minimum(net, [unit["standard"] for unit in units]) + accommodation = np.minimum( + [unit["accommodation"] for unit in units], net - standard + ) + wtc = np.array([unit["wtc"] for unit in units]) + ctc = np.array([unit["ctc"] for unit in units]) + np.testing.assert_allclose( + actual["limit"], + np.maximum(net - standard - accommodation, 0) + + np.maximum(wtc - actual["reserve"], 0) + + np.maximum(ctc, 0), + rtol=0, + atol=TOLERANCE, + ) + + @pytest.mark.parametrize("offset", [-0.01, 0, 0.01]) def test_additional_earnings_threshold_includes_equality(offset): unit = case(net=6_349.20 + offset) @@ -770,19 +859,140 @@ def apply(self): self.update_variable(limit_reading_childcare) -def test_replacement_deduction_reading_the_limit_stops_with_a_cycle(): +@pytest.mark.parametrize( + "unit,expected", + [ + # The limit keeps back the 100 of WTC, since 5,200 < 1,300 + 4,160 + + # 889.20, and comes to 3,900; the deduction is min(2,080, 3,900). + # 5,200 >= 1,300 + 2,080 + 889.20, so para 17(1) applies and para 56 + # does not: 5,200 + 100 - 2,189.20 - 2,080. + ( + case(), + dict( + childcare=2_080, + reserve=0, + earnings_disregard=2_189.20, + limit=3_900, + income=1_030.80, + ), + ), + # The limit binds. 2,000 < 260 + 9,100 + 889.20, so it keeps back + # 889.20 of WTC: 1,740 of earnings and 110.80 of WTC, 1,850.80. The + # deduction is min(4,550, 1,850.80), and 2,000 < 260 + 1,850.80 + + # 889.20, so para 56 disregards 889.20. Income: 2,000 + 1,000 + 1,000 + # - 260 - 889.20 - 1,850.80. + ( + case(net=2_000, standard=260, childcare=9_100, wtc=1_000, other=1_000), + dict( + childcare=1_850.80, + reserve=889.20, + earnings_disregard=260, + limit=1_850.80, + income=1_000, + ), + ), + ], +) +def test_replacement_deduction_can_read_the_limit(unit, expected): """A replacement deduction that reads the earnings and tax-credit limit - depends on the WTC disregard, which reads that deduction: the engine - stops rather than return figures that grant both disregards. Without - active tax credits the disregard reads nothing, so the reform runs.""" - reformed = limit_reading_reform(system) - with pytest.raises(CycleError): - simulation([case()], 2024, tax_benefit_system=reformed).calculate( - "housing_benefit_applicable_income", 2024 - ) - actual = results(simulation([case()], 2025, tax_benefit_system=reformed), 2025) + runs: the limit tests para 17 with the whole capped charge, so it reads + neither the deduction nor the WTC disregard.""" + sim = simulation([unit], 2024, tax_benefit_system=limit_reading_reform(system)) + actual = results(sim, 2024) + for key, value in expected.items(): + assert actual[key][0] == pytest.approx(value, abs=TOLERANCE), key + + +def test_neutralizing_the_wtc_disregard_restores_the_previous_path(): + """Childcare draws on all WTC again: 5,200 - 1,300 + 100 = 4,000 of the + 4,160 charge. 5,200 < 1,300 + 4,000 + 889.20, so the additional earnings + disregard does not apply. Income: 5,200 + 100 + 1,000 - 1,300 - 4,000.""" + actual = calculate([case(other=1_000)], 2024, previous=True) assert actual["reserve"][0] == 0 - assert actual["childcare"][0] == pytest.approx(2_080, abs=TOLERANCE) + assert actual["limit"][0] == pytest.approx(4_000, abs=TOLERANCE) + assert actual["childcare"][0] == pytest.approx(4_000, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx(1_300, abs=TOLERANCE) + assert actual["income"][0] == pytest.approx(1_000, abs=TOLERANCE) + + +def test_supplied_wtc_disregard_reaches_the_limit(): + sim = simulation([case(other=1_000)], 2024) + sim.set_input("housing_benefit_wtc_disregard", 2024, [50]) + actual = results(sim, 2024) + # Childcare draws on 5,200 - 1,300 = 3,900 of earnings and the 100 - 50 + # = 50 of WTC the supplied disregard leaves: 3,950 of the 4,160 charge. + # 5,200 < 1,300 + 3,950 + 889.20, so the additional earnings disregard + # does not apply. Income: 5,200 + 100 + 1,000 - 1,300 - 50 - 3,950. + assert actual["reserve"][0] == 50 + assert actual["limit"][0] == pytest.approx(3_950, abs=TOLERANCE) + assert actual["childcare"][0] == pytest.approx(3_950, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx(1_300, abs=TOLERANCE) + assert actual["income"][0] == pytest.approx(1_000, abs=TOLERANCE) + + +def test_supplied_deduction_leaves_the_limit_on_the_whole_charge(): + """A supplied deduction reads no limit. The limit still tests para 17 + with the whole capped charge: 5,200 < 1,300 + 4,160 + 889.20, so it keeps + back the 100 of WTC and comes to 3,900, though with the supplied nil + deduction para 17(1) applies and para 56 disregards nothing.""" + sim = simulation([case()], 2024) + sim.set_input(CHILDCARE, 2024, [0]) + actual = results(sim, 2024) + assert actual["limit"][0] == pytest.approx(3_900, abs=TOLERANCE) + assert actual["reserve"][0] == 0 + assert actual["earnings_disregard"][0] == pytest.approx(2_189.20, abs=TOLERANCE) + + +def assert_forwarding_changes_nothing(build, systems, outputs): + """Each forwarding reform alone leaves every output as the model's. + ``build`` makes the population's simulation under a system.""" + expected = outputs(build(systems[None])) + for name, reformed in systems.items(): + if name is None: + continue + actual = outputs(build(reformed)) + for key, values in expected.items(): + np.testing.assert_allclose( + actual[key], values, rtol=0, atol=TOLERANCE, err_msg=f"{name}: {key}" + ) + + +@PROPERTY_SETTINGS +@given(units=POPULATIONS) +@example(units=WITNESSES) +@example(units=EDGE_CASES) +@example(units=SUPPLIED_EDGE_CASES) +@example(units=SUPPLIED_LIMIT_EDGE_CASES) +def test_forwarding_reforms_change_nothing(units): + """A reform that replaces the childcare deduction, its limit or the WTC + disregard with a formula that only calls the model's own runs without a + circular definition and changes no output, with and without WTC.""" + assert_forwarding_changes_nothing( + lambda tax_benefit_system: simulation( + units, 2024, tax_benefit_system=tax_benefit_system + ), + {None: system, **FORWARDED}, + lambda sim: results(sim, 2024), + ) + + +@pytest.mark.parametrize("name", sorted(FORWARDING_REFORMS)) +def test_forwarding_reform_runs_for_an_adult_without_income(name): + """One adult aged 40, with no income, children, childcare or WTC, and + every other value left to the model.""" + situation = { + "people": {"adult": {"age": {2024: 40}}}, + "benunits": {"family": {"members": ["adult"]}}, + "households": {"home": {"members": ["adult"]}}, + } + baseline = Simulation(tax_benefit_system=system, situation=situation) + reformed = Simulation(tax_benefit_system=FORWARDED[name], situation=situation) + for variable in (*OUTPUTS.values(), "housing_benefit_entitlement"): + assert ( + reformed.calculate(variable, 2024)[0] + == baseline.calculate(variable, 2024)[0] + ), variable + assert baseline.calculate(CHILDCARE, 2024)[0] == 0 def test_revived_tax_credits_with_the_accommodation_disregard(): diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index c7e33fe086..85599ec9e5 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -13,8 +13,11 @@ segment and combined by days, and no segment gives a benefit unit both the additional earnings disregard and a positive WTC disregard. The annual WTC disregard combines the segments' amounts. Where para 56 applies in no -segment, the award equals the previous path's, with the new disregard set to -zero; under current law that holds for every family. +segment, the award equals the previous path's, with the new disregard +neutralized; under current law that holds for every family. Outside +specified or temporary accommodation, a reform that replaces the childcare +deduction, its limit or the WTC disregard with a formula that only calls the +model's own changes no output. """ import numpy as np @@ -26,12 +29,16 @@ from policyengine_uk.system import system from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( + FORWARDING_REFORMS, PROPERTY_SETTINGS, RENT, TOLERANCE, + WITNESSES, + assert_forwarding_changes_nothing, case, families, legal_components, + results, same_supply, simulation, without_wtc_reservation, @@ -39,6 +46,9 @@ from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( hb_segment_deductions, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + hb_childcare_wtc_reserve, +) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, ) @@ -73,6 +83,7 @@ def modify(parameters): True: without_wtc_reservation(TAX_CREDITS), False: without_wtc_reservation(system), } +FORWARDED = {name: reform(TAX_CREDITS) for name, reform in FORWARDING_REFORMS.items()} def legal_segments(unit, active): @@ -111,8 +122,9 @@ def segmented(units, active, previous=False): def model_segments(sim): - """Each segment's share of the year, additional earnings disregard and - WTC disregard, as the model applies them.""" + """Each segment's share of the year, additional earnings disregard, WTC + disregard and the WTC its childcare limit keeps back, as the model + applies them.""" benunit = sim.populations["benunit"] year = period_(YEAR) parameters = sim.tax_benefit_system.parameters @@ -131,6 +143,10 @@ def model_segments(sim): share=share, additional=np.asarray(disregard - standard - capped, dtype=float), reserve=np.asarray(reserve, dtype=float), + kept_back=np.asarray( + hb_childcare_wtc_reserve(benunit, year, parameters, accommodation), + dtype=float, + ), ) ) return result @@ -276,13 +292,102 @@ def test_each_segment_limits_childcare_with_its_own_wtc_disregard(): ) -def test_supplied_annual_wtc_disregard_applies_in_every_segment(): +@pytest.mark.parametrize( + "supplied,award", + [ + # Before: 10,400 - 0.65 * 2,850.80 = 8,546.98. After: 10,400 - 0.65 * + # (4,000 - 2,000) = 9,100. (182 * 8,546.98 + 183 * 9,100) / 365. + (0, 8_824.25), + # Before 5 October, 2,000 >= 260 + 889.20, so the additional earnings + # disregard applies alongside the supplied 100: income 4,000 - + # 1,149.20 - 100 = 2,750.80, and the award 10,400 - 0.65 * 2,750.80 = + # 8,611.98. After it, income 4,000 - 2,000 - 100 = 1,900, and the + # award 9,165. (182 * 8,611.98 + 183 * 9,165) / 365. + (100, 8_889.25), + ], +) +def test_supplied_annual_wtc_disregard_applies_in_every_segment(supplied, award): sim = segmented([specified_claimant(net=2_000)], active=True) - sim.set_input("housing_benefit_wtc_disregard", YEAR, [0]) - # Before: 10,400 - 0.65 * 2,850.80 = 8,546.98. After: 10,400 - 0.65 * - # (4,000 - 2,000) = 9,100. (182 * 8,546.98 + 183 * 9,100) / 365. + sim.set_input("housing_benefit_wtc_disregard", YEAR, [supplied]) + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +def test_supplied_wtc_disregard_reaches_each_segment_limit(): + """The lone parent of the childcare test above, with an annual WTC + disregard of £500 supplied.""" + unit = case(specified=True, net=8_000, wtc=2_000, other=3_000) + sim = segmented([unit], active=True) + sim.set_input("housing_benefit_wtc_disregard", YEAR, [500]) + # Before 5 October the limit is 6,700 + 1,500 = 8,200, so childcare + # takes the whole 4,160 charge, and 8,000 >= 1,300 + 4,160 + 889.20: + # income is 13,000 - 2,189.20 - 500 - 4,160 = 6,150.80, and the award + # 10,400 - 0.65 * 6,150.80 = 6,401.98. After it, childcare draws on + # 8,000 - 1,300 - 4,041.96 = 2,658.04 of earnings and 2,000 - 500 = + # 1,500 of WTC, 4,158.04 in all: income is 13,000 - 5,341.96 - 500 - + # 4,158.04 = 3,000, and the award 8,450. + # (182 * 6,401.98 + 183 * 8,450) / 365 = 7,428.80. assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( - 8_824.25, abs=TOLERANCE + 7_428.80, abs=TOLERANCE + ) + + +def segment_outputs(sim): + return { + **results(sim, YEAR), + "award": np.asarray( + sim.calculate("housing_benefit_entitlement", YEAR), dtype=float + ), + } + + +def outside_specified_accommodation(units): + return [{**unit, "specified": False} for unit in units] + + +@PROPERTY_SETTINGS +@given(units=segment_populations().map(outside_specified_accommodation)) +@example(units=WITNESSES) +@example(units=outside_specified_accommodation(SEGMENT_EDGE_CASES)) +@example(units=outside_specified_accommodation(SUPPLIED_SEGMENT_EDGE_CASES)) +def test_forwarding_reforms_change_nothing_with_tax_credits_kept(units): + """In 2026-27, under a reform that keeps tax credits, a reform that + replaces the childcare deduction, its limit or the WTC disregard with a + formula that only calls the model's own changes no output, award + included, for families outside specified or temporary accommodation.""" + assert_forwarding_changes_nothing( + lambda tax_benefit_system: simulation( + units, YEAR, tax_benefit_system=tax_benefit_system, dated_accommodation=True + ), + {None: TAX_CREDITS, **FORWARDED}, + segment_outputs, + ) + + +def test_replacement_wtc_disregard_applies_its_annual_amount_in_every_segment(): + """A replacement formula gives one annual amount, which every segment + deducts, as a replacement for the childcare deduction, its limit or the + earnings disregard does. That matches the + model's segments while both stay on the taper, so even a formula that + only calls the model's own can move the award once a segment leaves it. + The model's segments give 10,124.25. With the annual 445.82 in each: + before 5 October, income is 4,000 - 1,149.20 - 445.82 = 2,404.98, and + the award 10,400 - 0.65 * 404.98 = 10,136.76. After it, income is 4,000 + - 2,000 - 445.82 = 1,554.18, below the 2,000 applicable amount, so the + award is 10,400. (182 * 10,136.76 + 183 * 10,400) / 365 = 10,268.74.""" + unit = specified_claimant(net=2_000, applicable_amount=2_000) + sim = simulation( + [unit], + YEAR, + tax_benefit_system=FORWARDED["housing_benefit_wtc_disregard"], + dated_accommodation=True, + ) + assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( + 445.82, abs=TOLERANCE + ) + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + 10_268.74, abs=TOLERANCE ) @@ -301,9 +406,16 @@ def test_segmented_award_equals_the_regulations_with_one_additional_disregard( award, [legal_award(unit, active) for unit in units], rtol=0, atol=TOLERANCE ) segments = model_segments(sim) + calculated = units[0]["supplied"] is None and units[0]["supplied_limit"] is None for segment in segments: both = (segment["additional"] > TOLERANCE) & (segment["reserve"] > 0) assert not both.any(), [unit for unit, b in zip(units, both) if b] + if calculated: + # The whole-charge test and the test of the deduction in force + # agree wherever the model calculates the deduction. + np.testing.assert_allclose( + segment["kept_back"], segment["reserve"], rtol=0, atol=TOLERANCE + ) np.testing.assert_allclose( sim.calculate("housing_benefit_wtc_disregard", YEAR), sum(segment["share"] * segment["reserve"] for segment in segments), diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index e98b991cbf..9633595e92 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -1,9 +1,6 @@ from policyengine_uk.model_api import * -from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( - hb_capped_childcare_charges, -) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( - hb_childcare_earnings_limit, + hb_covers_additional_disregard, hb_standard_earnings_disregard, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( @@ -11,8 +8,7 @@ hb_uses_annual_override, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( - hb_covers_additional_disregard, - hb_fixed_childcare_deduction, + hb_segment_childcare_deduction, hb_segment_wtc_disregard, ) @@ -24,18 +20,12 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) accommodation = min_(max_(accommodation, 0), max_(net - standard, 0)) - wtc_disregard = hb_segment_wtc_disregard(benunit, period, parameters, accommodation) - childcare = hb_fixed_childcare_deduction(benunit, period, parameters) - if childcare is None: - childcare = min_( - hb_capped_childcare_charges(benunit, period, parameters), - hb_childcare_earnings_limit( - benunit, - period, - accommodation=accommodation, - wtc_disregard=wtc_disregard, - ), - ) + childcare = hb_segment_childcare_deduction( + benunit, period, parameters, accommodation + ) + wtc_disregard = hb_segment_wtc_disregard( + benunit, period, parameters, accommodation, childcare + ) name = "housing_benefit_applicable_income_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_applicable_income_disregard.formula diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index 3f087fbd57..c852653f5e 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -1,4 +1,11 @@ from policyengine_uk.model_api import * +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( + hb_capped_childcare_charges, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( + hb_accommodation_segments, + hb_runs_no_formula, +) def hb_standard_earnings_disregard(benunit, period): @@ -6,14 +13,77 @@ def hb_standard_earnings_disregard(benunit, period): return benunit("housing_benefit_applied_standard_earnings_disregard", period) -def hb_childcare_earnings_limit( - benunit, period, accommodation=None, wtc_disregard=None +def hb_covers_additional_disregard( + benunit, period, parameters, accommodation, childcare ): + """Sch 4 para 17(1), (3): whether net earnings at least equal the other + earnings disregards, the childcare deduction and the additional amount, + compared in pence, including equality at a float32 earnings boundary. + Capping the accommodation amount at the earnings the standard disregard + leaves does not change the answer: where the cap binds, those + disregards take all the earnings, which then cannot also cover the + additional amount.""" + net = benunit("housing_benefit_net_earnings", period) + standard = hb_standard_earnings_disregard(benunit, period) + p = parameters(period).gov.dwp.housing_benefit.means_test.income_disregard + additional = p.worker * WEEKS_IN_YEAR + return np.round(net.astype(float), 2) >= np.round( + (standard + accommodation + childcare + additional).astype(float), 2 + ) + + +def hb_wtc_disregard(benunit, period, parameters, accommodation, childcare): + """WTC disregarded under Sch 5 para 56 where the accommodation disregard + has this full annual amount and Sch 4 para 17(3)(b) counts this + childcare deduction.""" + p = parameters(period).gov.dwp + if not p.tax_credits.active: + return benunit.empty_array() + applies = benunit( + "meets_housing_benefit_additional_earnings_disregard_conditions", period + ) & ~hb_covers_additional_disregard( + benunit, period, parameters, accommodation, childcare + ) + additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR + return where( + applies, + min_(max_(benunit("working_tax_credit", period), 0), additional), + 0, + ) + + +def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): + """The WTC this limit keeps from childcare for the Sch 5 para 56 + disregard. By default the accommodation disregard has its annual + segments; an accommodation segment passes its own amount.""" + name = "housing_benefit_wtc_disregard" + if hb_runs_no_formula(benunit, period, name): + return benunit(name, period) + # Sch 4 para 17(3)(b) counts the childcare deduction, which this limit + # caps, so the limit tests para 17 with the whole capped charge instead. + # For the deduction the model calculates, the lesser of that charge and + # this limit, the answer is the same: if earnings cover the other + # disregards, the whole charge and the additional amount, they cover any + # smaller deduction; if not, either the deduction is the whole charge, or + # this limit caps it and it takes at least all the earnings left, so para + # 17(1) fails whatever credits remain. A replacement formula for the WTC + # disregard does not reach this limit, since it could read the deduction. + charge = hb_capped_childcare_charges(benunit, period, parameters) + if accommodation is not None: + return hb_wtc_disregard(benunit, period, parameters, accommodation, charge) + return sum( + hb_wtc_disregard(benunit, period, parameters, amount, charge) * share + for amount, share in hb_accommodation_segments(benunit, period, parameters) + ) + + +def hb_childcare_earnings_limit(benunit, period, parameters, accommodation=None): """Remaining earnings and tax credits, without an additional-disregard loop. - By default the accommodation and WTC disregards are the annual variables; - an accommodation segment passes its own.""" + By default the accommodation disregard is the annual variable; an + accommodation segment passes its own.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) + reserve = hb_childcare_wtc_reserve(benunit, period, parameters, accommodation) if accommodation is None: accommodation = benunit( "housing_benefit_specified_or_temporary_accommodation_disregard", period @@ -23,9 +93,7 @@ def hb_childcare_earnings_limit( # deducts childcare. DWP BW2 W2.179-W2.182 lets WTC/CTC in payment, not # other income, meet the charges earnings leave; only the WTC left after # that disregard counts. Both amounts are benefit-unit payments. - if wtc_disregard is None: - wtc_disregard = benunit("housing_benefit_wtc_disregard", period) - credits = max_(benunit("working_tax_credit", period) - wtc_disregard, 0) + max_( + credits = max_(benunit("working_tax_credit", period) - reserve, 0) + max_( benunit("child_tax_credit", period), 0 ) return max_(0, net - standard - accommodation) + credits @@ -46,6 +114,16 @@ class housing_benefit_childcare_earnings_limit(Variable): "as well as that disregard: when it applies the full capped childcare " "charge already fits, so this calculation need not depend on it. This " "avoids a circular calculation through the childcare deduction. The " + "WTC this limit keeps back for the paragraph 56 disregard follows the " + "same idea: the limit tests paragraph 17 with the whole capped charge, " + "which gives the disregard the model's own deduction leads to, so it " + "reads neither the deduction nor the housing_benefit_wtc_disregard " + "formula. A WTC disregard that a dataset, set_input or a scenario " + "supplies, or that a reform neutralizes, applies instead; a " + "replacement formula for it does not reach this limit. Where a " + "dataset, set_input or a reform supplies or replaces the deduction, " + "the limit still tests the whole charge, and can keep back WTC that " + "paragraph 56 does not disregard with the deduction in force. The " "WTC edge also runs from this limit through " "housing_benefit_applied_standard_earnings_disregard, " "housing_benefit_special_earnings_disregard and " @@ -73,4 +151,4 @@ class housing_benefit_childcare_earnings_limit(Variable): ) def formula(benunit, period, parameters): - return hb_childcare_earnings_limit(benunit, period) + return hb_childcare_earnings_limit(benunit, period, parameters) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index 7f29a3b4cc..ef8fe0a6bb 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -6,14 +6,18 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): """Keep annual inputs and replacement formulas out of recalculation.""" - simulation = benunit.simulation - variable = simulation.tax_benefit_system.get_variable(variable_name) + variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) formula = variable.get_formula(period) - if ( - variable.is_neutralized - or formula is None - or formula.__code__ != default_formula.__code__ - ): + if formula is not None and formula.__code__ != default_formula.__code__: + return True + return hb_runs_no_formula(benunit, period, variable_name) + + +def hb_runs_no_formula(benunit, period, variable_name): + """Whether reading the variable for this period runs no formula: a reform + neutralized it or left it without one, or an input supplies it.""" + variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) + if variable.is_neutralized or variable.get_formula(period) is None: return True # An input the caller set for this period overrides recalculation, and so # does a scenario's own value (set_model_value), which the variable then diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index 4a7782a917..fd2572a7d4 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -4,7 +4,8 @@ housing_benefit_applicable_income_childcare_element, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( - hb_standard_earnings_disregard, + hb_childcare_earnings_limit, + hb_wtc_disregard, housing_benefit_childcare_earnings_limit, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( @@ -30,71 +31,30 @@ def hb_fixed_childcare_deduction(benunit, period, parameters): return None -def hb_covers_additional_disregard( - benunit, period, parameters, accommodation, childcare -): - """Sch 4 para 17(1), (3): whether net earnings at least equal the other - earnings disregards, the childcare deduction and the additional amount, - compared in pence, including equality at a float32 earnings boundary. - Capping the accommodation amount at the earnings the standard disregard - leaves does not change the answer: where the cap binds, those - disregards take all the earnings, which then cannot also cover the - additional amount.""" - net = benunit("housing_benefit_net_earnings", period) - standard = hb_standard_earnings_disregard(benunit, period) - p = parameters(period).gov.dwp.housing_benefit.means_test.income_disregard - additional = p.worker * WEEKS_IN_YEAR - return np.round(net.astype(float), 2) >= np.round( - (standard + accommodation + childcare + additional).astype(float), 2 - ) - - -def hb_wtc_disregard(benunit, period, parameters, accommodation): - """WTC disregarded under Sch 5 para 56 where the accommodation disregard - has this full annual amount.""" - p = parameters(period).gov.dwp - if not p.tax_credits.active: - return benunit.empty_array() - # Sch 4 para 17(3)(b) counts the childcare charges deductible under reg - # 27(1)(c), which come from the earnings left and then from the credits - # this disregard reduces, so that deduction depends on this disregard. - # Where the model calculates the deduction, the whole capped charge - # settles para 17 instead. That gives the same answer only for the - # model's formula, the lesser of the capped charge and the earnings and - # tax-credit limit: if earnings cover the other disregards, the whole - # charge and the additional amount, they cover any smaller deduction; if - # not, either the deduction is the whole charge, or the limit caps it and - # it takes at least all the earnings left, so para 17 fails whatever - # credits remain. Where the deduction or its limit is supplied, neutralized or - # replaced, the two can differ, so the test reads the deduction the - # earnings disregard reads. A replacement deduction that itself reads - # the limit depends on this disregard, and the engine stops with a - # circular-definition error. +def hb_segment_childcare_deduction(benunit, period, parameters, accommodation): + """The childcare deduction in force where the accommodation disregard has + this full annual amount: the annual deduction where + hb_fixed_childcare_deduction gives one, and otherwise the lesser of the + capped charge and the earnings and tax-credit limit.""" childcare = hb_fixed_childcare_deduction(benunit, period, parameters) - if childcare is None: - childcare = hb_capped_childcare_charges(benunit, period, parameters) - applies = benunit( - "meets_housing_benefit_additional_earnings_disregard_conditions", period - ) & ~hb_covers_additional_disregard( - benunit, period, parameters, accommodation, childcare - ) - additional = p.housing_benefit.means_test.income_disregard.worker * WEEKS_IN_YEAR - return where( - applies, - min_(max_(benunit("working_tax_credit", period), 0), additional), - 0, + if childcare is not None: + return childcare + return min_( + hb_capped_childcare_charges(benunit, period, parameters), + hb_childcare_earnings_limit(benunit, period, parameters, accommodation), ) -def hb_segment_wtc_disregard(benunit, period, parameters, accommodation): - """The WTC disregard in one accommodation segment. A supplied, - neutralized or replaced annual amount applies in every segment.""" +def hb_segment_wtc_disregard(benunit, period, parameters, accommodation, childcare): + """The WTC disregard in one accommodation segment, where Sch 4 para + 17(3)(b) counts this childcare deduction. A supplied, neutralized or + replaced annual amount applies in every segment.""" name = "housing_benefit_wtc_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_wtc_disregard.formula ): return benunit(name, period) - return hb_wtc_disregard(benunit, period, parameters, accommodation) + return hb_wtc_disregard(benunit, period, parameters, accommodation, childcare) class housing_benefit_wtc_disregard(Variable): @@ -110,11 +70,13 @@ class housing_benefit_wtc_disregard(Variable): "WTC received and the statutory additional amount, using its dated " "history, including the temporary 2020 increase. The existing " "tax-credit active parameter suppresses it from fiscal year 2025. " - "This is separate from the earnings-only disregard. Where the " - "childcare deduction or its limit is supplied, neutralized or " - "replaced, the earnings test reads the same deduction as the " - "earnings disregard, so the two additional disregards never both " - "apply. Where the accommodation disregard starts within the fiscal " + "This is separate from the earnings-only disregard. Its earnings " + "test counts the childcare deduction in force, as the earnings " + "disregard does, so no accommodation segment gets both additional " + "disregards. That deduction is the one a dataset, set_input or a " + "reform supplies or replaces, or the one a supplied or replaced " + "limit gives; otherwise it is the deduction the model calculates in " + "the segment. Where the accommodation disregard starts within the fiscal " "year, each effective-date segment has its own earnings test, as " "the earnings disregard does; this annual amount combines the " "segments' disregards, and entitlement deducts each segment's own." @@ -133,7 +95,16 @@ class housing_benefit_wtc_disregard(Variable): def formula(benunit, period, parameters): return sum( - hb_wtc_disregard(benunit, period, parameters, accommodation) * share + hb_wtc_disregard( + benunit, + period, + parameters, + accommodation, + hb_segment_childcare_deduction( + benunit, period, parameters, accommodation + ), + ) + * share for accommodation, share in hb_accommodation_segments( benunit, period, parameters ) From 441ead1923d3dca18006d403c1cc5e7647685bee Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 06:14:42 -0400 Subject: [PATCH 13/29] Test the scope of the supplied-value invariants A supplied childcare deduction keeps its value above the charge and the limit, the annual additional earnings and WTC disregards can both be positive though no segment has both, and supplying the calculated annual deduction in a segmented year applies it in every segment. The test modules now build their forwarding reforms on demand, so they import where housing_benefit_wtc_disregard does not exist. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 60 ++++++++++--------- ..._housing_benefit_wtc_disregard_segments.py | 40 ++++++++++--- 2 files changed, 65 insertions(+), 35 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index a1ea047c39..08ec766cc6 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -33,6 +33,8 @@ tax-credit awards from those incomes. """ +from functools import cache + import numpy as np import pandas as pd import pytest @@ -48,13 +50,6 @@ from policyengine_uk.system import system from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_childcare_element import ( hb_capped_childcare_charges, - housing_benefit_applicable_income_childcare_element, -) -from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( - housing_benefit_childcare_earnings_limit, -) -from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( - housing_benefit_wtc_disregard, ) @@ -263,36 +258,37 @@ def apply(self): self.neutralize_variable("housing_benefit_wtc_disregard") -def forwarding_reform(original): - """A reform that replaces the variable's formula with one that only - calls the model's own.""" +FORWARDED_VARIABLES = (CHILDCARE, LIMIT, "housing_benefit_wtc_disregard") - class forwarded(Variable): + +@cache +def forwarded(name, baseline=system): + """``baseline`` under a reform that replaces the variable's formula with + one that only calls the model's own.""" + original = system.get_variable(name).get_formula() + + class forwarded_variable(Variable): value_type = float entity = BenUnit definition_period = YEAR def formula(benunit, period, parameters): - return original.formula(benunit, period, parameters) + return original(benunit, period, parameters) - forwarded.__name__ = original.__name__ + forwarded_variable.__name__ = name class forward(Reform): def apply(self): - self.update_variable(forwarded) + self.update_variable(forwarded_variable) - return forward + return forward(baseline) -FORWARDING_REFORMS = { - variable.__name__: forwarding_reform(variable) - for variable in ( - housing_benefit_applicable_income_childcare_element, - housing_benefit_childcare_earnings_limit, - housing_benefit_wtc_disregard, - ) -} -FORWARDED = {name: reform(system) for name, reform in FORWARDING_REFORMS.items()} +def forwarded_systems(baseline=system): + return { + None: baseline, + **{name: forwarded(name, baseline) for name in FORWARDED_VARIABLES}, + } def simulation( @@ -930,6 +926,16 @@ def test_supplied_wtc_disregard_reaches_the_limit(): assert actual["income"][0] == pytest.approx(1_000, abs=TOLERANCE) +def test_supplied_deduction_keeps_its_value(): + """The childcare bounds cover the deduction the model calculates. A + supplied £25,000 stays £25,000, above the £4,160 charge and the £3,900 + of earnings the standard disregard leaves; with it, income is nil.""" + actual = calculate([case(supplied=25_000)], 2024) + assert actual["childcare"][0] == 25_000 + assert actual["reserve"][0] == 100 + assert actual["income"][0] == 0 + + def test_supplied_deduction_leaves_the_limit_on_the_whole_charge(): """A supplied deduction reads no limit. The limit still tests para 17 with the whole capped charge: 5,200 < 1,300 + 4,160 + 889.20, so it keeps @@ -971,12 +977,12 @@ def test_forwarding_reforms_change_nothing(units): lambda tax_benefit_system: simulation( units, 2024, tax_benefit_system=tax_benefit_system ), - {None: system, **FORWARDED}, + forwarded_systems(), lambda sim: results(sim, 2024), ) -@pytest.mark.parametrize("name", sorted(FORWARDING_REFORMS)) +@pytest.mark.parametrize("name", FORWARDED_VARIABLES) def test_forwarding_reform_runs_for_an_adult_without_income(name): """One adult aged 40, with no income, children, childcare or WTC, and every other value left to the model.""" @@ -986,7 +992,7 @@ def test_forwarding_reform_runs_for_an_adult_without_income(name): "households": {"home": {"members": ["adult"]}}, } baseline = Simulation(tax_benefit_system=system, situation=situation) - reformed = Simulation(tax_benefit_system=FORWARDED[name], situation=situation) + reformed = Simulation(tax_benefit_system=forwarded(name), situation=situation) for variable in (*OUTPUTS.values(), "housing_benefit_entitlement"): assert ( reformed.calculate(variable, 2024)[0] diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index 85599ec9e5..b56dc8ee89 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -29,7 +29,7 @@ from policyengine_uk.system import system from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( - FORWARDING_REFORMS, + CHILDCARE, PROPERTY_SETTINGS, RENT, TOLERANCE, @@ -37,6 +37,8 @@ assert_forwarding_changes_nothing, case, families, + forwarded, + forwarded_systems, legal_components, results, same_supply, @@ -46,9 +48,6 @@ from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( hb_segment_deductions, ) -from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( - hb_childcare_wtc_reserve, -) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, ) @@ -83,7 +82,6 @@ def modify(parameters): True: without_wtc_reservation(TAX_CREDITS), False: without_wtc_reservation(system), } -FORWARDED = {name: reform(TAX_CREDITS) for name, reform in FORWARDING_REFORMS.items()} def legal_segments(unit, active): @@ -125,6 +123,10 @@ def model_segments(sim): """Each segment's share of the year, additional earnings disregard, WTC disregard and the WTC its childcare limit keeps back, as the model applies them.""" + from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + hb_childcare_wtc_reserve, + ) + benunit = sim.populations["benunit"] year = period_(YEAR) parameters = sim.tax_benefit_system.parameters @@ -264,7 +266,12 @@ def test_each_segment_settles_paragraph_56_with_its_own_earnings_test( assert before["additional"][0] == pytest.approx(889.20, abs=TOLERANCE) assert after["reserve"][0] == pytest.approx(889.20, abs=TOLERANCE) assert after["additional"][0] == pytest.approx(0, abs=TOLERANCE) - # The annual amount combines the segments: 889.20 * 183 / 365. + # The annual amounts combine the segments: 889.20 * 182 / 365 of + # additional earnings disregard and 889.20 * 183 / 365 of WTC disregard. + # Both are positive, though no segment has both. + assert sum( + segment["share"] * segment["additional"][0] for segment in (before, after) + ) == pytest.approx(443.38, abs=TOLERANCE) assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( 445.82, abs=TOLERANCE ) @@ -292,6 +299,23 @@ def test_each_segment_limits_childcare_with_its_own_wtc_disregard(): ) +def test_supplied_annual_deduction_applies_in_every_segment(): + """Supplying the lone parent's calculated annual deduction, £4,160, + applies it in both segments. From 5 October the WTC disregard is still + 889.20, so income is 13,000 - 5,341.96 - 889.20 - 4,160 = 2,608.84 and + the award 8,704.25 where the model's own deduction gives 8,450: + (182 * 6,076.98 + 183 * 8,704.25) / 365 = 7,394.22, not 7,266.74.""" + unit = case(specified=True, net=8_000, wtc=2_000, other=3_000) + calculated = segmented([unit], active=True) + deduction = calculated.calculate(CHILDCARE, YEAR) + assert deduction[0] == pytest.approx(4_160, abs=TOLERANCE) + replayed = segmented([unit], active=True) + replayed.set_input(CHILDCARE, YEAR, deduction) + assert replayed.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + 7_394.22, abs=TOLERANCE + ) + + @pytest.mark.parametrize( "supplied,award", [ @@ -360,7 +384,7 @@ def test_forwarding_reforms_change_nothing_with_tax_credits_kept(units): lambda tax_benefit_system: simulation( units, YEAR, tax_benefit_system=tax_benefit_system, dated_accommodation=True ), - {None: TAX_CREDITS, **FORWARDED}, + forwarded_systems(TAX_CREDITS), segment_outputs, ) @@ -380,7 +404,7 @@ def test_replacement_wtc_disregard_applies_its_annual_amount_in_every_segment(): sim = simulation( [unit], YEAR, - tax_benefit_system=FORWARDED["housing_benefit_wtc_disregard"], + tax_benefit_system=forwarded("housing_benefit_wtc_disregard", TAX_CREDITS), dated_accommodation=True, ) assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( From 9c2adcde9101230a2af870273d8c514a01853a96 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 06:19:43 -0400 Subject: [PATCH 14/29] Build the segment tests' previous-path systems on demand Co-Authored-By: Claude Opus 5.5 --- ...test_housing_benefit_wtc_disregard_segments.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index b56dc8ee89..8ece6ea405 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -20,6 +20,8 @@ model's own changes no output. """ +from functools import cache + import numpy as np import pytest from hypothesis import example, given @@ -78,10 +80,11 @@ def modify(parameters): TAX_CREDITS = keep_tax_credits(system) SYSTEMS = {True: TAX_CREDITS, False: system} -PREVIOUS = { - True: without_wtc_reservation(TAX_CREDITS), - False: without_wtc_reservation(system), -} + + +@cache +def previous_system(active): + return without_wtc_reservation(SYSTEMS[active]) def legal_segments(unit, active): @@ -113,9 +116,9 @@ def legal_award(unit, active): def segmented(units, active, previous=False): - systems = PREVIOUS if previous else SYSTEMS + tax_benefit_system = previous_system(active) if previous else SYSTEMS[active] return simulation( - units, YEAR, tax_benefit_system=systems[active], dated_accommodation=True + units, YEAR, tax_benefit_system=tax_benefit_system, dated_accommodation=True ) From fdc13f128301761e24e0aace9457138a48c595b8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 07:14:05 -0400 Subject: [PATCH 15/29] Test that the annual limit keeps back the annual WTC disregard In a year with two accommodation segments, the annual earnings and tax-credit limit keeps back the day-weighted WTC disregard, as each segment's limit keeps back its own. Co-Authored-By: Claude Opus 5.5 --- ..._housing_benefit_wtc_disregard_segments.py | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index 8ece6ea405..c37034c61a 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -443,12 +443,34 @@ def test_segmented_award_equals_the_regulations_with_one_additional_disregard( np.testing.assert_allclose( segment["kept_back"], segment["reserve"], rtol=0, atol=TOLERANCE ) + annual_wtc_disregard = sim.calculate("housing_benefit_wtc_disregard", YEAR) np.testing.assert_allclose( - sim.calculate("housing_benefit_wtc_disregard", YEAR), + annual_wtc_disregard, sum(segment["share"] * segment["reserve"] for segment in segments), rtol=0, atol=TOLERANCE, ) + if calculated: + # The annual limit keeps back the annual WTC disregard, from the + # earnings the standard and annual accommodation disregards leave. + net = np.array([unit["net"] for unit in units]) + standard = np.minimum(net, [unit["standard"] for unit in units]) + accommodation = np.minimum( + sim.calculate( + "housing_benefit_specified_or_temporary_accommodation_disregard", YEAR + ), + net - standard, + ) + wtc = np.array([unit["wtc"] for unit in units]) + ctc = np.array([unit["ctc"] for unit in units]) + np.testing.assert_allclose( + sim.calculate("housing_benefit_childcare_earnings_limit", YEAR), + np.maximum(net - standard - accommodation, 0) + + np.maximum(wtc - annual_wtc_disregard, 0) + + np.maximum(ctc, 0), + rtol=0, + atol=TOLERANCE, + ) @PROPERTY_SETTINGS From 3b53381c95bd31945474c879c3f387ad5b59e6a8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 13:09:06 -0400 Subject: [PATCH 16/29] Keep computed WTC disregard replacements out of the childcare limit The limit read a WTC disregard with no formula as a supplied amount, but core still computes adds and subtracts there, and calculates a defined_for mask before anything else, so an aggregate identity replacement cycled. The limit now reads the WTC disregard only where reading it reads no other variable: a neutralized variable, one with no formula, aggregate or mask (which core uprates, carries over or defaults from its own inputs), or a supplied input. hb_uses_annual_override still treats any variable without a formula as an annual replacement in every segment. Tests cover formula, adds and subtracts replacements, each as a list or a parameter path, in 2024 and in 2026-27 with tax credits kept, and an uprated input replacement with and without a mask. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 213 +++++++++++++++++- ..._housing_benefit_wtc_disregard_segments.py | 42 ++-- ...ousing_benefit_childcare_earnings_limit.py | 16 +- ...ed_or_temporary_accommodation_disregard.py | 32 ++- 4 files changed, 263 insertions(+), 40 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 08ec766cc6..937fc65ec6 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -40,6 +40,7 @@ import pytest from hypothesis import HealthCheck, example, given, settings from hypothesis import strategies as st +from policyengine_core.parameters import Parameter, ParameterNode from policyengine_core.periods import period as period_ from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation @@ -291,6 +292,131 @@ def forwarded_systems(baseline=system): } +class keep_tax_credits(Reform): + """Keep tax credits in 2026-27, so the two disregards coexist.""" + + def apply(self): + def modify(parameters): + parameters.gov.dwp.tax_credits.active.update( + period="year:2026:2", value=True + ) + return parameters + + self.modify_parameters(modify) + + +@cache +def tax_credits_kept(): + return keep_tax_credits(system) + + +WTC_DISREGARD = "housing_benefit_wtc_disregard" +MODELLED = "housing_benefit_wtc_disregard_as_modelled" +TEST_PARAMETERS = "gov.housing_benefit_wtc_disregard_test" +# Ways a reform can have core compute the WTC disregard from another +# variable: a formula, or adds or subtracts, each listing the variable or +# naming a parameter that lists it. +COMPUTED_REPLACEMENTS = ( + "formula", + "adds", + "subtracts", + "adds parameter", + "subtracts parameter", +) + + +def add_test_parameters(**values): + """A modify_parameters function that adds each dated value under + ``TEST_PARAMETERS``.""" + + def modify(parameters): + node = ParameterNode(TEST_PARAMETERS, data={}) + for name, dated in values.items(): + node.add_child( + name, Parameter(f"{TEST_PARAMETERS}.{name}", data={"values": dated}) + ) + parameters.gov.add_child(TEST_PARAMETERS.split(".")[-1], node) + return parameters + + return modify + + +@cache +def computed_replacement(mode, baseline=system): + """``baseline`` under a reform that adds ``MODELLED``, which runs the + model's WTC disregard formula, and replaces the WTC disregard with a + variable core computes from it, as ``mode`` names: a formula that reads + it, or adds or subtracts. Subtracting reads the negated amount.""" + original = system.get_variable(WTC_DISREGARD).get_formula() + sign = -1 if mode.startswith("subtracts") else 1 + names = f"{TEST_PARAMETERS}.names" if mode.endswith("parameter") else [MODELLED] + + class modelled(Variable): + value_type = float + entity = BenUnit + label = "Housing Benefit WTC disregard as the model calculates it" + definition_period = YEAR + + def formula(benunit, period, parameters): + return sign * original(benunit, period, parameters) + + modelled.__name__ = MODELLED + + class replacement(Variable): + value_type = float + entity = BenUnit + label = "Housing Benefit WTC disregard" + definition_period = YEAR + if mode == "formula": + + def formula(benunit, period, parameters): + return benunit(MODELLED, period) + + elif mode.startswith("adds"): + adds = names + else: + subtracts = names + + replacement.__name__ = WTC_DISREGARD + + class replace(Reform): + def apply(self): + self.modify_parameters( + add_test_parameters(names={"2015-01-01": [MODELLED]}) + ) + self.add_variable(modelled) + self.replace_variable(replacement) + + return replace(baseline) + + +@cache +def input_replacement(masked): + """A reform that leaves the WTC disregard as an input, which core uprates + by a fifth from 2023 to 2024. With ``masked`` it applies only where the + childcare deduction is positive, so reading it reads the deduction.""" + + class replacement(Variable): + value_type = float + entity = BenUnit + label = "Housing Benefit WTC disregard" + definition_period = YEAR + uprating = f"{TEST_PARAMETERS}.uprating" + if masked: + defined_for = CHILDCARE + + replacement.__name__ = WTC_DISREGARD + + class replace(Reform): + def apply(self): + self.modify_parameters( + add_test_parameters(uprating={"2023-01-01": 100, "2024-01-01": 120}) + ) + self.replace_variable(replacement) + + return replace(system) + + def simulation( units, year, previous=False, tax_benefit_system=None, dated_accommodation=False ): @@ -950,8 +1076,9 @@ def test_supplied_deduction_leaves_the_limit_on_the_whole_charge(): def assert_forwarding_changes_nothing(build, systems, outputs): - """Each forwarding reform alone leaves every output as the model's. - ``build`` makes the population's simulation under a system.""" + """Each forwarding reform alone leaves every output as the model's, which + this returns. ``build`` makes the population's simulation under a + system.""" expected = outputs(build(systems[None])) for name, reformed in systems.items(): if name is None: @@ -961,6 +1088,7 @@ def assert_forwarding_changes_nothing(build, systems, outputs): np.testing.assert_allclose( actual[key], values, rtol=0, atol=TOLERANCE, err_msg=f"{name}: {key}" ) + return expected @PROPERTY_SETTINGS @@ -1001,6 +1129,87 @@ def test_forwarding_reform_runs_for_an_adult_without_income(name): assert baseline.calculate(CHILDCARE, 2024)[0] == 0 +@pytest.mark.parametrize("year", [2024, 2026]) +@pytest.mark.parametrize("mode", COMPUTED_REPLACEMENTS) +def test_computed_replacements_of_the_wtc_disregard_change_nothing(mode, year): + """A reform that replaces the WTC disregard with a variable core computes + from the model's own, through a formula or through adds or subtracts, + each listing it or naming a parameter that lists it, runs without a + circular definition and changes no output, award included. In 2026-27 + tax credits stay in payment, and the model dates the accommodation + disregard for families outside specified or temporary accommodation.""" + baseline = system if year == 2024 else tax_credits_kept() + reformed = computed_replacement(mode, baseline) + # Core computes adds and subtracts only where no formula runs. + assert (reformed.get_variable(WTC_DISREGARD).get_formula(year) is None) == ( + mode != "formula" + ) + units = [ + *WITNESSES, + case(net=2_000, standard=260, childcare=9_100, wtc=1_000, other=1_000), + case(net=10_000), + case(pension_age=True), + case(region="NORTHERN_IRELAND"), + ] + + def outputs(sim): + return { + **results(sim, year), + "award": np.asarray( + sim.calculate("housing_benefit_entitlement", year), dtype=float + ), + } + + expected = assert_forwarding_changes_nothing( + lambda tax_benefit_system: simulation( + units, year, tax_benefit_system=tax_benefit_system, dated_accommodation=True + ), + {None: baseline, mode: reformed}, + outputs, + ) + # Para 56 applies to the issue's family, and to the family whose limit + # binds: the lesser of 1,000 of WTC and 889.20. + np.testing.assert_allclose( + expected["reserve"][3:5], [100, 889.20], rtol=0, atol=TOLERANCE + ) + + +@pytest.mark.parametrize( + "masked,limit,income", + [ + # Core uprates the 2023 input of 50 to 60 and reads no other + # variable, so the limit keeps back 60: 3,900 of earnings and 40 of + # WTC, 3,940. 5,200 < 1,300 + 3,940 + 889.20, so the additional + # earnings disregard does not apply. Income: 5,200 + 100 + 1,000 - + # 1,300 - 60 - 3,940. + (False, 3_940, 1_000), + # Core calculates the mask, and so the deduction, before it uprates + # the input. The limit tests para 17 with the whole capped charge + # instead: 5,200 < 1,300 + 4,160 + 889.20, so it keeps back the 100 + # of WTC and comes to 3,900. The deduction is positive, so the WTC + # disregard is the uprated 60. Income: 5,200 + 100 + 1,000 - 1,300 - + # 60 - 3,900. + (True, 3_900, 1_040), + ], +) +def test_input_replacement_reaches_the_limit_unless_reading_it_reads_more( + masked, limit, income +): + """A reform that leaves the WTC disregard as an input reaches the limit, + including an amount core uprates from an earlier year's input. One with + a defined_for mask does not.""" + sim = simulation( + [case(other=1_000)], 2024, tax_benefit_system=input_replacement(masked) + ) + sim.set_input(WTC_DISREGARD, 2023, [50]) + actual = results(sim, 2024) + assert actual["reserve"][0] == pytest.approx(60, abs=TOLERANCE) + assert actual["limit"][0] == pytest.approx(limit, abs=TOLERANCE) + assert actual["childcare"][0] == pytest.approx(limit, abs=TOLERANCE) + assert actual["earnings_disregard"][0] == pytest.approx(1_300, abs=TOLERANCE) + assert actual["income"][0] == pytest.approx(income, abs=TOLERANCE) + + def test_revived_tax_credits_with_the_accommodation_disregard(): """Under a reform that keeps tax credits, the 2027 accommodation disregard (£77.73 a week from 5 October 2026) can leave earnings short diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index c37034c61a..ad077b57dd 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -27,17 +27,18 @@ from hypothesis import example, given from hypothesis import strategies as st from policyengine_core.periods import period as period_ -from policyengine_core.reforms import Reform from policyengine_uk.system import system from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( CHILDCARE, + COMPUTED_REPLACEMENTS, PROPERTY_SETTINGS, RENT, TOLERANCE, WITNESSES, assert_forwarding_changes_nothing, case, + computed_replacement, families, forwarded, forwarded_systems, @@ -45,6 +46,7 @@ results, same_supply, simulation, + tax_credits_kept, without_wtc_reservation, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( @@ -65,20 +67,7 @@ WITHDRAWAL_RATE = 0.65 -class keep_tax_credits(Reform): - """Keep tax credits in 2026-27, so the two disregards coexist.""" - - def apply(self): - def modify(parameters): - parameters.gov.dwp.tax_credits.active.update( - period="year:2026:2", value=True - ) - return parameters - - self.modify_parameters(modify) - - -TAX_CREDITS = keep_tax_credits(system) +TAX_CREDITS = tax_credits_kept() SYSTEMS = {True: TAX_CREDITS, False: system} @@ -392,23 +381,26 @@ def test_forwarding_reforms_change_nothing_with_tax_credits_kept(units): ) -def test_replacement_wtc_disregard_applies_its_annual_amount_in_every_segment(): - """A replacement formula gives one annual amount, which every segment - deducts, as a replacement for the childcare deduction, its limit or the - earnings disregard does. That matches the - model's segments while both stay on the taper, so even a formula that - only calls the model's own can move the award once a segment leaves it. +@pytest.mark.parametrize("mode", ["forwarded", *COMPUTED_REPLACEMENTS]) +def test_replacement_wtc_disregard_applies_its_annual_amount_in_every_segment(mode): + """A replacement that core computes, through a formula or through adds + or subtracts, gives one annual amount, which every segment deducts, as a + replacement for the childcare deduction, its limit or the earnings + disregard does. That matches the model's segments while both stay on the + taper, so even a replacement that only calls the model's own can move + the award once a segment leaves it. The model's segments give 10,124.25. With the annual 445.82 in each: before 5 October, income is 4,000 - 1,149.20 - 445.82 = 2,404.98, and the award 10,400 - 0.65 * 404.98 = 10,136.76. After it, income is 4,000 - 2,000 - 445.82 = 1,554.18, below the 2,000 applicable amount, so the award is 10,400. (182 * 10,136.76 + 183 * 10,400) / 365 = 10,268.74.""" unit = specified_claimant(net=2_000, applicable_amount=2_000) + if mode == "forwarded": + reformed = forwarded("housing_benefit_wtc_disregard", TAX_CREDITS) + else: + reformed = computed_replacement(mode, TAX_CREDITS) sim = simulation( - [unit], - YEAR, - tax_benefit_system=forwarded("housing_benefit_wtc_disregard", TAX_CREDITS), - dated_accommodation=True, + [unit], YEAR, tax_benefit_system=reformed, dated_accommodation=True ) assert sim.calculate("housing_benefit_wtc_disregard", YEAR)[0] == pytest.approx( 445.82, abs=TOLERANCE diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index c852653f5e..173dc55741 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -4,7 +4,7 @@ ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, - hb_runs_no_formula, + hb_reads_no_other_variable, ) @@ -57,7 +57,7 @@ def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): disregard. By default the accommodation disregard has its annual segments; an accommodation segment passes its own amount.""" name = "housing_benefit_wtc_disregard" - if hb_runs_no_formula(benunit, period, name): + if hb_reads_no_other_variable(benunit, period, name): return benunit(name, period) # Sch 4 para 17(3)(b) counts the childcare deduction, which this limit # caps, so the limit tests para 17 with the whole capped charge instead. @@ -66,8 +66,10 @@ def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): # disregards, the whole charge and the additional amount, they cover any # smaller deduction; if not, either the deduction is the whole charge, or # this limit caps it and it takes at least all the earnings left, so para - # 17(1) fails whatever credits remain. A replacement formula for the WTC - # disregard does not reach this limit, since it could read the deduction. + # 17(1) fails whatever credits remain. A replacement for the WTC + # disregard that can read other variables (through a formula, an adds or + # subtracts aggregate, or a defined_for mask) does not reach this limit, + # since it could read the deduction. charge = hb_capped_childcare_charges(benunit, period, parameters) if accommodation is not None: return hb_wtc_disregard(benunit, period, parameters, accommodation, charge) @@ -119,8 +121,10 @@ class housing_benefit_childcare_earnings_limit(Variable): "which gives the disregard the model's own deduction leads to, so it " "reads neither the deduction nor the housing_benefit_wtc_disregard " "formula. A WTC disregard that a dataset, set_input or a scenario " - "supplies, or that a reform neutralizes, applies instead; a " - "replacement formula for it does not reach this limit. Where a " + "supplies, or that a reform neutralizes or leaves as an input, " + "applies instead. A replacement that can read other variables, " + "through a formula, an adds or subtracts aggregate or a defined_for " + "mask, does not reach this limit. Where a " "dataset, set_input or a reform supplies or replaces the deduction, " "the limit still tests the whole charge, and can keep back WTC that " "paragraph 56 does not disregard with the deduction in force. The " diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index ef8fe0a6bb..2f113fdaed 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -5,19 +5,37 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): - """Keep annual inputs and replacement formulas out of recalculation.""" + """Keep annual inputs, replacement formulas and computed aggregates out of + recalculation.""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) formula = variable.get_formula(period) - if formula is not None and formula.__code__ != default_formula.__code__: + if formula is None or formula.__code__ != default_formula.__code__: return True - return hb_runs_no_formula(benunit, period, variable_name) + return hb_reads_no_other_variable(benunit, period, variable_name) -def hb_runs_no_formula(benunit, period, variable_name): - """Whether reading the variable for this period runs no formula: a reform - neutralized it or left it without one, or an input supplies it.""" +def hb_can_read_other_variables(variable, period): + """Whether core, reading the variable for a period it holds no value + for, can read another variable. It first calculates any ``defined_for`` + mask, then runs the formula for the period or, without one, computes + ``adds`` and ``subtracts``, each a list of variable and parameter names + or the path of a parameter that lists them. Otherwise it uprates or + carries over the variable's own earlier inputs, or returns its + default.""" + return bool( + variable.defined_for is not None + or variable.get_formula(period) is not None + or variable.adds + or variable.subtracts + ) + + +def hb_reads_no_other_variable(benunit, period, variable_name): + """Whether reading the variable for this period reads no other variable: + a reform neutralized it, or left it with no formula, aggregate or + ``defined_for`` mask, or an input supplies it.""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) - if variable.is_neutralized or variable.get_formula(period) is None: + if variable.is_neutralized or not hb_can_read_other_variables(variable, period): return True # An input the caller set for this period overrides recalculation, and so # does a scenario's own value (set_model_value), which the variable then From b25e79ad9404dbb6643bd40f8711effd613fc255 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 13:43:02 -0400 Subject: [PATCH 17/29] Build the replacement test systems per test, not once per module Each reform system holds about 38 MB, and caching all eleven kept the main test module above the 2 GB cap the mutation runs use. Co-Authored-By: Claude Opus 5.5 --- policyengine_uk/tests/test_housing_benefit_wtc_disregard.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 937fc65ec6..bb9a4ba677 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -341,12 +341,12 @@ def modify(parameters): return modify -@cache def computed_replacement(mode, baseline=system): """``baseline`` under a reform that adds ``MODELLED``, which runs the model's WTC disregard formula, and replaces the WTC disregard with a variable core computes from it, as ``mode`` names: a formula that reads - it, or adds or subtracts. Subtracting reads the negated amount.""" + it, or adds or subtracts. Subtracting reads the negated amount. Each + test builds its own, so the systems don't stay in memory.""" original = system.get_variable(WTC_DISREGARD).get_formula() sign = -1 if mode.startswith("subtracts") else 1 names = f"{TEST_PARAMETERS}.names" if mode.endswith("parameter") else [MODELLED] @@ -390,7 +390,6 @@ def apply(self): return replace(baseline) -@cache def input_replacement(masked): """A reform that leaves the WTC disregard as an input, which core uprates by a fifth from 2023 to 2024. With ``masked`` it applies only where the From 6dc47664d4aba09767d826c0fccec30d43e1c629 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 13:44:34 -0400 Subject: [PATCH 18/29] Compute the model's outputs once per year in the replacement tests Each computed replacement now runs one simulation against outputs the model computes once for 2024 and once for 2026-27. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_wtc_disregard.py | 72 +++++++++++-------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index bb9a4ba677..20c1399787 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -1075,9 +1075,8 @@ def test_supplied_deduction_leaves_the_limit_on_the_whole_charge(): def assert_forwarding_changes_nothing(build, systems, outputs): - """Each forwarding reform alone leaves every output as the model's, which - this returns. ``build`` makes the population's simulation under a - system.""" + """Each forwarding reform alone leaves every output as the model's. + ``build`` makes the population's simulation under a system.""" expected = outputs(build(systems[None])) for name, reformed in systems.items(): if name is None: @@ -1087,7 +1086,6 @@ def assert_forwarding_changes_nothing(build, systems, outputs): np.testing.assert_allclose( actual[key], values, rtol=0, atol=TOLERANCE, err_msg=f"{name}: {key}" ) - return expected @PROPERTY_SETTINGS @@ -1128,6 +1126,38 @@ def test_forwarding_reform_runs_for_an_adult_without_income(name): assert baseline.calculate(CHILDCARE, 2024)[0] == 0 +# The issue's family with and without the work condition and WTC, a family +# whose limit binds, one whose earnings fund the additional disregard, a +# pension-age claimant and a Northern Ireland family. +REPLACEMENT_UNITS = [ + *WITNESSES, + case(net=2_000, standard=260, childcare=9_100, wtc=1_000, other=1_000), + case(net=10_000), + case(pension_age=True), + case(region="NORTHERN_IRELAND"), +] + + +def replacement_outputs(tax_benefit_system, year): + """Every output, award included, for ``REPLACEMENT_UNITS``, with the model + dating the accommodation disregard.""" + sim = simulation( + REPLACEMENT_UNITS, + year, + tax_benefit_system=tax_benefit_system, + dated_accommodation=True, + ) + award = sim.calculate("housing_benefit_entitlement", year) + return {**results(sim, year), "award": np.asarray(award, dtype=float)} + + +@cache +def model_replacement_outputs(year): + """The model's outputs for ``REPLACEMENT_UNITS``, with tax credits kept in + 2026-27.""" + return replacement_outputs(system if year == 2024 else tax_credits_kept(), year) + + @pytest.mark.parametrize("year", [2024, 2026]) @pytest.mark.parametrize("mode", COMPUTED_REPLACEMENTS) def test_computed_replacements_of_the_wtc_disregard_change_nothing(mode, year): @@ -1137,35 +1167,19 @@ def test_computed_replacements_of_the_wtc_disregard_change_nothing(mode, year): circular definition and changes no output, award included. In 2026-27 tax credits stay in payment, and the model dates the accommodation disregard for families outside specified or temporary accommodation.""" - baseline = system if year == 2024 else tax_credits_kept() - reformed = computed_replacement(mode, baseline) + reformed = computed_replacement( + mode, system if year == 2024 else tax_credits_kept() + ) # Core computes adds and subtracts only where no formula runs. assert (reformed.get_variable(WTC_DISREGARD).get_formula(year) is None) == ( mode != "formula" ) - units = [ - *WITNESSES, - case(net=2_000, standard=260, childcare=9_100, wtc=1_000, other=1_000), - case(net=10_000), - case(pension_age=True), - case(region="NORTHERN_IRELAND"), - ] - - def outputs(sim): - return { - **results(sim, year), - "award": np.asarray( - sim.calculate("housing_benefit_entitlement", year), dtype=float - ), - } - - expected = assert_forwarding_changes_nothing( - lambda tax_benefit_system: simulation( - units, year, tax_benefit_system=tax_benefit_system, dated_accommodation=True - ), - {None: baseline, mode: reformed}, - outputs, - ) + expected = model_replacement_outputs(year) + actual = replacement_outputs(reformed, year) + for key, values in expected.items(): + np.testing.assert_allclose( + actual[key], values, rtol=0, atol=TOLERANCE, err_msg=f"{mode}: {key}" + ) # Para 56 applies to the issue's family, and to the family whose limit # binds: the lesser of 1,000 of WTC and 889.20. np.testing.assert_allclose( From 1d4a3e4757f20b0b6cf8d36ad038784f1a9d2bc9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 19:37:40 -0400 Subject: [PATCH 19/29] Release the Housing Benefit test modules' caches Co-Authored-By: Claude Opus 5.5 --- .../tests/test_housing_benefit_wtc_disregard.py | 8 ++++++++ .../tests/test_housing_benefit_wtc_disregard_segments.py | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index 20c1399787..bcd03f873d 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -259,6 +259,14 @@ def apply(self): self.neutralize_variable("housing_benefit_wtc_disregard") +@pytest.fixture(scope="module", autouse=True) +def release_caches(): + yield + forwarded.cache_clear() + tax_credits_kept.cache_clear() + model_replacement_outputs.cache_clear() + + FORWARDED_VARIABLES = (CHILDCARE, LIMIT, "housing_benefit_wtc_disregard") diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py index ad077b57dd..0f0ca0c967 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -71,6 +71,14 @@ SYSTEMS = {True: TAX_CREDITS, False: system} +@pytest.fixture(scope="module", autouse=True) +def release_caches(): + yield + forwarded.cache_clear() + tax_credits_kept.cache_clear() + previous_system.cache_clear() + + @cache def previous_system(active): return without_wtc_reservation(SYSTEMS[active]) From b9b2c0165eab737f2e8f507f6b278f85af85f3ba Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 22:49:11 -0400 Subject: [PATCH 20/29] Apply reform defined_for masks in each Housing Benefit segment A reform that adds defined_for to a Housing Benefit deduction and keeps the model's formula masked only the annual output. In 2026-27 the segment helpers rebuilt each period's amount without the condition, and the award tapered income from those amounts. hb_apply_defined_for reads the condition from the variable the simulation holds and applies it as core does, so each segment's accommodation, earnings and WTC disregards, childcare deduction, childcare limit and applicable income are nil where it fails. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2777.fixed.md | 1 + ...ing_benefit_applicable_income_disregard.py | 9 ++++-- ...ed_or_temporary_accommodation_disregard.py | 26 +++++++++++++-- .../housing_benefit_wtc_disregard.py | 32 +++++++++++++++---- .../housing_benefit_entitlement.py | 18 +++++++++-- 5 files changed, 71 insertions(+), 15 deletions(-) create mode 100644 changelog.d/2777.fixed.md diff --git a/changelog.d/2777.fixed.md b/changelog.d/2777.fixed.md new file mode 100644 index 0000000000..bcbbf5473d --- /dev/null +++ b/changelog.d/2777.fixed.md @@ -0,0 +1 @@ +Housing Benefit applies a defined_for condition that a reform adds to its earnings, Working Tax Credit or accommodation disregard, childcare deduction, childcare limit or applicable income in each 2026-27 accommodation segment, so the award matches the masked annual amounts. diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index 9633595e92..d9a3258a9e 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -5,6 +5,7 @@ ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, + hb_apply_defined_for, hb_uses_annual_override, ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( @@ -16,7 +17,7 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): """Apply childcare/earnings limits to one full accommodation amount. Return the earnings disregard, the WTC disregard and the childcare - deduction.""" + deduction, each nil where its defined_for condition fails.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) accommodation = min_(max_(accommodation, 0), max_(net - standard, 0)) @@ -47,7 +48,11 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): net, standard + accommodation + additional, ) - return disregard, wtc_disregard, childcare + return ( + hb_apply_defined_for(benunit, period, name, disregard), + wtc_disregard, + childcare, + ) class housing_benefit_applicable_income_disregard(Variable): diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index 2f113fdaed..e271ff844d 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -6,7 +6,8 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): """Keep annual inputs, replacement formulas and computed aggregates out of - recalculation.""" + recalculation. A defined_for mask on the model's formula is none of + these: the segment helpers apply it themselves (hb_apply_defined_for).""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) formula = variable.get_formula(period) if formula is None or formula.__code__ != default_formula.__code__: @@ -14,6 +15,23 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): return hb_reads_no_other_variable(benunit, period, variable_name) +def hb_apply_defined_for(benunit, period, variable_name, amount): + """The amount a segment helper rebuilt for the variable, where the + variable's defined_for condition holds, and the variable's default + elsewhere. Core masks the variable's annual output this way + (Simulation._calculate): it maps the condition to the variable's entity + and tests it for a value above zero. Reading defined_for from the + variable the simulation holds lets a condition a reform adds reach each + segment, and so the award, as it reaches the annual output.""" + variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) + if variable.defined_for is None: + return amount + condition = benunit.simulation.calculate( + variable.defined_for, period, map_to=variable.entity.key + ) + return where(np.asarray(condition) > 0, amount, variable.default_value) + + def hb_can_read_other_variables(variable, period): """Whether core, reading the variable for a period it holds no value for, can read another variable. It first calculates any ``defined_for`` @@ -47,7 +65,8 @@ def hb_reads_no_other_variable(benunit, period, variable_name): def hb_accommodation_segments(benunit, period, parameters): - """Full annual-equivalent accommodation amounts and fiscal-year weights.""" + """Full annual-equivalent accommodation amounts and fiscal-year weights. + Each amount is nil where the disregard's defined_for condition fails.""" name = "housing_benefit_specified_or_temporary_accommodation_disregard" if hb_uses_annual_override( benunit, @@ -96,7 +115,8 @@ def hb_accommodation_segments(benunit, period, parameters): ], default=where(older, rates.single_older, rates.single_younger), ) - yield where(applies, weekly * WEEKS_IN_YEAR, 0), share + amount = where(applies, weekly * WEEKS_IN_YEAR, 0) + yield hb_apply_defined_for(benunit, period, name, amount), share class housing_benefit_specified_or_temporary_accommodation_disregard(Variable): diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index fd2572a7d4..ebb47816cf 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -10,6 +10,7 @@ ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, + hb_apply_defined_for, hb_uses_annual_override, ) @@ -24,10 +25,11 @@ def hb_fixed_childcare_deduction(benunit, period, parameters): return benunit(childcare.__name__, period) limit = housing_benefit_childcare_earnings_limit if hb_uses_annual_override(benunit, period, limit.__name__, limit.formula): - return min_( + deduction = min_( hb_capped_childcare_charges(benunit, period, parameters), benunit(limit.__name__, period), ) + return hb_apply_defined_for(benunit, period, childcare.__name__, deduction) return None @@ -35,26 +37,42 @@ def hb_segment_childcare_deduction(benunit, period, parameters, accommodation): """The childcare deduction in force where the accommodation disregard has this full annual amount: the annual deduction where hb_fixed_childcare_deduction gives one, and otherwise the lesser of the - capped charge and the earnings and tax-credit limit.""" + capped charge and the earnings and tax-credit limit. The limit is nil + where its defined_for condition fails, and so is the deduction where + its own fails.""" childcare = hb_fixed_childcare_deduction(benunit, period, parameters) if childcare is not None: return childcare - return min_( - hb_capped_childcare_charges(benunit, period, parameters), + limit = hb_apply_defined_for( + benunit, + period, + housing_benefit_childcare_earnings_limit.__name__, hb_childcare_earnings_limit(benunit, period, parameters, accommodation), ) + return hb_apply_defined_for( + benunit, + period, + housing_benefit_applicable_income_childcare_element.__name__, + min_(hb_capped_childcare_charges(benunit, period, parameters), limit), + ) def hb_segment_wtc_disregard(benunit, period, parameters, accommodation, childcare): """The WTC disregard in one accommodation segment, where Sch 4 para - 17(3)(b) counts this childcare deduction. A supplied, neutralized or - replaced annual amount applies in every segment.""" + 17(3)(b) counts this childcare deduction, and nil where its defined_for + condition fails. A supplied, neutralized or replaced annual amount + applies in every segment.""" name = "housing_benefit_wtc_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_wtc_disregard.formula ): return benunit(name, period) - return hb_wtc_disregard(benunit, period, parameters, accommodation, childcare) + return hb_apply_defined_for( + benunit, + period, + name, + hb_wtc_disregard(benunit, period, parameters, accommodation, childcare), + ) class housing_benefit_wtc_disregard(Variable): diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py index 9bf79e518c..c539637774 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py @@ -8,6 +8,7 @@ ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, + hb_apply_defined_for, hb_uses_annual_override, ) @@ -28,6 +29,9 @@ class housing_benefit_entitlement(Variable): "ages and household status remain constant. Other parameters keep " "the model's annual convention. Supplied annual income/deductions " "and replacement formulas retain their normal override semantics. " + "A defined_for condition that a reform adds to the income, a " + "disregard, the childcare deduction or its limit applies in each " + "segment. " "Annual income intermediates are not period-specific assessments." ) entity = BenUnit @@ -113,9 +117,17 @@ def formula(benunit, period, parameters): segment_income = where( retain_annual_income, income, - max_( - 0, - income_before_deductions - disregard - wtc_disregard - childcare, + hb_apply_defined_for( + benunit, + period, + "housing_benefit_applicable_income", + max_( + 0, + income_before_deductions + - disregard + - wtc_disregard + - childcare, + ), ), ) taper = max_(0, segment_income - applicable_amount) * withdrawal_rate From 9876ff9a23971c78013d986d7d657169d18917ab Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sat, 31 Oct 2026 23:28:23 -0400 Subject: [PATCH 21/29] Test reform defined_for masks in each Housing Benefit segment One test each for the accommodation, earnings and WTC disregards, the childcare deduction, its limit and applicable income, with the condition failing and holding; the issue's reform; a supplied deduction; and a condition, on benefit units or people, that holds for one of two benefit units in a household. Hypothesis properties check that annual disregards equal their day-weighted segments, failed conditions give nil, units whose conditions hold keep the model's outputs, the award matches an independent calculation within each segment, and one-segment years give the annual route's award. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_segment_masks.py | 627 ++++++++++++++++++ .../test_housing_benefit_wtc_disregard.py | 25 +- 2 files changed, 646 insertions(+), 6 deletions(-) create mode 100644 policyengine_uk/tests/test_housing_benefit_segment_masks.py diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py new file mode 100644 index 0000000000..c5fa180593 --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -0,0 +1,627 @@ +"""Housing Benefit accommodation segments under a reform's defined_for masks. + +A reform can give a Housing Benefit amount a ``defined_for`` condition and +keep the model's formula. Core then masks the annual output: the amount +where the condition holds, nil where it fails. In 2026-27 the award is +calculated separately before and after 5 October, when SI 2026/753 reg 1(1) +brings the Sch 4 para 18 accommodation disregard into force, from amounts +the segment helpers rebuild. Each helper applies the condition to its own +amount (issue #2777). + +For every generated population, with or without tax credits, and any +condition on the accommodation, earnings and WTC disregards, the childcare +deduction, its limit and applicable income: + +M1. Each annual disregard equals the day-weighted sum of its segment amounts. +M2. Where a condition fails, its amount is nil in the annual output and in + every segment, unless the population supplies the amount as an input, + which applies as supplied, as core applies it. +M3. A benefit unit whose conditions all hold has the model's outputs, award + included. +M4. The award equals an independent calculation that applies the + regulations within each segment, with each failed condition's amount + nil, and combines the segments' awards by days. +M5. Each year but 2026-27 has one segment, and the award built from it + equals the award the model builds from annual income. + +The annual childcare deduction and its limit keep their single annual +calculation. Populations use core situations, as in +test_housing_benefit_wtc_disregard.py; they never load a survey dataset. +""" + +from functools import cache + +import numpy as np +import pytest +from hypothesis import example, given +from hypothesis import strategies as st +from policyengine_core.periods import period as period_ +from policyengine_core.reforms import Reform + +from policyengine_uk.model_api import BenUnit, Person, Variable, YEAR +from policyengine_uk.system import system +from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( + ACCOMMODATION, + CHILDCARE, + LIMIT, + PROPERTY_SETTINGS, + RENT, + TOLERANCE, + WTC_DISREGARD, + case, + legal_components, + results, + simulation, + tax_credits_kept, +) +from policyengine_uk.tests.test_housing_benefit_wtc_disregard_segments import ( + FULL_ACCOMMODATION, + SEGMENT_DAYS, + SEGMENT_EDGE_CASES, + SUPPLIED_LIMIT_SEGMENT_EDGE_CASES, + SUPPLIED_SEGMENT_EDGE_CASES, + WITHDRAWAL_RATE, + segment_populations, + specified_claimant, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income import ( + hb_income_before_deductions, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( + hb_segment_deductions, +) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( + hb_accommodation_segments, +) + + +YEAR_WITH_SEGMENTS = 2026 +EARNINGS = "housing_benefit_applicable_income_disregard" +INCOME = "housing_benefit_applicable_income" +AWARD = "housing_benefit_entitlement" +MASKED = (ACCOMMODATION, EARNINGS, WTC_DISREGARD, CHILDCARE, LIMIT, INCOME) +# The issue's claimant: a single claimant aged 40 outside specified or +# temporary accommodation, with £500 of earnings, a £260 ordinary disregard +# and £2,000 of WTC. +ISSUE_CLAIMANT = specified_claimant(specified=False) +# The same claimant paying £1,000 a year for one child's care. +CHILDCARE_CLAIMANT = specified_claimant(specified=False, children=1, childcare=1_000) + + +@pytest.fixture(scope="module", autouse=True) +def release_caches(): + yield + conditioned.cache_clear() + tax_credits_kept.cache_clear() + + +def baseline(active): + """The model, with tax credits kept in 2026-27 where ``active``.""" + return tax_credits_kept() if active else system + + +def condition_of(name): + return f"{name}_condition" + + +def masking_reform(conditions, entity=BenUnit): + """A reform that adds each condition as an input of ``entity``, true + unless set, and makes it the defined_for of each variable it maps to, + keeping the model's formula.""" + + class mask(Reform): + def apply(self): + for condition, names in conditions.items(): + + class condition_variable(Variable): + value_type = bool + default_value = True + definition_period = YEAR + label = "Reform condition for Housing Benefit amounts" + + condition_variable.entity = entity + condition_variable.__name__ = condition + self.add_variable(condition_variable) + for name in names: + + class masked(Variable): + defined_for = condition + + masked.__name__ = name + self.update_variable(masked) + + return mask + + +@cache +def conditioned(active): + """The model under a reform that gives each variable in ``MASKED`` its own + benefit-unit condition.""" + reform = masking_reform({condition_of(name): [name] for name in MASKED}) + return reform(baseline(active)) + + +def masked_simulation(units, year, active, **options): + """``units`` under ``conditioned``, each with the conditions it lists.""" + sim = simulation( + units, + year, + tax_benefit_system=conditioned(active), + dated_accommodation=True, + **options, + ) + for name in MASKED: + sim.set_input( + condition_of(name), + year, + np.array([unit["conditions"][name] for unit in units]), + ) + return sim + + +def holding(unit, *failing): + """``unit`` with every condition holding but those named.""" + return {**unit, "conditions": {name: name not in failing for name in MASKED}} + + +def outputs(sim, year): + return { + **results(sim, year), + "accommodation": np.asarray(sim.calculate(ACCOMMODATION, year), dtype=float), + "award": np.asarray(sim.calculate(AWARD, year), dtype=float), + } + + +def segments(sim, year): + """Each segment's share of the year and the amounts its helpers give.""" + benunit = sim.populations["benunit"] + period = period_(year) + parameters = sim.tax_benefit_system.parameters + result = [] + for accommodation, share in hb_accommodation_segments(benunit, period, parameters): + disregard, reserve, childcare = hb_segment_deductions( + benunit, period, parameters, accommodation + ) + result.append( + dict( + share=share, + accommodation=np.asarray(accommodation, dtype=float), + earnings_disregard=np.asarray(disregard, dtype=float), + reserve=np.asarray(reserve, dtype=float), + childcare=np.asarray(childcare, dtype=float), + ) + ) + return result + + +def day_weighted(segment_list, key): + return sum(segment["share"] * segment[key] for segment in segment_list) + + +def assert_close(actual, expected, message=""): + np.testing.assert_allclose( + actual, expected, rtol=0, atol=TOLERANCE, err_msg=message + ) + + +def legal_masked_award(unit, active): + """Apply the regulations within each segment of 2026-27 to scalar + assessed inputs, as test_housing_benefit_wtc_disregard_segments.py does, + with each failed condition's amount nil, then combine the awards by days. + A failed condition on the accommodation disregard, the childcare + deduction or its limit removes that amount before the earnings tests; + one on the earnings or WTC disregard, or on applicable income, removes it + from income. A supplied deduction or limit applies as supplied.""" + holds = unit["conditions"] + awards = [] + for in_force in (False, True): + applies = ( + in_force + and unit["specified"] + and unit["net"] > 0 + and not unit["pension_age"] + and holds[ACCOMMODATION] + ) + segment = {**unit, "accommodation": FULL_ACCOMMODATION if applies else 0} + if unit["supplied"] is None and not holds[CHILDCARE]: + segment["supplied"] = 0 + elif ( + unit["supplied"] is None + and unit["supplied_limit"] is None + and not holds[LIMIT] + ): + segment["supplied_limit"] = 0 + components = legal_components(segment, YEAR_WITH_SEGMENTS, active) + income = max( + 0, + unit["net"] + + unit["wtc"] + + unit["ctc"] + + unit["other"] + - (components["earnings_disregard"] if holds[EARNINGS] else 0) + - (components["reserve"] if holds[WTC_DISREGARD] else 0) + - components["childcare"], + ) + if not holds[INCOME]: + income = 0 + awards.append( + max(0, RENT - WITHDRAWAL_RATE * max(0, income - unit["applicable_amount"])) + ) + return sum(days * award for days, award in zip(SEGMENT_DAYS, awards)) / 365 + + +@st.composite +def masked_populations(draw): + """A population from the segment tests, each benefit unit with its own + draw of the six conditions.""" + return [ + { + **unit, + "conditions": draw( + st.fixed_dictionaries({name: st.booleans() for name in MASKED}) + ), + } + for unit in draw(segment_populations()) + ] + + +def rotating(units): + """Each unit with one condition failing, in turn, and the others holding.""" + return [ + holding(unit, MASKED[index % len(MASKED)]) for index, unit in enumerate(units) + ] + + +def failing(units): + """Each unit with every condition but income's failing.""" + return [holding(unit, *MASKED[:-1]) for unit in units] + + +MASKED_EDGE_CASES = rotating(SEGMENT_EDGE_CASES) +FAILING_EDGE_CASES = failing(SEGMENT_EDGE_CASES) +SUPPLIED_MASKED_EDGE_CASES = rotating(SUPPLIED_SEGMENT_EDGE_CASES) +SUPPLIED_LIMIT_MASKED_EDGE_CASES = rotating(SUPPLIED_LIMIT_SEGMENT_EDGE_CASES) + + +class issue_reform(Reform): + """The issue's reform: the earnings and WTC disregards apply only in + specified or temporary accommodation.""" + + def apply(self): + for name in (EARNINGS, WTC_DISREGARD): + + class eligibility_only(Variable): + defined_for = "in_specified_or_temporary_accommodation" + + eligibility_only.__name__ = name + self.update_variable(eligibility_only) + + +@pytest.mark.parametrize( + "specified,earnings,wtc,award", + [ + # The condition fails. The annual disregards are nil, and so is + # each segment's: before the fix, £260 and £889.20. Income is the + # £500 of earnings and the £2,000 of WTC, so the award is 10,400 - + # 0.65 * 2,500 = 8,775 in both segments, the annual route's award. + (False, [0, 0], [0, 0], 8_775), + # The condition holds, so the model's figures apply: £260 before 5 + # October; then also the £240 of accommodation disregard that the + # earnings left; and £889.20 of WTC disregard in both segments. + (True, [260, 500], [889.20, 889.20], 9_600.19), + ], +) +def test_issue_2777_reform_masks_each_segment(specified, earnings, wtc, award): + reformed = issue_reform(tax_credits_kept()) + unit = specified_claimant(specified=specified) + sim = simulation( + [unit], + YEAR_WITH_SEGMENTS, + tax_benefit_system=reformed, + dated_accommodation=True, + ) + before, after = segments(sim, YEAR_WITH_SEGMENTS) + assert_close( + [before["earnings_disregard"][0], after["earnings_disregard"][0]], earnings + ) + assert_close([before["reserve"][0], after["reserve"][0]], wtc) + for key, name in (("earnings_disregard", EARNINGS), ("reserve", WTC_DISREGARD)): + assert_close( + sim.calculate(name, YEAR_WITH_SEGMENTS), + day_weighted([before, after], key), + name, + ) + assert sim.calculate(AWARD, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +# Each variable, for the issue's claimant or one who needs it, with its +# condition failing and holding: the segments' amounts, the annual amount and +# the award. Where the condition holds the figures are the model's. +SINGLE_MASKS = [ + # Without the earnings disregard income is 2,500 - 889.20 = 1,610.80, and + # the award 10,400 - 0.65 * 1,610.80 = 9,352.98 in both segments. With + # it, 1,350.80 and 9,521.98. + pytest.param( + EARNINGS, + ISSUE_CLAIMANT, + "earnings_disregard", + ([0, 0], 9_352.98), + ([260, 260], 9_521.98), + id="earnings disregard", + ), + # Without the WTC disregard income is 2,500 - 260 = 2,240, and the award + # 10,400 - 0.65 * 2,240 = 8,944. + pytest.param( + WTC_DISREGARD, + ISSUE_CLAIMANT, + "reserve", + ([0, 0], 8_944), + ([889.20, 889.20], 9_521.98), + id="WTC disregard", + ), + # In specified accommodation: without the accommodation disregard the + # claimant is as the issue's, with an award of 9,521.98. With it, £77.73 a + # week from 5 October. + pytest.param( + ACCOMMODATION, + specified_claimant(), + "accommodation", + ([0, 0], 9_521.98), + ([0, FULL_ACCOMMODATION], 9_600.19), + id="accommodation disregard", + ), + # The limit is the 240 of earnings the standard disregard leaves and the + # 2,000 - 889.20 of WTC left after the para 56 disregard, 1,350.80, so + # the deduction is the whole 1,000 charge. Income is 2,500 - 260 - 889.20 + # - 1,000 = 350.80 and the award 10,400 - 0.65 * 350.80 = 10,171.98. + # Without the deduction, the award is the issue's claimant's. + pytest.param( + CHILDCARE, + CHILDCARE_CLAIMANT, + "childcare", + ([0, 0], 9_521.98), + ([1_000, 1_000], 10_171.98), + id="childcare deduction", + ), + # A nil limit leaves nil to deduct. + pytest.param( + LIMIT, + CHILDCARE_CLAIMANT, + "childcare", + ([0, 0], 9_521.98), + ([1_000, 1_000], 10_171.98), + id="childcare limit", + ), +] + + +@pytest.mark.parametrize("holds", [False, True]) +@pytest.mark.parametrize("name,unit,key,fails,held", SINGLE_MASKS) +def test_a_condition_reaches_each_segment(name, unit, key, fails, held, holds): + amounts, award = held if holds else fails + reformed = holding(unit) if holds else holding(unit, name) + sim = masked_simulation([reformed], YEAR_WITH_SEGMENTS, active=True) + segment_list = segments(sim, YEAR_WITH_SEGMENTS) + assert_close([segment[key][0] for segment in segment_list], amounts) + if name in (ACCOMMODATION, EARNINGS, WTC_DISREGARD): + assert_close( + sim.calculate(name, YEAR_WITH_SEGMENTS), day_weighted(segment_list, key) + ) + elif holds: + # The annual deduction and its limit keep their single calculation. + assert sim.calculate(CHILDCARE, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + 1_000, abs=TOLERANCE + ) + assert sim.calculate(LIMIT, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + 1_350.80, abs=TOLERANCE + ) + else: + assert sim.calculate(CHILDCARE, YEAR_WITH_SEGMENTS)[0] == 0 + if name == LIMIT: + assert sim.calculate(LIMIT, YEAR_WITH_SEGMENTS)[0] == 0 + assert sim.calculate(AWARD, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +@pytest.mark.parametrize( + "holds,income,award", + [ + # Nil income leaves the whole rent of 10,400. + (False, 0, 10_400), + (True, 1_350.80, 9_521.98), + ], +) +def test_a_condition_on_applicable_income_reaches_each_segment(holds, income, award): + unit = holding(ISSUE_CLAIMANT) if holds else holding(ISSUE_CLAIMANT, INCOME) + sim = masked_simulation([unit], YEAR_WITH_SEGMENTS, active=True) + assert sim.calculate(INCOME, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + income, abs=TOLERANCE + ) + assert sim.calculate(AWARD, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +def test_a_supplied_deduction_applies_whatever_its_condition(): + """Core returns an input without applying the variable's condition, and + each segment deducts the supplied annual amount too. The lone parent of + test_supplied_annual_deduction_applies_in_every_segment, supplying the + £4,160 the model calculates, keeps its award of 7,394.22.""" + unit = holding(case(specified=True, net=8_000, wtc=2_000, other=3_000), CHILDCARE) + sim = masked_simulation([unit], YEAR_WITH_SEGMENTS, active=True) + sim.set_input(CHILDCARE, YEAR_WITH_SEGMENTS, [4_160]) + assert sim.calculate(CHILDCARE, YEAR_WITH_SEGMENTS)[0] == 4_160 + for segment in segments(sim, YEAR_WITH_SEGMENTS): + assert segment["childcare"][0] == pytest.approx(4_160, abs=TOLERANCE) + assert sim.calculate(AWARD, YEAR_WITH_SEGMENTS)[0] == pytest.approx( + 7_394.22, abs=TOLERANCE + ) + + +@pytest.mark.parametrize("entity", [BenUnit, Person]) +def test_a_condition_holding_for_one_of_two_benefit_units_in_a_household(entity): + """Two of the issue's claimants in specified accommodation share a + household. One condition masks the accommodation, earnings and WTC + disregards, the childcare deduction and its limit, and holds only for + the first benefit unit, or for its adult. Core maps a person's condition + to the benefit unit as it does for the annual amounts.""" + names = (ACCOMMODATION, EARNINGS, WTC_DISREGARD, CHILDCARE, LIMIT) + condition = "housing_benefit_reform_condition" + reformed = masking_reform({condition: names}, entity)(tax_credits_kept()) + units = [specified_claimant(), specified_claimant()] + sim = simulation( + units, + YEAR_WITH_SEGMENTS, + tax_benefit_system=reformed, + dated_accommodation=True, + one_household=True, + ) + assert len(sim.calculate("household_id", YEAR_WITH_SEGMENTS)) == 1 + # One adult in each benefit unit, so the people's and the benefit + # units' conditions both read [True, False]. + sim.set_input(condition, YEAR_WITH_SEGMENTS, [True, False]) + before, after = segments(sim, YEAR_WITH_SEGMENTS) + # The first keeps the model's amounts; the second has none, so its + # income is 2,500 and its award 10,400 - 0.65 * 2,500 = 8,775. + assert_close(after["accommodation"], [FULL_ACCOMMODATION, 0]) + assert_close(before["earnings_disregard"], [260, 0]) + assert_close(after["earnings_disregard"], [500, 0]) + assert_close(before["reserve"], [889.20, 0]) + assert_close(after["reserve"], [889.20, 0]) + for key, name in ( + ("accommodation", ACCOMMODATION), + ("earnings_disregard", EARNINGS), + ("reserve", WTC_DISREGARD), + ): + assert_close( + sim.calculate(name, YEAR_WITH_SEGMENTS), + day_weighted([before, after], key), + name, + ) + assert_close(sim.calculate(AWARD, YEAR_WITH_SEGMENTS), [9_600.19, 8_775]) + + +@PROPERTY_SETTINGS +@given(units=masked_populations(), active=st.booleans()) +@example(units=MASKED_EDGE_CASES, active=True) +@example(units=MASKED_EDGE_CASES, active=False) +@example(units=FAILING_EDGE_CASES, active=True) +@example(units=SUPPLIED_MASKED_EDGE_CASES, active=True) +@example(units=SUPPLIED_LIMIT_MASKED_EDGE_CASES, active=True) +def test_masked_segments_add_up_and_match_the_regulations(units, active): + """M1, M2 and M4 in 2026-27.""" + sim = masked_simulation(units, YEAR_WITH_SEGMENTS, active) + actual = outputs(sim, YEAR_WITH_SEGMENTS) + segment_list = segments(sim, YEAR_WITH_SEGMENTS) + assert len(segment_list) == 2 + # M1. + for key in ("accommodation", "earnings_disregard", "reserve"): + assert_close(actual[key], day_weighted(segment_list, key), key) + # M2. + holds = { + name: np.array([unit["conditions"][name] for unit in units]) for name in MASKED + } + deduction_supplied = units[0]["supplied"] is not None + limit_supplied = units[0]["supplied_limit"] is not None + fails = { + "accommodation": ~holds[ACCOMMODATION], + "earnings_disregard": ~holds[EARNINGS], + "reserve": ~holds[WTC_DISREGARD], + } + if not deduction_supplied: + fails["childcare"] = ~holds[CHILDCARE] | ( + ~holds[LIMIT] if not limit_supplied else False + ) + if not deduction_supplied and not limit_supplied: + fails["limit"] = ~holds[LIMIT] + for key, failed in fails.items(): + assert np.all(actual[key][failed] == 0), key + for segment in segment_list: + if key in segment: + assert np.all(segment[key][failed] == 0), key + assert np.all(actual["income"][~holds[INCOME]] == 0) + # Nil income leaves the whole rent. + assert_close(actual["award"][~holds[INCOME]], RENT) + # M4. + assert_close(actual["award"], [legal_masked_award(unit, active) for unit in units]) + + +@PROPERTY_SETTINGS +@given(units=masked_populations(), active=st.booleans()) +@example(units=MASKED_EDGE_CASES, active=True) +@example(units=SUPPLIED_MASKED_EDGE_CASES, active=True) +def test_benefit_units_whose_conditions_hold_keep_the_models_outputs(units, active): + """M3, against the model without the reform. Benefit units are assessed + separately, so a failed condition in one does not reach another.""" + sim = masked_simulation(units, YEAR_WITH_SEGMENTS, active) + model = simulation( + units, + YEAR_WITH_SEGMENTS, + tax_benefit_system=baseline(active), + dated_accommodation=True, + ) + held = np.array([all(unit["conditions"].values()) for unit in units]) + expected = outputs(model, YEAR_WITH_SEGMENTS) + for key, values in outputs(sim, YEAR_WITH_SEGMENTS).items(): + assert_close(values[held], expected[key][held], key) + + +def segment_route_award(sim, units, year): + """The award built from each segment's income, as entitlement builds it + in 2026-27, applying the income condition from the units directly.""" + benunit = sim.populations["benunit"] + period = period_(year) + parameters = sim.tax_benefit_system.parameters + before = np.asarray(hb_income_before_deductions(benunit, period, parameters)) + retain = np.asarray( + sim.calculate("housing_benefit_pension_age_regulations_apply", year) + ) | np.asarray(sim.calculate("housing_benefit_on_passporting_benefit", year)) + income = np.asarray(sim.calculate(INCOME, year), dtype=float) + income_holds = np.array([unit["conditions"][INCOME] for unit in units]) + applicable_amount = np.array([unit["applicable_amount"] for unit in units]) + award = 0 + for segment in segments(sim, year): + segment_income = np.where( + income_holds, + np.maximum( + 0, + before + - segment["earnings_disregard"] + - segment["reserve"] + - segment["childcare"], + ), + 0, + ) + segment_income = np.where(retain, income, segment_income) + award = award + segment["share"] * np.maximum( + 0, + RENT - WITHDRAWAL_RATE * np.maximum(0, segment_income - applicable_amount), + ) + return award + + +@PROPERTY_SETTINGS +@given( + units=masked_populations(), + year=st.sampled_from([2024, 2025, 2027]), + active=st.booleans(), +) +@example(units=MASKED_EDGE_CASES, year=2027, active=True) +@example(units=MASKED_EDGE_CASES, year=2024, active=True) +@example(units=FAILING_EDGE_CASES, year=2027, active=True) +@example(units=SUPPLIED_MASKED_EDGE_CASES, year=2027, active=True) +@example(units=SUPPLIED_LIMIT_MASKED_EDGE_CASES, year=2024, active=False) +def test_one_segment_gives_the_annual_routes_award(units, year, active): + """M5: outside 2026-27 the accommodation amounts do not change within + the year. The single segment's amounts are the annual outputs, and the + award built from them is the model's, which reads annual income.""" + sim = masked_simulation(units, year, active) + actual = outputs(sim, year) + (segment,) = segments(sim, year) + assert segment["share"] == 1 + for key in ("accommodation", "earnings_disregard", "reserve", "childcare"): + assert_close(segment[key], actual[key], key) + assert_close(segment_route_award(sim, units, year), actual["award"]) diff --git a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py index bcd03f873d..4bd875aa47 100644 --- a/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -425,11 +425,18 @@ def apply(self): def simulation( - units, year, previous=False, tax_benefit_system=None, dated_accommodation=False + units, + year, + previous=False, + tax_benefit_system=None, + dated_accommodation=False, + one_household=False, ): """Build the population. With ``dated_accommodation`` the model dates the accommodation disregard itself, and the population pays rent of - ``RENT``; otherwise each unit supplies its annual accommodation amount.""" + ``RENT``; otherwise each unit supplies its annual accommodation amount. + With ``one_household`` every unit lives in one household, in the first + unit's region; otherwise each lives in its own.""" for key in ("supplied", "supplied_limit"): supplied = [unit[key] is not None for unit in units] assert all(supplied) or not any(supplied), f"{key} for all or none" @@ -523,10 +530,16 @@ def simulation( family[CHILDCARE] = {year: unit["supplied"]} if unit["supplied_limit"] is not None: family[LIMIT] = {year: unit["supplied_limit"]} - households[f"household_{index}"] = { - "members": members, - "region": {year: unit["region"]}, - } + if one_household: + household = households.setdefault( + "household", {"members": [], "region": {year: unit["region"]}} + ) + household["members"].extend(members) + else: + households[f"household_{index}"] = { + "members": members, + "region": {year: unit["region"]}, + } if tax_benefit_system is None: tax_benefit_system = without_wtc_reservation(system) if previous else system return Simulation( From 90b4622bcf079c34e56f0b7a5ca7224595874f34 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 00:17:41 -0400 Subject: [PATCH 22/29] Tighten the hb_apply_defined_for docstring Co-Authored-By: Claude Opus 5.5 --- ...t_specified_or_temporary_accommodation_disregard.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index e271ff844d..2c260a89ec 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -16,13 +16,13 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): def hb_apply_defined_for(benunit, period, variable_name, amount): - """The amount a segment helper rebuilt for the variable, where the + """The amount a segment helper rebuilt for the variable where the variable's defined_for condition holds, and the variable's default - elsewhere. Core masks the variable's annual output this way + elsewhere. Core masks the annual output the same way (Simulation._calculate): it maps the condition to the variable's entity - and tests it for a value above zero. Reading defined_for from the - variable the simulation holds lets a condition a reform adds reach each - segment, and so the award, as it reaches the annual output.""" + and keeps the amount where the condition exceeds zero. The condition + comes from the variable the simulation holds, so one that a reform adds + reaches each segment, as it reaches the annual output.""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) if variable.defined_for is None: return amount From 6e631d335e46226c94df4036c861ac97f67bb947 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 04:36:21 -0500 Subject: [PATCH 23/29] Calculate the segment earnings disregard without the WTC disregard The annual earnings disregard summed hb_segment_deductions(...)[0], and that helper calculated the WTC disregard the caller discarded. With the segment mask in place, a reform giving the WTC disregard a defined_for condition that reads the earnings disregard raised CycleError: the earnings formula reached the WTC condition. hb_segment_earnings_disregard now returns the earnings disregard and the childcare deduction, and hb_segment_deductions adds the WTC disregard for entitlement. The amounts don't change. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_segment_masks.py | 85 +++++++++++++++++++ ...ing_benefit_applicable_income_disregard.py | 47 +++++++--- 2 files changed, 119 insertions(+), 13 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index c5fa180593..7f84b6cca6 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -37,6 +37,7 @@ from hypothesis import strategies as st from policyengine_core.periods import period as period_ from policyengine_core.reforms import Reform +from policyengine_core.simulations import Simulation from policyengine_uk.model_api import BenUnit, Person, Variable, YEAR from policyengine_uk.system import system @@ -625,3 +626,87 @@ def test_one_segment_gives_the_annual_routes_award(units, year, active): for key in ("accommodation", "earnings_disregard", "reserve", "childcare"): assert_close(segment[key], actual[key], key) assert_close(segment_route_award(sim, units, year), actual["award"]) + + +class wtc_disregard_reads_earnings(Reform): + """The WTC disregard applies only where the earnings disregard is + positive.""" + + def apply(self): + class masked(Variable): + defined_for = EARNINGS + + masked.__name__ = WTC_DISREGARD + self.update_variable(masked) + + +def test_a_wtc_condition_can_read_the_earnings_disregard(): + """The annual earnings disregard calculates no WTC disregard, so a + condition on the WTC disregard can read it. Assessed inputs for 2024: + £500 of net earnings, a £260 standard disregard, no accommodation + disregard or childcare deduction, the work condition met and £2,000 of + WTC. The earnings disregard is the £260 standard disregard, with the + condition and without it.""" + inputs = { + "housing_benefit_net_earnings": 500, + "housing_benefit_applied_standard_earnings_disregard": 260, + ACCOMMODATION: 0, + CHILDCARE: 0, + "housing_benefit_on_passporting_benefit": False, + "meets_housing_benefit_additional_earnings_disregard_conditions": True, + "working_tax_credit": 2_000, + } + situation = { + "people": {"adult": {}}, + "benunits": { + "family": { + "members": ["adult"], + **{name: {2024: value} for name, value in inputs.items()}, + } + }, + "households": {"home": {"members": ["adult"]}}, + } + for tax_benefit_system in (system, wtc_disregard_reads_earnings(system)): + sim = Simulation(tax_benefit_system=tax_benefit_system, situation=situation) + assert sim.calculate(EARNINGS, 2024)[0] == pytest.approx(260, abs=TOLERANCE) + + +@pytest.mark.parametrize( + "year,active,unit,earnings,wtc,award", + [ + # The issue's claimant in 2024. The earnings disregard is £260, so + # the condition holds and the model's figures apply: income is 2,500 + # - 260 - 889.20 = 1,350.80 and the award 10,400 - 0.65 * 1,350.80. + (2024, False, ISSUE_CLAIMANT, 260, 889.20, 9_521.98), + # Without earnings the disregard is nil and the condition fails, so + # the WTC disregard is nil too: income is the £2,000 of WTC and the + # award 10,400 - 0.65 * 2,000. + (2024, False, specified_claimant(specified=False, net=0), 0, 0, 9_100), + # In 2026-27 in specified accommodation, with tax credits kept: £260 + # before 5 October and £500 after, weighted by 182 and 183 days, so + # the condition holds and the issue's figures apply. + ( + 2026, + True, + specified_claimant(), + (182 * 260 + 183 * 500) / 365, + 889.20, + 9_600.19, + ), + ], +) +def test_a_wtc_condition_reading_the_earnings_disregard_runs( + year, active, unit, earnings, wtc, award +): + """The issue's claimant, with every component the model calculates, + under a condition that gives the WTC disregard only where the earnings + disregard is positive.""" + sim = simulation( + [unit], + year, + tax_benefit_system=wtc_disregard_reads_earnings(baseline(active)), + dated_accommodation=True, + ) + assert sim.calculate(EARNINGS, year)[0] == pytest.approx(earnings, abs=TOLERANCE) + assert sim.calculate(WTC_DISREGARD, year)[0] == pytest.approx(wtc, abs=TOLERANCE) + assert sim.calculate(AWARD, year)[0] == pytest.approx(award, abs=TOLERANCE) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index d9a3258a9e..e93c2665ea 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -14,24 +14,30 @@ ) -def hb_segment_deductions(benunit, period, parameters, accommodation): - """Apply childcare/earnings limits to one full accommodation amount. - Return the earnings disregard, the WTC disregard and the childcare - deduction, each nil where its defined_for condition fails.""" +def hb_capped_accommodation(benunit, period, accommodation): + """Cap a full accommodation amount at the earnings the standard + disregard leaves (Sch 4 para 18).""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) - accommodation = min_(max_(accommodation, 0), max_(net - standard, 0)) + return min_(max_(accommodation, 0), max_(net - standard, 0)) + + +def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): + """Apply the childcare and earnings limits to one full accommodation + amount. Return the earnings disregard, or its default where its + defined_for condition fails, and the childcare deduction. Calculate no + WTC disregard, so a condition on that disregard can read this one.""" + net = max_(benunit("housing_benefit_net_earnings", period), 0) + standard = hb_standard_earnings_disregard(benunit, period) + accommodation = hb_capped_accommodation(benunit, period, accommodation) childcare = hb_segment_childcare_deduction( benunit, period, parameters, accommodation ) - wtc_disregard = hb_segment_wtc_disregard( - benunit, period, parameters, accommodation, childcare - ) name = "housing_benefit_applicable_income_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_applicable_income_disregard.formula ): - return benunit(name, period), wtc_disregard, childcare + return benunit(name, period), childcare p = parameters(period).gov.dwp.housing_benefit.means_test.income_disregard additional = where( benunit( @@ -48,11 +54,25 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): net, standard + accommodation + additional, ) - return ( - hb_apply_defined_for(benunit, period, name, disregard), - wtc_disregard, + return hb_apply_defined_for(benunit, period, name, disregard), childcare + + +def hb_segment_deductions(benunit, period, parameters, accommodation): + """Apply the childcare and earnings limits to one full accommodation + amount. Return the earnings disregard, the WTC disregard and the + childcare deduction, each its variable's default where its defined_for + condition fails.""" + disregard, childcare = hb_segment_earnings_disregard( + benunit, period, parameters, accommodation + ) + wtc_disregard = hb_segment_wtc_disregard( + benunit, + period, + parameters, + hb_capped_accommodation(benunit, period, accommodation), childcare, ) + return disregard, wtc_disregard, childcare class housing_benefit_applicable_income_disregard(Variable): @@ -104,7 +124,8 @@ class housing_benefit_applicable_income_disregard(Variable): def formula(benunit, period, parameters): return sum( - hb_segment_deductions(benunit, period, parameters, accommodation)[0] * share + hb_segment_earnings_disregard(benunit, period, parameters, accommodation)[0] + * share for accommodation, share in hb_accommodation_segments( benunit, period, parameters ) From 02718346ba9ee76254c10bfed71ef071787a76b8 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 04:36:25 -0500 Subject: [PATCH 24/29] Test numeric defined_for conditions and non-nil defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Conditions of -1, 1 and 0 with a default of 7 give 7, 99 and 7 from Core and from hb_apply_defined_for, and applicable income with a £17 default reaches each 2026-27 segment. The tests fail if the helper uses nil instead of the variable's default or tests the condition with != 0. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_segment_masks.py | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index 7f84b6cca6..af2f552a1d 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -73,6 +73,7 @@ ) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, + hb_apply_defined_for, ) @@ -710,3 +711,68 @@ def test_a_wtc_condition_reading_the_earnings_disregard_runs( assert sim.calculate(EARNINGS, year)[0] == pytest.approx(earnings, abs=TOLERANCE) assert sim.calculate(WTC_DISREGARD, year)[0] == pytest.approx(wtc, abs=TOLERANCE) assert sim.calculate(AWARD, year)[0] == pytest.approx(award, abs=TOLERANCE) + + +NUMERIC_CONDITION = "housing_benefit_numeric_reform_condition" +PROBE = "housing_benefit_reform_probe_amount" + + +class numeric_conditions(Reform): + """A numeric benefit-unit condition. A probe amount of £99, with a + default of £7, and applicable income, with a default of £17, apply where + it exceeds zero.""" + + def apply(self): + class condition(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + label = "Numeric reform condition for Housing Benefit amounts" + + class probe(Variable): + value_type = float + entity = BenUnit + definition_period = YEAR + label = "Reform probe amount" + default_value = 7 + defined_for = NUMERIC_CONDITION + + def formula(benunit, period, parameters): + return benunit.filled_array(99) + + class income(Variable): + default_value = 17 + defined_for = NUMERIC_CONDITION + + condition.__name__ = NUMERIC_CONDITION + probe.__name__ = PROBE + income.__name__ = INCOME + self.add_variable(condition) + self.add_variable(probe) + self.update_variable(income) + + +def test_a_numeric_condition_applies_where_it_exceeds_zero(): + """Core keeps an amount where its condition exceeds zero and returns the + variable's default elsewhere, negative conditions included, and so does + hb_apply_defined_for. Three of the issue's claimants in 2026-27, with + tax credits kept, have conditions of -1, 1 and 0. Where income's + condition fails, each segment's income is its £17 default, and the award + is 10,400 - 0.65 * 17 = 10,388.95; where it holds, the model's + £1,350.80 gives 9,521.98.""" + sim = simulation( + [ISSUE_CLAIMANT] * 3, + YEAR_WITH_SEGMENTS, + tax_benefit_system=numeric_conditions(tax_credits_kept()), + dated_accommodation=True, + ) + sim.set_input(NUMERIC_CONDITION, YEAR_WITH_SEGMENTS, [-1, 1, 0]) + helper = hb_apply_defined_for( + sim.populations["benunit"], period_(YEAR_WITH_SEGMENTS), PROBE, np.full(3, 99) + ) + assert_close(helper, [7, 99, 7]) + assert_close(sim.calculate(PROBE, YEAR_WITH_SEGMENTS), [7, 99, 7]) + assert_close(sim.calculate(INCOME, YEAR_WITH_SEGMENTS), [17, 1_350.80, 17]) + assert_close( + sim.calculate(AWARD, YEAR_WITH_SEGMENTS), [10_388.95, 9_521.98, 10_388.95] + ) From b8aec25f7fa640afb42262f0ac7ea5f8aa490bc1 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 04:36:29 -0500 Subject: [PATCH 25/29] State what a failed disregard condition leaves in the childcare limit The limit's WTC reserve ignores a condition on the WTC disregard, and the limit subtracts the standard disregard whatever the earnings disregard's condition gives. The docstrings and M4 now say so, and a test pins both cases with a limit a reform author can substitute. M2 states that a failed condition gives the variable's default, and that the award is the maximum benefit after non-dependant deductions. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_segment_masks.py | 173 +++++++++++++++--- ...ousing_benefit_childcare_earnings_limit.py | 11 +- 2 files changed, 160 insertions(+), 24 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index af2f552a1d..6ea19e6d0a 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -1,32 +1,44 @@ """Housing Benefit accommodation segments under a reform's defined_for masks. -A reform can give a Housing Benefit amount a ``defined_for`` condition and -keep the model's formula. Core then masks the annual output: the amount -where the condition holds, nil where it fails. In 2026-27 the award is -calculated separately before and after 5 October, when SI 2026/753 reg 1(1) -brings the Sch 4 para 18 accommodation disregard into force, from amounts -the segment helpers rebuild. Each helper applies the condition to its own -amount (issue #2777). +A reform author can add a ``defined_for`` condition to a Housing Benefit +amount and keep the model's formula. Core then masks the annual output: it +keeps the amount where the condition exceeds zero and returns the +variable's default elsewhere. In 2026-27 entitlement calculates the award +separately before and after 5 October, when SI 2026/753 reg 1(1) brings the +Sch 4 para 18 accommodation disregard into force, from amounts the segment +helpers rebuild. Each helper applies the condition to its own amount (issue +#2777). For every generated population, with or without tax credits, and any condition on the accommodation, earnings and WTC disregards, the childcare -deduction, its limit and applicable income: +deduction, its limit and applicable income that reads none of these +amounts: M1. Each annual disregard equals the day-weighted sum of its segment amounts. -M2. Where a condition fails, its amount is nil in the annual output and in - every segment, unless the population supplies the amount as an input, - which applies as supplied, as core applies it. +M2. Where a condition fails, its amount takes the variable's default in the + annual output and in every segment, unless the population supplies the + amount as an input, which applies as supplied, as core applies it. + Where applicable income's condition fails, the award is the maximum + benefit less 65% of any excess of that default over the applicable + amount. M3. A benefit unit whose conditions all hold has the model's outputs, award included. M4. The award equals an independent calculation that applies the regulations within each segment, with each failed condition's amount - nil, and combines the segments' awards by days. + nil, and combines the segments' awards by days. The calculation settles + the childcare deduction before it removes a failed earnings or WTC + disregard from income, as the model does: the limit still counts the + standard and accommodation disregards and keeps back the WTC the model + would disregard (test_a_failed_disregard_still_limits_childcare). M5. Each year but 2026-27 has one segment, and the award built from it equals the award the model builds from annual income. -The annual childcare deduction and its limit keep their single annual -calculation. Populations use core situations, as in -test_housing_benefit_wtc_disregard.py; they never load a survey dataset. +The fixture's conditions are inputs, and its variables default to nil. Its +eligible rent is the rent, ``RENT``, with no non-dependant deductions, so +the maximum benefit is the whole rent. The annual childcare deduction and +its limit keep their single annual calculation. Populations use core +situations, as in test_housing_benefit_wtc_disregard.py; they never load a +survey dataset. """ from functools import cache @@ -39,7 +51,7 @@ from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation -from policyengine_uk.model_api import BenUnit, Person, Variable, YEAR +from policyengine_uk.model_api import BenUnit, Person, Variable, YEAR, max_, where from policyengine_uk.system import system from policyengine_uk.tests.test_housing_benefit_wtc_disregard import ( ACCOMMODATION, @@ -71,6 +83,9 @@ from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_applicable_income_disregard import ( hb_segment_deductions, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_childcare_earnings_limit import ( + hb_childcare_wtc_reserve, +) from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_specified_or_temporary_accommodation_disregard import ( hb_accommodation_segments, hb_apply_defined_for, @@ -429,16 +444,23 @@ def test_a_condition_reaches_each_segment(name, unit, key, fails, held, holds): @pytest.mark.parametrize( - "holds,income,award", + "holds,non_dependant,income,award", [ - # Nil income leaves the whole rent of 10,400. - (False, 0, 10_400), - (True, 1_350.80, 9_521.98), + # Income takes its nil default, so the award is the maximum benefit: + # the eligible rent of 10,400 less any non-dependant deductions. + (False, 0, 0, 10_400), + (False, 500, 0, 9_900), + (True, 0, 1_350.80, 9_521.98), ], ) -def test_a_condition_on_applicable_income_reaches_each_segment(holds, income, award): +def test_a_condition_on_applicable_income_reaches_each_segment( + holds, non_dependant, income, award +): unit = holding(ISSUE_CLAIMANT) if holds else holding(ISSUE_CLAIMANT, INCOME) sim = masked_simulation([unit], YEAR_WITH_SEGMENTS, active=True) + sim.set_input( + "housing_benefit_non_dep_deductions", YEAR_WITH_SEGMENTS, [non_dependant] + ) assert sim.calculate(INCOME, YEAR_WITH_SEGMENTS)[0] == pytest.approx( income, abs=TOLERANCE ) @@ -545,7 +567,9 @@ def test_masked_segments_add_up_and_match_the_regulations(units, active): if key in segment: assert np.all(segment[key][failed] == 0), key assert np.all(actual["income"][~holds[INCOME]] == 0) - # Nil income leaves the whole rent. + # The fixture's nil default income leaves the maximum benefit, the + # whole rent: the eligible rent is RENT, with no non-dependant + # deductions. assert_close(actual["award"][~holds[INCOME]], RENT) # M4. assert_close(actual["award"], [legal_masked_award(unit, active) for unit in units]) @@ -776,3 +800,108 @@ def test_a_numeric_condition_applies_where_it_exceeds_zero(): assert_close( sim.calculate(AWARD, YEAR_WITH_SEGMENTS), [10_388.95, 9_521.98, 10_388.95] ) + + +class limit_follows_conditions(Variable): + """The earnings and tax-credit limit, releasing to childcare the + earnings a failed earnings condition no longer disregards and the WTC a + failed WTC condition no longer reserves.""" + + value_type = float + entity = BenUnit + definition_period = YEAR + + def formula(benunit, period, parameters): + net = max_(benunit("housing_benefit_net_earnings", period), 0) + disregarded = benunit( + "housing_benefit_applied_standard_earnings_disregard", period + ) + benunit(ACCOMMODATION, period) + earnings = where( + benunit(condition_of(EARNINGS), period), + max_(0, net - disregarded), + net, + ) + reserve = where( + benunit(condition_of(WTC_DISREGARD), period), + hb_childcare_wtc_reserve(benunit, period, parameters), + 0, + ) + return ( + earnings + + max_(benunit("working_tax_credit", period) - reserve, 0) + + max_(benunit("child_tax_credit", period), 0) + ) + + +limit_follows_conditions.__name__ = LIMIT + + +class release_to_childcare(Reform): + def apply(self): + self.update_variable(limit_follows_conditions) + + +@pytest.mark.parametrize( + "fails,unit,active,limit,award,released_limit,released_award", + [ + # WTC condition fails, for £500 of earnings, a £260 standard + # disregard, £2,000 of WTC and £3,000 of childcare. The limit still + # keeps back £889.20 of WTC: 240 + 2,000 - 889.20 = 1,350.80. Income + # is 2,500 - 260 - 1,350.80 = 889.20 and the award 10,400 - 0.65 * + # 889.20. A limit that releases that WTC gives 2,240, nil income and + # the whole rent. + ( + WTC_DISREGARD, + case(net=500, standard=260, wtc=2_000, childcare=3_000), + True, + 1_350.80, + 9_822.02, + 2_240, + 10_400, + ), + # Earnings condition fails, for £500 of earnings, a £260 standard + # disregard, no WTC and £500 of childcare. The limit still subtracts + # the standard disregard, 500 - 260 = 240, so income is 500 - 240 = + # 260 and the award 10,400 - 0.65 * 260. A limit that releases those + # earnings gives 500, nil income and the whole rent. + ( + EARNINGS, + case(net=500, standard=260, wtc=0, childcare=500), + False, + 240, + 10_231, + 500, + 10_400, + ), + ], +) +def test_a_failed_disregard_still_limits_childcare( + fails, unit, active, limit, award, released_limit, released_award +): + """hb_childcare_wtc_reserve ignores a condition on the WTC disregard, + and the limit counts the standard disregard whatever the earnings + disregard's condition. A reform author who wants a failed condition to + fund childcare changes the limit too. In 2026-27, for a claimant with + one child outside specified accommodation.""" + unit = holding(unit, fails) + sim = masked_simulation([unit], YEAR_WITH_SEGMENTS, active) + benunit = sim.populations["benunit"] + period = period_(YEAR_WITH_SEGMENTS) + parameters = sim.tax_benefit_system.parameters + reserve = 889.20 if active else 0 + assert_close(hb_childcare_wtc_reserve(benunit, period, parameters), [reserve]) + assert sim.calculate(fails, YEAR_WITH_SEGMENTS)[0] == 0 + assert_close(sim.calculate(LIMIT, YEAR_WITH_SEGMENTS), [limit]) + assert_close(sim.calculate(AWARD, YEAR_WITH_SEGMENTS), [award]) + released = simulation( + [unit], + YEAR_WITH_SEGMENTS, + tax_benefit_system=release_to_childcare(conditioned(active)), + dated_accommodation=True, + ) + for name in MASKED: + released.set_input( + condition_of(name), YEAR_WITH_SEGMENTS, [unit["conditions"][name]] + ) + assert_close(released.calculate(LIMIT, YEAR_WITH_SEGMENTS), [released_limit]) + assert_close(released.calculate(AWARD, YEAR_WITH_SEGMENTS), [released_award]) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index 173dc55741..d655031aac 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -55,7 +55,11 @@ def hb_wtc_disregard(benunit, period, parameters, accommodation, childcare): def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): """The WTC this limit keeps from childcare for the Sch 5 para 56 disregard. By default the accommodation disregard has its annual - segments; an accommodation segment passes its own amount.""" + segments; an accommodation segment passes its own amount. A defined_for + condition on the WTC disregard doesn't reach this reserve: where the + condition fails, the limit still keeps back the WTC the model would + disregard. A reform author who wants that WTC to fund childcare changes + the limit too.""" name = "housing_benefit_wtc_disregard" if hb_reads_no_other_variable(benunit, period, name): return benunit(name, period) @@ -82,7 +86,10 @@ def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): def hb_childcare_earnings_limit(benunit, period, parameters, accommodation=None): """Remaining earnings and tax credits, without an additional-disregard loop. By default the accommodation disregard is the annual variable; an - accommodation segment passes its own.""" + accommodation segment passes its own. The limit subtracts the standard + and accommodation disregards even where a defined_for condition on the + earnings disregard fails; a reform author who wants those earnings to + fund childcare changes the limit too.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) reserve = hb_childcare_wtc_reserve(benunit, period, parameters, accommodation) From 3abb4115462b1cf4e367d40fccadb3c83202db6c Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 05:25:54 -0500 Subject: [PATCH 26/29] Use active verbs in the segment-mask docstrings and changelog Docstrings now say what each helper does and that a failed condition gives the variable's default. The changelog names the amounts the helpers rebuild. No code path changes. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2777.fixed.md | 2 +- .../test_housing_benefit_segment_masks.py | 122 ++++++++++-------- ...ing_benefit_applicable_income_disregard.py | 17 ++- ...ed_or_temporary_accommodation_disregard.py | 22 ++-- .../housing_benefit_wtc_disregard.py | 25 ++-- .../housing_benefit_entitlement.py | 6 +- 6 files changed, 101 insertions(+), 93 deletions(-) diff --git a/changelog.d/2777.fixed.md b/changelog.d/2777.fixed.md index bcbbf5473d..0ffc4b70a9 100644 --- a/changelog.d/2777.fixed.md +++ b/changelog.d/2777.fixed.md @@ -1 +1 @@ -Housing Benefit applies a defined_for condition that a reform adds to its earnings, Working Tax Credit or accommodation disregard, childcare deduction, childcare limit or applicable income in each 2026-27 accommodation segment, so the award matches the masked annual amounts. +Housing Benefit helpers apply reform conditions when they rebuild the earnings, Working Tax Credit and accommodation disregards, the childcare deduction, its limit and applicable income. diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index 6ea19e6d0a..e33b57682c 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -18,9 +18,9 @@ M2. Where a condition fails, its amount takes the variable's default in the annual output and in every segment, unless the population supplies the amount as an input, which applies as supplied, as core applies it. - Where applicable income's condition fails, the award is the maximum - benefit less 65% of any excess of that default over the applicable - amount. + Where applicable income's condition fails, the award equals the + maximum benefit less 65% of any excess of that default over the + applicable amount. M3. A benefit unit whose conditions all hold has the model's outputs, award included. M4. The award equals an independent calculation that applies the @@ -33,9 +33,9 @@ M5. Each year but 2026-27 has one segment, and the award built from it equals the award the model builds from annual income. -The fixture's conditions are inputs, and its variables default to nil. Its -eligible rent is the rent, ``RENT``, with no non-dependant deductions, so -the maximum benefit is the whole rent. The annual childcare deduction and +The fixture supplies the conditions as inputs, and its variables default +to nil. It sets the eligible rent to ``RENT`` and non-dependant deductions +to nil, so the maximum benefit equals the whole rent. The annual childcare deduction and its limit keep their single annual calculation. Populations use core situations, as in test_housing_benefit_wtc_disregard.py; they never load a survey dataset. @@ -122,8 +122,8 @@ def condition_of(name): def masking_reform(conditions, entity=BenUnit): - """A reform that adds each condition as an input of ``entity``, true - unless set, and makes it the defined_for of each variable it maps to, + """Return a reform that adds each condition as an input of ``entity``, + true unless set, and makes it the defined_for of each variable it maps to, keeping the model's formula.""" class mask(Reform): @@ -152,14 +152,15 @@ class masked(Variable): @cache def conditioned(active): - """The model under a reform that gives each variable in ``MASKED`` its own - benefit-unit condition.""" + """Return the model under a reform that gives each variable in + ``MASKED`` its own benefit-unit condition.""" reform = masking_reform({condition_of(name): [name] for name in MASKED}) return reform(baseline(active)) def masked_simulation(units, year, active, **options): - """``units`` under ``conditioned``, each with the conditions it lists.""" + """Build ``units`` under ``conditioned``, each with the conditions it + lists.""" sim = simulation( units, year, @@ -177,7 +178,7 @@ def masked_simulation(units, year, active, **options): def holding(unit, *failing): - """``unit`` with every condition holding but those named.""" + """Return ``unit`` with every condition holding but those named.""" return {**unit, "conditions": {name: name not in failing for name in MASKED}} @@ -190,7 +191,8 @@ def outputs(sim, year): def segments(sim, year): - """Each segment's share of the year and the amounts its helpers give.""" + """Return each segment's share of the year and the amounts its helpers + give.""" benunit = sim.populations["benunit"] period = period_(year) parameters = sim.tax_benefit_system.parameters @@ -269,8 +271,8 @@ def legal_masked_award(unit, active): @st.composite def masked_populations(draw): - """A population from the segment tests, each benefit unit with its own - draw of the six conditions.""" + """Draw a population from the segment tests, each benefit unit with its + own draw of the six conditions.""" return [ { **unit, @@ -283,14 +285,15 @@ def masked_populations(draw): def rotating(units): - """Each unit with one condition failing, in turn, and the others holding.""" + """Return each unit with one condition failing, in turn, and the others + holding.""" return [ holding(unit, MASKED[index % len(MASKED)]) for index, unit in enumerate(units) ] def failing(units): - """Each unit with every condition but income's failing.""" + """Return each unit with every condition but income's failing.""" return [holding(unit, *MASKED[:-1]) for unit in units] @@ -301,8 +304,8 @@ def failing(units): class issue_reform(Reform): - """The issue's reform: the earnings and WTC disregards apply only in - specified or temporary accommodation.""" + """Apply the earnings and WTC disregards only in specified or temporary + accommodation, as the issue's reform does.""" def apply(self): for name in (EARNINGS, WTC_DISREGARD): @@ -536,7 +539,7 @@ def test_a_condition_holding_for_one_of_two_benefit_units_in_a_household(entity) @example(units=SUPPLIED_MASKED_EDGE_CASES, active=True) @example(units=SUPPLIED_LIMIT_MASKED_EDGE_CASES, active=True) def test_masked_segments_add_up_and_match_the_regulations(units, active): - """M1, M2 and M4 in 2026-27.""" + """Check M1, M2 and M4 in 2026-27.""" sim = masked_simulation(units, YEAR_WITH_SEGMENTS, active) actual = outputs(sim, YEAR_WITH_SEGMENTS) segment_list = segments(sim, YEAR_WITH_SEGMENTS) @@ -580,8 +583,9 @@ def test_masked_segments_add_up_and_match_the_regulations(units, active): @example(units=MASKED_EDGE_CASES, active=True) @example(units=SUPPLIED_MASKED_EDGE_CASES, active=True) def test_benefit_units_whose_conditions_hold_keep_the_models_outputs(units, active): - """M3, against the model without the reform. Benefit units are assessed - separately, so a failed condition in one does not reach another.""" + """Check M3 against the model without the reform. The model assesses + each benefit unit separately, so a failed condition in one doesn't + reach another.""" sim = masked_simulation(units, YEAR_WITH_SEGMENTS, active) model = simulation( units, @@ -596,8 +600,8 @@ def test_benefit_units_whose_conditions_hold_keep_the_models_outputs(units, acti def segment_route_award(sim, units, year): - """The award built from each segment's income, as entitlement builds it - in 2026-27, applying the income condition from the units directly.""" + """Build the award from each segment's income, as entitlement does in + 2026-27, and apply the income condition from the units directly.""" benunit = sim.populations["benunit"] period = period_(year) parameters = sim.tax_benefit_system.parameters @@ -641,9 +645,10 @@ def segment_route_award(sim, units, year): @example(units=SUPPLIED_MASKED_EDGE_CASES, year=2027, active=True) @example(units=SUPPLIED_LIMIT_MASKED_EDGE_CASES, year=2024, active=False) def test_one_segment_gives_the_annual_routes_award(units, year, active): - """M5: outside 2026-27 the accommodation amounts do not change within - the year. The single segment's amounts are the annual outputs, and the - award built from them is the model's, which reads annual income.""" + """Check M5. Outside 2026-27 the accommodation amounts don't change + within the year, so the single segment's amounts equal the annual + outputs, and the award built from them equals the model's, which reads + annual income.""" sim = masked_simulation(units, year, active) actual = outputs(sim, year) (segment,) = segments(sim, year) @@ -654,8 +659,8 @@ def test_one_segment_gives_the_annual_routes_award(units, year, active): class wtc_disregard_reads_earnings(Reform): - """The WTC disregard applies only where the earnings disregard is - positive.""" + """Apply the WTC disregard only where the earnings disregard exceeds + zero.""" def apply(self): class masked(Variable): @@ -666,12 +671,13 @@ class masked(Variable): def test_a_wtc_condition_can_read_the_earnings_disregard(): - """The annual earnings disregard calculates no WTC disregard, so a - condition on the WTC disregard can read it. Assessed inputs for 2024: - £500 of net earnings, a £260 standard disregard, no accommodation - disregard or childcare deduction, the work condition met and £2,000 of - WTC. The earnings disregard is the £260 standard disregard, with the - condition and without it.""" + """The earnings disregard's annual formula calculates no WTC + disregard, so a condition on the WTC disregard can read it. The + situation supplies assessed inputs for 2024: £500 of net earnings, a + £260 standard disregard, no accommodation disregard or childcare + deduction, the work condition met and £2,000 of WTC. With the condition + and without it, the earnings disregard comes to the £260 standard + disregard.""" inputs = { "housing_benefit_net_earnings": 500, "housing_benefit_applied_standard_earnings_disregard": 260, @@ -699,13 +705,14 @@ def test_a_wtc_condition_can_read_the_earnings_disregard(): @pytest.mark.parametrize( "year,active,unit,earnings,wtc,award", [ - # The issue's claimant in 2024. The earnings disregard is £260, so - # the condition holds and the model's figures apply: income is 2,500 - # - 260 - 889.20 = 1,350.80 and the award 10,400 - 0.65 * 1,350.80. + # The issue's claimant in 2024. The £260 earnings disregard exceeds + # zero, so the condition holds and the model's figures apply: income + # of 2,500 - 260 - 889.20 = 1,350.80 and an award of 10,400 - 0.65 * + # 1,350.80. (2024, False, ISSUE_CLAIMANT, 260, 889.20, 9_521.98), - # Without earnings the disregard is nil and the condition fails, so - # the WTC disregard is nil too: income is the £2,000 of WTC and the - # award 10,400 - 0.65 * 2,000. + # Without earnings the earnings disregard comes to nil and the + # condition fails, so the WTC disregard falls to nil too: income of + # the £2,000 of WTC and an award of 10,400 - 0.65 * 2,000. (2024, False, specified_claimant(specified=False, net=0), 0, 0, 9_100), # In 2026-27 in specified accommodation, with tax credits kept: £260 # before 5 October and £500 after, weighted by 182 and 183 days, so @@ -723,9 +730,9 @@ def test_a_wtc_condition_can_read_the_earnings_disregard(): def test_a_wtc_condition_reading_the_earnings_disregard_runs( year, active, unit, earnings, wtc, award ): - """The issue's claimant, with every component the model calculates, - under a condition that gives the WTC disregard only where the earnings - disregard is positive.""" + """The model calculates every component for the issue's claimant, under + a condition that gives the WTC disregard only where the earnings + disregard exceeds zero.""" sim = simulation( [unit], year, @@ -742,9 +749,9 @@ def test_a_wtc_condition_reading_the_earnings_disregard_runs( class numeric_conditions(Reform): - """A numeric benefit-unit condition. A probe amount of £99, with a - default of £7, and applicable income, with a default of £17, apply where - it exceeds zero.""" + """Add a numeric benefit-unit condition. Apply a probe amount of £99, + with a default of £7, and applicable income, with a default of £17, + where the condition exceeds zero.""" def apply(self): class condition(Variable): @@ -781,9 +788,9 @@ def test_a_numeric_condition_applies_where_it_exceeds_zero(): variable's default elsewhere, negative conditions included, and so does hb_apply_defined_for. Three of the issue's claimants in 2026-27, with tax credits kept, have conditions of -1, 1 and 0. Where income's - condition fails, each segment's income is its £17 default, and the award - is 10,400 - 0.65 * 17 = 10,388.95; where it holds, the model's - £1,350.80 gives 9,521.98.""" + condition fails, each segment's income takes its £17 default, and the + award comes to 10,400 - 0.65 * 17 = 10,388.95; where it holds, the + model's £1,350.80 gives 9,521.98.""" sim = simulation( [ISSUE_CLAIMANT] * 3, YEAR_WITH_SEGMENTS, @@ -803,9 +810,9 @@ def test_a_numeric_condition_applies_where_it_exceeds_zero(): class limit_follows_conditions(Variable): - """The earnings and tax-credit limit, releasing to childcare the - earnings a failed earnings condition no longer disregards and the WTC a - failed WTC condition no longer reserves.""" + """Release to childcare the earnings a failed earnings condition no + longer disregards and the WTC a failed WTC condition no longer + reserves.""" value_type = float entity = BenUnit @@ -879,10 +886,11 @@ def test_a_failed_disregard_still_limits_childcare( fails, unit, active, limit, award, released_limit, released_award ): """hb_childcare_wtc_reserve ignores a condition on the WTC disregard, - and the limit counts the standard disregard whatever the earnings - disregard's condition. A reform author who wants a failed condition to - fund childcare changes the limit too. In 2026-27, for a claimant with - one child outside specified accommodation.""" + and the limit subtracts the standard disregard whatever the earnings + disregard's condition gives. A reform author who wants a failed + condition to fund childcare changes the limit too. Each case runs in + 2026-27 for a claimant with one child outside specified + accommodation.""" unit = holding(unit, fails) sim = masked_simulation([unit], YEAR_WITH_SEGMENTS, active) benunit = sim.populations["benunit"] diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index e93c2665ea..b365d543cc 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -15,8 +15,8 @@ def hb_capped_accommodation(benunit, period, accommodation): - """Cap a full accommodation amount at the earnings the standard - disregard leaves (Sch 4 para 18).""" + """Cap a full accommodation amount at the net earnings the standard + disregard leaves.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) return min_(max_(accommodation, 0), max_(net - standard, 0)) @@ -24,9 +24,9 @@ def hb_capped_accommodation(benunit, period, accommodation): def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): """Apply the childcare and earnings limits to one full accommodation - amount. Return the earnings disregard, or its default where its - defined_for condition fails, and the childcare deduction. Calculate no - WTC disregard, so a condition on that disregard can read this one.""" + amount. Return the earnings disregard, with its defined_for condition + applied, and the childcare deduction. Calculate no WTC disregard, so a + condition on that disregard can read the earnings disregard.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) accommodation = hb_capped_accommodation(benunit, period, accommodation) @@ -58,10 +58,9 @@ def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): def hb_segment_deductions(benunit, period, parameters, accommodation): - """Apply the childcare and earnings limits to one full accommodation - amount. Return the earnings disregard, the WTC disregard and the - childcare deduction, each its variable's default where its defined_for - condition fails.""" + """Return the earnings disregard, the WTC disregard and the childcare + deduction for one full accommodation amount, each with its variable's + defined_for condition applied.""" disregard, childcare = hb_segment_earnings_disregard( benunit, period, parameters, accommodation ) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index 2c260a89ec..ec979336e4 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -6,8 +6,8 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): """Keep annual inputs, replacement formulas and computed aggregates out of - recalculation. A defined_for mask on the model's formula is none of - these: the segment helpers apply it themselves (hb_apply_defined_for).""" + recalculation. A defined_for condition on the model's own formula takes + no annual route: each segment helper applies it (hb_apply_defined_for).""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) formula = variable.get_formula(period) if formula is None or formula.__code__ != default_formula.__code__: @@ -16,13 +16,13 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): def hb_apply_defined_for(benunit, period, variable_name, amount): - """The amount a segment helper rebuilt for the variable where the - variable's defined_for condition holds, and the variable's default - elsewhere. Core masks the annual output the same way - (Simulation._calculate): it maps the condition to the variable's entity - and keeps the amount where the condition exceeds zero. The condition - comes from the variable the simulation holds, so one that a reform adds - reaches each segment, as it reaches the annual output.""" + """Return the amount a segment helper rebuilt where the variable's + defined_for condition exceeds zero, and the variable's default + elsewhere, as Core masks the annual output (Simulation._calculate). + Calculate the condition for the helper's annual period and map it to + the variable's entity, as Core does. Read the condition from the + variable the simulation holds, so a condition a reform author adds + reaches each segment.""" variable = benunit.simulation.tax_benefit_system.get_variable(variable_name) if variable.defined_for is None: return amount @@ -65,8 +65,8 @@ def hb_reads_no_other_variable(benunit, period, variable_name): def hb_accommodation_segments(benunit, period, parameters): - """Full annual-equivalent accommodation amounts and fiscal-year weights. - Each amount is nil where the disregard's defined_for condition fails.""" + """Yield full annual accommodation amounts and fiscal-year weights. + Apply the disregard's defined_for condition to each amount.""" name = "housing_benefit_specified_or_temporary_accommodation_disregard" if hb_uses_annual_override( benunit, diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index ebb47816cf..e50e49de93 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -18,8 +18,10 @@ def hb_fixed_childcare_deduction(benunit, period, parameters): """The annual childcare deduction where it, or the limit it reads, is supplied (by a dataset, set_input or a scenario), neutralized or - calculated by a formula a reform put in place of the model's. Otherwise - None: each accommodation segment calculates its own deduction.""" + calculated by a formula a reform put in place of the model's. Where the + limit is supplied or replaced, apply the deduction's defined_for + condition. Otherwise None: each accommodation segment calculates its own + deduction.""" childcare = housing_benefit_applicable_income_childcare_element if hb_uses_annual_override(benunit, period, childcare.__name__, childcare.formula): return benunit(childcare.__name__, period) @@ -34,12 +36,11 @@ def hb_fixed_childcare_deduction(benunit, period, parameters): def hb_segment_childcare_deduction(benunit, period, parameters, accommodation): - """The childcare deduction in force where the accommodation disregard has - this full annual amount: the annual deduction where - hb_fixed_childcare_deduction gives one, and otherwise the lesser of the - capped charge and the earnings and tax-credit limit. The limit is nil - where its defined_for condition fails, and so is the deduction where - its own fails.""" + """Return the childcare deduction in force where the accommodation + disregard has this full annual amount. Use the annual deduction where + hb_fixed_childcare_deduction gives one. Otherwise take the lesser of the + capped charge and the earnings and tax-credit limit, and apply the + limit's and the deduction's defined_for conditions.""" childcare = hb_fixed_childcare_deduction(benunit, period, parameters) if childcare is not None: return childcare @@ -58,10 +59,10 @@ def hb_segment_childcare_deduction(benunit, period, parameters, accommodation): def hb_segment_wtc_disregard(benunit, period, parameters, accommodation, childcare): - """The WTC disregard in one accommodation segment, where Sch 4 para - 17(3)(b) counts this childcare deduction, and nil where its defined_for - condition fails. A supplied, neutralized or replaced annual amount - applies in every segment.""" + """Calculate one accommodation segment's WTC disregard with the + childcare deduction that Sch 4 para 17(3)(b) counts, and apply the + disregard's defined_for condition. A supplied, neutralized or replaced + annual amount applies in every segment.""" name = "housing_benefit_wtc_disregard" if hb_uses_annual_override( benunit, period, name, housing_benefit_wtc_disregard.formula diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py index c539637774..bfef19a9a2 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/entitlement/housing_benefit_entitlement.py @@ -29,9 +29,9 @@ class housing_benefit_entitlement(Variable): "ages and household status remain constant. Other parameters keep " "the model's annual convention. Supplied annual income/deductions " "and replacement formulas retain their normal override semantics. " - "A defined_for condition that a reform adds to the income, a " - "disregard, the childcare deduction or its limit applies in each " - "segment. " + "Apply in each segment any defined_for condition a reform author " + "adds to applicable income, a disregard, the childcare deduction or " + "its limit. " "Annual income intermediates are not period-specific assessments." ) entity = BenUnit From 2cafac7bd6e6a2ee57303f8b63c6a6f0bb1e109e Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 07:12:54 -0500 Subject: [PATCH 27/29] Rewrap the segment-mask module docstring Co-Authored-By: Claude Opus 5.5 --- .../tests/test_housing_benefit_segment_masks.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index e33b57682c..a6e0e38084 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -35,10 +35,10 @@ The fixture supplies the conditions as inputs, and its variables default to nil. It sets the eligible rent to ``RENT`` and non-dependant deductions -to nil, so the maximum benefit equals the whole rent. The annual childcare deduction and -its limit keep their single annual calculation. Populations use core -situations, as in test_housing_benefit_wtc_disregard.py; they never load a -survey dataset. +to nil, so the maximum benefit equals the whole rent. The annual childcare +deduction and its limit keep their single annual calculation. Populations +use core situations, as in test_housing_benefit_wtc_disregard.py; they +never load a survey dataset. """ from functools import cache From af4819b144f3b452904df2041758c4ed96eacd72 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 1 Nov 2026 09:26:02 -0500 Subject: [PATCH 28/29] Finish the Housing Benefit helper docstrings Name the annual overrides each helper keeps, state the award floor in M2 and limit M4 to the generated cases. Co-Authored-By: Claude Opus 5.5 --- .../test_housing_benefit_segment_masks.py | 19 +++++++-------- ...ing_benefit_applicable_income_disregard.py | 15 ++++++------ ...ousing_benefit_childcare_earnings_limit.py | 24 +++++++++---------- ...ed_or_temporary_accommodation_disregard.py | 3 ++- .../housing_benefit_wtc_disregard.py | 11 ++++----- 5 files changed, 35 insertions(+), 37 deletions(-) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index a6e0e38084..c44f2d85e3 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -18,18 +18,17 @@ M2. Where a condition fails, its amount takes the variable's default in the annual output and in every segment, unless the population supplies the amount as an input, which applies as supplied, as core applies it. - Where applicable income's condition fails, the award equals the - maximum benefit less 65% of any excess of that default over the - applicable amount. + Where applicable income's condition fails, the award equals + max(0, maximum benefit - 0.65 * max(0, default - applicable amount)). M3. A benefit unit whose conditions all hold has the model's outputs, award included. -M4. The award equals an independent calculation that applies the - regulations within each segment, with each failed condition's amount - nil, and combines the segments' awards by days. The calculation settles - the childcare deduction before it removes a failed earnings or WTC - disregard from income, as the model does: the limit still counts the - standard and accommodation disregards and keeps back the WTC the model - would disregard (test_a_failed_disregard_still_limits_childcare). +M4. For the generated cases, whose variables default to nil, the award + agrees with an independent scalar calculation within each segment, + combined by days. The calculation settles the childcare deduction + before it removes a failed earnings or WTC disregard from income, as + the model does: the limit still counts the standard and accommodation + disregards and keeps back the WTC the model would disregard + (test_a_failed_disregard_still_limits_childcare). M5. Each year but 2026-27 has one segment, and the award built from it equals the award the model builds from annual income. diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index b365d543cc..7d29253fab 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py @@ -23,10 +23,11 @@ def hb_capped_accommodation(benunit, period, accommodation): def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): - """Apply the childcare and earnings limits to one full accommodation - amount. Return the earnings disregard, with its defined_for condition - applied, and the childcare deduction. Calculate no WTC disregard, so a - condition on that disregard can read the earnings disregard.""" + """Apply childcare and earnings limits to one full accommodation amount. + Return the earnings disregard and childcare deduction. Use an annual + override for the earnings disregard where present; otherwise apply its + defined_for condition. Leave WTC to hb_segment_deductions so a condition + on WTC can read the earnings disregard.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) accommodation = hb_capped_accommodation(benunit, period, accommodation) @@ -58,9 +59,9 @@ def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): def hb_segment_deductions(benunit, period, parameters, accommodation): - """Return the earnings disregard, the WTC disregard and the childcare - deduction for one full accommodation amount, each with its variable's - defined_for condition applied.""" + """Return the earnings disregard, WTC disregard and childcare deduction + for one full accommodation amount. Use annual overrides where present; + otherwise apply each variable's defined_for condition.""" disregard, childcare = hb_segment_earnings_disregard( benunit, period, parameters, accommodation ) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py index d655031aac..4acfa36b85 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_childcare_earnings_limit.py @@ -53,13 +53,11 @@ def hb_wtc_disregard(benunit, period, parameters, accommodation, childcare): def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): - """The WTC this limit keeps from childcare for the Sch 5 para 56 - disregard. By default the accommodation disregard has its annual - segments; an accommodation segment passes its own amount. A defined_for - condition on the WTC disregard doesn't reach this reserve: where the - condition fails, the limit still keeps back the WTC the model would - disregard. A reform author who wants that WTC to fund childcare changes - the limit too.""" + """Return the WTC the childcare limit reserves for the Sch 5 para 56 + disregard. Combine annual accommodation segments by default, or use the + accommodation amount the caller supplies. Keep this reserve when the + WTC disregard's defined_for condition fails. A reform author who wants + that WTC to fund childcare changes the limit too.""" name = "housing_benefit_wtc_disregard" if hb_reads_no_other_variable(benunit, period, name): return benunit(name, period) @@ -84,12 +82,12 @@ def hb_childcare_wtc_reserve(benunit, period, parameters, accommodation=None): def hb_childcare_earnings_limit(benunit, period, parameters, accommodation=None): - """Remaining earnings and tax credits, without an additional-disregard loop. - By default the accommodation disregard is the annual variable; an - accommodation segment passes its own. The limit subtracts the standard - and accommodation disregards even where a defined_for condition on the - earnings disregard fails; a reform author who wants those earnings to - fund childcare changes the limit too.""" + """Return earnings and tax credits available for childcare without + reading the additional earnings disregard. Read the annual + accommodation disregard by default, or use the amount the caller + supplies. Subtract the standard and accommodation disregards even when + the earnings disregard's defined_for condition fails. A reform author + who wants those earnings to fund childcare changes the limit too.""" net = max_(benunit("housing_benefit_net_earnings", period), 0) standard = hb_standard_earnings_disregard(benunit, period) reserve = hb_childcare_wtc_reserve(benunit, period, parameters, accommodation) diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py index ec979336e4..8fcf928534 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_specified_or_temporary_accommodation_disregard.py @@ -66,7 +66,8 @@ def hb_reads_no_other_variable(benunit, period, variable_name): def hb_accommodation_segments(benunit, period, parameters): """Yield full annual accommodation amounts and fiscal-year weights. - Apply the disregard's defined_for condition to each amount.""" + Preserve an annual override where present; otherwise apply the + disregard's defined_for condition to each amount.""" name = "housing_benefit_specified_or_temporary_accommodation_disregard" if hb_uses_annual_override( benunit, diff --git a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py index e50e49de93..04b958ef49 100644 --- a/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -16,12 +16,11 @@ def hb_fixed_childcare_deduction(benunit, period, parameters): - """The annual childcare deduction where it, or the limit it reads, is - supplied (by a dataset, set_input or a scenario), neutralized or - calculated by a formula a reform put in place of the model's. Where the - limit is supplied or replaced, apply the deduction's defined_for - condition. Otherwise None: each accommodation segment calculates its own - deduction.""" + """Return the annual childcare deduction when an input or reform + overrides it or its limit. If the deduction keeps the model's formula + but its limit takes an annual override, cap the charges at that limit + and apply the deduction's defined_for condition. Otherwise return None + so each accommodation segment calculates its own deduction.""" childcare = housing_benefit_applicable_income_childcare_element if hb_uses_annual_override(benunit, period, childcare.__name__, childcare.formula): return benunit(childcare.__name__, period) From 2f087ae7c349abcb7651e1b48b099230dd57f1d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 3 Nov 2026 06:56:21 +0000 Subject: [PATCH 29/29] Test a couples-only WTC disregard through a lone parent's final Housing Benefit A reform that adds defined_for = "is_couple" to housing_benefit_wtc_disregard and keeps its formula must take the disregard away in both 2026-27 accommodation segments, so the final award and household net income equal a neutralized-disregard control. The 2024 case checks the one-segment year. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LwQq6JE7NGFKUqVxTbNfqw --- .../test_housing_benefit_segment_masks.py | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) diff --git a/policyengine_uk/tests/test_housing_benefit_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py index c44f2d85e3..966e0590f4 100644 --- a/policyengine_uk/tests/test_housing_benefit_segment_masks.py +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -912,3 +912,165 @@ def test_a_failed_disregard_still_limits_childcare( ) assert_close(released.calculate(LIMIT, YEAR_WITH_SEGMENTS), [released_limit]) assert_close(released.calculate(AWARD, YEAR_WITH_SEGMENTS), [released_award]) + + +class couples_only(Reform): + """Give the WTC disregard only to couples, keeping the model's + formula.""" + + def apply(self): + class masked(Variable): + defined_for = "is_couple" + + masked.__name__ = WTC_DISREGARD + self.update_variable(masked) + + +class without_wtc_disregard(Reform): + def apply(self): + self.neutralize_variable(WTC_DISREGARD) + + +def lone_parent_in_temporary_accommodation(year): + """A lone parent aged 60 with a child aged 8, continuing a Housing + Benefit award in London council accommodation that counts as specified + or temporary accommodation. The parent works 16 hours a week for + £11,000, draws a £10,000 private pension and pays £12,000 for + qualifying childcare, and reports £2,000 of WTC and £4,000 of CTC, so + the model calculates both credits.""" + return { + "people": { + "parent": { + "age": {year: 60}, + "employment_income": {year: 11_000}, + "weekly_hours": {year: 16}, + "private_pension_income": {year: 10_000}, + "childcare_expenses": {year: 12_000}, + "housing_benefit_reported": {year: 1}, + "working_tax_credit_reported": {year: 2_000}, + "child_tax_credit_reported": {year: 4_000}, + }, + "child": {"age": {year: 8}}, + }, + "benunits": { + "family": { + "members": ["parent", "child"], + "in_specified_or_temporary_accommodation": {year: True}, + "claims_universal_credit": {year: False}, + } + }, + "households": { + "home": { + "members": ["parent", "child"], + "region": {year: "LONDON"}, + "rent": {year: 10_400}, + "tenure_type": {year: "RENT_FROM_COUNCIL"}, + } + }, + } + + +LONE_PARENT_OUTPUTS = ( + WTC_DISREGARD, + EARNINGS, + CHILDCARE, + INCOME, + "housing_benefit_benefit_cap_reduction", + "housing_benefit", + "household_net_income", +) + + +@pytest.mark.parametrize( + "year,wtc,ctc,earnings_disregard,segment_disregards,income,award,model_award", + [ + # 2026-27, with tax credits kept. The model calculates WTC of + # £6,530.35 and CTC of £3,646.49 from the reported awards, and + # attributes £883.14 of the £1,686 income tax to the £11,000 of + # wages (11,000 / 21,000 of it), leaving net earnings of £10,116.86. + # Income before deductions comes to 11,000 + 10,000 - 1,686 + + # 10,176.84 = 29,490.84. The lone parent disregard + # (means_test/income_disregard/lone_parent.yaml) gives £25 a week, + # £1,300; the accommodation disregard + # (specified_or_temporary_accommodation/lone_parent/older.yaml) + # £77.73 a week, £4,041.96, from 5 October; the WTC childcare + # element cap (working_tax_credit/elements/childcare_1.yaml) £175 a + # week, £9,100; and the worker disregard (income_disregard/ + # worker.yaml) £17.10 a week, £889.20. Net earnings fall short of + # 1,300 + 9,100 + 889.20 = 11,289.20 before 5 October and of + # 15,331.16 after, so the model disregards £889.20 of WTC in both + # segments, and the mask takes it away. The applicable amount + # (allowances/lone_parent/older.yaml) comes to £95.55 a week, + # £4,968.60, and withdrawal_rate.yaml tapers 65%. + # Before 5 October: 29,490.84 - 1,300 - 9,100 = 19,090.84, and an + # award of 10,400 - 0.65 * (19,090.84 - 4,968.60) = 1,220.54. + # After: 29,490.84 - 5,341.96 - 9,100 = 15,048.88, and 3,847.82. + # Combined, (182 * 1,220.54 + 183 * 3,847.82) / 365 = 2,537.78. + # Annual income: 29,490.84 - 3,326.52 - 9,100 = 17,064.32. The + # model's own award adds 0.65 * 889.20 = 577.98 in each segment. + ( + 2026, + 6_530.35, + 3_646.49, + 1_300 + 2_026.52, + [1_300, 1_300 + 4_041.96], + 17_064.32, + 2_537.78, + 3_115.76, + ), + # 2024, one segment and no accommodation disregard. Income comes to + # 29,393.55 - 1,300 - 9,100 = 18,993.55 with WTC of £6,079.55 and + # CTC of £4,000, and the award to 10,400 - 0.65 * (18,993.55 - + # 4,706) = 1,113.09, where the £90.50 allowance gives £4,706. + (2024, 6_079.55, 4_000, 1_300, [1_300], 18_993.55, 1_113.09, 1_691.07), + ], +) +def test_a_couples_only_wtc_disregard_reaches_a_lone_parents_award( + year, wtc, ctc, earnings_disregard, segment_disregards, income, award, model_award +): + """A reform gives the WTC disregard only to couples and keeps the + model's formula. The lone parent then gets no WTC disregard in the + annual output or in either accommodation segment, so the final award + and household net income equal those of a reform that neutralizes the + disregard. The model's own award, with the disregard, exceeds it by + 0.65 * 889.20 = 577.98.""" + base = tax_credits_kept() if year == YEAR_WITH_SEGMENTS else system + situation = lone_parent_in_temporary_accommodation(year) + masked, neutralized, model = ( + Simulation(tax_benefit_system=tax_benefit_system, situation=situation) + for tax_benefit_system in ( + couples_only(base), + without_wtc_disregard(base), + base, + ) + ) + assert_close(masked.calculate("working_tax_credit", year), [wtc]) + assert_close(masked.calculate("child_tax_credit", year), [ctc]) + assert_close(masked.calculate("housing_benefit_net_earnings", year), [10_116.86]) + before, *after = segments(masked, year) + assert len(after) == len(segment_disregards) - 1 + for segment, disregard in zip([before, *after], segment_disregards): + assert_close(segment["earnings_disregard"], [disregard]) + assert_close(segment["reserve"], [0]) + assert_close(segment["childcare"], [9_100]) + expected = { + WTC_DISREGARD: 0, + EARNINGS: earnings_disregard, + CHILDCARE: 9_100, + INCOME: income, + "housing_benefit_benefit_cap_reduction": 0, + "housing_benefit": award, + } + for name, value in expected.items(): + assert_close(masked.calculate(name, year), [value], name) + for name in LONE_PARENT_OUTPUTS: + assert_close( + masked.calculate(name, year), neutralized.calculate(name, year), name + ) + assert_close(model.calculate(WTC_DISREGARD, year), [889.20]) + assert_close(model.calculate("housing_benefit", year), [model_award]) + assert_close( + model.calculate("household_net_income", year) + - masked.calculate("household_net_income", year), + [model_award - award], + )