From 3606387a848e764633b362a1d2720a7ee2ac0069 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 00:54:05 -0500 Subject: [PATCH 1/5] Tax NZ Superannuation and Jobseeker Support taxable_income adds the gross nz_superannuation, and jobseeker_support with the new jobseeker_support_tax (Income Tax Act 2007, sections CF 1(1)(c) and (e)). jobseeker_support_tax is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018. It grosses the year's payment up on the personal tax schedule, apart from other income, and section 351(b)(iv) makes it the person's income. For a period that starts before 1 April 2022, taxable income keeps the old sources and raises an error for a person marked as a recipient of either benefit or given a nonzero amount of one. Part of #18. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- changelog.d/benefit-income-tax.fixed.md | 1 + changelog.d/superannuation-rates.fixed.md | 2 +- docs/index.md | 2 +- .../gov/msd/jobseeker/payment_rates.yaml | 2 +- .../baseline/test_benefit_income_tax.yaml | 126 +++++++++++++ .../tests/test_benefit_income_tax.py | 170 ++++++++++++++++++ .../gov/ird/income_tax/income_tax.py | 6 +- .../gov/ird/income_tax/taxable_income.py | 60 ++++++- .../gov/msd/jobseeker/jobseeker_support.py | 8 +- .../msd/jobseeker/jobseeker_support_tax.py | 68 +++++++ 11 files changed, 434 insertions(+), 15 deletions(-) create mode 100644 changelog.d/benefit-income-tax.fixed.md create mode 100644 policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml create mode 100644 policyengine_nz/tests/test_benefit_income_tax.py create mode 100644 policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py diff --git a/README.md b/README.md index 66ce095..b80e741 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ PolicyEngine New Zealand is a microsimulation model for New Zealand's tax and be ## Features -- **Tax**: income tax and the ACC Earners' Levy +- **Tax**: income tax on earnings, investment income, NZ Superannuation and Jobseeker Support, and the ACC Earners' Levy - **Working for Families**: Family Tax Credit, In-Work Tax Credit, Best Start - **Benefits**: annualised Jobseeker Support net of tax, from a supplied grant and supplied weekly assessable income, including a linked partner's share of a couple rate; annualised gross NZ Superannuation for a supplied recipient; the annualised Accommodation Supplement before income abatement and rounding; and a separate Accommodation Supplement cash assets test - **Parameters that no formula uses yet**: the GST rate, the KiwiSaver contribution rates and the government contribution's settings @@ -48,7 +48,7 @@ print(f"ACC levy: ${acc_levy[0]:,.2f}") ## System Coverage ### Tax System (Inland Revenue Department) -- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds +- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds, on employment, self-employment and investment income, gross NZ Superannuation, and Jobseeker Support with the income tax MSD pays on it (`jobseeker_support_tax`), from the 2022-23 tax year. The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it is part of `income_tax` but does not come out of the benefit. - **ACC Earners' Levy** on liable employee earnings, capped by tax year: an annual estimate at the GST-inclusive rate Inland Revenue publishes. It does not compute PAYE deductions pay by pay. A bare year uses the rate and cap in force on 1 January of that year, so `2025` uses those of the tax year from April 2024 to March 2025. - **GST**: the model stores the 15% rate as a parameter and does not calculate GST. diff --git a/changelog.d/benefit-income-tax.fixed.md b/changelog.d/benefit-income-tax.fixed.md new file mode 100644 index 0000000..a154108 --- /dev/null +++ b/changelog.d/benefit-income-tax.fixed.md @@ -0,0 +1 @@ +Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, found by grossing up the year's payment on its own; section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The floor at zero still applies to the sum of the modelled sources, so a self-employment loss now reduces the taxable benefit. For a period that starts before 1 April 2022, taxable income raises an error for a person marked as a recipient of either benefit or given a nonzero amount of one, and taxes other income as before. `family_income` and the Working for Families credits do not yet include either benefit. diff --git a/changelog.d/superannuation-rates.fixed.md b/changelog.d/superannuation-rates.fixed.md index 323d276..e3cfa7f 100644 --- a/changelog.d/superannuation-rates.fixed.md +++ b/changelog.d/superannuation-rates.fixed.md @@ -1 +1 @@ -Annual NZ Superannuation amounts are now 52 times the gross weekly rates in Schedule 1 of the New Zealand Superannuation and Retirement Income Act 2001, as set by the rates orders through 2026–27. Period N is the tax year ending 31 March N. This changes no other output, because no variable reads nz_superannuation yet. +Annual NZ Superannuation amounts are now 52 times the gross weekly rates in Schedule 1 of the New Zealand Superannuation and Retirement Income Act 2001, as set by the rates orders through 2026–27. Period N is the tax year ending 31 March N. diff --git a/docs/index.md b/docs/index.md index bde49bb..f61164e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -6,7 +6,7 @@ PolicyEngine New Zealand is a microsimulation model for New Zealand's tax and be ### Calculations -- Personal income tax before credits, using the progressive schedule for the tax year. +- Personal income tax before credits, using the progressive schedule for the tax year, on employment, self-employment and investment income, gross NZ Superannuation, and Jobseeker Support with the income tax that the model assumes MSD pays on it, from the 2022-23 tax year. - Estimated ACC Earners' Levy on liable employee earnings, using the tax year's rate and cap. - Working for Families tax credits (Family Tax Credit, In-Work Tax Credit, and Best Start). Before abatement, the formulas pay the Family Tax Credit and Best Start for each eligible day and the In-Work Tax Credit for each whole week of eligible days. They leave out, among other rules, the Minimum Family Tax Credit, shared care, the principal caregiver and residence tests, protected months, and changes in caregivers' relationships during the year. They spread a family's annual income evenly through the tax year, and the default family scheme income calculation leaves out main benefits and NZ Superannuation. - Jobseeker Support payment amounts based on a supplied grant status. diff --git a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml index 74a0111..44edbf0 100644 --- a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml +++ b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml @@ -1,4 +1,4 @@ -description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1) +description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), the amounts the beneficiary receives; the model assumes MSD pays the income tax on them to Inland Revenue on top, as section 350(2) allows metadata: label: Jobseeker Support payment rates reference: diff --git a/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml new file mode 100644 index 0000000..408f489 --- /dev/null +++ b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml @@ -0,0 +1,126 @@ +# NZ Superannuation and Jobseeker Support in taxable income (Income Tax Act +# 2007, sections CF 1(1)(c) and (e)). Period 2027 is the 2026-27 tax year, +# taxed at 10.5% to $15,600, 17.5% to $53,500, 30% to $78,100, 33% to +# $180,000 and 39% above (Schedule 1 Part A clause 1, Table 1). Benefits are +# 52 times the weekly rate from 1 April 2026. + +# 52 x 647.37 (NZS Act Schedule 1 Part 1 clause 1(a)). Tax is 10.5% of +# 15,600 plus 17.5% of 18,063.24. +- name: NZ Superannuation alone is taxed gross + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + output: + nz_superannuation: 33_663.24 + taxable_income: 33_663.24 + income_tax: 4_799.07 + +# 1,638 + 17.5% of 37,900 + 30% of 10,163.24. +- name: NZ Superannuation and wages are taxed together + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + employment_income: 30_000 + output: + taxable_income: 63_663.24 + income_tax: 11_319.47 + +# 52 x 492.14 (clause 1(c)). Tax is 1,638 plus 17.5% of 9,991.28. +- name: A partner's NZ Superannuation is taxed as their own income + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + has_partner: true + output: + nz_superannuation: 25_591.28 + taxable_income: 25_591.28 + income_tax: 3_386.47 + +# 52 x 372.55 (Social Security Act 2018 Schedule 4 Part 1 clause 1(d)). +# Section 350(3) grosses it up: $15,600 leaves 13,962 after tax, and the +# other 5,410.60 needs 5,410.60 / 0.825 = 6,558.30 of gross income, so the +# gross is 22,158.30 and the tax 2,785.70. +- name: Jobseeker Support is grossed up by the tax MSD pays on it + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 22_158.30 + income_tax: 2_785.70 + +- name: A Jobseeker Support grant at the clause 1(d) rate gives the same tax + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + receiving_jobseeker_support: true + output: + jobseeker_support: 19_372.60 + jobseeker_support_tax: 2_785.70 + taxable_income: 22_158.30 + income_tax: 2_785.70 + +# The gross-up ignores other income. 1,638 + 17.5% of 16,558.30 = 4,535.70, +# of which the earnings bear 1,750. +- name: Wages do not change the tax MSD pays on Jobseeker Support + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + employment_income: 10_000 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 32_158.30 + income_tax: 4_535.70 + +# 1,638 + 17.5% of 14,400. +- name: Wages alone are taxed as before + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + employment_income: 30_000 + output: + jobseeker_support_tax: 0 + taxable_income: 30_000 + income_tax: 4_158 + +# Net income is the sum of all sources, so a loss reduces the benefit too +# (sections BC 4 and BC 5). +- name: A self-employment loss offsets NZ Superannuation + period: 2027 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + self_employment_income: -40_000 + output: + taxable_income: 0 + income_tax: 0 + +# 52 x 538.24 from 1 April 2022, taxed at 10.5% to $14,000 and 17.5% to +# $48,000: 1,470 + 17.5% of 13,988.48. +- name: NZ Superannuation is taxed from the 2022-23 tax year + period: 2023 + absolute_error_margin: 0.01 + input: + age: 70 + receiving_nz_super: true + living_alone: true + output: + nz_superannuation: 27_988.48 + taxable_income: 27_988.48 + income_tax: 3_917.98 diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py new file mode 100644 index 0000000..2a694bd --- /dev/null +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -0,0 +1,170 @@ +"""Benefit income tax rules that YAML cases cannot state. + +Section 350(3) of the Social Security Act 2018 grosses Jobseeker Support up so +that what remains after tax equals the payment. These tests check that inverse +against the income tax schedule itself, at every bracket boundary of each +modelled tax year. +""" + +from types import SimpleNamespace + +import numpy as np +import pytest +from policyengine_core.simulations import Simulation + +from policyengine_nz import NewZealandTaxBenefitSystem +from policyengine_nz.variables.gov.msd.jobseeker.jobseeker_support_tax import ( + grossed_up_tax, +) + +PERIODS = range(2023, 2029) +# A simulation stores 32-bit floats, a step of up to 1/64 of a dollar at these +# amounts, so its results match to within 3 cents. +STORED = 0.03 + + +@pytest.fixture(scope="module") +def system(): + return NewZealandTaxBenefitSystem() + + +def _people(system, people, period): + situation = { + "people": { + name: {key: {str(period): value} for key, value in person.items()} + for name, person in people.items() + } + } + return Simulation(tax_benefit_system=system, situation=situation) + + +def _net_amounts(schedule): + """Amounts after tax at each threshold, a cent either side, and between.""" + thresholds = np.asarray(schedule.thresholds, dtype=float) + tax = np.array([schedule.calc(np.array([t]))[0] for t in thresholds]) + edges = thresholds - tax + amounts = [0.0, 0.01, 1.0] + for edge in edges[1:]: + amounts += [edge - 0.01, edge, edge + 0.01] + amounts += list((edges[:-1] + edges[1:]) / 2) + [edges[-1] + 50_000] + return np.array(sorted(amounts)) + + +@pytest.mark.parametrize("period", PERIODS) +def test_the_gross_up_leaves_the_payment_after_tax(system, period): + schedule = system.parameters(f"{period}-01-01").gov.ird.income_tax.schedule + net = _net_amounts(schedule) + tax = grossed_up_tax(net, schedule) + assert np.all(tax >= 0) + assert schedule.calc(net + tax) == pytest.approx(tax, abs=1e-6) + + +@pytest.mark.parametrize("period", PERIODS) +def test_a_benefit_only_recipient_owes_nothing_beyond_the_msd_tax(system, period): + schedule = system.parameters(f"{period}-01-01").gov.ird.income_tax.schedule + net = _net_amounts(schedule) + people = {f"p{i}": {"age": 30, "jobseeker_support": b} for i, b in enumerate(net)} + simulation = _people(system, people, period) + msd_tax = simulation.calculate("jobseeker_support_tax", period) + taxable = simulation.calculate("taxable_income", period) + assert taxable - msd_tax == pytest.approx(net, abs=STORED) + income_tax = simulation.calculate("income_tax", period) + assert income_tax - msd_tax == pytest.approx(0, abs=STORED) + + +def test_other_income_leaves_the_msd_tax_unchanged(system): + wages = [0, 10_000, 60_000, 100_000, 250_000] + people = { + f"p{i}": {"age": 30, "jobseeker_support": 19_372.60, "employment_income": w} + for i, w in enumerate(wages) + } + simulation = _people(system, people, 2027) + msd_tax = simulation.calculate("jobseeker_support_tax", 2027) + assert msd_tax == pytest.approx([2_785.70] * len(wages), abs=0.01) + + +def test_each_person_is_grossed_up_on_their_own(system): + # Two partners' shares of a couple rate and a single grant, in one + # simulation: each person's tax is the gross-up of their own payment. + payments = [13_936.00, 13_936.00, 19_372.60, 0.0] + people = { + f"p{i}": {"age": 40, "jobseeker_support": b} for i, b in enumerate(payments) + } + simulation = _people(system, people, 2027) + schedule = system.parameters("2027-01-01").gov.ird.income_tax.schedule + expected = [grossed_up_tax(np.array([b]), schedule)[0] for b in payments] + msd_tax = simulation.calculate("jobseeker_support_tax", 2027) + assert msd_tax == pytest.approx(expected, abs=STORED) + assert msd_tax[0] < grossed_up_tax(np.array([2 * 13_936.00]), schedule)[0] / 2 + + +def test_a_small_schedule_gives_exact_gross_ups(): + # 10% to 100 and 50% above: 45 after tax is 50 gross, 90 is 100 gross, + # and 100 is 100 + 10 / 0.5 = 120 gross. + schedule = SimpleNamespace(thresholds=[0, 100], rates=[0.1, 0.5]) + net = np.array([-5.0, 0.0, 45.0, 90.0, 100.0]) + assert grossed_up_tax(net, schedule) == pytest.approx([0, 0, 5, 10, 20]) + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([], []), + ([10, 100], [0.1, 0.2]), + ([0, 100, 100], [0.1, 0.2, 0.3]), + ([0, 100, 50], [0.1, 0.2, 0.3]), + ([0, 100], [-0.1, 0.2]), + ([0, 100], [0.1, 1.0]), + ([0, 100], [0.1, 1.5]), + ], +) +def test_a_schedule_the_gross_up_cannot_invert_raises(thresholds, rates): + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([1_000.0]), schedule) + + +@pytest.mark.parametrize("flag", ["receiving_nz_super", "receiving_jobseeker_support"]) +def test_a_recipient_before_april_2022_raises(system, flag): + simulation = _people(system, {"p": {"age": 70, flag: True}}, 2022) + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", 2022) + + +@pytest.mark.parametrize("benefit", ["nz_superannuation", "jobseeker_support"]) +def test_a_benefit_amount_before_april_2022_raises(system, benefit): + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "benefit": {"age": 30, benefit: 10_000}, + } + simulation = _people(system, people, 2022) + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", 2022) + + +def test_before_april_2022_an_earner_is_taxed_as_before(system): + # No benefit amount is given, so nothing may read the benefit variables, + # which raise for a period before their rates start. + simulation = _people( + system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 + ) + assert simulation.calculate("jobseeker_support_tax", 2022) == pytest.approx([0]) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020]) + + +def test_before_april_2022_zero_benefit_amounts_are_accepted(system): + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "zero_benefits": { + "age": 30, + "nz_superannuation": 0, + "jobseeker_support": 0, + "receiving_nz_super": False, + "receiving_jobseeker_support": False, + }, + } + simulation = _people(system, people, 2022) + assert simulation.calculate("jobseeker_support_tax", 2022) == pytest.approx([0, 0]) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000, 0]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) diff --git a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py index 3f4f78e..67a159f 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py +++ b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py @@ -11,7 +11,11 @@ class income_tax(Variable): documentation = ( "Annual personal income tax at basic rates before credits. Bare year " "labels refer to the tax year ending on 31 March of that year. " - "Provide the income totals for that tax year. The schedule starts " + "Provide the income totals for that tax year. For a Jobseeker Support " + "recipient, the model assumes MSD pays jobseeker_support_tax of this tax " + "to Inland Revenue, as section 350(2) of the Social Security Act 2018 " + "allows, so the recipient pays only " + "the rest. The schedule starts " "with the 2021-22 tax year (period 2022); earlier periods raise an " "error." ) diff --git a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py index 603aa44..249b072 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py +++ b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py @@ -2,6 +2,24 @@ from policyengine_nz.model_api import * +ACT = "https://www.legislation.govt.nz/act/public/2007/0097/latest/" + + +def _other_income(person, period): + return ( + person("employment_income", period) + + person("self_employment_income", period) + + person("investment_income", period) + ) + + +def _supplied(person, name, period): + """Whether each person was given a nonzero amount of the variable.""" + values = person.simulation.get_holder(name).get_array(period) + if values is None: + return np.zeros(person.count, dtype=bool) + return values != 0 + class taxable_income(Variable): value_type = float @@ -9,18 +27,48 @@ class taxable_income(Variable): definition_period = YEAR label = "Taxable income" documentation = ( - "Approximate annual taxable income from the modeled income sources, " - "assuming no additional deductions or available tax losses." + "Net income from the modelled sources, floored at zero (sections BC 4 " + "and BC 5): employment, self-employment and investment income, NZ " + "Superannuation (section CF 1(1)(e)), and Jobseeker Support " + "(section CF 1(1)(c)) together with the income tax MSD pays on it, " + "jobseeker_support_tax, which section 351(b)(iv) of the Social " + "Security Act 2018 makes the person's income. A loss in one source " + "reduces the others. The model assumes no other income, deductions or " + "available tax losses. The benefit rates start on 1 April 2022, and " + "for a period that starts earlier nz_superannuation and " + "jobseeker_support raise an error unless an amount is given. For such " + "a period, taxable income raises an error for a person whom " + "receiving_nz_super or receiving_jobseeker_support marks as a " + "recipient, or who is given a nonzero amount of either benefit." ) reference = ( - "https://www.legislation.govt.nz/act/public/2007/97/en/latest/parts/DLM1512313/" + ACT + "DLM1512339.html", + ACT + "DLM1512344.html", + ACT + "DLM1512819.html", + "https://www.legislation.govt.nz/act/public/2018/0032/latest/DLM6783844.html", ) unit = NZD def formula(person, period, parameters): + recipient = ( + person("receiving_nz_super", period) + | person("receiving_jobseeker_support", period) + | _supplied(person, "nz_superannuation", period) + | _supplied(person, "jobseeker_support", period) + ) + if np.any(recipient): + raise ValueError( + "NZ Superannuation and Jobseeker Support are modelled from 1 April " + f"2022, so taxable income for period {period} cannot include them. " + "Use a period that starts on or after 1 April 2022, such as 2023." + ) + return max_(_other_income(person, period), 0) + + def formula_2022_04_01(person, period, parameters): income = ( - person("employment_income", period) - + person("self_employment_income", period) - + person("investment_income", period) + _other_income(person, period) + + person("nz_superannuation", period) + + person("jobseeker_support", period) + + person("jobseeker_support_tax", period) ) return max_(income, 0) diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py index 8cc96d2..8bbfc53 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py @@ -229,9 +229,11 @@ class jobseeker_support(Variable): "52 times the weekly Jobseeker Support MSD pays the person, at the rates in " "force on the period's start date. A bare year N starts on 1 January N and " "stands for the tax year ending on 31 March N, so it reads the rates from 1 " - "April N - 1. The amount is net cash: MSD pays the income tax on an " - "instalment to Inland Revenue on top of it (section 350), and that tax " - "counts as the person's income (section 351). Under regulation 191(2) of " + "April N - 1. The amount is net cash: the model assumes MSD pays the " + "income tax on each instalment to Inland Revenue on top of it, as " + "section 350(2) allows, and that tax " + "counts as the person's income (section 351); jobseeker_support_tax " + "models it. Under regulation 191(2) of " "the Social Security Regulations 2018, MSD pays a " "clause 1(j) couple rate half to the beneficiary and half to the partner: " "in a benefit unit of two partners in one household each gets half, and a " diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py new file mode 100644 index 0000000..5e17cf1 --- /dev/null +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -0,0 +1,68 @@ +"""Income tax that MSD pays on Jobseeker Support under section 350.""" + +from policyengine_nz.model_api import * + +SSA = "https://www.legislation.govt.nz/act/public/2018/0032/latest/" + + +def grossed_up_tax(net, schedule): + """Tax on the gross amount that the schedule's tax reduces to net. + + The schedule's tax rises by each bracket's rate, below 1, so the amount left + after tax rises with the gross amount, and each net amount has one gross + amount. A net amount at or below zero gives no tax. + """ + thresholds = np.asarray(schedule.thresholds, dtype=float) + rates = np.asarray(schedule.rates, dtype=float) + if ( + len(thresholds) == 0 + or thresholds[0] != 0 + or np.any(np.diff(thresholds) <= 0) + or np.any(rates < 0) + or np.any(rates >= 1) + ): + raise ValueError( + "The gross-up needs a schedule whose first threshold is 0, whose " + "thresholds rise and whose rates lie in [0, 1)." + ) + tax_at = np.concatenate([[0.0], np.cumsum(rates[:-1] * np.diff(thresholds))]) + net_at = thresholds - tax_at + net = np.maximum(np.asarray(net, dtype=float), 0) + bracket = np.searchsorted(net_at, net, side="right") - 1 + gross = thresholds[bracket] + (net - net_at[bracket]) / (1 - rates[bracket]) + return gross - net + + +class jobseeker_support_tax(Variable): + value_type = float + entity = Person + definition_period = YEAR + label = "Income tax MSD pays on Jobseeker Support" + documentation = ( + "The income tax MSD pays to Inland Revenue on the person's " + "jobseeker_support instead of deducting it from the payments " + "(Social Security Act 2018, section 350(2)). Section 350(3) grosses each " + "payment up so that what remains after tax equals the payment, and " + "section 351(b)(iv) makes the tax the person's income under the Income " + "Tax Act 2007. The model assumes MSD uses that power. It grosses up the " + "year's jobseeker_support, apart from the person's other income, on the " + "personal income tax schedule for the tax year. Section 350(3) uses the " + "rate that the Commissioner determines for each payment, in consultation " + "with MSD's chief executive, under section RD 11(3) of the Income Tax Act " + "2007, so the tax on each payment can differ from this annual figure. " + "A partner's share of a couple rate is " + "grossed up on its own. The benefit rates start on 1 April 2022, and a " + "period that starts earlier gives 0." + ) + reference = ( + SSA + "DLM6783836.html", + SSA + "DLM6783843.html", + SSA + "DLM6783844.html", + "https://www.legislation.govt.nz/act/public/2007/0097/latest/DLM1519963.html", + ) + unit = NZD + + def formula_2022_04_01(person, period, parameters): + benefit = person("jobseeker_support", period) + schedule = parameters(period).gov.ird.income_tax.schedule + return grossed_up_tax(benefit, schedule) From 63e9c99a0709c01fc45dde2e018241b67b354c54 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 07:10:35 -0500 Subject: [PATCH 2/5] Answer the first review of #18 PR A - taxable_income reads a benefit amount stored for the period on the simulation's own branch, else on the branch it was made from, else on disk, and compares whole periods. Core's lookup read the default branch's amount in a named branch, and failed for a period-2022 calculation when either benefit had an input for a year that starts in April. - grossed_up_tax rejects a schedule with a NaN or infinite threshold, a NaN rate, or thresholds and rates of different shapes. - The income_tax documentation, the README and the docs describe income_tax as the year's liability before credits and jobseeker_support_tax as a separate estimate, whose difference can be negative. The README and the docs say income tax starts in 2021-22 and the benefits enter it in 2022-23. - New tests cover a linked couple's two Jobseeker shares, a partnered NZ Super recipient beside a working partner, a loss beside Jobseeker Support, branch, anchored-year and disk reads, and invalid schedules. - The Jobseeker Support rate description says the rates come before the income test, and the README's clause 1(d) example leaves out 2013 transferees. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- changelog.d/benefit-income-tax.fixed.md | 2 +- docs/index.md | 2 +- .../gov/msd/jobseeker/payment_rates.yaml | 2 +- .../baseline/test_benefit_income_tax.yaml | 48 +++++- .../tests/test_benefit_income_tax.py | 153 +++++++++++++++++- .../gov/ird/income_tax/income_tax.py | 21 +-- .../gov/ird/income_tax/taxable_income.py | 73 +++++++-- .../msd/jobseeker/jobseeker_support_tax.py | 31 ++-- 9 files changed, 280 insertions(+), 56 deletions(-) diff --git a/README.md b/README.md index b80e741..909bbb9 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ print(f"ACC levy: ${acc_levy[0]:,.2f}") ## System Coverage ### Tax System (Inland Revenue Department) -- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds, on employment, self-employment and investment income, gross NZ Superannuation, and Jobseeker Support with the income tax MSD pays on it (`jobseeker_support_tax`), from the 2022-23 tax year. The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it is part of `income_tax` but does not come out of the benefit. +- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds, from the 2021-22 tax year (period `2022`) on employment, self-employment and investment income, and from the 2022-23 tax year (period `2023`) also on gross NZ Superannuation and on Jobseeker Support with the income tax MSD pays on it (`jobseeker_support_tax`). The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it does not come out of the benefit, and estimates it from the benefit alone. `income_tax` is the year's liability on all the modelled income before credits. `income_tax - jobseeker_support_tax` is the balance after MSD's payment, which is negative when a loss brings the liability below that payment. - **ACC Earners' Levy** on liable employee earnings, capped by tax year: an annual estimate at the GST-inclusive rate Inland Revenue publishes. It does not compute PAYE deductions pay by pay. A bare year uses the rate and cap in force on 1 January of that year, so `2025` uses those of the tax year from April 2024 to March 2025. - **GST**: the model stores the 15% rate as a parameter and does not calculate GST. @@ -72,7 +72,7 @@ sim.calculate("family_tax_credit", "2027") # 7,921 ``` ### Social Security Benefits (Work and Income) -- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) +- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children who was not transferred to Jobseeker Support on 15 July 2013 (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) - **New Zealand Superannuation**: the annualised gross standard rate, from age 65, for a person that `receiving_nz_super` marks as a recipient - **Accommodation Supplement**: the annualised amount for the area before income abatement and rounding, and a separate cash assets test diff --git a/changelog.d/benefit-income-tax.fixed.md b/changelog.d/benefit-income-tax.fixed.md index a154108..09df8bb 100644 --- a/changelog.d/benefit-income-tax.fixed.md +++ b/changelog.d/benefit-income-tax.fixed.md @@ -1 +1 @@ -Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, found by grossing up the year's payment on its own; section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The floor at zero still applies to the sum of the modelled sources, so a self-employment loss now reduces the taxable benefit. For a period that starts before 1 April 2022, taxable income raises an error for a person marked as a recipient of either benefit or given a nonzero amount of one, and taxes other income as before. `family_income` and the Working for Families credits do not yet include either benefit. +Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, found by grossing up the year's payment on its own; section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The model still offsets a loss in one modelled source against the others and floors the total at zero, so a self-employment loss now reduces taxable income that includes a benefit, and can leave `income_tax` below `jobseeker_support_tax`. For a period that starts before 1 April 2022, taxable income raises an error for a person marked as a recipient of either benefit or given a nonzero amount of one for that period, and taxes other income as before. The documentation now states the assumption that MSD pays the tax, and the Jobseeker Support rate metadata now says the rates come before the income test. `family_income` and the Working for Families credits do not yet include either benefit. diff --git a/docs/index.md b/docs/index.md index f61164e..6029880 100644 --- a/docs/index.md +++ b/docs/index.md @@ -6,7 +6,7 @@ PolicyEngine New Zealand is a microsimulation model for New Zealand's tax and be ### Calculations -- Personal income tax before credits, using the progressive schedule for the tax year, on employment, self-employment and investment income, gross NZ Superannuation, and Jobseeker Support with the income tax that the model assumes MSD pays on it, from the 2022-23 tax year. +- Personal income tax before credits, using the progressive schedule for the tax year, from the 2021-22 tax year on employment, self-employment and investment income, and from the 2022-23 tax year also on gross NZ Superannuation and on Jobseeker Support with the income tax that the model assumes MSD pays on it. - Estimated ACC Earners' Levy on liable employee earnings, using the tax year's rate and cap. - Working for Families tax credits (Family Tax Credit, In-Work Tax Credit, and Best Start). Before abatement, the formulas pay the Family Tax Credit and Best Start for each eligible day and the In-Work Tax Credit for each whole week of eligible days. They leave out, among other rules, the Minimum Family Tax Credit, shared care, the principal caregiver and residence tests, protected months, and changes in caregivers' relationships during the year. They spread a family's annual income evenly through the tax year, and the default family scheme income calculation leaves out main benefits and NZ Superannuation. - Jobseeker Support payment amounts based on a supplied grant status. diff --git a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml index 44edbf0..f6aac69 100644 --- a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml +++ b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml @@ -1,4 +1,4 @@ -description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), the amounts the beneficiary receives; the model assumes MSD pays the income tax on them to Inland Revenue on top, as section 350(2) allows +description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), before the applicable income test; the model assumes MSD pays the income tax on the payments to Inland Revenue on top of them, as section 350(2) allows metadata: label: Jobseeker Support payment rates reference: diff --git a/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml index 408f489..b3c8dbc 100644 --- a/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml +++ b/policyengine_nz/tests/policy/baseline/test_benefit_income_tax.yaml @@ -31,18 +31,35 @@ taxable_income: 63_663.24 income_tax: 11_319.47 -# 52 x 492.14 (clause 1(c)). Tax is 1,638 plus 17.5% of 9,991.28. -- name: A partner's NZ Superannuation is taxed as their own income +# 52 x 492.14 (clause 1(c)). Tax is 1,638 plus 17.5% of 9,991.28. The +# partner's $30,000 of wages are taxed on their own: 1,638 plus 17.5% of +# 14,400. Taxing the couple's $55,591.28 together would give 8,897.88. +- name: Each partner of a couple is taxed on their own income period: 2027 absolute_error_margin: 0.01 input: - age: 70 - receiving_nz_super: true - has_partner: true + people: + retiree: + age: 70 + receiving_nz_super: true + has_partner: true + partner: + age: 45 + has_partner: true + employment_income: 30_000 + households: + household: + members: [retiree, partner] output: - nz_superannuation: 25_591.28 - taxable_income: 25_591.28 - income_tax: 3_386.47 + people: + retiree: + nz_superannuation: 25_591.28 + taxable_income: 25_591.28 + income_tax: 3_386.47 + partner: + nz_superannuation: 0 + taxable_income: 30_000 + income_tax: 4_158 # 52 x 372.55 (Social Security Act 2018 Schedule 4 Part 1 clause 1(d)). # Section 350(3) grosses it up: $15,600 leaves 13,962 after tax, and the @@ -111,6 +128,21 @@ taxable_income: 0 income_tax: 0 +# The tax MSD pays on Jobseeker Support depends on the benefit alone, so a +# loss that cancels the taxable income leaves it at 2,785.70 while the year's +# liability is 0. +- name: A self-employment loss can leave the liability below the tax MSD pays + period: 2027 + absolute_error_margin: 0.01 + input: + age: 30 + jobseeker_support: 19_372.60 + self_employment_income: -40_000 + output: + jobseeker_support_tax: 2_785.70 + taxable_income: 0 + income_tax: 0 + # 52 x 538.24 from 1 April 2022, taxed at 10.5% to $14,000 and 17.5% to # $48,000: 1,470 + 17.5% of 13,988.48. - name: NZ Superannuation is taxed from the 2022-23 tax year diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py index 2a694bd..bd8e384 100644 --- a/policyengine_nz/tests/test_benefit_income_tax.py +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -2,14 +2,17 @@ Section 350(3) of the Social Security Act 2018 grosses Jobseeker Support up so that what remains after tax equals the payment. These tests check that inverse -against the income tax schedule itself, at every bracket boundary of each -modelled tax year. +against the income tax schedule itself, at every bracket boundary of each tax +year from 2021-22 to 2027-28, and check simulations from 2022-23, when the +benefit rates start, to 2027-28. They also check how taxable income reads +benefit amounts for a period that starts before 1 April 2022. """ from types import SimpleNamespace import numpy as np import pytest +from policyengine_core.periods import period as as_period from policyengine_core.simulations import Simulation from policyengine_nz import NewZealandTaxBenefitSystem @@ -17,7 +20,9 @@ grossed_up_tax, ) +SCHEDULE_PERIODS = range(2022, 2029) PERIODS = range(2023, 2029) +BENEFITS = ["nz_superannuation", "jobseeker_support"] # A simulation stores 32-bit floats, a step of up to 1/64 of a dollar at these # amounts, so its results match to within 3 cents. STORED = 0.03 @@ -50,7 +55,7 @@ def _net_amounts(schedule): return np.array(sorted(amounts)) -@pytest.mark.parametrize("period", PERIODS) +@pytest.mark.parametrize("period", SCHEDULE_PERIODS) def test_the_gross_up_leaves_the_payment_after_tax(system, period): schedule = system.parameters(f"{period}-01-01").gov.ird.income_tax.schedule net = _net_amounts(schedule) @@ -84,8 +89,9 @@ def test_other_income_leaves_the_msd_tax_unchanged(system): def test_each_person_is_grossed_up_on_their_own(system): - # Two partners' shares of a couple rate and a single grant, in one - # simulation: each person's tax is the gross-up of their own payment. + # Four payments given directly to four people, whom the simulation puts + # in one benefit unit: each person's tax is the gross-up of their own + # payment, and two equal payments are not pooled. payments = [13_936.00, 13_936.00, 19_372.60, 0.0] people = { f"p{i}": {"age": 40, "jobseeker_support": b} for i, b in enumerate(payments) @@ -98,6 +104,43 @@ def test_each_person_is_grossed_up_on_their_own(system): assert msd_tax[0] < grossed_up_tax(np.array([2 * 13_936.00]), schedule)[0] / 2 +@pytest.mark.parametrize( + "grants", [(True, False), (True, True)], ids=["one_grant", "both_granted"] +) +def test_each_partner_of_a_linked_couple_is_grossed_up_on_their_own(system, grants): + # Clause 1(j)(i) pays a childless couple 633.94 a week, half to each + # partner under regulation 191(2): 52 x 316.97 = 16,482.44. That leaves + # 2,520.44 above the 13,962 that $15,600 leaves after tax, which needs + # 2,520.44 / 0.825 = 3,055.08 of gross income at 17.5%, so each partner's + # tax is 18,655.08 - 16,482.44 = 2,172.64. + period = "2027" + situation = { + "people": { + name: { + "age": {period: age}, + "has_partner": {period: True}, + "receiving_jobseeker_support": {period: grant}, + } + for name, age, grant in ( + ("first", 35, grants[0]), + ("second", 42, grants[1]), + ) + }, + "benefit_units": {"unit": {"adults": ["first", "second"], "children": []}}, + "households": {"household": {"members": ["first", "second"]}}, + } + simulation = Simulation(tax_benefit_system=system, situation=situation) + expected = { + "jobseeker_support": 16_482.44, + "jobseeker_support_tax": 2_172.64, + "taxable_income": 18_655.08, + "income_tax": 2_172.64, + } + for name, amount in expected.items(): + values = simulation.calculate(name, period) + assert values == pytest.approx([amount] * 2, abs=STORED), name + + def test_a_small_schedule_gives_exact_gross_ups(): # 10% to 100 and 50% above: 45 after tax is 50 gross, 90 is 100 gross, # and 100 is 100 + 10 / 0.5 = 120 gross. @@ -116,6 +159,15 @@ def test_a_small_schedule_gives_exact_gross_ups(): ([0, 100], [-0.1, 0.2]), ([0, 100], [0.1, 1.0]), ([0, 100], [0.1, 1.5]), + ([0, 100], [0.1, np.nan]), + ([0, 100], [np.nan, 0.2]), + ([0, np.nan], [0.1, 0.2]), + ([0, 100, np.nan], [0.1, 0.2, 0.3]), + ([0, np.inf], [0.1, 0.2]), + ([0, 100], [0.1, 0.2, 0.3]), + ([0, 100, 200], [0.1, 0.2]), + ([[0, 100]], [[0.1, 0.2]]), + (0, 0.1), ], ) def test_a_schedule_the_gross_up_cannot_invert_raises(thresholds, rates): @@ -124,6 +176,17 @@ def test_a_schedule_the_gross_up_cannot_invert_raises(thresholds, rates): grossed_up_tax(np.array([1_000.0]), schedule) +def test_a_nan_rate_in_a_real_schedule_raises(system): + # The 2024-25 schedule, with its 12.82% bracket made NaN as a reform could. + schedule = system.parameters("2025-01-01").gov.ird.income_tax.schedule + rates = np.array(schedule.rates, dtype=float) + assert np.sum(rates == 0.1282) == 1 + rates[rates == 0.1282] = np.nan + broken = SimpleNamespace(thresholds=schedule.thresholds, rates=rates) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([13_000.0, 19_000.0]), broken) + + @pytest.mark.parametrize("flag", ["receiving_nz_super", "receiving_jobseeker_support"]) def test_a_recipient_before_april_2022_raises(system, flag): simulation = _people(system, {"p": {"age": 70, flag: True}}, 2022) @@ -168,3 +231,83 @@ def test_before_april_2022_zero_benefit_amounts_are_accepted(system): assert simulation.calculate("jobseeker_support_tax", 2022) == pytest.approx([0, 0]) assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000, 0]) assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) + + +def _branch_case(system, benefit, default, branch): + """A period-2022 earner with a benefit amount on default, a branch, or both.""" + earner = {"age": 40, "employment_income": 50_000} + if default is not None: + earner[benefit] = default + simulation = _people(system, {"earner": earner}, 2022) + fork = simulation.get_branch("fork") + if branch is not None: + fork.set_input(benefit, "2022", np.array([branch], dtype=float)) + return simulation, fork + + +@pytest.mark.parametrize("benefit", BENEFITS) +@pytest.mark.parametrize( + "default, branch, default_raises, branch_raises", + [ + (None, 10_000, False, True), + (10_000, None, True, True), + (0, 10_000, False, True), + (10_000, 0, True, False), + ], + ids=["branch_only", "default_only", "zero_on_default", "zero_on_branch"], +) +def test_before_april_2022_each_branch_reads_its_own_amount( + system, benefit, default, branch, default_raises, branch_raises +): + # A branch inherits the amounts stored when it was made, and its own input + # replaces them. Each read uses a fresh simulation, so neither caches the + # other's result. + for read_branch, raises in ((False, default_raises), (True, branch_raises)): + simulation, fork = _branch_case(system, benefit, default, branch) + target = fork if read_branch else simulation + if raises: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + target.calculate("taxable_income", 2022) + else: + assert target.calculate("taxable_income", 2022) == pytest.approx([50_000]) + assert target.calculate("income_tax", 2022) == pytest.approx([8_020]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_before_april_2022_an_amount_for_another_year_is_ignored(system, benefit): + # Core's own lookup fails when a stored year starts in April, as + # year:2025-04 does, so taxable income compares whole periods instead. + simulation = _people( + system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 + ) + simulation.set_input(benefit, "year:2025-04", np.array([10_000.0])) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_before_april_2022_an_amount_stored_on_disk_raises(system, benefit, tmp_path): + # Under a memory limit, Core can store an input on disk instead of in + # memory. Taxable income still finds it. + simulation = _people( + system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 + ) + holder = simulation.get_holder(benefit) + holder._disk_storage = holder.create_disk_storage(str(tmp_path)) + holder._disk_storage.put(np.array([10_000.0]), as_period("2022")) + assert holder._memory_storage.get(as_period("2022")) is None + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", 2022) + + +@pytest.mark.parametrize("benefit", BENEFITS) +@pytest.mark.parametrize("on_branch", [False, True], ids=["simulation", "branch"]) +def test_an_amount_for_a_year_from_july_2021_raises(system, benefit, on_branch): + # A year that starts on 1 July 2021 also starts before the benefit rates, + # and an amount stored for exactly that year counts, on the simulation and + # on a branch made from it. + simulation = _people(system, {"person": {"age": 40}}, 2022) + simulation.set_input(benefit, "year:2021-07", np.array([10_000.0])) + target = simulation.get_branch("fork") if on_branch else simulation + with pytest.raises(ValueError, match=r"from 1 April 2022"): + target.calculate("taxable_income", "year:2021-07") diff --git a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py index 67a159f..42f1004 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py +++ b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py @@ -9,15 +9,18 @@ class income_tax(Variable): definition_period = YEAR label = "Income tax" documentation = ( - "Annual personal income tax at basic rates before credits. Bare year " - "labels refer to the tax year ending on 31 March of that year. " - "Provide the income totals for that tax year. For a Jobseeker Support " - "recipient, the model assumes MSD pays jobseeker_support_tax of this tax " - "to Inland Revenue, as section 350(2) of the Social Security Act 2018 " - "allows, so the recipient pays only " - "the rest. The schedule starts " - "with the 2021-22 tax year (period 2022); earlier periods raise an " - "error." + "Annual personal income tax at basic rates before credits: the year's " + "liability on taxable_income. Bare year labels refer to the tax year " + "ending on 31 March of that year. Provide the income totals for that " + "tax year. For a Jobseeker Support recipient, jobseeker_support_tax is " + "a separate estimate of the tax that the model assumes MSD pays to " + "Inland Revenue on the benefit, as section 350(2) of the Social " + "Security Act 2018 allows. income_tax less jobseeker_support_tax is the " + "balance after that payment, and it is negative when a loss brings the " + "liability below the payment: in 2026-27, $19,372.60 of Jobseeker " + "Support beside a $40,000 self-employment loss gives $2,785.70 of " + "jobseeker_support_tax and no income tax. The schedule starts with the " + "2021-22 tax year (period 2022); earlier periods raise an error." ) reference = [ # Part B, ss BC 4 to BC 6: net income, taxable income and tax liability diff --git a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py index 249b072..2d16afa 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py +++ b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py @@ -1,5 +1,7 @@ """Taxable income calculation for New Zealand residents.""" +from policyengine_core import periods + from policyengine_nz.model_api import * ACT = "https://www.legislation.govt.nz/act/public/2007/0097/latest/" @@ -13,12 +15,52 @@ def _other_income(person, period): ) -def _supplied(person, name, period): - """Whether each person was given a nonzero amount of the variable.""" - values = person.simulation.get_holder(name).get_array(period) - if values is None: - return np.zeros(person.count, dtype=bool) - return values != 0 +def _given(person, name, period): + """The amount of the variable stored for the period, or None. + + It reads the stored amounts in the order Core's own lookup does, without + running the variable's formula: the amount stored for the simulation's + branch, else the first one stored for the period on another branch, which + a branch inherits from the simulation it was made from, else one stored on + disk. Core's lookup reads each storage key's period by splitting the key at + every colon, which fails when any key holds a year that starts in a month + other than January, such as year:2025-04, so this compares each key's + whole period instead. Core 3.20's lookup also recurses without end on an + amount stored only on disk, which this reads directly. Core ignores an + input to a neutralized variable, so no amount is stored for one. + """ + simulation = person.simulation + holder = simulation.get_holder(name) + key = str(periods.period(period)) + stored = holder._memory_storage._arrays + value = stored.get(f"{simulation.branch_name}:{key}") + if value is None: + value = next( + (array for k, array in stored.items() if k.partition(":")[2] == key), + None, + ) + if value is None and holder._disk_storage is not None: + value = holder._disk_storage.get(period, simulation.branch_name) + return value + + +def benefit_recipients(person, period): + """Who receives NZ Superannuation or Jobseeker Support, by flag or amount. + + A person counts when receiving_nz_super or receiving_jobseeker_support + marks them as a recipient, or when either benefit has a nonzero amount + stored for them for the period. Reading the stored amounts never runs the + benefits' formulas, which raise for a period that starts before their + rates do on 1 April 2022. + """ + recipients = person("receiving_nz_super", period) | person( + "receiving_jobseeker_support", period + ) + for name in ("nz_superannuation", "jobseeker_support"): + given = _given(person, name, period) + if given is not None: + recipients = recipients | (given != 0) + return recipients class taxable_income(Variable): @@ -32,14 +74,17 @@ class taxable_income(Variable): "Superannuation (section CF 1(1)(e)), and Jobseeker Support " "(section CF 1(1)(c)) together with the income tax MSD pays on it, " "jobseeker_support_tax, which section 351(b)(iv) of the Social " - "Security Act 2018 makes the person's income. A loss in one source " - "reduces the others. The model assumes no other income, deductions or " - "available tax losses. The benefit rates start on 1 April 2022, and " + "Security Act 2018 makes the person's income. The model offsets a loss " + "in one modelled source against the others, and assumes no other " + "income, no further deductions and no available tax losses. The " + "benefit rates start on 1 April 2022, and " "for a period that starts earlier nz_superannuation and " "jobseeker_support raise an error unless an amount is given. For such " "a period, taxable income raises an error for a person whom " "receiving_nz_super or receiving_jobseeker_support marks as a " - "recipient, or who is given a nonzero amount of either benefit." + "recipient, or who is given a nonzero amount of either benefit for " + "that period on the simulation's branch, or on the simulation it was " + "made from." ) reference = ( ACT + "DLM1512339.html", @@ -50,13 +95,7 @@ class taxable_income(Variable): unit = NZD def formula(person, period, parameters): - recipient = ( - person("receiving_nz_super", period) - | person("receiving_jobseeker_support", period) - | _supplied(person, "nz_superannuation", period) - | _supplied(person, "jobseeker_support", period) - ) - if np.any(recipient): + if np.any(benefit_recipients(person, period)): raise ValueError( "NZ Superannuation and Jobseeker Support are modelled from 1 April " f"2022, so taxable income for period {period} cannot include them. " diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py index 5e17cf1..14a7c74 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -10,20 +10,27 @@ def grossed_up_tax(net, schedule): The schedule's tax rises by each bracket's rate, below 1, so the amount left after tax rises with the gross amount, and each net amount has one gross - amount. A net amount at or below zero gives no tax. + amount. The function finds the bracket whose net amounts hold the net + amount, divides the net amount's excess over the bracket's lowest net + amount by one minus the bracket's rate, and adds the bracket's threshold to + give the gross amount. A net amount at or below zero gives no tax. """ thresholds = np.asarray(schedule.thresholds, dtype=float) rates = np.asarray(schedule.rates, dtype=float) - if ( - len(thresholds) == 0 - or thresholds[0] != 0 - or np.any(np.diff(thresholds) <= 0) - or np.any(rates < 0) - or np.any(rates >= 1) - ): + valid = ( + thresholds.ndim == 1 + and rates.shape == thresholds.shape + and len(thresholds) > 0 + and np.all(np.isfinite(thresholds)) + and thresholds[0] == 0 + and np.all(np.diff(thresholds) > 0) + and np.all((rates >= 0) & (rates < 1)) + ) + if not valid: raise ValueError( - "The gross-up needs a schedule whose first threshold is 0, whose " - "thresholds rise and whose rates lie in [0, 1)." + "The gross-up needs a schedule of finite thresholds, with one rate " + "for each, whose first threshold is 0, whose thresholds rise and " + "whose rates lie in [0, 1)." ) tax_at = np.concatenate([[0.0], np.cumsum(rates[:-1] * np.diff(thresholds))]) net_at = thresholds - tax_at @@ -50,8 +57,8 @@ class jobseeker_support_tax(Variable): "rate that the Commissioner determines for each payment, in consultation " "with MSD's chief executive, under section RD 11(3) of the Income Tax Act " "2007, so the tax on each payment can differ from this annual figure. " - "A partner's share of a couple rate is " - "grossed up on its own. The benefit rates start on 1 April 2022, and a " + "The model grosses up each partner's share of a couple rate " + "separately. The benefit rates start on 1 April 2022, and a " "period that starts earlier gives 0." ) reference = ( From 128f88bf8b840b9697ef71b97e4dde473b207faa Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Tue, 1 Dec 2026 07:49:43 -0500 Subject: [PATCH 3/5] Answer the second review of #18 PR A - taxable_income decides whether a period that starts before 1 April 2022 has a benefit recipient from the receiving_nz_super and receiving_jobseeker_support flags alone. The supplied-amount check, which read Core's storage directly, is gone, and an amount given without a flag is left out, as on main. - grossed_up_tax sums each bracket's tax and its amount left after tax, finds the bracket by that amount, and raises when the tax on a finite amount overflows a float. A tiny rate keeps its tax, a rate just below one keeps a finite tax, and a large bracket keeps its small after-tax width. - jobseeker_support_tax raises a TypeError when a reform makes the income tax schedule anything other than a marginal-rate scale. - The documentation, README and changelog say the model assumes MSD pays the tax, and name the clause each couple rate comes from. - New tests cover a NaN rate set through a reform, an average-rate schedule, two grants on the clause 1(g)(i) rate, and the float limits. Co-Authored-By: Claude Opus 5.5 --- README.md | 4 +- changelog.d/benefit-income-tax.fixed.md | 2 +- .../gov/msd/jobseeker/payment_rates.yaml | 2 +- .../tests/test_benefit_income_tax.py | 305 +++++++++++++----- .../gov/ird/income_tax/income_tax.py | 7 +- .../gov/ird/income_tax/taxable_income.py | 71 +--- .../gov/msd/jobseeker/jobseeker_support.py | 8 +- .../msd/jobseeker/jobseeker_support_tax.py | 66 ++-- 8 files changed, 295 insertions(+), 170 deletions(-) diff --git a/README.md b/README.md index 909bbb9..bb5cd84 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ print(f"ACC levy: ${acc_levy[0]:,.2f}") ## System Coverage ### Tax System (Inland Revenue Department) -- **Personal Income Tax**: Progressive rates (10.5%, 17.5%, 30%, 33%, 39%) with current thresholds, from the 2021-22 tax year (period `2022`) on employment, self-employment and investment income, and from the 2022-23 tax year (period `2023`) also on gross NZ Superannuation and on Jobseeker Support with the income tax MSD pays on it (`jobseeker_support_tax`). The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it does not come out of the benefit, and estimates it from the benefit alone. `income_tax` is the year's liability on all the modelled income before credits. `income_tax - jobseeker_support_tax` is the balance after MSD's payment, which is negative when a loss brings the liability below that payment. +- **Personal income tax**: the progressive schedule for each tax year from 2021-22 (period `2022`). To 2023-24, rates of 10.5%, 17.5%, 30%, 33% and 39% start at $0, $14,000, $48,000, $70,000 and $180,000. From 2025-26, the same rates start at $0, $15,600, $53,500, $78,100 and $180,000, and 2024-25 uses the composite schedule that the Taxation (Budget Measures) Act 2024 sets for the year of the change. The tax applies to employment, self-employment and investment income from 2021-22, and from the 2022-23 tax year (period `2023`) also to gross NZ Superannuation and to Jobseeker Support with the income tax that the model assumes MSD pays on it (`jobseeker_support_tax`). The model assumes MSD pays that tax to Inland Revenue on top of the benefit, as section 350(2) of the Social Security Act 2018 allows, so it does not come out of the benefit, and estimates it from the benefit alone. `income_tax` is the year's liability on all the modelled income before credits. `income_tax - jobseeker_support_tax` is the balance after MSD's payment, which is negative when a loss brings the liability below that payment. - **ACC Earners' Levy** on liable employee earnings, capped by tax year: an annual estimate at the GST-inclusive rate Inland Revenue publishes. It does not compute PAYE deductions pay by pay. A bare year uses the rate and cap in force on 1 January of that year, so `2025` uses those of the tax year from April 2024 to March 2025. - **GST**: the model stores the 15% rate as a parameter and does not calculate GST. @@ -72,7 +72,7 @@ sim.calculate("family_tax_credit", "2027") # 7,921 ``` ### Social Security Benefits (Work and Income) -- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children who was not transferred to Jobseeker Support on 15 July 2013 (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) +- **Jobseeker Support**: $372.55 a week after tax from 1 April 2026 for a single person aged 25 or over without dependent children who falls outside clause 1(c), which covers some people moved to Jobseeker Support on 15 July 2013 under the Social Security Act 1964's transitional provisions (the clause 1(d) rate), before the income test (period `2027` reads the rates for April 2026 to March 2027) - **New Zealand Superannuation**: the annualised gross standard rate, from age 65, for a person that `receiving_nz_super` marks as a recipient - **Accommodation Supplement**: the annualised amount for the area before income abatement and rounding, and a separate cash assets test diff --git a/changelog.d/benefit-income-tax.fixed.md b/changelog.d/benefit-income-tax.fixed.md index 09df8bb..30e3fdc 100644 --- a/changelog.d/benefit-income-tax.fixed.md +++ b/changelog.d/benefit-income-tax.fixed.md @@ -1 +1 @@ -Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, found by grossing up the year's payment on its own; section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The model still offsets a loss in one modelled source against the others and floors the total at zero, so a self-employment loss now reduces taxable income that includes a benefit, and can leave `income_tax` below `jobseeker_support_tax`. For a period that starts before 1 April 2022, taxable income raises an error for a person marked as a recipient of either benefit or given a nonzero amount of one for that period, and taxes other income as before. The documentation now states the assumption that MSD pays the tax, and the Jobseeker Support rate metadata now says the rates come before the income test. `family_income` and the Working for Families credits do not yet include either benefit. +Tax NZ Superannuation and Jobseeker Support from the 2022-23 tax year (period 2023), under sections CF 1(1)(c) and (e) of the Income Tax Act 2007. `taxable_income` now adds the gross `nz_superannuation`, and `jobseeker_support` with the new `jobseeker_support_tax`. That variable is the income tax that the model assumes MSD pays on Jobseeker Support under section 350 of the Social Security Act 2018, and the model finds it by grossing up the year's payment on its own. Section 351 makes it the person's income. A person aged 70 on NZ Superannuation alone, living alone, now owes $4,799.07 of income tax for 2026-27 in place of $0, and a person aged 30 on $19,372.60 of Jobseeker Support has taxable income of $22,158.30, with $2,785.70 of tax that MSD pays. The model still offsets a loss in one modelled source against the others and floors the total at zero, so a self-employment loss now reduces taxable income that includes a benefit, and can leave `income_tax` below `jobseeker_support_tax`. For a period that starts before 1 April 2022, taxable income leaves out both benefits as before, and raises an error for the whole calculation when anyone is marked as a recipient of either. The documentation now states the assumption that MSD pays the tax, and the Jobseeker Support rate metadata now says the rates come before the income test. `family_income` and the Working for Families credits do not yet include either benefit. diff --git a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml index f6aac69..b1db866 100644 --- a/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml +++ b/policyengine_nz/parameters/gov/msd/jobseeker/payment_rates.yaml @@ -1,4 +1,4 @@ -description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), before the applicable income test; the model assumes MSD pays the income tax on the payments to Inland Revenue on top of them, as section 350(2) allows +description: Jobseeker Support weekly rates (Social Security Act 2018, Schedule 4 Part 1 clause 1), before the applicable income test. The model assumes MSD pays the income tax on the payments to Inland Revenue on top of them, as section 350(2) allows. metadata: label: Jobseeker Support payment rates reference: diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py index bd8e384..02fa978 100644 --- a/policyengine_nz/tests/test_benefit_income_tax.py +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -4,15 +4,19 @@ that what remains after tax equals the payment. These tests check that inverse against the income tax schedule itself, at every bracket boundary of each tax year from 2021-22 to 2027-28, and check simulations from 2022-23, when the -benefit rates start, to 2027-28. They also check how taxable income reads -benefit amounts for a period that starts before 1 April 2022. +benefit rates start, to 2027-28. They also check what taxable income does +with the receipt flags and benefit amounts for a period that starts before +1 April 2022. """ +from fractions import Fraction from types import SimpleNamespace import numpy as np import pytest -from policyengine_core.periods import period as as_period +from policyengine_core import periods +from policyengine_core.parameters import ParameterScale +from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation from policyengine_nz import NewZealandTaxBenefitSystem @@ -23,6 +27,7 @@ SCHEDULE_PERIODS = range(2022, 2029) PERIODS = range(2023, 2029) BENEFITS = ["nz_superannuation", "jobseeker_support"] +FLAGS = ["receiving_nz_super", "receiving_jobseeker_support"] # A simulation stores 32-bit floats, a step of up to 1/64 of a dollar at these # amounts, so its results match to within 3 cents. STORED = 0.03 @@ -43,6 +48,16 @@ def _people(system, people, period): return Simulation(tax_benefit_system=system, situation=situation) +def _reformed(modify): + """The tax-benefit system with a reform that applies modify to its parameters.""" + + class _Reform(Reform): + def apply(self): + self.modify_parameters(modify) + + return _Reform(NewZealandTaxBenefitSystem()) + + def _net_amounts(schedule): """Amounts after tax at each threshold, a cent either side, and between.""" thresholds = np.asarray(schedule.thresholds, dtype=float) @@ -104,15 +119,8 @@ def test_each_person_is_grossed_up_on_their_own(system): assert msd_tax[0] < grossed_up_tax(np.array([2 * 13_936.00]), schedule)[0] / 2 -@pytest.mark.parametrize( - "grants", [(True, False), (True, True)], ids=["one_grant", "both_granted"] -) -def test_each_partner_of_a_linked_couple_is_grossed_up_on_their_own(system, grants): - # Clause 1(j)(i) pays a childless couple 633.94 a week, half to each - # partner under regulation 191(2): 52 x 316.97 = 16,482.44. That leaves - # 2,520.44 above the 13,962 that $15,600 leaves after tax, which needs - # 2,520.44 / 0.825 = 3,055.08 of gross income at 17.5%, so each partner's - # tax is 18,655.08 - 16,482.44 = 2,172.64. +def _couple(system, grants): + """Two childless partners in one benefit unit and household, in 2026-27.""" period = "2027" situation = { "people": { @@ -129,16 +137,70 @@ def test_each_partner_of_a_linked_couple_is_grossed_up_on_their_own(system, gran "benefit_units": {"unit": {"adults": ["first", "second"], "children": []}}, "households": {"household": {"members": ["first", "second"]}}, } - simulation = Simulation(tax_benefit_system=system, situation=situation) + return Simulation(tax_benefit_system=system, situation=situation) + + +def _each_partner(simulation, expected): + for name, amount in expected.items(): + values = simulation.calculate(name, "2027") + assert values == pytest.approx([amount] * 2, abs=STORED), name + + +@pytest.mark.parametrize( + "grants", [(True, False), (True, True)], ids=["one_grant", "both_granted"] +) +def test_each_partner_of_a_linked_couple_is_grossed_up_on_their_own(system, grants): + # With one grant, clause 1(j)(i) pays the childless couple 633.94 a week, + # half to each partner under regulation 191(2). With both granted, clause + # 1(g)(i) pays each partner 316.97 a week. Either way each partner gets + # 52 x 316.97 = 16,482.44. That leaves 2,520.44 above the 13,962 that + # $15,600 leaves after tax, which needs 2,520.44 / 0.825 = 3,055.08 of + # gross income at 17.5%, so each partner's tax is + # 18,655.08 - 16,482.44 = 2,172.64. expected = { "jobseeker_support": 16_482.44, "jobseeker_support_tax": 2_172.64, "taxable_income": 18_655.08, "income_tax": 2_172.64, } - for name, amount in expected.items(): - values = simulation.calculate(name, period) - assert values == pytest.approx([amount] * 2, abs=STORED), name + _each_partner(_couple(system, grants), expected) + + +@pytest.fixture(scope="module") +def clause_1g_system(): + """A reform that raises only the clause 1(g)(i) rate, to $401 a week.""" + + def modify(parameters): + rates = parameters.gov.msd.jobseeker.payment_rates.rates + rates.couple_one_eligible.update( + start=periods.instant("2026-04-01"), value=401.0 + ) + return parameters + + return _reformed(modify) + + +@pytest.mark.parametrize( + "grants, expected", + [ + ((True, False), (16_482.44, 2_172.64)), + ((True, True), (20_852.00, 3_099.52)), + ], + ids=["one_grant", "both_granted"], +) +def test_two_grants_take_the_clause_1g_rate(clause_1g_system, grants, expected): + # The couple with one grant keeps clause 1(j)(i). Each partner of the + # couple with two gets 52 x 401 = 20,852, which leaves 6,890 above 13,962 + # and needs 6,890 / 0.825 = 8,351.52 of gross income at 17.5%, so each + # partner's tax is 23,951.52 - 20,852 = 3,099.52. + payment, tax = expected + amounts = { + "jobseeker_support": payment, + "jobseeker_support_tax": tax, + "taxable_income": payment + tax, + "income_tax": tax, + } + _each_partner(_couple(clause_1g_system, grants), amounts) def test_a_small_schedule_gives_exact_gross_ups(): @@ -149,6 +211,68 @@ def test_a_small_schedule_gives_exact_gross_ups(): assert grossed_up_tax(net, schedule) == pytest.approx([0, 0, 5, 10, 20]) +def test_a_nan_amount_gives_nan(): + schedule = SimpleNamespace(thresholds=[0, 100], rates=[0.1, 0.5]) + tax = grossed_up_tax(np.array([np.nan, 45.0]), schedule) + assert np.isnan(tax[0]) + assert tax[1] == pytest.approx(5) + + +def test_a_tiny_rate_keeps_its_tax_and_a_large_tax_stays_finite(): + # 1,000 at a rate of 1e-20 owes 1e-17. A net amount of 1e308 at 50% owes + # 1e308, which a 64-bit float holds although the gross amount does not. + tiny = SimpleNamespace(thresholds=[0], rates=[1e-20]) + assert grossed_up_tax(np.array([1_000.0]), tiny)[0] == pytest.approx( + 1e-17, rel=1e-9 + ) + half = SimpleNamespace(thresholds=[0], rates=[0.5]) + assert grossed_up_tax(np.array([1e308]), half)[0] == 1e308 + + +def test_rates_just_below_one_leave_nothing_untaxed_and_nothing_taxed(system): + # The 2025-26 schedule with its top three rates just below 1. Nothing + # after tax owes nothing, and an amount in the first bracket owes + # 10.5 / 89.5 of itself. + schedule = system.parameters("2026-01-01").gov.ird.income_tax.schedule + rates = np.array(schedule.rates, dtype=float) + rates[-3:] = np.nextafter(1.0, 0.0) + steep = SimpleNamespace(thresholds=schedule.thresholds, rates=rates) + tax = grossed_up_tax(np.array([0.0, 1.0, 10_000.0]), steep) + assert tax[0] == 0 + assert tax[1:] == pytest.approx([0.105 / 0.895, 10_000 * 0.105 / 0.895]) + + +def _exact_tax(net, thresholds, rates): + """The gross-up in exact rational arithmetic, for a reference.""" + net = Fraction(net) + t = [Fraction(x) for x in thresholds] + r = [Fraction(x) for x in rates] + bounds = [Fraction(0)] + for k in range(len(t) - 1): + bounds.append(bounds[-1] + (1 - r[k]) * (t[k + 1] - t[k])) + k = max(i for i, bound in enumerate(bounds) if bound <= net) + return float(t[k] + (net - bounds[k]) / (1 - r[k]) - net) + + +def test_a_large_bracket_keeps_its_small_net_width(): + # The middle bracket, at a rate just below 1, leaves 2**-53 of each of its + # 1e17 - 100 dollars, about 11.10 in all, so 61.10 after tax marks the top + # bracket. Subtracting a tax near 1e17 from the threshold would lose those + # 11.10 to rounding. + thresholds = [0.0, 100.0, 1e17] + rates = [0.5, float(np.nextafter(1.0, 0.0)), 0.1] + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + net = [55.0, 62.0, 100.0] + expected = [_exact_tax(n, thresholds, rates) for n in net] + assert grossed_up_tax(np.array(net), schedule) == pytest.approx(expected, rel=1e-12) + + +def test_a_tax_too_large_for_a_float_raises(): + steep = SimpleNamespace(thresholds=[0], rates=[np.nextafter(1.0, 0.0)]) + with pytest.raises(ValueError, match="too large for a 64-bit float"): + grossed_up_tax(np.array([1e300]), steep) + + @pytest.mark.parametrize( "thresholds, rates", [ @@ -187,26 +311,74 @@ def test_a_nan_rate_in_a_real_schedule_raises(system): grossed_up_tax(np.array([13_000.0, 19_000.0]), broken) -@pytest.mark.parametrize("flag", ["receiving_nz_super", "receiving_jobseeker_support"]) -def test_a_recipient_before_april_2022_raises(system, flag): - simulation = _people(system, {"p": {"age": 70, flag: True}}, 2022) +def test_a_nan_rate_set_by_a_reform_raises(): + # The same rate made NaN through Core's Parameter.update. + def modify(parameters): + rate = parameters.gov.ird.income_tax.schedule.brackets[1].rate + rate.update( + start=periods.instant("2024-04-01"), + stop=periods.instant("2025-03-31"), + value=float("nan"), + ) + return parameters + + simulation = _people( + _reformed(modify), {"p": {"age": 30, "jobseeker_support": 13_000}}, 2025 + ) + with pytest.raises(ValueError, match="gross-up needs a schedule"): + simulation.calculate("jobseeker_support_tax", 2025) + + +def test_an_average_rate_schedule_raises(): + # A reform can give the schedule average rates, which Core builds into a + # linear average-rate scale. The gross-up inverts only a marginal-rate one. + def modify(parameters): + node = parameters.gov.ird.income_tax + brackets = [ + {"threshold": {"2000-01-01": t}, "average_rate": {"2000-01-01": r}} + for t, r in ((0, 0.1), (100, 0.3)) + ] + scale = ParameterScale( + "gov.ird.income_tax.schedule", {"brackets": brackets}, None + ) + node.children["schedule"] = scale + node.schedule = scale + return parameters + + simulation = _people( + _reformed(modify), {"p": {"age": 30, "jobseeker_support": 45}}, 2027 + ) + with pytest.raises(TypeError, match="marginal-rate"): + simulation.calculate("jobseeker_support_tax", 2027) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_recipient_before_april_2022_stops_the_calculation(system, flag): + # One recipient stops the calculation for everyone in it. + people = { + "earner": {"age": 40, "employment_income": 50_000}, + "recipient": {"age": 70, flag: True}, + } + simulation = _people(system, people, 2022) with pytest.raises(ValueError, match=r"from 1 April 2022"): simulation.calculate("taxable_income", 2022) -@pytest.mark.parametrize("benefit", ["nz_superannuation", "jobseeker_support"]) -def test_a_benefit_amount_before_april_2022_raises(system, benefit): +@pytest.mark.parametrize("benefit", BENEFITS) +def test_before_april_2022_an_amount_without_a_flag_is_left_out(system, benefit): + # Taxable income for such a period leaves out a benefit amount given + # without a receipt flag, as it did before. people = { "earner": {"age": 40, "employment_income": 50_000}, "benefit": {"age": 30, benefit: 10_000}, } simulation = _people(system, people, 2022) - with pytest.raises(ValueError, match=r"from 1 April 2022"): - simulation.calculate("taxable_income", 2022) + assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000, 0]) + assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) def test_before_april_2022_an_earner_is_taxed_as_before(system): - # No benefit amount is given, so nothing may read the benefit variables, + # No benefit input is given, so nothing may run the benefit formulas, # which raise for a period before their rates start. simulation = _people( system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 @@ -216,7 +388,7 @@ def test_before_april_2022_an_earner_is_taxed_as_before(system): assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020]) -def test_before_april_2022_zero_benefit_amounts_are_accepted(system): +def test_before_april_2022_false_flags_and_zero_amounts_are_accepted(system): people = { "earner": {"age": 40, "employment_income": 50_000}, "zero_benefits": { @@ -233,37 +405,31 @@ def test_before_april_2022_zero_benefit_amounts_are_accepted(system): assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020, 0]) -def _branch_case(system, benefit, default, branch): - """A period-2022 earner with a benefit amount on default, a branch, or both.""" - earner = {"age": 40, "employment_income": 50_000} - if default is not None: - earner[benefit] = default - simulation = _people(system, {"earner": earner}, 2022) - fork = simulation.get_branch("fork") - if branch is not None: - fork.set_input(benefit, "2022", np.array([branch], dtype=float)) - return simulation, fork - - -@pytest.mark.parametrize("benefit", BENEFITS) +@pytest.mark.parametrize("flag", FLAGS) @pytest.mark.parametrize( "default, branch, default_raises, branch_raises", [ - (None, 10_000, False, True), - (10_000, None, True, True), - (0, 10_000, False, True), - (10_000, 0, True, False), + (None, True, False, True), + (True, None, True, True), + (False, True, False, True), + (True, False, True, False), ], - ids=["branch_only", "default_only", "zero_on_default", "zero_on_branch"], + ids=["branch_only", "default_only", "false_on_default", "false_on_branch"], ) -def test_before_april_2022_each_branch_reads_its_own_amount( - system, benefit, default, branch, default_raises, branch_raises +def test_before_april_2022_each_branch_reads_its_own_flag( + system, flag, default, branch, default_raises, branch_raises ): - # A branch inherits the amounts stored when it was made, and its own input - # replaces them. Each read uses a fresh simulation, so neither caches the - # other's result. + # A branch inherits the flags stored when it was made, and its own input + # replaces them. Each read uses a fresh simulation, since Core 3.20 hands + # a branch the results its parent had already calculated. for read_branch, raises in ((False, default_raises), (True, branch_raises)): - simulation, fork = _branch_case(system, benefit, default, branch) + earner = {"age": 40, "employment_income": 50_000} + if default is not None: + earner[flag] = default + simulation = _people(system, {"earner": earner}, 2022) + fork = simulation.get_branch("fork") + if branch is not None: + fork.set_input(flag, "2022", np.array([branch])) target = fork if read_branch else simulation if raises: with pytest.raises(ValueError, match=r"from 1 April 2022"): @@ -273,41 +439,10 @@ def test_before_april_2022_each_branch_reads_its_own_amount( assert target.calculate("income_tax", 2022) == pytest.approx([8_020]) -@pytest.mark.parametrize("benefit", BENEFITS) -def test_before_april_2022_an_amount_for_another_year_is_ignored(system, benefit): - # Core's own lookup fails when a stored year starts in April, as - # year:2025-04 does, so taxable income compares whole periods instead. - simulation = _people( - system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 - ) - simulation.set_input(benefit, "year:2025-04", np.array([10_000.0])) - assert simulation.calculate("taxable_income", 2022) == pytest.approx([50_000]) - assert simulation.calculate("income_tax", 2022) == pytest.approx([8_020]) - - -@pytest.mark.parametrize("benefit", BENEFITS) -def test_before_april_2022_an_amount_stored_on_disk_raises(system, benefit, tmp_path): - # Under a memory limit, Core can store an input on disk instead of in - # memory. Taxable income still finds it. - simulation = _people( - system, {"earner": {"age": 40, "employment_income": 50_000}}, 2022 - ) - holder = simulation.get_holder(benefit) - holder._disk_storage = holder.create_disk_storage(str(tmp_path)) - holder._disk_storage.put(np.array([10_000.0]), as_period("2022")) - assert holder._memory_storage.get(as_period("2022")) is None - with pytest.raises(ValueError, match=r"from 1 April 2022"): - simulation.calculate("taxable_income", 2022) - - -@pytest.mark.parametrize("benefit", BENEFITS) -@pytest.mark.parametrize("on_branch", [False, True], ids=["simulation", "branch"]) -def test_an_amount_for_a_year_from_july_2021_raises(system, benefit, on_branch): - # A year that starts on 1 July 2021 also starts before the benefit rates, - # and an amount stored for exactly that year counts, on the simulation and - # on a branch made from it. +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_july_2021_raises(system, flag): + # A year that starts on 1 July 2021 also starts before the benefit rates. simulation = _people(system, {"person": {"age": 40}}, 2022) - simulation.set_input(benefit, "year:2021-07", np.array([10_000.0])) - target = simulation.get_branch("fork") if on_branch else simulation + simulation.set_input(flag, "year:2021-07", np.array([True])) with pytest.raises(ValueError, match=r"from 1 April 2022"): - target.calculate("taxable_income", "year:2021-07") + simulation.calculate("taxable_income", "year:2021-07") diff --git a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py index 42f1004..0481c39 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/income_tax.py +++ b/policyengine_nz/variables/gov/ird/income_tax/income_tax.py @@ -9,7 +9,7 @@ class income_tax(Variable): definition_period = YEAR label = "Income tax" documentation = ( - "Annual personal income tax at basic rates before credits: the year's " + "Annual personal income tax at basic rates before credits, the year's " "liability on taxable_income. Bare year labels refer to the tax year " "ending on 31 March of that year. Provide the income totals for that " "tax year. For a Jobseeker Support recipient, jobseeker_support_tax is " @@ -17,10 +17,11 @@ class income_tax(Variable): "Inland Revenue on the benefit, as section 350(2) of the Social " "Security Act 2018 allows. income_tax less jobseeker_support_tax is the " "balance after that payment, and it is negative when a loss brings the " - "liability below the payment: in 2026-27, $19,372.60 of Jobseeker " + "liability below the payment. In 2026-27, $19,372.60 of Jobseeker " "Support beside a $40,000 self-employment loss gives $2,785.70 of " "jobseeker_support_tax and no income tax. The schedule starts with the " - "2021-22 tax year (period 2022); earlier periods raise an error." + "2021-22 tax year (period 2022), and an earlier period raises an " + "error." ) reference = [ # Part B, ss BC 4 to BC 6: net income, taxable income and tax liability diff --git a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py index 2d16afa..f04b28a 100644 --- a/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py +++ b/policyengine_nz/variables/gov/ird/income_tax/taxable_income.py @@ -1,7 +1,5 @@ """Taxable income calculation for New Zealand residents.""" -from policyengine_core import periods - from policyengine_nz.model_api import * ACT = "https://www.legislation.govt.nz/act/public/2007/0097/latest/" @@ -15,52 +13,17 @@ def _other_income(person, period): ) -def _given(person, name, period): - """The amount of the variable stored for the period, or None. - - It reads the stored amounts in the order Core's own lookup does, without - running the variable's formula: the amount stored for the simulation's - branch, else the first one stored for the period on another branch, which - a branch inherits from the simulation it was made from, else one stored on - disk. Core's lookup reads each storage key's period by splitting the key at - every colon, which fails when any key holds a year that starts in a month - other than January, such as year:2025-04, so this compares each key's - whole period instead. Core 3.20's lookup also recurses without end on an - amount stored only on disk, which this reads directly. Core ignores an - input to a neutralized variable, so no amount is stored for one. - """ - simulation = person.simulation - holder = simulation.get_holder(name) - key = str(periods.period(period)) - stored = holder._memory_storage._arrays - value = stored.get(f"{simulation.branch_name}:{key}") - if value is None: - value = next( - (array for k, array in stored.items() if k.partition(":")[2] == key), - None, - ) - if value is None and holder._disk_storage is not None: - value = holder._disk_storage.get(period, simulation.branch_name) - return value - - def benefit_recipients(person, period): - """Who receives NZ Superannuation or Jobseeker Support, by flag or amount. + """Who receives NZ Superannuation or Jobseeker Support, by flag. A person counts when receiving_nz_super or receiving_jobseeker_support - marks them as a recipient, or when either benefit has a nonzero amount - stored for them for the period. Reading the stored amounts never runs the - benefits' formulas, which raise for a period that starts before their - rates do on 1 April 2022. + marks them as a recipient. The function reads only the flags, so neither + benefit's formula runs. Both formulas raise for a period that starts + before their rates do on 1 April 2022. """ - recipients = person("receiving_nz_super", period) | person( + return person("receiving_nz_super", period) | person( "receiving_jobseeker_support", period ) - for name in ("nz_superannuation", "jobseeker_support"): - given = _given(person, name, period) - if given is not None: - recipients = recipients | (given != 0) - return recipients class taxable_income(Variable): @@ -70,21 +33,19 @@ class taxable_income(Variable): label = "Taxable income" documentation = ( "Net income from the modelled sources, floored at zero (sections BC 4 " - "and BC 5): employment, self-employment and investment income, NZ " - "Superannuation (section CF 1(1)(e)), and Jobseeker Support " - "(section CF 1(1)(c)) together with the income tax MSD pays on it, " - "jobseeker_support_tax, which section 351(b)(iv) of the Social " - "Security Act 2018 makes the person's income. The model offsets a loss " + "and BC 5). The sources are employment, self-employment and " + "investment income, NZ Superannuation (section CF 1(1)(e)), and " + "Jobseeker Support (section CF 1(1)(c)) together with " + "jobseeker_support_tax, the income tax that the model assumes MSD " + "pays on it, which section 351(b)(iv) of the Social Security Act 2018 " + "makes the person's income. The model offsets a loss " "in one modelled source against the others, and assumes no other " "income, no further deductions and no available tax losses. The " - "benefit rates start on 1 April 2022, and " - "for a period that starts earlier nz_superannuation and " - "jobseeker_support raise an error unless an amount is given. For such " - "a period, taxable income raises an error for a person whom " - "receiving_nz_super or receiving_jobseeker_support marks as a " - "recipient, or who is given a nonzero amount of either benefit for " - "that period on the simulation's branch, or on the simulation it was " - "made from." + "benefit rates start on 1 April 2022, and for a period that starts " + "earlier taxable income leaves out both benefits. It raises an error, " + "for every person in the calculation, when receiving_nz_super or " + "receiving_jobseeker_support marks anyone as a recipient, and leaves " + "out an amount of either benefit given without one of those flags." ) reference = ( ACT + "DLM1512339.html", diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py index 8bbfc53..5bae85b 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support.py @@ -229,11 +229,11 @@ class jobseeker_support(Variable): "52 times the weekly Jobseeker Support MSD pays the person, at the rates in " "force on the period's start date. A bare year N starts on 1 January N and " "stands for the tax year ending on 31 March N, so it reads the rates from 1 " - "April N - 1. The amount is net cash: the model assumes MSD pays the " + "April N - 1. The amount is net cash. The model assumes MSD pays the " "income tax on each instalment to Inland Revenue on top of it, as " - "section 350(2) allows, and that tax " - "counts as the person's income (section 351); jobseeker_support_tax " - "models it. Under regulation 191(2) of " + "section 350(2) allows, and that tax counts as the person's income " + "(section 351). jobseeker_support_tax models that tax. Under " + "regulation 191(2) of " "the Social Security Regulations 2018, MSD pays a " "clause 1(j) couple rate half to the beneficiary and half to the partner: " "in a benefit unit of two partners in one household each gets half, and a " diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py index 14a7c74..7d58041 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -1,5 +1,6 @@ -"""Income tax that MSD pays on Jobseeker Support under section 350.""" +"""Income tax that the model assumes MSD pays on Jobseeker Support.""" +from policyengine_core.taxscales import MarginalRateTaxScale from policyengine_nz.model_api import * SSA = "https://www.legislation.govt.nz/act/public/2018/0032/latest/" @@ -10,10 +11,19 @@ def grossed_up_tax(net, schedule): The schedule's tax rises by each bracket's rate, below 1, so the amount left after tax rises with the gross amount, and each net amount has one gross - amount. The function finds the bracket whose net amounts hold the net - amount, divides the net amount's excess over the bracket's lowest net - amount by one minus the bracket's rate, and adds the bracket's threshold to - give the gross amount. A net amount at or below zero gives no tax. + amount. The function adds up, bracket by bracket, the tax on each full + bracket and the amount it leaves after tax. It finds the bracket whose net + amounts hold the net amount, and adds the tax at the bracket's threshold to + the net amount's excess over the bracket's lowest net amount, times the + bracket's rate over one minus that rate. A net amount at or below zero + gives no tax, and a NaN gives NaN. Each sum adds positive amounts, so the + net amounts at the thresholds rise and stay finite. + + The function reads the schedule's thresholds and rates as arrays of 64-bit + floats, as NumPy converts them, and checks the converted arrays. For a + schedule built from a Core parameter scale, these are the brackets that + Core builds for the instant. It raises a ValueError when the tax on a + finite net amount is too large for a 64-bit float. """ thresholds = np.asarray(schedule.thresholds, dtype=float) rates = np.asarray(schedule.rates, dtype=float) @@ -32,26 +42,36 @@ def grossed_up_tax(net, schedule): "for each, whose first threshold is 0, whose thresholds rise and " "whose rates lie in [0, 1)." ) - tax_at = np.concatenate([[0.0], np.cumsum(rates[:-1] * np.diff(thresholds))]) - net_at = thresholds - tax_at - net = np.maximum(np.asarray(net, dtype=float), 0) - bracket = np.searchsorted(net_at, net, side="right") - 1 - gross = thresholds[bracket] + (net - net_at[bracket]) / (1 - rates[bracket]) - return gross - net + widths = np.diff(thresholds) + tax_at = np.concatenate([[0.0], np.cumsum(rates[:-1] * widths)]) + net_at = np.concatenate([[0.0], np.cumsum((1 - rates[:-1]) * widths)]) + net = np.asarray(net, dtype=float) + positive = net > 0 + amount = np.where(positive, net, 0) + bracket = np.searchsorted(net_at, amount, side="right") - 1 + rate = rates[bracket] + excess = amount - net_at[bracket] + with np.errstate(over="ignore", invalid="ignore"): + above = np.where(rate == 0, 0, excess * (rate / (1 - rate))) + tax = tax_at[bracket] + above + tax = np.where(positive, tax, np.where(np.isnan(net), np.nan, 0)) + if np.any(np.isfinite(net) & ~np.isfinite(tax)): + raise ValueError("The tax on a net amount is too large for a 64-bit float.") + return tax class jobseeker_support_tax(Variable): value_type = float entity = Person definition_period = YEAR - label = "Income tax MSD pays on Jobseeker Support" + label = "Income tax the model assumes MSD pays on Jobseeker Support" documentation = ( - "The income tax MSD pays to Inland Revenue on the person's " - "jobseeker_support instead of deducting it from the payments " - "(Social Security Act 2018, section 350(2)). Section 350(3) grosses each " - "payment up so that what remains after tax equals the payment, and " - "section 351(b)(iv) makes the tax the person's income under the Income " - "Tax Act 2007. The model assumes MSD uses that power. It grosses up the " + "The income tax that the model assumes MSD pays to Inland Revenue on " + "the person's jobseeker_support instead of deducting it from the " + "payments, as section 350(2) of the Social Security Act 2018 allows. " + "Section 350(3) grosses each payment up so that what remains after tax " + "equals the payment, and section 351(b)(iv) makes the tax the person's " + "income under the Income Tax Act 2007. The model grosses up the " "year's jobseeker_support, apart from the person's other income, on the " "personal income tax schedule for the tax year. Section 350(3) uses the " "rate that the Commissioner determines for each payment, in consultation " @@ -59,7 +79,9 @@ class jobseeker_support_tax(Variable): "2007, so the tax on each payment can differ from this annual figure. " "The model grosses up each partner's share of a couple rate " "separately. The benefit rates start on 1 April 2022, and a " - "period that starts earlier gives 0." + "period that starts earlier gives 0. A reform that makes the income " + "tax schedule anything other than a marginal-rate scale raises an " + "error." ) reference = ( SSA + "DLM6783836.html", @@ -72,4 +94,10 @@ class jobseeker_support_tax(Variable): def formula_2022_04_01(person, period, parameters): benefit = person("jobseeker_support", period) schedule = parameters(period).gov.ird.income_tax.schedule + if not isinstance(schedule, MarginalRateTaxScale): + raise TypeError( + "The gross-up inverts a marginal-rate income tax schedule, and " + f"the schedule for period {period} is a " + f"{type(schedule).__name__}." + ) return grossed_up_tax(benefit, schedule) From bb0d13da47b337ec6634011efc75f6ecb2ef2ef9 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 08:50:46 -0500 Subject: [PATCH 4/5] Answer third review of #18 PR A --- .../tests/test_benefit_income_tax.py | 286 +++++++++++++++++- .../msd/jobseeker/jobseeker_support_tax.py | 76 +++-- 2 files changed, 329 insertions(+), 33 deletions(-) diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py index 02fa978..23cef36 100644 --- a/policyengine_nz/tests/test_benefit_income_tax.py +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -9,15 +9,18 @@ 1 April 2022. """ +import math from fractions import Fraction from types import SimpleNamespace import numpy as np import pytest from policyengine_core import periods +from policyengine_core.experimental import MemoryConfig from policyengine_core.parameters import ParameterScale from policyengine_core.reforms import Reform from policyengine_core.simulations import Simulation +from policyengine_core.warnings import MemoryConfigWarning from policyengine_nz import NewZealandTaxBenefitSystem from policyengine_nz.variables.gov.msd.jobseeker.jobseeker_support_tax import ( @@ -242,16 +245,29 @@ def test_rates_just_below_one_leave_nothing_untaxed_and_nothing_taxed(system): assert tax[1:] == pytest.approx([0.105 / 0.895, 10_000 * 0.105 / 0.895]) -def _exact_tax(net, thresholds, rates): - """The gross-up in exact rational arithmetic, for a reference.""" - net = Fraction(net) - t = [Fraction(x) for x in thresholds] - r = [Fraction(x) for x in rates] +def _exact_bounds(thresholds, rates): + """The exact net amounts at the thresholds.""" bounds = [Fraction(0)] - for k in range(len(t) - 1): - bounds.append(bounds[-1] + (1 - r[k]) * (t[k + 1] - t[k])) + for k in range(len(thresholds) - 1): + width = Fraction(thresholds[k + 1]) - Fraction(thresholds[k]) + bounds.append(bounds[-1] + (1 - Fraction(rates[k])) * width) + return bounds + + +def _exact_fraction(net, thresholds, rates): + """The gross-up's tax in exact rational arithmetic, for a reference.""" + net = Fraction(net) + if net <= 0: + return Fraction(0) + bounds = _exact_bounds(thresholds, rates) k = max(i for i, bound in enumerate(bounds) if bound <= net) - return float(t[k] + (net - bounds[k]) / (1 - r[k]) - net) + gross = Fraction(thresholds[k]) + (net - bounds[k]) / (1 - Fraction(rates[k])) + return gross - net + + +def _exact_tax(net, thresholds, rates): + """The gross-up in exact rational arithmetic, as a float.""" + return float(_exact_fraction(net, thresholds, rates)) def test_a_large_bracket_keeps_its_small_net_width(): @@ -267,6 +283,133 @@ def test_a_large_bracket_keeps_its_small_net_width(): assert grossed_up_tax(np.array(net), schedule) == pytest.approx(expected, rel=1e-12) +Q = float(np.nextafter(1.0, 0.0)) +TOP = float(np.finfo(float).max) +# One unit in the last place of the largest float. +TOP_ULP = Fraction(2) ** 971 +SIGNALLING = np.array([0x7F800001], dtype=np.uint32).view(np.float32) + + +def _around(values, steps=2): + """Each value and the floats up to steps away on either side.""" + out = set() + for value in values: + low = high = float(value) + out.add(low) + for _ in range(steps): + low = float(np.nextafter(low, -np.inf)) + high = float(np.nextafter(high, np.inf)) + out.update([low, high]) + return sorted(out) + + +def test_a_rounded_net_boundary_takes_the_exact_bracket(): + # 100 after tax is the exact net amount at the threshold of 100, so it + # owes nothing. The next bracket's 25 dollars leave 25 * 2**-53 after + # tax, which rounds away, so the next float above 100 owes about 25. + tied = SimpleNamespace(thresholds=[0.0, 100.0, 125.0], rates=[0.0, Q, 0.0]) + tax = grossed_up_tax(np.array([100.0, float(np.nextafter(100.0, 200.0))]), tied) + assert tax[0] == 0 + assert tax[1] == pytest.approx(25) + # 10% of 100 leaves an exact net amount 10 * 2**-54 below 90, which + # rounds to 90. So 90 lies above it and owes 10 plus that excess times + # Q / (1 - Q), about 5 more. + close = SimpleNamespace(thresholds=[0.0, 100.0], rates=[0.1, Q]) + assert grossed_up_tax(np.array([90.0]), close)[0] == pytest.approx(15) + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([0.0, 100.0, 125.0], [0.0, Q, 0.0]), + ([0.0, 100.0], [0.1, Q]), + # The third review's six-bracket reform, with three rates just below 1. + ( + [0.0, 12314.1, 12573.35, 66449.16, 78100.0, 180000.0], + [Q, Q, Q, 0.30, 0.33, 0.39], + ), + ], +) +def test_amounts_around_each_net_boundary_owe_the_exact_tax(thresholds, rates): + bounds = [float(bound) for bound in _exact_bounds(thresholds, rates)] + nets = [net for net in _around([0.0, *bounds]) if net >= 0] + tax = grossed_up_tax( + np.array(nets), SimpleNamespace(thresholds=thresholds, rates=rates) + ) + for net, value in zip(nets, tax): + exact = _exact_fraction(net, thresholds, rates) + error = abs(Fraction(float(value)) - exact) + assert error <= 4 * Fraction(math.ulp(float(exact))), (net, value) + + +def test_widths_that_add_past_the_largest_float_give_no_overflow(): + # In 64-bit arithmetic the two widths add up past the largest float. The + # sums run in exact arithmetic, so no amount overflows. + schedule = SimpleNamespace( + thresholds=[0.0, 3 * 2.0**970, TOP], rates=[0.0, 0.0, 0.0] + ) + with np.errstate(all="raise"): + tax = grossed_up_tax(np.array([0.0, 1.0, TOP]), schedule) + assert tax.tolist() == [0, 0, 0] + + +def test_a_first_bracket_one_subnormal_wide_owes_nothing_on_nothing(): + # Half the smallest subnormal float rounds to 0, so the exact net amount + # at the second threshold rounds to the first's. + schedule = SimpleNamespace(thresholds=[0.0, 5e-324, 1.0], rates=[0.5, 0.2, 0.3]) + tax = grossed_up_tax(np.array([-1.0, -0.0, 0.0]), schedule) + assert tax.tolist() == [0, 0, 0] + + +@pytest.mark.parametrize( + "thresholds, rates, net", + [ + ([0.0, 1.0], [0.75, 0.5], TOP), + ([0.0], [0.8125], 4.1485226189130364e307), + ([0.0], [0.54], 1.5313682259938243e308), + ([0.0], [0.53125], 1.586199824878514e308), + ([0.0], [0.9999999999999997], 5.987520928604161e292), + ([0.0, 3.4927205416857597e292, 4.49064069645312e292], [0.5, 0.75, 0.5], TOP), + ([0.0], [0.5625], 1.3982057715595789e308), + ([0.0], [0.999999999999987], 2.3351331621556522e294), + ([0.0, 3.7422005803775996e291], [0.0, 0.75], 5.992310449541053e307), + ([0.0, 5.987520928604159e292], [0.5, 0.5], TOP), + ], +) +def test_a_tax_near_the_largest_float_is_close_or_raises(thresholds, rates, net): + exact = _exact_fraction(net, thresholds, rates) + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + try: + tax = grossed_up_tax(np.array([net]), schedule)[0] + except ValueError: + assert exact >= Fraction(TOP) - 4 * TOP_ULP + else: + assert abs(Fraction(float(tax)) - exact) <= 4 * TOP_ULP + + +@pytest.mark.parametrize( + "thresholds, rates", + [ + ([0.0, -TOP, TOP], [0.0, 0.0, 0.0]), + ([0.0, TOP, -TOP], [0.0, 0.0, 0.0]), + ([0.0], SIGNALLING), + (SIGNALLING, [0.5]), + ], +) +def test_a_bad_schedule_raises_its_own_error_under_strict_numpy(thresholds, rates): + schedule = SimpleNamespace(thresholds=thresholds, rates=rates) + with np.errstate(all="raise"): + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([1.0]), schedule) + + +def test_a_signalling_nan_amount_gives_nan_under_strict_numpy(): + schedule = SimpleNamespace(thresholds=[0.0], rates=[0.5]) + with np.errstate(all="raise"): + assert np.isnan(grossed_up_tax(SIGNALLING, schedule)).all() + assert np.isnan(grossed_up_tax(SIGNALLING[0], schedule)) + + def test_a_tax_too_large_for_a_float_raises(): steep = SimpleNamespace(thresholds=[0], rates=[np.nextafter(1.0, 0.0)]) with pytest.raises(ValueError, match="too large for a 64-bit float"): @@ -420,8 +563,8 @@ def test_before_april_2022_each_branch_reads_its_own_flag( system, flag, default, branch, default_raises, branch_raises ): # A branch inherits the flags stored when it was made, and its own input - # replaces them. Each read uses a fresh simulation, since Core 3.20 hands - # a branch the results its parent had already calculated. + # replaces them. Each read uses a fresh simulation, so neither read sees + # the other's results. for read_branch, raises in ((False, default_raises), (True, branch_raises)): earner = {"age": 40, "employment_income": 50_000} if default is not None: @@ -446,3 +589,126 @@ def test_a_flag_for_a_year_from_july_2021_raises(system, flag): simulation.set_input(flag, "year:2021-07", np.array([True])) with pytest.raises(ValueError, match=r"from 1 April 2022"): simulation.calculate("taxable_income", "year:2021-07") + + +# Core 3.38.0 reads a year that starts in April, keeps a value on disk under a +# memory limit, and drops a branch's results calculated from an input that +# the branch replaces. Taxable income reads both benefits and both receipt +# flags through each. + +# On $60,000 in 2025-26, tax is 1,638 + 6,632.50 + 1,950 = $10,220.50. The +# Jobseeker Support gross-up adds 10,000 * 0.105 / 0.895 = $1,173.18, taxed +# at 30%. +WITH_BENEFIT = { + "nz_superannuation": (60_000, 10_220.5), + "jobseeker_support": (61_173.18, 10_572.45), +} + + +def _earner(system, inputs): + """One earner aged 40 with inputs as {variable: {period: value}}.""" + person = {"age": {"2022": 40}, **inputs} + situation = { + "people": {"earner": person}, + "households": {"household": {"members": ["earner"]}}, + } + return Simulation(tax_benefit_system=system, situation=situation) + + +def _on_disk(simulation): + """Keep every input but age on disk from now on.""" + with pytest.warns(MemoryConfigWarning): + simulation.memory_config = MemoryConfig(0.0, priority_variables=["age"]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_for_a_year_from_april_leaves_other_years_working(system, benefit): + wages = {"2023": 50_000, "2027": 50_000} + simulation = _earner(system, {"employment_income": wages}) + simulation.set_input(benefit, "year:2025-04", np.array([10_000])) + assert simulation.calculate("taxable_income", "2023") == pytest.approx([50_000]) + assert simulation.calculate("income_tax", "2023") == pytest.approx([8_020]) + assert simulation.calculate("income_tax", "2027") == pytest.approx([7_658]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_for_a_year_from_april_counts_in_that_year(system, benefit): + year = "year:2025-04" + inputs = {"employment_income": {year: 50_000}, benefit: {year: 10_000}} + simulation = _earner(system, inputs) + taxable, tax = WITH_BENEFIT[benefit] + assert simulation.calculate("taxable_income", year) == pytest.approx( + [taxable], abs=STORED + ) + assert simulation.calculate("income_tax", year) == pytest.approx([tax], abs=STORED) + + +@pytest.mark.parametrize("value", [True, False]) +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_april_leaves_2022_working(system, flag, value): + simulation = _earner(system, {"employment_income": {"2022": 50_000}}) + simulation.set_input(flag, "year:2025-04", np.array([value])) + assert simulation.calculate("taxable_income", "2022") == pytest.approx([50_000]) + assert simulation.calculate("income_tax", "2022") == pytest.approx([8_020]) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_for_a_year_from_april_2021_counts_in_that_year(system, flag): + year = "year:2021-04" + for value in (False, True): + inputs = {"employment_income": {year: 50_000}, flag: {year: value}} + simulation = _earner(system, inputs) + if value: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", year) + else: + assert simulation.calculate("income_tax", year) == pytest.approx([8_020]) + + +@pytest.mark.parametrize("flag", FLAGS) +def test_a_flag_kept_on_disk_is_read(system, flag): + for value in (False, True): + simulation = _earner(system, {}) + _on_disk(simulation) + simulation.set_input("employment_income", "2022", np.array([50_000])) + simulation.set_input(flag, "2022", np.array([value])) + holder, year = simulation.get_holder(flag), periods.period("2022") + assert holder._memory_storage.get(year) is None + assert holder._disk_storage.get(year).tolist() == [value] + if value: + with pytest.raises(ValueError, match=r"from 1 April 2022"): + simulation.calculate("taxable_income", "2022") + else: + assert simulation.calculate("income_tax", "2022") == pytest.approx([8_020]) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_benefit_kept_on_disk_is_taxed(system, benefit): + simulation = _earner(system, {}) + _on_disk(simulation) + simulation.set_input("employment_income", "2026", np.array([50_000])) + simulation.set_input(benefit, "2026", np.array([10_000])) + holder, year = simulation.get_holder(benefit), periods.period("2026") + assert holder._memory_storage.get(year) is None + assert holder._disk_storage.get(year).tolist() == [10_000] + taxable, tax = WITH_BENEFIT[benefit] + assert simulation.calculate("taxable_income", "2026") == pytest.approx( + [taxable], abs=STORED + ) + assert simulation.calculate("income_tax", "2026") == pytest.approx( + [tax], abs=STORED + ) + + +@pytest.mark.parametrize("benefit", BENEFITS) +def test_a_branch_made_after_a_calculation_taxes_its_own_benefit(system, benefit): + parent = _earner(system, {"employment_income": {"2026": 50_000}}) + assert parent.calculate("income_tax", "2026") == pytest.approx([7_658]) + branch = parent.get_branch("benefit") + branch.set_input(benefit, "2026", np.array([10_000])) + taxable, tax = WITH_BENEFIT[benefit] + assert branch.calculate("taxable_income", "2026") == pytest.approx( + [taxable], abs=STORED + ) + assert branch.calculate("income_tax", "2026") == pytest.approx([tax], abs=STORED) + assert parent.calculate("income_tax", "2026") == pytest.approx([7_658]) diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py index 7d58041..3e37c00 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -1,39 +1,58 @@ """Income tax that the model assumes MSD pays on Jobseeker Support.""" +from fractions import Fraction + from policyengine_core.taxscales import MarginalRateTaxScale from policyengine_nz.model_api import * SSA = "https://www.legislation.govt.nz/act/public/2018/0032/latest/" +def _exact_parts(values): + """Each Fraction as its nearest float, the rest as a float and its sign.""" + near = np.array([float(value) for value in values]) + rests = [value - Fraction(x) for value, x in zip(values, near)] + rest = np.array([float(r) for r in rests]) + sign = np.array([(r > 0) - (r < 0) for r in rests]) + return near, rest, sign + + def grossed_up_tax(net, schedule): """Tax on the gross amount that the schedule's tax reduces to net. The schedule's tax rises by each bracket's rate, below 1, so the amount left after tax rises with the gross amount, and each net amount has one gross - amount. The function adds up, bracket by bracket, the tax on each full - bracket and the amount it leaves after tax. It finds the bracket whose net - amounts hold the net amount, and adds the tax at the bracket's threshold to - the net amount's excess over the bracket's lowest net amount, times the - bracket's rate over one minus that rate. A net amount at or below zero - gives no tax, and a NaN gives NaN. Each sum adds positive amounts, so the - net amounts at the thresholds rise and stay finite. + amount. The function adds up, in exact rational arithmetic, the tax on each + full bracket and the amount it leaves after tax. It finds the bracket whose + net amounts hold the net amount, comparing exactly, and adds the tax at the + bracket's threshold to the net amount's excess over the bracket's lowest net + amount, times the bracket's rate over one minus that rate. A net amount at + or below zero gives no tax, and a NaN gives NaN. The function reads the schedule's thresholds and rates as arrays of 64-bit floats, as NumPy converts them, and checks the converted arrays. For a schedule built from a Core parameter scale, these are the brackets that - Core builds for the instant. It raises a ValueError when the tax on a - finite net amount is too large for a 64-bit float. + Core builds for the instant. For a finite net amount, the result lies + within four units in the last place of the exact tax on those converted + values, or within 1e-300 of it, where a subnormal float loses precision. + The function raises a ValueError when the exact tax exceeds the largest + 64-bit float by more than four units in the last place, and it may raise + one when the exact tax lies within four such units of the largest float. + It raises no FloatingPointError under any NumPy error setting. """ - thresholds = np.asarray(schedule.thresholds, dtype=float) - rates = np.asarray(schedule.rates, dtype=float) + # Converting a signalling NaN signals an invalid operation and gives a + # quiet NaN, which the checks below handle. + with np.errstate(invalid="ignore"): + thresholds = np.asarray(schedule.thresholds, dtype=float) + rates = np.asarray(schedule.rates, dtype=float) + net = np.asarray(net, dtype=float) valid = ( thresholds.ndim == 1 and rates.shape == thresholds.shape and len(thresholds) > 0 and np.all(np.isfinite(thresholds)) and thresholds[0] == 0 - and np.all(np.diff(thresholds) > 0) + and np.all(thresholds[1:] > thresholds[:-1]) and np.all((rates >= 0) & (rates < 1)) ) if not valid: @@ -42,19 +61,30 @@ def grossed_up_tax(net, schedule): "for each, whose first threshold is 0, whose thresholds rise and " "whose rates lie in [0, 1)." ) - widths = np.diff(thresholds) - tax_at = np.concatenate([[0.0], np.cumsum(rates[:-1] * widths)]) - net_at = np.concatenate([[0.0], np.cumsum((1 - rates[:-1]) * widths)]) - net = np.asarray(net, dtype=float) - positive = net > 0 - amount = np.where(positive, net, 0) - bracket = np.searchsorted(net_at, amount, side="right") - 1 + net_at, tax_at = [Fraction(0)], [Fraction(0)] + for low, high, rate in zip(thresholds[:-1], thresholds[1:], rates[:-1]): + width = Fraction(high) - Fraction(low) + net_at.append(net_at[-1] + (1 - Fraction(rate)) * width) + tax_at.append(tax_at[-1] + Fraction(rate) * width) + net_near, net_rest, net_sign = _exact_parts(net_at) + tax_near = np.array([float(value) for value in tax_at]) + # A net amount at or below zero, or a NaN, becomes 0, which takes the + # first bracket with no excess and so gives no tax. + amount = np.where(net > 0, net, 0.0) + # The exact net amounts at the thresholds rise, so their nearest floats + # never fall, and among those that round to one float, the signs of their + # rests never fall. The bracket starts at the last threshold whose exact + # net amount is at most the amount. + below = np.searchsorted(net_near, amount, side="left") + tied = np.searchsorted(net_near, amount, side="right") + at_most = np.concatenate([[0], np.cumsum(net_sign <= 0)]) + bracket = below + at_most[tied] - at_most[below] - 1 rate = rates[bracket] - excess = amount - net_at[bracket] - with np.errstate(over="ignore", invalid="ignore"): + with np.errstate(over="ignore", invalid="ignore", under="ignore"): + excess = (amount - net_near[bracket]) - net_rest[bracket] above = np.where(rate == 0, 0, excess * (rate / (1 - rate))) - tax = tax_at[bracket] + above - tax = np.where(positive, tax, np.where(np.isnan(net), np.nan, 0)) + tax = tax_near[bracket] + above + tax = np.where(np.isnan(net), np.nan, tax) if np.any(np.isfinite(net) & ~np.isfinite(tax)): raise ValueError("The tax on a net amount is too large for a 64-bit float.") return tax From ef3a5ea03f494e556ad278fa64a90461f93bfd9d Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 3 Dec 2026 09:19:34 -0500 Subject: [PATCH 5/5] Ignore overflow and underflow when casting gross-up inputs --- .../tests/test_benefit_income_tax.py | 49 +++++++++++++++++++ .../msd/jobseeker/jobseeker_support_tax.py | 6 +-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/policyengine_nz/tests/test_benefit_income_tax.py b/policyengine_nz/tests/test_benefit_income_tax.py index 23cef36..f41c381 100644 --- a/policyengine_nz/tests/test_benefit_income_tax.py +++ b/policyengine_nz/tests/test_benefit_income_tax.py @@ -712,3 +712,52 @@ def test_a_branch_made_after_a_calculation_taxes_its_own_benefit(system, benefit ) assert branch.calculate("income_tax", "2026") == pytest.approx([tax], abs=STORED) assert parent.calculate("income_tax", "2026") == pytest.approx([7_658]) + + +_HAS_WIDER_LONGDOUBLE = np.finfo(np.longdouble).max > np.finfo(float).max + + +@pytest.mark.skipif( + not _HAS_WIDER_LONGDOUBLE, + reason="requires a longdouble wider than 64-bit float", +) +def test_wider_floating_inputs_match_quiet_mode_under_strict_numpy(): + basic = SimpleNamespace(thresholds=[0.0], rates=[0.5]) + underflow_rate = SimpleNamespace( + thresholds=[0.0], rates=np.array([np.longdouble("1e-400")]) + ) + with np.errstate(all="raise"): + assert grossed_up_tax(np.array([100.0]), underflow_rate).tolist() == [0.0] + assert grossed_up_tax(np.array([np.longdouble("1e-400")]), basic).tolist() == [ + 0.0 + ] + assert grossed_up_tax(np.array([np.longdouble("-1e-400")]), basic).tolist() == [ + 0.0 + ] + assert grossed_up_tax(np.array([np.longdouble("-1e400")]), basic).tolist() == [ + 0.0 + ] + overflow_net = grossed_up_tax(np.array([np.longdouble("1e400")]), basic) + with np.errstate(all="ignore"): + quiet_overflow_net = grossed_up_tax(np.array([np.longdouble("1e400")]), basic) + assert np.array_equal(overflow_net, quiet_overflow_net) + + for bad_schedule in ( + SimpleNamespace(thresholds=[0.0], rates=np.array([np.longdouble("1e400")])), + SimpleNamespace( + thresholds=np.array([np.longdouble("0"), np.longdouble("1e400")]), + rates=[0.5, 0.5], + ), + SimpleNamespace( + thresholds=np.array([np.longdouble("0"), np.longdouble("1e-400")]), + rates=[0.5, 0.2], + ), + ): + with np.errstate(all="raise"): + with pytest.raises(ValueError, match="gross-up needs a schedule"): + grossed_up_tax(np.array([100.0]), bad_schedule) + + +def test_a_subnormal_tied_boundary_with_strict_rounding_owes_nothing_on_zero(): + schedule = SimpleNamespace(thresholds=[0.0, 5e-324], rates=[0.75, Q]) + assert grossed_up_tax(np.array([0.0]), schedule).tolist() == [0.0] diff --git a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py index 3e37c00..18ddedf 100644 --- a/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py +++ b/policyengine_nz/variables/gov/msd/jobseeker/jobseeker_support_tax.py @@ -40,9 +40,9 @@ def grossed_up_tax(net, schedule): one when the exact tax lies within four such units of the largest float. It raises no FloatingPointError under any NumPy error setting. """ - # Converting a signalling NaN signals an invalid operation and gives a - # quiet NaN, which the checks below handle. - with np.errstate(invalid="ignore"): + # Converting a signalling NaN or wide floating dtype (e.g., longdouble) + # can raise invalid, overflow, or underflow before the checks below run. + with np.errstate(over="ignore", under="ignore", invalid="ignore"): thresholds = np.asarray(schedule.thresholds, dtype=float) rates = np.asarray(schedule.rates, dtype=float) net = np.asarray(net, dtype=float)