diff --git a/changelog.d/2730.fixed.md b/changelog.d/2730.fixed.md new file mode 100644 index 0000000000..c79626bf3f --- /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, and settles it separately before and after the accommodation disregard starts under a reform that keeps tax credits. diff --git a/changelog.d/2777.fixed.md b/changelog.d/2777.fixed.md new file mode 100644 index 0000000000..0ffc4b70a9 --- /dev/null +++ b/changelog.d/2777.fixed.md @@ -0,0 +1 @@ +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/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..5a703c6ff8 --- /dev/null +++ b/policyengine_uk/tests/policy/baseline/finance/benefit/family/housing_benefit/applicable_income/housing_benefit_wtc_disregard.yaml @@ -0,0 +1,385 @@ +# 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 + +- 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 + +- 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_segment_masks.py b/policyengine_uk/tests/test_housing_benefit_segment_masks.py new file mode 100644 index 0000000000..966e0590f4 --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_segment_masks.py @@ -0,0 +1,1076 @@ +"""Housing Benefit accommodation segments under a reform's defined_for masks. + +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 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 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 + 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. 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. + +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. +""" + +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_core.simulations import Simulation + +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, + 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_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, +) + + +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): + """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): + 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): + """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): + """Build ``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): + """Return ``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): + """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 + 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): + """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): + """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): + """Return 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): + """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): + + 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,non_dependant,income,award", + [ + # 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, 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 + ) + 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): + """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) + 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) + # 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]) + + +@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): + """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, + 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): + """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 + 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): + """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) + 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"]) + + +class wtc_disregard_reads_earnings(Reform): + """Apply the WTC disregard only where the earnings disregard exceeds + zero.""" + + 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 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, + 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 £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 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 + # 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 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, + 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) + + +NUMERIC_CONDITION = "housing_benefit_numeric_reform_condition" +PROBE = "housing_benefit_reform_probe_amount" + + +class numeric_conditions(Reform): + """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): + 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 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, + 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] + ) + + +class limit_follows_conditions(Variable): + """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 + 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 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"] + 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]) + + +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], + ) 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..4bd875aa47 --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard.py @@ -0,0 +1,1290 @@ +"""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 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, 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 +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 +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. 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. +""" + +from functools import cache + +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.parameters import Parameter, ParameterNode +from policyengine_core.periods import period as period_ +from policyengine_core.reforms import Reform +from policyengine_core.simulations import Simulation + +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 +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], +) +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): + result = dict( + net=5_200, + standard=1_300, + accommodation=0, + childcare=4_160, + supplied=None, + supplied_limit=None, + children=1, + wtc=100, + ctc=0, + other=0, + 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 + + +def pounds(maximum): + return st.integers(0, maximum * 100).map(lambda pence: pence / 100) + + +@st.composite +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)), + other=draw(pounds(20_000)), + worker=draw(st.booleans()), + pension_age=draw(st.booleans()), + region=draw(st.sampled_from(REGIONS)), + ) + + +@st.composite +def populations(draw): + # 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.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), + 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(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), +] +# 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), + 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), +] +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): + """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. + 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 + 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, limit(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): + # 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 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 + childcare = deduction(reserve) + income = max( + 0, + net + + unit["wtc"] + + unit["ctc"] + + unit["other"] + - standard + - accommodation + - additional + - reserve + - childcare, + ) + return dict( + childcare=childcare, + reserve=reserve, + earnings_disregard=standard + accommodation + additional, + limit=limit(reserve), + income=income, + ) + + +class without_wtc_reservation(Reform): + """The previous path: no WTC disregard, and childcare draws on all WTC.""" + + 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") + + +@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(benunit, period, parameters) + + forwarded_variable.__name__ = name + + class forward(Reform): + def apply(self): + self.update_variable(forwarded_variable) + + return forward(baseline) + + +def forwarded_systems(baseline=system): + return { + None: baseline, + **{name: forwarded(name, baseline) for name in FORWARDED_VARIABLES}, + } + + +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 + + +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. 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] + + 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) + + +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, + 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. + 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" + 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_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}, + } + 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: + family[CHILDCARE] = {year: unit["supplied"]} + if unit["supplied_limit"] is not None: + family[LIMIT] = {year: unit["supplied_limit"]} + 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( + tax_benefit_system=tax_benefit_system, + situation={"people": people, "benunits": benunits, "households": households}, + ) + + +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 OUTPUTS.items() + } + + +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) + + +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.""" + 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 + # 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] + + +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(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 + + +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(CHILDCARE, 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(CHILDCARE, 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) +@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] + assert_matches(actual, expected) + 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) +@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 + assert np.all(actual["reserve"] >= 0) + assert np.all( + actual["reserve"] + <= np.minimum([unit["wtc"] for unit in units], annual_amount) + 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) +# 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) +@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 or limit 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] + # Always include a work-condition failure, no WTC, and sufficient + # earnings, so every population exercises the differential check. + unchanged.extend( + [ + 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) + 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 + ) + + +@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): + """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)} + 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 + ) + + +@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) + 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("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) + 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) + + +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", + [ + # 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_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]) + 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) + + +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), + ], +) +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) + + +@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 + 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["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_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 + 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 + ), + forwarded_systems(), + lambda sim: results(sim, 2024), + ) + + +@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.""" + 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 + + +# 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): + """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.""" + 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" + ) + 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( + 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 + 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/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..0f0ca0c967 --- /dev/null +++ b/policyengine_uk/tests/test_housing_benefit_wtc_disregard_segments.py @@ -0,0 +1,498 @@ +"""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 +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. +""" + +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_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, + legal_components, + 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 ( + 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 + + +TAX_CREDITS = tax_credits_kept() +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]) + + +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): + tax_benefit_system = previous_system(active) if previous else SYSTEMS[active] + return simulation( + units, YEAR, tax_benefit_system=tax_benefit_system, dated_accommodation=True + ) + + +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 + 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, _ = 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), + kept_back=np.asarray( + hb_childcare_wtc_reserve(benunit, year, parameters, accommodation), + dtype=float, + ), + ) + ) + return result + + +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( + **{ + "net": 500, + "standard": 260, + "childcare": 0, + "children": 0, + "wtc": 2_000, + "specified": True, + **overrides, + } + ) + + +@st.composite +def segment_families(draw, supplied=False, supplied_limit=False): + return { + **draw(families(supplied, supplied_limit)), + "specified": draw(st.booleans()), + "applicable_amount": draw(st.sampled_from([0, 2_000, 5_000])), + } + + +@st.composite +def segment_populations(draw): + 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 = [ + 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), + 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, 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, 3_000] + ) +] + + +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. + # 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 = specified_claimant(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 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 + ) + assert sim.calculate("housing_benefit_entitlement", YEAR)[0] == pytest.approx( + award, abs=TOLERANCE + ) + + +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_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", + [ + # 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, [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( + 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 + ), + forwarded_systems(TAX_CREDITS), + segment_outputs, + ) + + +@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=reformed, 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 + ) + + +@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) +@example(units=SUPPLIED_LIMIT_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) + 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 + ) + annual_wtc_disregard = sim.calculate("housing_benefit_wtc_disregard", YEAR) + np.testing.assert_allclose( + 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 +@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) + unchanged.append(specified_claimant(net=8_000, **same_supply(units, 0))) + 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 c04b516bcb..d8a01bb8c8 100644 --- a/policyengine_uk/utils/supplied_inputs.py +++ b/policyengine_uk/utils/supplied_inputs.py @@ -69,6 +69,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.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_applicable_income_disregard.py b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_applicable_income_disregard.py index f98756fd01..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 @@ -1,65 +1,53 @@ 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_covers_additional_disregard, 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_apply_defined_for, hb_uses_annual_override, ) +from policyengine_uk.variables.gov.dwp.housing_benefit.applicable_income.housing_benefit_wtc_disregard import ( + hb_segment_childcare_deduction, + hb_segment_wtc_disregard, +) -def hb_segment_deductions(benunit, period, parameters, accommodation): - """Apply childcare/earnings limits to one full accommodation amount.""" +def hb_capped_accommodation(benunit, period, accommodation): + """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) - 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 - ) - childcare = min_( - hb_capped_childcare_charges(benunit, period, parameters), childcare_limit - ) + return min_(max_(accommodation, 0), max_(net - standard, 0)) + + +def hb_segment_earnings_disregard(benunit, period, parameters, accommodation): + """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) + childcare = hb_segment_childcare_deduction( + benunit, period, parameters, accommodation + ) 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 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 +55,24 @@ def hb_segment_deductions(benunit, period, parameters, accommodation): net, standard + accommodation + additional, ) - return disregard, childcare + return hb_apply_defined_for(benunit, period, name, disregard), childcare + + +def hb_segment_deductions(benunit, period, parameters, accommodation): + """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 + ) + 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): @@ -119,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 ) 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..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 @@ -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_reads_no_other_variable, +) def hb_standard_earnings_disregard(benunit, period): @@ -6,18 +13,94 @@ 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_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): + """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) + # 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 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) + 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): + """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) if accommodation is None: accommodation = benunit( "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_( + # Reg 40(2) and Sch 5 para 56 disregard WTC before reg 27(1)(c) + # 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. + credits = max_(benunit("working_tax_credit", period) - reserve, 0) + max_( benunit("child_tax_credit", period), 0 ) return max_(0, net - standard - accommodation) + credits @@ -31,12 +114,25 @@ 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 " "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 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 " "WTC edge also runs from this limit through " "housing_benefit_applied_standard_earnings_disregard, " "housing_benefit_special_earnings_disregard and " @@ -59,7 +155,9 @@ 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): - 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..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 @@ -5,15 +5,55 @@ 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) + """Keep annual inputs, replacement formulas and computed aggregates out of + 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 ( - variable.is_neutralized - or formula is None - or formula.__code__ != default_formula.__code__ - ): + if formula is None or formula.__code__ != default_formula.__code__: + return True + return hb_reads_no_other_variable(benunit, period, variable_name) + + +def hb_apply_defined_for(benunit, period, variable_name, amount): + """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 + 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`` + 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 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 @@ -25,7 +65,9 @@ def hb_uses_annual_override(benunit, period, variable_name, default_formula): def hb_accommodation_segments(benunit, period, parameters): - """Full annual-equivalent accommodation amounts and fiscal-year weights.""" + """Yield full annual accommodation amounts and fiscal-year weights. + 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, @@ -74,7 +116,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 new file mode 100644 index 0000000000..04b958ef49 --- /dev/null +++ b/policyengine_uk/variables/gov/dwp/housing_benefit/applicable_income/housing_benefit_wtc_disregard.py @@ -0,0 +1,129 @@ +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_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 ( + hb_accommodation_segments, + hb_apply_defined_for, + hb_uses_annual_override, +) + + +def hb_fixed_childcare_deduction(benunit, period, parameters): + """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) + limit = housing_benefit_childcare_earnings_limit + if hb_uses_annual_override(benunit, period, limit.__name__, limit.formula): + 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 + + +def hb_segment_childcare_deduction(benunit, period, parameters, accommodation): + """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 + 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): + """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 + ): + return benunit(name, period) + return hb_apply_defined_for( + benunit, + period, + name, + hb_wtc_disregard(benunit, period, parameters, accommodation, childcare), + ) + + +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. 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." + ) + 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", + "https://www.legislation.gov.uk/uksi/2026/978/regulation/2", + ) + + def formula(benunit, period, parameters): + return sum( + 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 + ) + ) 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..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 @@ -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, ) @@ -21,12 +22,16 @@ 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. " + "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 @@ -55,6 +60,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 +109,26 @@ 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), + 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 annual_award = annual_award + share * max_(