Skip to content

Make the Working for Families helpers exact on unusual inputs - #31

Merged
MaxGhenis merged 5 commits into
mainfrom
wff-helper-edge-cases
Dec 1, 2026
Merged

MaxGhenis merged 5 commits into
mainfrom
wff-helper-edge-cases

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Agent-written for Max, by Claude Code for Max Ghenis.

Fixes #27.

What this fixes

The helper items in #27. #27's comment also asked that the checks on a reform's amounts accept the 32-bit float nearest a cent and reject the next one; the 16-bit float nearest a cent follows the same path and now passes too. A reform reaches these values when it sets a parameter row's value directly, since Core 3.20.0's Parameter.update rejects a 32-bit value. #27 found that none of its helper items changes a result the formulas produce today, and the model grid below agrees. #27's test items landed in #30.

#27's last helper item, the OverflowError in _dollars_over, no longer occurs on main, and #30 added the test that pins it.

Changes

In policyengine_nz/working_for_families.py:

  • cents_by_family adds integer and boolean cents as 64-bit integers when their absolute sum stays below 2**62, after it widens them to 64-bit floats to bound that sum. Every other array, Decimals included, takes an exact path that splits each value into a finite Python integer, an infinity or NaN, adds the finite parts, and gives NaN where a family has NaN or both infinities. On main, one family's −2**63 and −1 sum to 2**63 − 1, unsigned 2**53 + 1 and 1 sum to 2**53, and an object-held 10**350 beside an infinity raises OverflowError.
  • add_cents follows the same rule: integer and boolean arrays add as 64-bit integers when no sum can reach 2**63, and as Python integers otherwise. Zero-dimensional arrays give a zero-dimensional array on both paths. On main, 8-bit 127 and 1 sum to −128, a signed −1 and an unsigned 2**53 + 3 sum to the 64-bit float 2**53 + 4, and 8-bit 127 and True sum to −128.
  • stored holds each numerator exactly, as a Python integer, float or Fraction, and the denominator as a Fraction. It divides in 64 bits only when every numerator is a built-in float or a built-in integer below 2**53 and a 64-bit float holds the denominator exactly, so the one division rounds once. That division ignores NumPy's floating-point error settings, since an underflow or overflow in it rounds correctly. An integer over a whole denominator divides as Python integers, as on main, which also round the exact quotient once. Every other numerator divides exactly through Fraction. Where a 64-bit quotient lies halfway between two 32-bit floats, or equals the 32-bit overflow midpoint, the exact quotient settles the rounding. A sequence that is not an array keeps its integers, a matrix divides like an array, zeros and infinities take the sign that the division gives them, and NaN stays NaN with its sign and the payload bits that a 32-bit float holds; like any conversion to 32 bits, the result drops the rest of the payload. On main, an infinity over −100 stays positive, stored([2**54 + 2**30 + 1, inf], 1) raises TypeError, and a float16 [1] divided by 3 gives 0.333251953125, the float16 quotient, where the nearest 32-bit float is 0.3333333432674408.
  • _python_number, which every helper uses, turns NumPy booleans and integers into Python ones, a NumPy float into the float it holds, and a subclass of float, or of int other than bool, into the built-in number it holds, so a subclass divides as that number whatever its own __float__, __truediv__ or as_integer_ratio gives. A NumPy float wider than 64 bits that no 64-bit float holds, and a finite Decimal, become the exact int or Fraction they hold; a Decimal zero, infinity or NaN, a signalling NaN included, becomes that float with its sign. A built-in float or integer returns at once.
  • The helpers accept arrays of booleans, integers, floats and objects only, alone or inside any sequence or array-like value that NumPy reads, and check an array subclass as the plain array it holds. Text, bytes and mappings count as single values, as they do for NumPy. The cent sums keep an array held in a slot of an object array as one value, which no helper accepts as a number, and _python_number rejects an object-held NumPy duration. On main, add_cents adds nanosecond dates and durations as integers, stored divides durations, and finite_parts passes dates, durations and text through.
  • finite_parts turns a sequence into an object array, reads NumPy booleans, integers and floats as the Python numbers they hold, keeps a finite count's exact value, and returns all three outputs in the input's shape. On main, an object-held float32 infinity or NaN sets neither mask, a (1, 5) input gives (1,) masks, and a count of 2.5 gives 0 and counts as infinite.
  • whole takes the value's type and rounds the nearest whole number of steps to that NumPy float type before it compares, and _checked passes the type. It compares an integer exactly and holds the step exactly, so a step of 1.0 works as 1 does; on main, whose whole takes no type, whole(2**53 + 1, 1) is false. Its docstring names the steps it supports, CENT and 1, the steps the formulas use.
  • A new exact_counts checks the daily counts of children that credit_sums and best_start_sums add, and returns them for the sums to use. Counts need a day axis and must be whole numbers. When the largest count times the number of days reaches 2**53, it sums each row's absolute counts exactly and raises a ValueError if a row reaches 2**53, giving a sum too large to print as a power of 2. It keeps 32- and 64-bit signed counts and converts every other type to 64-bit integers, so unsigned and float counts give the same sums as signed ones. Core's counts are 32-bit integers far below the bound.

policyengine_nz/tests/test_working_for_families_helpers.py holds the new tests, and changelog.d/wff-helper-edge-cases.fixed.md the changelog fragment.

Inputs that now raise an error

This version raises a ValueError that names the problem for each of these:

  • a denominator of zero, infinity or NaN in stored (main gives [inf], [0.0] and [nan] for a numerator of 1), and a numerator or denominator that is not a number (main raises TypeError);
  • cents that are not whole numbers in add_cents or cents_by_family (main's cents_by_family turns 1.5 cents into 1);
  • daily counts of children that are not whole numbers, or whose sizes in a row sum to 2**53 or more;
  • an array of dates, durations or text, alone or inside a sequence or array-like value, an array held in a slot of an object array, or an object-held duration, in any helper, and a value that is not a number in finite_parts (main's results for arrays of dates, durations and text are in the bullet on accepted arrays above).

Tests

The new file has 58 tests, 169 with their parametrized cases. One runs only where NumPy's long double is wider than 64 bits, as on CI's Linux runners, and skips on this Mac. An x86-64 interpreter whose long double has 80 bits runs it along with every other test that needs no Core simulation, 167 in all, and all pass there. On main at d8ee910, with a stub exact_counts that returns its input so the file imports, 126 fail. The other 42 pin results main already gives: the sequence and array cases that agree on main, main's results for other denominators, the −0.0 numerator, the matrix, the overflow midpoint, the boundary denominators and the separate cent operands and families that the second review's mutations broke, the error for the next 32-bit float above a cent and for a 32-bit month value that is not whole, a sparse row of counts, which the stub accepts, the NaN bits that main's _quotient keeps, a positive integer quotient just below the overflow midpoint, an int subclass's quotient, the sign and the payload bits that main's stored keeps for a NaN, in 16 cases, and the check that the tests' own reference rounding raises no floating-point error.

I made 104 changes to working_for_families.py, one at a time, and ran the new file after each on this Mac; the one that needs a long double wider than 64 bits also ran on the x86-64 interpreter. They include my versions of the changes the reviews tried. One hundred fail at least one new test, as the table shows; one of them, rounding a NumPy float wider than 64 bits first, fails only on the x86-64 interpreter, since this Mac's long double has 64 bits. The other four change nothing a test can see. Sending boolean cents in cents_by_family to the exact path gives the same exact sums. Rounding to infinity only above the overflow midpoint, on the integer or the Fraction path, still gives infinity at the midpoint itself, where the 32-bit rounding gives infinity and the tie repair keeps it. The 64-bit path's own type check now sees no subclass other than bool, since _python_number has already turned each other subclass into the built-in number it holds, and a bool divides the same on either path.

The 104 changes and a new test each fails
Change A new test that fails
Keep an array subclass as it is test_a_matrix_divides_like_an_array
Convert a sequence with np.asarray test_a_sequence_keeps_an_integer_above_2_to_the_53
Add integer cents in their own type in cents_by_family test_unsigned_and_float_cents_sum_exactly_beside_an_empty_family
Send boolean cents in cents_by_family to the exact path none: both paths give the same exact sums
Keep a whole float cent as a float on the exact path test_unsigned_and_float_cents_sum_exactly_beside_an_empty_family
Accept a float cent that is not whole test_cents_must_be_whole_numbers[float]
Accept any fraction as cents test_decimals_are_held_exactly
Accept cents that are not numbers test_decimals_are_held_exactly
Leave a family with both infinities infinite test_a_zero_dimensional_sum_is_an_array
Set NaN before the infinities test_a_zero_dimensional_sum_is_an_array
Send boolean arrays in add_cents to the exact path test_booleans_add_as_integers
Leave the first array uncast in add_cents test_narrow_and_mixed_sign_integers_add_exactly
Keep only the first array's infinities and NaN in add_cents test_a_zero_dimensional_sum_is_an_array
Accept a zero denominator test_a_denominator_must_be_a_finite_number_other_than_zero
Accept an infinite or NaN denominator test_a_denominator_must_be_a_finite_number_other_than_zero
Accept a numerator that is not a number test_a_numerator_must_be_a_number
Divide by the 64-bit float nearest a denominator that no 64-bit float holds test_a_finite_float_numerator_divides_exactly
Keep the sign of a float zero or infinity over a negative denominator test_zeros_and_infinities_take_the_sign_of_the_quotient
Give +0.0 for an integer zero over a negative denominator test_zeros_and_infinities_take_the_sign_of_the_quotient
Divide in floats instead of Fractions in _quotient test_a_finite_float_numerator_divides_exactly
Round to infinity only above the 32-bit overflow midpoint none: at the midpoint itself the 32-bit rounding gives infinity, and the tie repair keeps it
Leave NumPy booleans unconverted in _python_number test_booleans_add_as_integers
Convert finite_parts' sequence with np.asarray test_dates_and_durations_are_not_numbers[dates]
Raise whenever the fast count bound trips test_only_a_rows_own_counts_add_together
Add all rows' counts together test_only_a_rows_own_counts_add_together
Accept a float count that is not whole test_counts_must_be_whole_numbers[2.5]
Return every count array in its own type test_core_counts_stay_as_they_are_and_others_become_64_bit
Keep signed counts within 3 of their type's minimum test_core_counts_stay_as_they_are_and_others_become_64_bit
Accept counts with no day axis test_counts_keep_their_shape_and_need_a_day_axis
Check credit_sums' counts but sum the originals test_unsigned_counts_give_the_signed_results
Check best_start_sums' counts but sum the originals test_whole_float_counts_sum_exactly
Skip the whole-number check for counts test_counts_must_sum_below_2_to_the_53
Bound cents_by_family's sum before widening test_the_smallest_int64_sums_exactly_beside_an_empty_family
Convert stored's sequence with np.asarray test_a_sequence_keeps_an_integer_above_2_to_the_53
Build the tie's exact value as Fraction(value, denominator) test_a_float_numerator_halfway_between_32_bit_floats_rounds_to_even
Leave NumPy floats unconverted in _python_number test_finite_parts_keeps_the_shape_and_reads_numpy_floats
Read only the top level of finite_parts' input test_finite_parts_keeps_the_shape_and_reads_numpy_floats
Give 0 for every float count in finite_parts test_finite_parts_keeps_a_finite_float_count
Drop the rounding to the value's type in whole test_the_32_bit_float_nearest_a_cent_pays_one_cent
Call whole without the value's type in _checked test_the_32_bit_float_nearest_a_cent_pays_one_cent
Check and use only the Family Tax Credit counts in credit_sums test_each_sum_of_children_checks_both_counts[1-_credit_sums]
Check and use only the In-Work Tax Credit counts in credit_sums test_each_sum_of_children_checks_both_counts[0-_credit_sums]
Check and use only the exempt counts in best_start_sums test_each_sum_of_children_checks_both_counts[1-_best_start_sums]
Check and use only the abatable counts in best_start_sums test_each_sum_of_children_checks_both_counts[0-_best_start_sums]
Check rows exactly only above 2**53 test_counts_must_sum_below_2_to_the_53
Raise only above 2**53 test_counts_must_sum_below_2_to_the_53
Leave the number of days out of the count bound test_counts_must_sum_below_2_to_the_53
Drop the downward tie repair test_a_quotient_just_below_a_32_bit_midpoint_rounds_down
Leave NumPy integers unconverted in _python_number test_dates_and_durations_are_not_numbers[held durations]
Bound counts by their largest value alone, not their largest size test_counts_must_sum_below_2_to_the_53
Bound an empty array of counts test_counts_keep_their_shape_and_need_a_day_axis
Take the number of days from the second axis test_counts_must_sum_below_2_to_the_53
Check a narrow float against a cent whatever the step test_a_32_bit_value_with_a_step_of_1_must_be_whole
Read the smallest of an empty array of counts test_counts_keep_their_shape_and_need_a_day_axis
Give an overflowing integer quotient the numerator's sign test_integers_near_the_32_bit_overflow_midpoint_take_the_quotients_sign
Round an integer quotient to infinity only above the overflow midpoint none: at the midpoint itself the 32-bit rounding gives infinity, and the tie repair keeps it
Divide an integer by the numerator of any denominator test_a_value_that_is_not_a_64_bit_float_divides_exactly
Divide integers of any size in 64 bits test_a_value_that_is_not_a_64_bit_float_divides_exactly
Divide integers below 2**54 in 64 bits test_more_exact_denominators_and_boundaries
Divide fractions below 2**53 in 64 bits test_a_value_that_is_not_a_64_bit_float_divides_exactly
Divide in 64 bits under the caller's floating-point error settings test_a_quotient_that_underflows_or_overflows_raises_no_floating_point_error
Skip the tie repair at the overflow midpoint test_integers_near_the_32_bit_overflow_midpoint_take_the_quotients_sign
Repair only a positive quotient at the overflow midpoint test_integers_near_the_32_bit_overflow_midpoint_take_the_quotients_sign
Read an object-held NumPy duration as an integer test_dates_and_durations_are_not_numbers[held durations]
Round a NumPy float wider than 64 bits to the nearest 64-bit float test_a_wider_float_is_held_exactly on the x86-64 interpreter
Hold a NumPy NaN as a ratio test_finite_parts_keeps_the_shape_and_reads_numpy_floats
Drop the Decimal NaN check test_a_decimal_nan_keeps_its_sign[NaN-100-64-bit]
Hold a Decimal zero as the integer 0, losing its sign test_decimals_are_held_exactly
Round a finite Decimal to the nearest 64-bit float test_counts_must_sum_below_2_to_the_53
Leave Decimals unconverted test_counts_must_sum_below_2_to_the_53
Accept an array of any kind test_dates_and_durations_are_not_numbers[dates]
Accept an array of any kind in the cent sums, stored and finite_parts test_dates_and_durations_are_not_numbers[dates]
Accept an array of any kind in exact_counts test_rows_of_text_are_not_counts[text]
Copy the exact sum instead of making it an array test_a_zero_dimensional_sum_is_an_array
Accept values that are not numbers in finite_parts test_dates_and_durations_are_not_numbers[held dates]
Compare an integer in whole through a 64-bit float test_an_integer_is_whole_exactly
Return a zero-dimensional integer sum as a NumPy number test_a_zero_dimensional_sum_is_an_array
Negate NaN over a negative denominator test_zeros_and_infinities_take_the_sign_of_the_quotient
Reject a Fraction denominator test_zeros_and_infinities_take_the_sign_of_the_quotient
Skip the tie repair where the nearest 32-bit float is zero test_more_exact_denominators_and_boundaries
Convert a denominator too large for a 64-bit float without catching the overflow test_more_exact_denominators_and_boundaries
Add integer cents in 64 bits whatever their size test_cents_keep_each_operand_and_family_apart
Add the finite parts in place in add_cents test_cents_keep_each_operand_and_family_apart
Drop the first array's NaN in add_cents test_cents_keep_each_operand_and_family_apart
Combine add_cents' masks with exclusive or test_cents_keep_each_operand_and_family_apart
Apply one family's infinities and NaN to every family test_cents_keep_each_operand_and_family_apart
Widen int32 counts that lie exactly 3 above the type's minimum test_core_counts_stay_as_they_are_and_others_become_64_bit
Divide a subclass of float or int in 64 bits through its own __float__ none: _python_number has already turned every subclass but bool into the built-in number it holds, and a bool divides the same on either path
Skip the check of arrays inside a sequence in the cent sums, stored and finite_parts test_dates_and_durations_inside_a_sequence_are_not_numbers
Skip the check of arrays inside a sequence in exact_counts test_dates_and_durations_inside_a_sequence_are_not_numbers
Divide by a step of 1.0 in whole without holding it exactly test_an_integer_is_whole_exactly
Test the Fraction path's quotient against the overflow midpoint in 64 bits test_the_exact_paths_keep_a_quotient_below_the_midpoint_finite
Test the integer path's quotient against the overflow midpoint in 64 bits test_integers_near_the_32_bit_overflow_midpoint_take_the_quotients_sign
Return a new NaN for a NaN on the exact path test_the_exact_quotient_keeps_a_nans_bits
Print a row's sum of counts in full in exact_counts' error test_counts_must_sum_below_2_to_the_53
Leave a float subclass unconverted in _python_number test_a_subclass_with_its_own_arithmetic_divides_as_the_number_it_holds
Leave an int subclass unconverted in _python_number test_a_subclass_with_its_own_arithmetic_divides_as_the_number_it_holds
Check only lists and tuples for arrays inside a sequence test_dates_and_durations_inside_a_sequence_are_not_numbers
Check an array subclass by its own dtype test_an_array_subclass_is_checked_as_the_array_it_holds
Skip the check of values with __array__ or an array interface test_dates_and_durations_inside_a_sequence_are_not_numbers
Rebuild the cent sums' object slots with np.array test_an_array_held_in_one_slot_is_not_a_number
Drop a Decimal NaN's sign test_a_decimal_nan_keeps_its_sign[-NaN-100-64-bit]
Read text, bytes and mappings item by item in the nested check test_a_numerator_must_be_a_number
Turn True and False into 1 and 0 in _python_number test_finite_parts_gives_python_numbers

Other checks, each run at this version merged with main at d8ee910:

  • The whole suite passes: 1,793 tests, with the long-double test skipped.
  • A battery of 886 cases of stored, add_cents, cents_by_family, finite_parts and the two sums of children, across numerator types, Decimals, dates, durations and text, zero-dimensional arrays, exponent extremes, the overflow midpoint with both signs, integer, float, Fraction and Decimal denominators, many kinds of cents, and sequence, object and array inputs, gives the same output as an exact reference, built from Fractions and Python integers, in all 886, with NumPy set to raise on any floating-point error in both. The reference guards its own 32-bit conversions against those errors; before it did, 12 of its own conversions raised, as the third review found, and it matched 874. It gives the same output with those errors ignored, and every error it raises is one of the ValueErrors listed above. For the two sums of children, the reference converts the counts to int64 and calls this version's own sums, so that part checks that other count types give the int64 results. Main differs from this version in 555 cases: main returns a value other than the exact one in 290, raises where this version returns the exact value in 92, raises a different error in 28, and returns a value where this version raises one of the errors listed above in 145.
  • whole agrees with an exact nearest-value check, built from Fractions, at steps of a cent and 1, on 387,488 checks: each step with every finite non-negative float16, and with 162,000 float32 values.
  • An independent per-day reference, built from dates, Fractions and Core's 32-bit storage, gives the same stored credits, abatement and net credits as the model for 18,823 random families across nine reform schedules. Every family keeps its results beside an extreme family and with the families and their members in reverse order, and no credit is negative. No net Family Tax Credit, In-Work Tax Credit or Best Start payment rises by more than 1e-6 when income goes up by $1 or $1,000; the Family Tax Credit and In-Work Tax Credit checks skip families whose first parent has AUTOMATIC status and no wages, where a first dollar of wages can start the In-Work Tax Credit.
  • Across two alternating runs of all nine schedules, the model took 10.55 and 10.40 seconds on main and 11.21 and 10.42 seconds at this version. On 20,000 Python integers over the denominator the formulas use, stored takes 4.0 to 4.1 milliseconds at this version, 5.6 to 5.8 at 1a405f8 and 3.2 to 3.3 on main, across three alternating runs that each take the best of five.
  • Ruff 0.16.7 reports the same four findings in working_for_families.py as on main, finds none in the new test file, and leaves both files' formatting as it is.
  • git merge-tree finds no conflicts with main at d8ee910, which changes no file this PR touches.

The first review reproduced its findings 2 to 5 on main as well as at the first version, and my own runs on main agree.

Revisions

  • First version (9d6fe64).
  • Second version (70fde42), for the first review's eight P1 and four P2 findings: stored holds the denominator exactly, divides an integer over a whole denominator as Python integers and any other value that a 64-bit float does not hold through Fraction, and keeps main's results for negative and NumPy denominators and for matrices; the cent sums add booleans, unsigned integers and whole floats exactly and keep a huge integer exact beside an infinity; finite_parts keeps a sequence's integers and gives Python numbers; exact_counts replaces check_counts, bounds each row's own counts, and converts unsigned and float counts; whole's docstring names its steps; the description credits Working for Families helpers: int64, mixed-sequence and shape edge cases, and three missed mutations #27's comment with the 32-bit cent. Zero, infinite or NaN denominators and cents or counts that are not whole numbers now raise a ValueError.
  • Third version (27c679e), for the second review's eight P1 and four P2 findings: stored settles a 64-bit quotient at the overflow midpoint with the exact quotient (and drops two clamps that had no effect left), divides in 64 bits on normalized values with NumPy's floating-point errors ignored, and keeps NaN's bits in _quotient; _python_number holds Decimals and NumPy floats wider than 64 bits exactly; the helpers reject date, duration and text arrays and object-held durations, and finite_parts rejects values that are not numbers; zero-dimensional sums return arrays; whole compares integers exactly; the description's parity, battery and grid wording is narrower; tests cover each witness.
  • Fourth version (1a405f8), for the third review's seven P1 findings and one P2: stored divides only built-in floats and integers in 64 bits, so a subclass with its own __float__ divides as the number it holds; the helpers reject arrays of dates, durations or text inside a sequence; whole holds its step exactly; exact_counts gives its 2**53 error for a row sum too large to print; new tests cover the integer and Fraction paths just below the overflow midpoint and _quotient's NaN bits, and the test helper _nearest_float32 works up to the largest 32-bit float. The description now says stored keeps a NaN's sign, where the third version's entry said its bits, gives main's two-argument whole call, and gives the battery's strict comparison with the guarded reference.
  • Fifth version (606e9b2), for the fourth review's three P1 findings and one P2: _python_number turns a subclass of float or int into the built-in number it holds before anything converts or divides it; the helpers check every sequence and array-like value that NumPy reads, check an array subclass as the plain array it holds, and keep an array held in a slot of an object array as one value; a Decimal NaN keeps its sign; the test helper _nearest_float32 raises no floating-point error; a built-in float or integer leaves _python_number at once, so stored runs faster than at the fourth version; a new test pins exact_counts' error for rows of text. The description and stored's docstring now say that a NaN keeps its sign and the payload bits that a 32-bit float holds, and drops the rest; the fourth version's commit message said stored keeps NaN's bits.

axiom: no RuleSpec change (helper code, tests and changelog)

🤖 Generated with Claude Code

Fix the helper items in issue #27, none of which today's formulas
reach except a 32-bit reform value:

- cents_by_family bounds the sum after widening, so the smallest int64
  takes the exact path, and add_cents adds narrow integers and mixed
  signed and unsigned integers as int64 when no sum can reach 2**63.
- stored keeps the integers of a sequence, divides a whole number held
  as a finite float exactly, and repairs a tie for a float numerator.
- finite_parts reads NumPy floats and keeps the input's shape.
- whole rounds the nearest whole number of steps to the value's own
  NumPy float type, so the 16- or 32-bit value nearest a cent passes.
- credit_sums and best_start_sums raise a named error when a row of
  daily counts of children could sum to 2**53.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- stored holds the denominator exactly as a Fraction and raises a
  ValueError for a zero, infinite or NaN denominator or a numerator
  that is not a number. Its 64-bit fast path runs only for an array
  that is not an object array, whose values lie below 2**53, and a
  denominator that a 64-bit float holds exactly. An integer over a
  whole denominator divides as Python integers, as on main, which
  round the exact quotient once; every other value divides exactly
  through Fraction. A matrix divides like an array, and zeros and
  infinities take the sign of the quotient.
- cents_by_family and add_cents add booleans and unsigned integers as
  64-bit integers, and split any other array into exact finite parts
  and infinities, so a huge integer beside an infinity stays exact.
  Cents that are not whole numbers raise a ValueError.
- finite_parts turns a sequence into an object array and gives Python
  numbers.
- exact_counts replaces check_counts. It needs a day axis, requires
  whole numbers, bounds each row's own sum of absolute counts, and
  returns int32 or int64 counts, which the two sums now use.
- whole's docstring names the steps it supports, a cent and 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent-written for Max, by Claude Code for Max Ghenis.

Answer to the first review, which requested changes at 9d6fe64. 70fde42 addresses each finding; the description's Tests section has the checks behind these answers.

P1, stored regressions. stored([100], -100) gives [-1.0] again, stored([100], np.int64(100)) gives [1.0], and a np.matrix divides like an array. stored holds the denominator as a Fraction, converts an array subclass with np.asarray, and gives zeros and infinities the sign of the quotient. New tests: test_stored_keeps_mains_results_for_other_denominators, test_a_matrix_divides_like_an_array, test_zeros_and_infinities_take_the_sign_of_the_quotient, and test_a_sequence_and_an_array_give_the_same_bits over six denominators.

P1, narrow arrays. The 64-bit path widens the numerators to 64-bit floats before it divides, and runs only when they lie below 2**53 and a 64-bit float holds the denominator exactly. A float16 [1] over 3 gives 0.3333333432674408 with or without an infinity beside it, float32 [1] over 2**24 + 1 gives 2**-24 − 2**-48, and float16 [1] over 100,000 no longer casts the denominator. test_narrow_floats_divide_exactly covers each, alone and beside an infinity. test_a_value_that_is_not_a_64_bit_float_divides_exactly covers an integer above 2**53, a fraction, and a denominator above 2**53, each of which the 64-bit path would round twice.

P1, unsigned and float cents. Integer and boolean cents add as 64-bit integers; every other array takes an exact path. test_unsigned_and_float_cents_sum_exactly_beside_an_empty_family pins 2**53 + 2 and 2**53 + 1.

P1, booleans. Booleans count as integers in both sums, and _python_number turns an object-held np.bool_ into a bool. test_booleans_add_as_integers covers your three witnesses.

P1, a huge integer beside an infinity. Both cent sums split each value into a finite Python integer, an infinity or NaN before they add. test_a_huge_integer_beside_infinities_and_nan expects infinity beside one infinity and NaN beside both, in each helper.

P1, finite_parts. A sequence becomes an object array, so [2**53 + 1, inf] keeps its integer, and NumPy booleans and integers become Python numbers (test_finite_parts_keeps_a_sequences_integers_exact, test_finite_parts_gives_python_numbers). This departs from your suggestion in one place: a NumPy float wider than 64 bits becomes the 64-bit float nearest it, as the docstrings of _python_number and stored now say, instead of an exact value. No caller passes such a float, and holding one exactly would need a separate path for that one type. test_a_wider_float_becomes_the_nearest_64_bit_float_first pins the documented result. This Mac's long double has 64 bits, so the test skips here, and CI's Linux runners give it its first run.

P1, sparse rows. exact_counts replaces check_counts. It keeps the bound of the largest count times the days as a fast path, and when that reaches 2**53 it sums each row's absolute counts exactly and raises only if a row reaches 2**53. test_only_a_rows_own_counts_add_together pins your [[2**52, 0]] case.

P1, unsigned and float counts. exact_counts requires whole numbers and returns 32- or 64-bit signed counts, which credit_sums and best_start_sums now use. test_unsigned_counts_give_the_signed_results and test_whole_float_counts_sum_exactly pin your three witnesses, and test_core_counts_stay_as_they_are_and_others_become_64_bit the type rules.

P2, whole's steps. I took your first option: the docstring names the steps it supports, a cent and 1, the only steps the formulas pass, and says what rounding twice can give for other steps. The code is unchanged.

P2, the four missing stored and finite_parts assertions. test_a_finite_float_numerator_divides_exactly, test_a_quotient_just_below_a_32_bit_midpoint_rounds_down, test_the_32_bit_overflow_midpoint_rounds_to_infinity and test_finite_parts_gives_python_numbers hold them.

P2, the count and month assertions. test_counts_must_sum_below_2_to_the_53 adds [-(2**53)] and [[-(2**53), 0]], test_counts_keep_their_shape_and_need_a_day_axis adds the (0, 7), (1, 0) and one-dimensional cases, and test_a_32_bit_value_with_a_step_of_1_must_be_whole accepts 1 and rejects 1.25.

P2, credit to #27. The description now credits #27's comment with the 32-bit cent and calls the 16-bit cent the extension, and the test module's opening comment covers both row types.

New errors. Finding 1 objected to inputs main handled and the fix rejected. This version rejects four kinds of input that main accepted, each now a ValueError: a zero, infinite or NaN denominator in stored (main gives [inf], [0.0] and [nan] for a numerator of 1); cents that are not whole numbers (main's cents_by_family turns 1.5 cents into 1); counts of children that are not whole numbers; and a row of counts whose sizes reach 2**53. No formula passes any of them. stored gets the denominators 100 and the Python integers from credit_sums and best_start_sums. The cent sums get whole numbers of cents built from whole_cents: 64-bit integers, or object arrays of Python integers, infinities and NaN. The count sums get 32-bit integers built from daily_counts. The model grid gives the same results as the exact reference on every family.

Speed. Holding the denominator as a Fraction made stored ten times slower on the object arrays the formulas pass it. An integer over a whole denominator now divides as Python integers, as on main, which round the exact quotient once. On 20,000 such values stored takes about 8.5 milliseconds, against 3.5 on main and 33 before this change. Across two alternating runs of the grid's nine schedules, the model took 21.7 seconds on main and 22.3 here, within the spread between runs.

Round 2 can start from 70fde42.

- stored's 64-bit division runs on the normalized values when each is a
  float or an integer below 2**53 and a 64-bit float holds the
  denominator exactly, inside np.errstate(all="ignore"), so underflow
  and overflow round without raising. The tie repair also settles a
  quotient that rounds to the signed 32-bit overflow midpoint in 64
  bits, so an exact quotient just inside it gives the largest 32-bit
  float on every path; the clamps that did that for the integer and
  Fraction paths had no effect left and are gone. NaN keeps its bits.
- _python_number holds a finite Decimal, and a NumPy float wider than
  64 bits that no 64-bit float holds, as the exact int or Fraction
  they hold; a Decimal zero, infinity or NaN becomes that float. It
  raises for a NumPy duration.
- The helpers accept arrays of booleans, integers, floats and objects
  only, so dates, durations and text raise a ValueError, and
  finite_parts raises for a value that is not a number.
- add_cents returns a zero-dimensional array for zero-dimensional
  input on both paths. Integer cents still add in 64 bits only while
  no sum can reach 2**63 in size, and cents_by_family's only while
  the absolute sum stays below 2**62; other sums are Python integers.
- whole compares an integer exactly, and its docstring names CENT.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent-written for Max, by Claude Code for Max Ghenis.

Answer to the second review, which requested changes at 70fde42. 27c679e addresses each finding. Each result below comes from a run at 27c679e, on this Mac's 64-bit long double and on an x86-64 interpreter whose long double has 80 bits.

Correction first. My first answer said test_booleans_add_as_integers covered your three boolean witnesses. It covered two: True + True and the object-held 2**63 - 1 + np.bool_(True). No test covered 8-bit 127 plus True. The test now asserts it gives 128.

P1, the overflow midpoint in arrays. stored now treats a 64-bit quotient equal to the signed overflow midpoint as a tie and settles it with the exact quotient, so your n / d gives the largest 32-bit float in an array as well as in a sequence. With the tie repair covering that midpoint on every path, the two clamps to the largest 32-bit float in _quotient had no effect left, so I removed them. test_a_quotient_just_below_the_32_bit_overflow_midpoint_stays_finite covers an integer array, a float array beside an infinity, and a sequence, each with both signs, under np.errstate(all="raise").

P1, strict floating-point errors. The 64-bit division runs on the normalized values inside np.errstate(all="ignore"), where underflow and overflow round correctly. test_a_quotient_that_underflows_or_overflows_raises_no_floating_point_error pins your two witnesses under np.errstate(all="raise"): 0.0 and infinity.

P1, zero-dimensional sums. The exact path turns the total into an object array before it sets the infinities, and the integer path returns an array too, so a zero-dimensional sum is a zero-dimensional array on both paths. test_a_zero_dimensional_sum_is_an_array covers integers and floats, and the opposing-infinity witness gives NaN.

P1, Decimals. _python_number turns a finite Decimal into the exact int or Fraction it holds, a Decimal zero into the float zero of its sign, and a Decimal infinity or NaN, signalling NaN included, into that float. Your four main-compatibility witnesses give main's results again, and finite_parts masks Decimal infinities and NaN. test_decimals_are_held_exactly covers each, plus 2**53 + 1 cents, which a 64-bit float would round to 2**53.

P1, wider floats. I took your fix: _python_number keeps a NumPy float that no 64-bit float holds as the exact int or Fraction it holds, so denominators, numerators, cents and counts all keep their exact values. test_a_wider_float_is_held_exactly replaces the test that pinned the round-first rule and covers your denominator, range, whole-cent and fractional-validation witnesses plus the exact finite_parts value. It skips on this Mac; under the x86-64 interpreter it passes, and every wide witness gives your expected result.

P1, dates and durations. The helpers check an array's kind before they read any value, and accept only booleans, integers, floats and objects. _python_number raises for an object-held duration, which NumPy makes a kind of integer; an object-held date is not a number, so each helper's own check rejects it. test_dates_and_durations_are_not_numbers runs every helper on date and duration arrays and on object-held dates and durations.

P1, whole. An integer value is now compared exactly, so whole(2**53 + 1, 1, int) is true. The docstring names the step as CENT, exactly a hundredth, or 1, and says the float 0.01 is not a cent. test_an_integer_is_whole_exactly covers both steps.

P2, the five stored mutations and the oracle's range. test_more_exact_denominators_and_boundaries pins your Fraction-denominator, zero-candidate, 2**54-guard and conversion-overflow witnesses, and the overflow-midpoint test above pins the Fraction-path witness. The Fraction overflow clamp is gone, as above. _nearest_float32's docstring limits it to numbers below the overflow midpoint.

P2, the six cent and count mutations. test_cents_keep_each_operand_and_family_apart pins typed int64 overflow, cross-axis broadcasting, a first-operand NaN, repeated infinity and separate families' infinities. test_core_counts_stay_as_they_are_and_others_become_64_bit asserts that an int32 array at int32.min + 3 comes back unchanged.

P2, wording. The description now calls the child-sum battery a check that other count types give the int64 results, gives the grid's filter (it ignores rises up to 1e-6 and skips the Family Tax Credit and In-Work Tax Credit comparisons for an AUTOMATIC first parent with no starting wages), and says the parity tests compare bits between input forms. The cents_by_family comment names signed and unsigned 64-bit promotion. The commit message keeps the accumulation bounds. stored's docstring says NaN stays NaN, and NaN now keeps its bits on every path. The changelog lists the repaired inputs and the new errors.

Mutations. I ran 87 changes to working_for_families.py against the new test file on both interpreters: the last round's 61, less four whose code is gone, plus new ones for this round's branches and ten of your eleven. The eleventh removes the Fraction overflow clamp, which this version already removes. Eighty-four fail at least one test; rounding a wider float first fails only on the x86-64 interpreter. Three change nothing a test can see: boolean cents on cents_by_family's exact path give the same sums, and rounding to infinity only above the overflow midpoint, on the integer or Fraction path, still gives infinity at the midpoint itself, where the 32-bit rounding gives infinity and the tie repair keeps it. The description's table names a failing test for each.

Other checks. A battery of 886 cases, now with Decimals, dates, durations, text, zero-dimensional arrays, exponent extremes and the overflow midpoint with both signs, matches an exact reference in every case with NumPy set to raise on floating-point errors, and every error this version raises there is a ValueError from the description's list. The model grid matches its independent reference on all 18,823 families. The suite passes, 1,711 tests. Across two alternating timing runs of the grid's nine schedules, the model took 8.95 and 8.96 seconds on main and 9.27 and 9.41 here, about 4 percent more; stored takes about 5.4 milliseconds on 20,000 production-shaped values, against 2.9 to 3.5 on main and 8.5 at the last version. scripts/witnesses.py, which holds your witnesses, reports 0 failures under both interpreters.

Round 3 can start from 27c679e.

- stored divides only built-in floats and ints on its 64-bit path, so a
  subclass with its own __float__ divides as the number it holds.
- A sequence's nested arrays of dates, durations or text raise an error
  in stored, the cent sums, finite_parts and exact_counts, before NumPy
  turns their values into integers.
- whole holds a step other than an int or Fraction exactly, so a step of
  1.0 compares a large integer exactly.
- exact_counts gives its 2**53 error for a row sum too large to print.

Tests pin each case, the integer and Fraction paths just below the
32-bit overflow midpoint, and the NaN bits on the exact path. The test
helper _nearest_float32 now works up to the largest 32-bit float.

Correction to 27c679e's message: NaN keeps all its bits only in
_quotient. stored keeps a NaN's sign on every path, and its 32-bit
result drops the payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent-written for Max, by Claude Code for Max Ghenis.

Answer to the third review, which requested changes at 27c679e. 1a405f8 addresses each finding. Each result below comes from a run at 1a405f8 merged with main, on this Mac and, where it says so, on the x86-64 interpreter whose long double has 80 bits.

P1, a subclass on the 64-bit path. stored now divides in 64 bits only when every numerator is a built-in float, or a built-in int below 2**53. test_a_number_subclass_divides_as_the_number_it_holds covers your float and int subclasses whose __float__ gives 2.0, alone and beside a Fraction; each gives 1.0. Restoring the isinstance guard fails it.

P1, dates and durations inside a sequence. The cent sums, stored, finite_parts and exact_counts check the kind of every array inside a list or tuple, at any depth, before NumPy builds an array around it. test_dates_and_durations_inside_a_sequence_are_not_numbers runs your witnesses for nanosecond dates and durations, including exact_counts([row, np.array([Decimal(2)], dtype=object)]) and a list of date or duration scalars, with a 64-bit integer row as the control that each call accepts. Removing either nested check fails it. The earlier change that drops exact_counts' own kind check would otherwise have become invisible, since the nested check now also covers a top-level array; the scalar case fails it.

P1, whole with a step of 1.0. whole holds a step other than an int or Fraction exactly, through _python_number and Fraction. whole(2**53 + 1, 1.0, int) and the same call with a 32-bit 1 are now true, and test_an_integer_is_whole_exactly asserts both; removing the conversion fails it. You were right about main's signature: main's whole takes two arguments, and whole(2**53 + 1, 1) is false there. The description now gives that call.

P1, the Fraction path below the midpoint. test_the_exact_paths_keep_a_quotient_below_the_midpoint_finite adds [NEAR_TOP, Fraction(1, 3)] over ±TOP_DIVISOR, which takes the Fraction path, and [3 * (2**128 - 2**103) - 1] over ±3, which takes the integer path. Each first quotient gives the signed largest 32-bit float. Testing either path's quotient against the midpoint in 64 bits fails both signs of that path's case.

P1, NaN bits. You were right: stored keeps a NaN's sign on every path, and its 32-bit result drops any payload. I checked 0xfff8000000000001, which both paths return as 0xfff8000000000000. The test comment now says both paths give the same stored bits for NaN, the description says NaN stays NaN with its sign, and the third version's Revisions entry limits the bits claim to _quotient. test_the_exact_quotient_keeps_a_nans_bits pins that private guarantee with your negative NaN with a payload, for both denominator signs; returning a new NaN fails it. 1a405f8's commit message corrects 27c679e's.

P1, the strict battery comparison. You were right that the reference raised in 12 of its own conversions under np.errstate(all="raise") and matched 874 of 886. The reference now guards its own 32-bit conversions, and under strict errors in both it matches the helpers in all 886. The helpers' 886 outputs are the same as at 27c679e. The description says how the reference changed.

P1, the row-sum error. exact_counts prints a row's sum in full only up to 256 bits, and as a power of 2 past that. exact_counts([[Decimal("1e5000")]]) gives the 2**53 error ("at least 2**16609"), and test_counts_must_sum_below_2_to_the_53 asserts it; restoring the full print fails it. Under the x86-64 interpreter, a long-double count of 2**16380 gives the same error, in an array and in a sequence.

P2, _nearest_float32. The test helper ignores overflow when it rounds its guess and drops any candidate that is not finite, so it gives the largest 32-bit float for an exact value at or just below it.

Mutations. The table now covers 95 changes: the last round's 87, with four re-anchored to the moved code, and eight for this round's fixes. Ninety-two fail at least one test, one of them only on the x86-64 interpreter, and the same three as before change nothing a test can see.

Other checks. Round two's witnesses give 0 failures under both interpreters. The new test file has 98 cases: on this Mac 97 pass and the long-double one skips, and on the x86-64 interpreter all 96 that need no Core simulation pass. The suite passes, 1,722 tests. whole agrees with the exact check on all 387,488 values, and the model grid matches its independent reference on all 18,823 families. Ruff reports the same four findings as on main. The branch merges with main at d8ee910 without conflicts.

Round 4 can start from 1a405f8.

- _python_number turns a subclass of float or int into the built-in
  number it holds, so its own __float__, division or as_integer_ratio
  cannot change a result, its zeros, infinities and NaNs included.
- The check for dates, durations and text reads every sequence and
  array-like value NumPy would read, and checks an array subclass as
  the plain array it holds. The cent sums keep an array held in an
  object array's slot as one value, which they reject.
- A Decimal NaN keeps its sign.
- _python_number returns built-in floats and ints at once, so plain
  numbers skip the subclass checks.

Tests pin each case, and exact_counts' error for rows of text. The
test helper _nearest_float32 raises no floating-point error at either
end of the 32-bit range.

Correction to 1a405f8's message: stored's 32-bit result keeps a NaN's
sign and the payload bits that 32 bits hold, and drops the rest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@MaxGhenis

Copy link
Copy Markdown
Contributor Author

Agent-written for Max, by Claude Code for Max Ghenis.

Answer to the fourth review, which requested changes at 1a405f8. Round 4 was the last scoped round, so the review rules leave its open findings with this hub: I fixed each one in 606e9b2 and checked it here, as below. Each result comes from a run at 606e9b2 merged with main at d8ee910, on this Mac and, where it says so, on the x86-64 interpreter whose long double has 80 bits. I reproduced every witness in the review at 1a405f8 first.

P1, a subclass's special values and its own arithmetic. _python_number, which every helper uses, now turns a subclass of float, or of int other than bool, into the built-in number it holds, through float.__float__ and int.__int__, before anything converts or divides it. Your witnesses now give the held value: a float subclass whose __float__ gives 2.0 and that holds −0.0, infinity or NaN keeps that value, alone and beside a Fraction; an int subclass whose __truediv__ gives 2.0 and a float subclass whose as_integer_ratio gives (2, 1) both give 1.0. test_a_subclass_with_its_own_arithmetic_divides_as_the_number_it_holds checks eight held values (1.0, −0.0, ±infinity, ±NaN and two integers) over three denominators, alone, in an object array and beside a Fraction, against the built-in number's bits. Removing either conversion fails it. The 64-bit path's own type check now changes nothing a test can see: no subclass other than bool reaches it, and a bool gives the same bits on either path in all 45 cases I tried. It stays as a second guard.

P1, dates and durations past the sequence check. _nested_numbers now reads what NumPy reads: the items of any value with a length and items (a UserList included), any value with __array__ or an array interface, and each array as the plain array it holds, so a subclass's own dtype cannot hide or invent dates. Text, bytes and mappings stay single values, as they are to NumPy. The cent sums now keep an array held in an object array's slot as one value, which they reject as not a whole number, where np.array used to read its items. Your witnesses now raise for both temporal kinds: stored(UserList([row])), exact_counts(UserList([row, object_row])), the two array subclasses, and the held row in add_cents and cents_by_family. A value with __array__ inside a list also leaked dates into stored and add_cents at 1a405f8, and now raises too. The 64-bit integer controls give their earlier results, except that an integer array held in an object array's slot now raises in every helper, since it is not a number. Reverting to list-and-tuple traversal, reading a subclass's own dtype, dropping the array-like check, or rebuilding the cent slots with np.array each fails a test. exact_counts' own check of an array's kind still decides the error for rows of text in a plain list, which _nested_numbers leaves as single values; the new test_rows_of_text_are_not_counts pins that error.

P1, NaN. You were right on both counts. A Decimal NaN, quiet or signalling, now keeps its sign. The description, stored's docstring and the test comment now say that stored keeps a NaN's sign and the payload bits that 32 bits hold, and drops the rest, as any conversion to 32 bits does; _quotient keeps every bit. test_a_stored_nan_keeps_its_sign_and_the_payload_bits_32_bits_hold checks your low-bit and high-bit payloads of each sign on both paths and both denominator signs, and test_a_decimal_nan_keeps_its_sign checks five Decimal NaNs the same way; returning an unsigned NaN for a Decimal fails it. 606e9b2's commit message corrects 1a405f8's.

P2, _nearest_float32. The test helper now ignores floating-point errors while it builds its candidates too. test_the_reference_rounding_raises_no_floating_point_error checks the largest 32-bit float and the smallest subnormal under np.errstate(all="raise").

Speed. The subclass checks slowed stored on plain numbers, so _python_number now returns a built-in float or int at once. On 20,000 Python integers, stored takes 4.0 to 4.1 milliseconds at 606e9b2, 5.6 to 5.8 at 1a405f8 and 3.2 to 3.3 on main, across three alternating runs that each take the best of five.

Checks. The mutation table now covers 104 changes: round 3's 95, with two re-anchored to the moved Decimal lines, and nine for this round's fixes. One hundred fail at least one test, one of them only on the x86-64 interpreter. The other four change nothing a test can see: round 3's three, and the 64-bit path's type check above. The battery gives the same 886 outputs as at 1a405f8 and as the guarded reference, under strict errors and with errors ignored. Round two's witnesses give 0 failures under both interpreters. The new file has 169 cases: on this Mac 168 pass and the long-double one skips, and on the x86-64 interpreter all 167 that need no Core simulation pass. On main with the stub exact_counts, 126 fail and 42 pass. The suite passes, 1,793 tests. whole agrees with the exact check on all 387,488 values, and the model grid matches its independent reference on all 18,823 families.

No P0 or P1 stays open. I'll mark this ready and merge it once CI passes at 606e9b2.

@MaxGhenis
MaxGhenis marked this pull request as ready for review December 1, 2026 11:41
@MaxGhenis
MaxGhenis merged commit ba0a233 into main Dec 1, 2026
11 checks passed
@MaxGhenis
MaxGhenis deleted the wff-helper-edge-cases branch December 1, 2026 11:41
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Working for Families helpers: int64, mixed-sequence and shape edge cases, and three missed mutations

1 participant