Skip to content

fix: stabilise the variance/covariance accumulators in the moving functions - #758

Closed
numbagg-bot wants to merge 4 commits into
mainfrom
fix/moving-variance-numerical-stability
Closed

numbagg-bot wants to merge 4 commits into
mainfrom
fix/moving-variance-numerical-stability

Conversation

@numbagg-bot

@numbagg-bot numbagg-bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

move_var, move_std, move_cov and move_corr all accumulate a sum of squares (or of products) and then subtract the square of the sum. Both terms scale with the square of the values, so when the values are large relative to their spread the subtraction is nearly all cancellation — on a constant float32 series at 1e8, move_var returned 3.4e8 instead of 0, and move_corr on float32 values around 1e6 returned correlations more than 30 outside [-1, 1]. This offsets each series by the mean of its first window observations and computes the products in float64, which leaves the answer unchanged in exact arithmetic (all three statistics are translation-invariant) but keeps the significant digits. Found during the nightly survey of numbagg/moving.py.

Two independent losses were stacked on top of each other:

  • Products computed in the input dtype. ai * ai for a float32 value of 1e8 is 1e16, which float32 holds to ~7 digits — the rounding error there is 1.4e9, so the variance of a constant series came back as 3.4e8. Promoting to float64 before squaring fixes it.
  • The offset dominating the spread. Even in float64, move_cov on values around 1e8 was off by ~10 in absolute terms. Subtracting a per-series constant fixes it.

Which constant. The accumulators run for the whole series, so the offset sets the rounding floor everywhere, not just where it fits well. The mean of the whole series is the most accurate choice on most inputs but is ruled out: it depends on values that haven't been seen yet, so it breaks the guarantee that appending to a series doesn't change results already emitted. The first observation keeps that guarantee but rests on a[0] being representative; when it isn't, the whole series pays for it. Averaging the first window observations keeps the guarantee, dilutes an outlier by the window, and costs O(window) rather than a second pass. Measurements are in the review thread.

Clamping. move_var, move_std and move_corr clamp the variance at zero now. That was the original symptom I chased — a float64 constant series at 1e8 + 1 produced a variance of -2.0, and sqrt turned that into a NaN from move_std. The offsetting makes it much harder to hit, but a variance is never negative and the clamp is free. move_corr computes its own var_a / var_b and previously guarded only their product, so two variances that both rounded slightly negative multiplied to a positive number and passed the guard: move_corr(a, a, window=5) on concatenate([zeros(5), full(25, 123456789.123)]) returned -1.0 — a series anticorrelated with itself — where move_var on the same windows returns 0.0. With the clamp those windows emit NaN, which is the right answer for a correlation against a constant series, and the output is unchanged on well-conditioned data.

To be clear about what that does not fix: the clamp doesn't bound move_corr's output to [-1, 1] in general. A poorly-fitting offset (a small head followed by a large near-constant tail) still yields |corr| up to 2, because there both variances are positive-but-tiny while the covariance isn't. That path is unchanged by this PR — the same value comes out with the offsetting removed — so it's pre-existing rather than a regression, but it's outside what's fixed here. What this PR closes is the float32/large-offset path, where the correlations were out by more than 30. Bounding the output would be a separate design call.

Accuracy, measured against an exact rational reference

Rolling window of 10 over 60 standard-normal values, maximum absolute error scaled by the median of the reference, median over 25 seeds. "outlier at head" sets a[0] = b[0] = 1e6 and measures only windows the outlier has already left.

input statistic no offset (6c4e6cc) offset a[0] offset first-window mean
+1e8 var 7.40e+00 1.09e-15 5.98e-16
+1e8 cov 4.02e+01 1.57e-15 9.10e-16
outlier at head var 7.93e-06 1.32e-03 1.47e-05
outlier at head cov 3.29e-05 4.68e-03 5.20e-05

Worth flagging for review: numbagg is now more accurate than pandas on large-magnitude input, so the existing test_move_pandas_comp comparisons are only safe because they run on unit-scale data. If a large-magnitude case is ever added there, pandas is the side that will be wrong.

Performance impact

(100, 10_000) float64 input, best of 5:

before (window=20) after (window=20) after (window=200) after (window=2000)
move_var 1.17 ms 1.24 ms 1.23 ms 1.15 ms
move_std 2.13 ms 2.08 ms 2.06 ms 1.82 ms
move_cov 1.16 ms 1.23 ms 1.23 ms 1.22 ms
move_corr 2.40 ms 2.52 ms 2.49 ms 2.27 ms

So roughly 5% on move_var/move_cov and within noise on the other two — the added work is one subtraction per value read plus a scan over the first window. The scan doesn't show up even at window=2000 on a 10,000-long series; it's a sequential read that the main loop's memory traffic dominates. I judged the 5% worth it for results that are currently wrong by more than their own magnitude, but it's a real cost in a library whose point is speed, so flagging it rather than burying it.

Tests. test_numerical_issues_constant_series, test_numerical_issues_large_offset and test_numerical_issues_vs_exact_reference in numbagg/test/test_moving.py, following the existing test_numerical_issues_* convention. The last of those measures against an exact rational reference (rationals rather than np.longdouble, which is float64 on Windows) on both the input the offset exists for and the input it's most exposed to; it fails on the pre-fix code and on the a[0] offset.

test_appending_doesnt_change_earlier_results pins the property the offset choice is built around — that f(a[:n]) equals f(a)[:n] exactly, over two windows and a large offset. test_moving_bigger_arrays_have_same_beginning in test_property.py covers the same ground, but that module carries an unconditional pytest.mark.skip, so it doesn't run even under --run-nightly: the constraint that ruled out the full-series mean had no enforcement in CI. Bit-exact rather than approximate, since a tolerance would let a future look-ahead offset through.

test_numerical_issues_degenerate_window_clamps pins the three clamps themselves, which nothing else in the suite reaches — reverting any of them leaves every other test passing. It uses two series, because no single one exercises all three: a small head followed by a large near-constant tail at 1e8 + 1 for move_var and move_std, and the same shape at 123456789.123 for move_corr, whose variances round to -4.0 there but to exactly 0.0 on the first, where the pre-existing var_a_var_b > 0 guard already emits NaN and the clamp is inert.

Full suite passes under -W error, as does pre-commit run --all-files.

Not covered here. The same one-pass form, with the same problem, also appears in:

  • numbagg/moving_matrix.py
  • nancorrmatrix / nancovmatrix in numbagg/funcs.py — nancovmatrix on values around 1e8 is off by a factor of 267
  • move_exp_nanvar, move_exp_nanstd, move_exp_nancov and move_exp_nancorr in numbagg/moving_exp.py — var_biased = (sum_x_2 / sum_weight) - ((sum_x / sum_weight) ** 2), with move_exp_nanstd feeding the result straight into np.sqrt with no clamp. Weighted variance is translation-invariant too, so the same remedy applies

I've left those for a separate PR rather than widening this one.

@numbagg-bot numbagg-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The accuracy win on homogeneous data reproduces — I measured move_var/move_cov at offsets 1e6 and 1e8 against a longdouble reference and got the same ~1e-15 absolute errors the table reports. One finding I'd want settled before this lands (inline on _first_valid), plus a scoping note.

The offset choice trades one failure mode for another. Because the offset is a[0] rather than something central, a single unrepresentative first observation now degrades every window in the series — including windows that no longer contain it. Details and measurements are in the inline comment; the short version is that move_cov on standard_normal(40) with a[0] = 1e6 goes from 2.9e-04 relative error to 1.2e-02, and the gap grows as a[0]**2. Using the series mean as the offset is better than both the old code and this one on every input I tried, at the cost of one genuine extra pass over the data.

moving_exp.py is missing from the "Not covered here" list. The PR body names moving_matrix.py and nancorrmatrix/nancovmatrix, but move_exp_nanvar, move_exp_nanstd, move_exp_nancov and move_exp_nancorr have the identical form — var_biased = (sum_x_2 / sum_weight) - ((sum_x / sum_weight) ** 2) in move_exp_nanvar, and the same shape in the other three. move_exp_nanstd then feeds var_biased / bias straight into np.sqrt with no clamp, which is exactly the NaN path this PR fixes in move_std. Weighted variance is translation-invariant too, so the same remedy applies. Worth naming so the follow-up is scoped to all four files rather than two.

How the measurements were produced

Reference is the same window recomputed in np.longdouble (two-pass, subtract the window mean). "before" is 6c4e6cc, "after" is dd41e75, "mean offset" is dd41e75 with _first_valid replaced by a mean over the non-NaN values.

Homogeneous case — standard_normal(300) + offset, window=20, max absolute error over i >= 19:

offset statistic after (a[0]) after (mean)
1e6 var 4.22e-15 1.11e-15
1e6 cov 4.72e-16 3.33e-16
1e8 var 6.00e-15 8.88e-16
1e8 cov 7.49e-16 2.22e-16

Heterogeneous case — standard_normal(40) with a[0] = b[0] = 1e6, window=10, max relative error over i >= 10:

statistic before after (a[0]) after (mean)
var 3.51e-05 1.41e-03 3.64e-05
cov 2.88e-04 1.24e-02 2.87e-04

Also checked and found fine: numba's max(x, 0.0) propagates NaN rather than clamping it to zero (so the new clamps don't turn an inf-contaminated window into a spurious 0.0); move_corr stayed inside [-1, 1] on every near-constant and degenerate series I threw at it; and offsetting by the first observation preserves the test_moving_bigger_arrays_have_same_beginning property, since truncating the tail can't change a[0].

Comment thread numbagg/moving.py Resolved
Comment thread numbagg/test/test_moving.py Resolved
Offsetting by a[0] made the rounding floor for the whole series scale
with a[0]**2, so an unrepresentative first observation degraded every
window — including ones it had already left. The mean of the whole
series would be the natural fix, but it depends on data that hasn't
been seen yet and so breaks the guarantee that appending to a series
doesn't change results already emitted.

The mean of the first `window` observations keeps that guarantee,
dilutes an outlier by the window, and costs O(window) rather than a
second pass. Adds a test measuring both cases against an exact
rational reference.

@numbagg-bot numbagg-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The offset change lands the point I raised: I reproduced the strategy comparison independently (replicating the accumulator in float64 and measuring against a Fraction reference, seed 0, n=60, window=10) and got none → 8.7e+00 / a[0] → 6.5e-16 / first-window mean → 6.5e-16 on the large-offset case, and 1.4e-05 / 1.5e-03 / 6.5e-06 on the unrepresentative-first-value case. So the new offset is the only one of the three that clears both bars in test_numerical_issues_vs_exact_reference, and the test genuinely discriminates rather than just passing. I also checked the appending property directly — 1200 random truncations across move_var/move_std/move_cov/move_corr with offsets up to 1e8, zero violations — and confirmed _offset's all-NaN fallback can't break it, since a prefix that disagrees has no non-NaN values and emits NaN either way. pytest -W error and pre-commit run --all-files (including stubtest and ty) both pass here. Two things below; neither is a regression this PR introduces.

move_corr doesn't get the clamp its siblings just gained. move_var and move_std now clamp the variance at zero, but move_corr computes its own var_a / var_b inline (var_a = asum_sq * count_reciprocal - avg_a**2) and guards only the product, if var_a_var_b > 0. When both variances round to a small negative, their product is positive, the guard passes, and sqrt of it is a meaningless denominator. Concretely, on a = np.concatenate([np.zeros(5), np.full(25, 123456789.123)]), move_corr(a, a, window=5) returns -1.0 at indices 10–14 — a series correlated with itself, at −1 — while move_var(a, window=5) on those same windows now returns 0.0 because of the new clamp. Clamping var_a and var_b the same way turns those into NaN, matches move_var's answer for a degenerate window, and is bit-identical on well-conditioned data (checked over standard_normal(200)). I'd rather not push it into this PR unprompted, since it isn't a full fix — see below — but happy to if you want it here rather than in the follow-up.

Worth scoping the PR body's move_corr claim while you're there: the clamp doesn't close |corr| > 1 in general. With a poorly-fitting offset (small head, large near-constant tail with 1e-9 jitter) I still get |corr| up to exactly 2.0 with the clamp applied, because there both variances are positive-but-tiny while the covariance isn't. That path is unchanged by this PR — I get the same 2.0 with offsetting disabled — so it's pre-existing, but the body currently reads as though the out-of-range correlations are dealt with, and what's actually fixed is the float32/large-offset path. Bounding the output to [-1, 1] would close the rest, and that's a design call rather than a clamp.

The property the offset choice is built around isn't tested. The header comment and the PR body both rest on test_moving_bigger_arrays_have_same_beginning to rule out the full-series mean, and the inline reply notes it uses assert_array_equal so there's no tolerance to hide in — but that test never runs. test_property.py carries a module-level pytestmark = [pytest.mark.nightly, pytest.mark.skip(reason="These need more work; ...")], and the unconditional skip means --run-nightly doesn't re-enable it either; pytest numbagg/test/test_property.py -q --run-nightly reports 3 skipped. So the constraint that rejected the most accurate option on this PR's target input has no enforcement anywhere in CI, and a later change to _offset would meet nothing. The property does hold today — I measured it — which makes this the cheap moment to pin it: a small non-hypothesis case in test_moving.py asserting f(a)[:n-1] == f(a[:n-1]) exactly, over a couple of windows and a large offset, would defend the decision this PR is making. Failing that, the comment and body should say the property is intended rather than pinned.

How these were measured

Repo at 56ff8fc, merged onto 6c4e6cc.

move_corr degenerate-window case, against the installed build:

a = np.concatenate([np.zeros(5), np.full(25, 123456789.123)])
move_corr(a, a, window=5)[10:14]  ->  [-1. -1. -1. -1.]
move_var(a, window=5)[10:14]      ->  [0. 0. 0. 0.]

The offset here is mean(a[:5]) == 0.0, so it doesn't fit the tail — that's what leaves the cancellation in place. move_corr with var_a/var_b clamped at 0.0 gives [nan nan nan nan], and is array_equal to the unclamped version on standard_normal(200) at window=20.

The |corr| == 2.0 figure is over 500 trials of a = concatenate([standard_normal(5), tail + 1e-9 * standard_normal(45)]) with tail = 1e8 + standard_normal(), window=5, max |corr| over non-NaN output — 2.0 both on this branch and with the offsetting removed from a float64 replica of the loop, hence pre-existing.

Strategy comparison used a float64 Python replica of the move_var accumulator (including the new clamp) against a Fraction two-pass reference, scaled by the median of the reference over the scored range, matching _error_vs_exact. Numbers differ from the PR body's table by a factor of ~2 on the outlier case (6.5e-06 vs 1.5e-05) since it's a replica rather than the compiled gufunc and it's a single seed rather than a median over 25 — the ordering between strategies is the same, and the compiled test_numerical_issues_vs_exact_reference passes as written.

Appending-property check: for each of 300 trials, random n in [10, 60), window in [2, 9), series offset 10**k for k in [0, 9), compare f(a)[:n-1] against f(a[:n-1]) with np.array_equal(..., equal_nan=True) for all four functions — 0 violations of 1200. Note window > len(a) raises ValueError: window not in valid range in decorators.py before reaching the kernel, so _offset's min(window, len(a)) is unreachable via the public API and the prefix always sees the same first window values.

Also checked and found fine: inf in the input yields an all-NaN series on this branch, but it did before the offsetting too — asum -= aold with aold = inf poisons the accumulator permanently either way, so no regression; a NaN-only first window falls through to the scan and stays prefix-consistent; 1e8 is exactly representable in float32, so test_numerical_issues_constant_series isn't measuring input quantisation; stubtest is happy without a stub entry since _offset is private.

move_var and move_std clamp their variance at zero; move_corr computes
var_a/var_b inline and guarded only their product, so two variances that
both rounded slightly negative multiplied to a positive number and passed
the guard. move_corr(a, a, window=5) on a series of zeros followed by a
large constant returned -1.0 where move_var returns 0.0 on the same
windows. Clamping each variance sends those to NaN and leaves
well-conditioned data unchanged.

The offset choice rests on appending to a series not changing results
already emitted, but test_property.py is skipped at module level (an
unconditional skip, so --run-nightly doesn't re-enable it), leaving that
constraint unenforced. Pin it directly in test_moving.py.
@numbagg-bot

Copy link
Copy Markdown
Collaborator Author

Both points taken; pushed as 5a6171e.

move_corr's clamp. Added — var_a and var_b now each go through max(..., 0.0) rather than only their product being guarded. It's a small change and it's the same defect the PR is already fixing in the sibling functions, so leaving it to a follow-up would ship a PR that gives move_var a clamp and move_corr a -1.0 on a series against itself. Reproduced the case before and after against the built extension:

a = np.concatenate([np.zeros(5), np.full(25, 123456789.123)])
move_corr(a, a, window=5)[8:16]   before -> [ 1. -1. -1. -1. -1. -1. -1. -1.]
                                   after -> [ 1. nan nan nan nan nan nan nan]
move_var(a, window=5)[8:16]              -> [3.05e+15 0. 0. 0. 0. 0. 0. 0.]

NaN is the right answer there rather than a number, since the window is constant and a correlation against it is undefined — and it's what the existing var_a_var_b > 0 guard already emits when one variance is exactly zero, so the clamp just makes the rounding-noise case reach the same branch. Unchanged on well-conditioned data.

I scoped the PR body's claim rather than trying to close |corr| > 1 here: there's now a paragraph saying explicitly that the clamp doesn't bound the output in general, that the poorly-fitting-offset path still reaches 2, that it's pre-existing rather than a regression, and that what this PR closes is the float32/large-offset path. Bounding the output is a design call and belongs with the follow-up.

The unpinned property. Confirmed — pytest numbagg/test/test_property.py -q --run-nightly gives 3 skipped here, because the module-level pytest.mark.skip is unconditional and --run-nightly only clears the nightly mark. Added test_appending_doesnt_change_earlier_results to test_moving.py: assert_array_equal on f(a[:n]) against f(a)[:n] for all four functions, at n in (window, window+1, len(a)-1), over window in {5, 20} and offsets {0, 1e8} — 16 comparisons per parametrisation, bit-exact. Also repointed the _offset header comment at the test that actually runs, since citing a skipped one was the substance of the finding.

Verification

Branch at 5a6171e. uv run pytest -q -W error — 1122 passed, 1049 skipped, 1 xfailed. uv run pre-commit run --all-files — all hooks pass, including ty and stubtest.

Checked that the new test discriminates: it's the full-series-mean offset it has to reject, and that offset changes the emitted prefix as soon as the appended values move the mean, which assert_array_equal catches with no tolerance to absorb it. The n = window case is the tightest — the prefix is exactly the window _offset averages, so an offset defined over any wider range disagrees immediately.

move_corr's clamp is inert on well-conditioned input: standard_normal(200) at window=20 gives the same output either way, and max|corr| on 300-long float32 and float64 series offset to 1e6 stays at 0.58 and 0.62 — the clamp only fires where the unclamped variance was already negative, which is only reachable through rounding.

CI is running on the new head; I'll follow up here if it comes back red.

@numbagg-bot numbagg-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both points from the last round land: move_corr's var_a/var_b now clamp the same way move_var does, and test_appending_doesnt_change_earlier_results pins the property that ruled out the full-series mean. I re-derived the second one independently — min_count=3 with window=20, and a series whose first ten values are NaN (so _offset takes the fallback scan), both hold bit-exact across truncations, so the property isn't only true for the default min_count the new test exercises. pytest -W error --skip-slow is 752 passed here, and the test matrix is green on 5a6171e across all six OS/Python jobs.

One finding on the increment.

None of the three clamps is pinned by a test. I reverted all three — move_std's variance = max(...), move_var's out[i] = max(...), and the two move_corr lines this commit adds — and ran the full suite: 752 passed, 1419 skipped, 1 xfailed, identical to the clamped run. test_moving.py alone is 92 passed either way. So the behaviour change this commit makes — move_corr(a, a, window=5) going from -1.0 to NaN on a degenerate window — is unobservable to CI, and a later refactor that drops a max(..., 0.0) while cleaning up would meet nothing. That matters more here than it usually would, because the offsetting made the clamps harder to reach: the reproducer in the PR body (np.full(20, 1e8)) now leaves ai exactly 0.0, so it no longer produces the negative variance it was found with, and the case that does reach it is no longer the obvious one to reach for.

np.concatenate([np.zeros(5), np.full(25, 1e8 + 1)]) at window=5 fires all three at once — it's the same 1e8 + 1 series the PR body cites for the original -2.0 variance, with a small head so _offset doesn't fit the tail. Unclamped it gives move_var -2.0, move_std NaN out of sqrt, and move_corr(a, a) -1.0; clamped, 0.0 / 0.0 / NaN from index 9 on. Suggestion inline.

How this was measured

Merged tree at 5a6171e, built extension.

Clamps reverted by textual replacement of the three sites in numbagg/moving.py, then uv run pytest -q -W error --skip-slow:

all three clamps reverted   -> 752 passed, 1419 skipped, 1 xfailed
move_corr clamp only        -> 752 passed, 1419 skipped, 1 xfailed
test_moving.py, corr only   -> 92 passed, 8 skipped

Unclamped values on a = np.concatenate([np.zeros(5), np.full(25, 1e8 + 1)]), window=5, from a float64 njit replica of the move_var accumulator including the _offset subtraction:

min unclamped (asum_sq - asum**2/count)/(count-1)  ->  -2.0   at i in 9..13
move_var  clamped  [9:]  ->  all 0.0
move_std  clamped  [9:]  ->  all 0.0
move_corr clamped  [9:]  ->  all nan   (unclamped: -1.0)

np.concatenate([np.zeros(5), np.full(25, 123456789.123)]) — the series in the reply above — fires only move_corr's clamp; the (asum_sq - asum**2/count) form in move_var/move_std reaches exactly 0.0 there rather than going negative, which is why the assertion uses 1e8 + 1.

Also checked and found fine, so not part of the finding: numba lowers max(nan, 0.0) to nan rather than 0.0 (verified directly under @njit), so none of the clamps can turn a NaN-contaminated window into a spurious zero. An inf anywhere in the input still yields an all-NaN tail, but it did before the offsetting too — asum -= aold with aold = inf poisons the accumulator either way — and an inf inside the first window now also poisons _offset, which reaches the same all-NaN output rather than a new one. _offset's fallback scan stays prefix-consistent as its comment claims: a 10-NaN head with window=10 compares bit-exact against truncations at n in (12, 20, 39).

func(a[:n], b[:n], window=window),
func(a, b, window=window)[:n],
err_msg=f"{func.__name__}, n={n}",
)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pins all three clamps in one input, and passes as written on 5a6171e (pytest -W error). Index 9 is the first window fully inside the tail; 1e8 + 1 rather than a round 1e8 because a round one leaves ai exactly 0.0 after the offset and never reaches the clamp.

Suggested change
)
)
def test_numerical_issues_degenerate_window_clamps():
# A small head followed by a large near-constant tail: `_offset` averages the
# head, so it doesn't fit the tail and the sums of squares still cancel to a
# slightly negative number. Unclamped, that surfaces as a negative variance
# from `move_var`, a NaN out of `sqrt` in `move_std`, and a series
# anticorrelated with itself from `move_corr`. Reverting any of the three
# clamps leaves the rest of the suite passing, so pin them here.
a = np.concatenate([np.zeros(5), np.full(25, 1e8 + 1)])
np.testing.assert_array_equal(move_var(a, window=5)[9:], 0.0)
np.testing.assert_array_equal(move_std(a, window=5)[9:], 0.0)
assert np.all(np.isnan(move_corr(a, a, window=5)[9:]))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied with one amendment, in d111f20: the 1e8 + 1 series pins move_var and move_std, but not move_corr — its unclamped var_a/var_b are exactly 0.0 there, so the pre-existing var_a_var_b > 0 guard already emits NaN and reverting the clamp leaves the assertion passing. Added the 123456789.123 series alongside it for the move_corr case, where the variances round to -4.0 and the unclamped answer is -1.0. Per-site revert results in the conversation comment.

Reverting any of the clamps left the whole suite passing. Pins them on two
series: a small head followed by a large near-constant tail at 1e8 + 1 for
move_var/move_std, and at 123456789.123 for move_corr, whose variances only
round negative — rather than to exactly 0.0 — on the latter.
@numbagg-bot

Copy link
Copy Markdown
Collaborator Author

Finding taken; pushed as d111f20. I reproduced the gap first — with all four clamp sites reverted and the new test deselected, uv run pytest -q -W error gives 1122 passed, 1049 skipped, 1 deselected, 1 xfailed, i.e. every other test in the suite still passes — so the behaviour was indeed unobservable to CI.

The suggested assertion needed one amendment before it pinned what it claims to. On np.concatenate([np.zeros(5), np.full(25, 1e8 + 1)]), move_corr's unclamped var_a and var_b come out as exactly 0.0, not slightly negative, so the pre-existing var_a_var_b > 0 guard already emits NaN and move_corr's clamp is inert on that input: reverting it leaves the suggested test passing. The 123456789.123 series from the previous round is the one that discriminates — there the variances round to -4.0, their product is +16.0, the guard passes, and the unclamped answer is -1.0. So test_numerical_issues_degenerate_window_clamps uses both series: 1e8 + 1 for move_var/move_std, 123456789.123 for move_corr. The comment in the test says why each is there, since the obvious instinct on reading it is to collapse them into one.

PR body updated with the same scoping.

Per-site verification

Branch at d111f20, built extension. Each clamp site reverted by textual replacement in numbagg/moving.py, then uv run pytest numbagg/test/test_moving.py -q -W error -k degenerate_window_clamps:

move_std   variance = max(...)          reverted -> 1 failed   (nan from sqrt)
move_var   out[i] = max(...)            reverted -> 1 failed   (-2.0)
move_corr  var_a = max(...)   alone     reverted -> 1 passed
move_corr  var_b = max(...)   alone     reverted -> 1 passed
move_corr  var_a and var_b   together   reverted -> 1 failed   (-1.0)

move_corr's two sites mask each other individually: with one clamped and one not, the product is -0.0, the guard fails, and NaN comes out anyway — which is the correct answer, so a single-site revert isn't a behaviour change to catch. Both together is the reachable regression, and the test fails on it.

Unclamped accumulator values at i = 10, window=5, from a float64 replica of the move_corr loop including the _offset subtraction:

series            var_a   var_b   var_a*var_b   cov
1e8 + 1            0.0     0.0        0.0        0.0    -> guard fails, nan either way
123456789.123     -4.0    -4.0       16.0       -4.0    -> guard passes, corr = -1.0

uv run pytest -q -W error on d111f20 is 1123 passed, 1049 skipped, 1 xfailed; uv run pre-commit run --all-files passes all hooks including ty and stubtest.

@numbagg-bot

Copy link
Copy Markdown
Collaborator Author

A review on #767 flagged a look-ahead in that PR's offset, and it reproduces here too — I built this branch (d111f20) in a worktree and ran it rather than inferring from the shared shape.

_offset(a, window) averages the first window values unconditionally, but a windowed result is emitted as soon as the count reaches min_count. With min_count < window the value written at time t is therefore a function of a[t+1 : window] — the same dependence on unseen values the comment above _offset rules out for the whole-series mean, just bounded to the first window.

It isn't only theoretical, because the offset sets the rounding floor everywhere. When the first window holds a value much larger than a partial window's own values, the offset is orders of magnitude off for those early steps and cancellation gets worse than with no offset at all. With window=10, min_count=2, col = [1, 2, ..., 20] and col[9] = 1e12 (second series 2*col + 1 for the pairwise functions):

at t=3 this branch exact
move_cov -5592405.33 3.3333
move_corr nan 1.0
move_var 0.0 1.6667
move_std 0.0 1.2910

move_var/move_std come back as 0.0 rather than as an obviously wrong magnitude because this PR's variance clamp catches them first — worth knowing, since it means a bound-shaped or non-negativity-shaped test passes on this input.

The remedy that worked on #767 is to bound the scan by min_count as well: _offset(a, min(window, min_count)) at each call site, with min_count read after its max(min_count, 1) normalisation. It keeps the outlier dilution the helper exists for, and it is look-ahead-free because a non-NaN result at t already requires t >= min_count - 1, so those rows are always in hand. window still bounds it in turn, since min_count may nominally exceed the window.

test_appending_doesnt_change_earlier_results can't catch this, on either PR: window <= n_obs is enforced, so every admissible prefix already contains the whole first window. A test needs to compare against the exact answer for a partial window — #767's test_offset_doesnt_look_ahead_inside_the_first_window is the shape that worked, and parametrising the existing offset-invariance cases over min_count covers the regime more broadly.

Leaving this here rather than pushing, since the fix belongs to this PR's own diff.

@max-sixty

Copy link
Copy Markdown
Collaborator

Closing this version because the fixed prefix anchor is not correct across the supported rolling semantics. When min_count < window, it reads observations that should not affect an early result; after a level change, the same fixed anchor can also remain badly scaled after the original values have left the window, leaving inaccurate results including correlations outside [-1, 1].

The float64-promotion work, regression cases, and performance measurements remain useful. A replacement should choose its anchor without looking ahead, adapt when the live window moves far from that anchor, and be evaluated separately on ordinary data and on cases that take a stability path. We will reconsider this as a fresh design rather than add more patches to this PR.

This was written by Codex on behalf of @max-sixty

@max-sixty max-sixty closed this Aug 29, 2026
@numbagg-bot

Copy link
Copy Markdown
Collaborator Author

Understood on the close — not relitigating it. One scoping point for the fresh design, since it isn't visible from this PR: the same fixed prefix anchor is already on main. #767 merged it into numbagg/moving_matrix.py about twenty hours before this close, using the identical _leading_rows_shift(a, min(window, min_count)) construction at move_corrmatrix and move_covmatrix.

Your first objection is handled there — the min_count bound is what stops the look-ahead. Your second one isn't, and it reproduces on main today: with a level change, the covariance at a step whose window sits entirely past the change comes back [0, 2.22, 2.22, 6.67] against an exact [0.70, -0.39, -0.39, 1.64], sign flipped on the off-diagonal and the first variance clamped to zero.

The one thing that argues against urgency: I built 01b1453^ and ran the same input, and the unoffset kernel is equally wrong there ([0, 0, 0, 6.67]), so this is a limitation the anchor never fixed rather than a regression #767 introduced. I also swept 30 seeds × 3 step sizes × 3 window/min_count settings for the out-of-range correlations you mention and didn't find any on main — the diagonal clamp catches them, and the observable symptom is the wrong covariance rather than a correlation past 1. Pre-#767 did produce 1.15 on one of those inputs.

So the redesign has a live call site to cover, not just this closed diff. #759's nancovmatrix / nancorrmatrix anchor on the first valid observation instead, and being whole-array reductions they have no window to drift away from, so I don't think your second objection reaches them. Not proposing a patch — flagging it so the anchor choice gets made once across all three.

Reproduction

Against main at f35203d, and 01b1453^ (19f281c, pre-#767) built in a worktree:

import numpy as np
from numbagg import move_corrmatrix, move_covmatrix

a = np.random.default_rng(0).standard_normal((60, 2))
a[20:] += 1e8          # level change; rows 0-9 set the anchor and leave the window by t=30

cov = move_covmatrix(a, window=10, min_count=10)
corr = move_corrmatrix(a, window=10, min_count=10)
w = a[31:41]
print("  move_covmatrix :", np.round(cov[40].ravel(), 4))
print("  np.cov exact   :", np.round(np.cov(w.T, ddof=1).ravel(), 4))
print("  move_corrmatrix: %.4f" % corr[40, 0, 1])
print("  np.corrcoef    : %.4f" % np.corrcoef(w.T)[0, 1])

At t = 40 the window is rows 31–40, all of it past the step:

move_covmatrix move_corrmatrix
main (f35203d) [0, 2.2222, 2.2222, 6.6667] nan
pre-#767 (19f281c) [0, 0, 0, 6.6667] nan
exact (np.cov / np.corrcoef) [0.7007, -0.3874, -0.3874, 1.6394] -0.3614

The correlation is NaN on both sides because the first variance rounds non-positive and hits the var_i > 0 guard, so the correlation is undefined rather than wrong here; the covariance is the entry that shows the error.

The module comment #767 added already documents the crossover from its own side — it puts the point where the anchor becomes worse than none at roughly min(window, min_count) / sqrt(eps) — but it frames it as a scanned outlier in the leading rows, not as a level change that leaves the anchor behind. Both are the same stale-reference failure.

numbagg-bot added a commit that referenced this pull request Sep 19, 2026
#758's final diff clamps the variances only; it adds no clip on the
correlation and its body defers bounding move_corr to a separate design
call. Both correlation comments said it proposed the bound.
max-sixty pushed a commit to max-sixty/tend that referenced this pull request Sep 22, 2026
…d to what it read (#1379)

`/tend-ci-runner:ground-claims` names the shape where a session reads
the wrong *commit* for a past run, but nothing named its sibling for a
past *pull request*. A PR's body, comments, and reviews record what was
**discussed**; only its diff records what was **proposed**, and on a PR
closed unmerged the two routinely diverge — the thread is exactly where
the author explains what they chose *not* to do. A session that reads
`gh pr view <n> --json body,comments,reviews` and stops there states
what the PR's code proposed from its prose. `/tend-ci-runner:open-pr`'s
**Fetch the prior rejection before re-deriving a fix** actively sends
sessions to read closed PRs, and its recipe fetched only the thread.

The second gap is in the layer that should catch the first. The
truncation example (`head -120`) sat inside **An exhaustiveness claim
needs a method that could have found a counterexample**, whose trigger
is publishing "all", "every", "none". A bounded read that underwrites a
*single specific* claim never trips that trigger, so a `| head -N` that
stopped short of the hunk deciding the claim exits 0 and reports back as
a check that passed — turning unverified into verified without any
exhaustiveness word being published.

## Changes

- **`ground-claims`** — new entry: a claim about what a past PR proposed
is read from its diff, placed beside the past-run sibling it mirrors.
- **`ground-claims`** — new entry: a bounded read verifies only the part
it read, stated for a truncated *document* as much as a truncated result
set, and for a single claim as much as an exhaustiveness claim. The
`head -120` clause moves out of the exhaustiveness entry so truncation
has one home rather than two partial ones.
- **`open-pr`** — the prior-rejection recipe now reads `gh pr diff <n>`
alongside the thread. That section's own closing question — whether a PR
was closed on the **code** or on the **approach** — can't be answered
from the discussion alone.

## Verification

Re-checked the reporter's case directly rather than from the issue body:
[numbagg/numbagg#758](numbagg/numbagg#758) is
closed, and its diff clamps the two variances (`var_a = max(asum_sq *
count_reciprocal - avg_a**2, 0.0)`, same for `var_b`) while adding no
clip to the correlation output — so a comment describing it as having
proposed bounding `move_corr` was wrong, which
[numbagg/numbagg#825](numbagg/numbagg#825)
corrected on merge. The deciding hunk sits past line 150 of that diff,
which is how a truncated read of it came back clean.

`uv run pytest generator/tests/test_repo_pins.py` (46 passed) and `uv
tool run pre-commit run --all-files` (all 12 hooks) pass on this branch.

This is bundled text, so it reaches every consumer on the next release;
a maintainer decides whether these are the right two rules and whether
the `open-pr` recipe line belongs in the same change.

Closes #1378 — automated triage

---------

Co-authored-by: tend-agent <[email protected]>
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.

2 participants