Skip to content

fix: stabilize variance aggregates at large offsets - #27549

Merged
XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
Lundomn:fix/stable-variance-large-offset
Aug 28, 2026
Merged

XuPeng-SH merged 17 commits into
matrixorigin:mainfrom
Lundomn:fix/stable-variance-large-offset

Conversation

@Lundomn

@Lundomn Lundomn commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • BUG

Which issue(s) this PR fixes:

Fixes #27543

What this PR does / why we need it:

Replace the unstable sum-of-squares variance calculation with Welford online state and Chan parallel merging. DECIMAL aggregates retain an exact origin and convert only the deviation, preventing loss of small variance around large offsets.

Validation

  • go test ./pkg/sql/colexec/aggexec -count=1
  • focused go test -race ./pkg/sql/colexec/aggexec
  • go test ./pkg/sql/colexec/group -count=1
  • go vet ./pkg/sql/colexec/...
  • aggexec coverage: 79.0%
  • latest-main isolated SQL regression (DOUBLE/DECIMAL, NULL, index before/after)
  • 100k Kafka→MatrixOne regression and 500k transactional/replay regression

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@matrix-meow matrix-meow added the size/M Denotes a PR that changes [100,499] lines label Aug 24, 2026
@mergify mergify Bot added the kind/bug Something isn't working label Aug 24, 2026
@Lundomn
Lundomn requested a review from LeftHandCold as a code owner August 24, 2026 10:16
@Lundomn
Lundomn force-pushed the fix/stable-variance-large-offset branch from fcd7648 to 913ab79 Compare August 25, 2026 02:36

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review of exact head 0cea946. The rewrite closes my previous DECIMAL(38,20) subtraction-overflow case, and the normalized state plus v30/legacy protocol gate close the later M2-overflow and mixed-version state-layout findings. One finite-result intermediate overflow remains.

In pkg/sql/colexec/aggexec/vardev2.go:300, the carried normalized variance is multiplied before it is divided. With FLOAT64 rows [0, 2e154, 1e154], after two rows the mean is 1e154 and VAR_POP state is 1e308. The third row equals the mean, so its increment is zero and the exact next VAR_POP is 1e308 * 2 / 3 = 6.666666666666667e307, which is finite. The current left-associative expression evaluates 1e308 * 2 as +Inf first, then divides by 3, so BulkFill followed by Flush returns +Inf. I reproduced this with an operator-level regression; require.False(math.IsInf(result, 0)) fails.

Please evaluate the count ratio before multiplying (or use the scaled helper) and retain this counterexample as a regression.

Comment thread pkg/sql/colexec/aggexec/vardev2.go Resolved

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Reviewed exact head 0cea946. This head does fix the previously reported Decimal128 deviation, unnormalized-M2 overflow, and mixed-version state-layout problems, but blocking numeric edges remain.

[P1] The old normalized variance is still multiplied before it is divided at pkg/sql/colexec/aggexec/vardev2.go:300. For the finite input [1.3e154, -1.3e154, 0], the first two rows produce a finite state variance of 1.69e308. The third row evaluates 1.69e308 * 2 before / 3, stores +Inf, and returns +Inf although VAR_POP is the representable 1.1266666666666666e308. A temporary focused test failed deterministically. Apply the same scaled product/quotient treatment to the existing-variance rescale and add this three-row regression.

[P1] A raw variance state cannot preserve a representable STDDEV when only the squared result exceeds float64. STDDEV_POP over [1e200, -1e200] is the finite 1e200, but updateVarianceState stores +Inf and getResult returns sqrt(+Inf). The same issue affects resident, DISTINCT, and merged execution. The shared VAR/STDDEV state needs an exponent-scaled representation or a STDDEV-safe equivalent, with resident and merge tests.

Performance: the unconditional Frexp/Ldexp path is now in every non-DISTINCT variance row. On this head, a focused M4 microbenchmark measured 8.58 ns/update versus 5.63 ns for the arithmetic path, about 52 percent slower in the recurrence itself. Keep the overflow-safe fallback, but use a finite direct-product fast path for normal values.

Please also revert or split the unrelated HNSW BVT edits. They remove the pre-delta f32 ANN oracle and add an unconditional sleep(20), deterministically increasing the suite while explicitly avoiding a stale-cache behavior unrelated to #27543. The existing variance-focused tests pass, but they do not cover the two counterexamples above.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Re-review after the rebase: the variance implementation and its tests are byte-for-byte unchanged from 0cea9464, so the blockers from my previous review remain on this head.

  1. The normalized update still multiplies before dividing (variance * count / nextCount). [1.3e154, -1.3e154, 0] therefore returns +Inf although the finite VAR_POP result is about 1.1266666666666666e308.
  2. STDDEV still stores raw variance and loses finite answers when only the square overflows: STDDEV_POP([1e200, -1e200]) returns +Inf, while the correct result is 1e200.
  3. The unconditional Frexp/Ldexp path remains roughly 52% slower in the focused update microbenchmark; use a finite direct arithmetic fast path with exponent scaling only near overflow/underflow.
  4. The PR still contains unrelated HNSW BVT edits; keep those out of this numerical fix.

Please address the finite-result counterexamples and add regression coverage before approval.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-review of exact head a1dd839498bbb584644b4e4db3a7a7b08d4f6d13 against merge base 77c9ae710c991b219d1aabfb245cb9109dc5cd3c completed. The scaled normalized-variance representation closes the remaining finite-result overflow cases, including the multiply-before-divide counterexamples and finite STDDEV with unrepresentable squared variance. The common path now stays on direct arithmetic and only falls back to Frexp/Ldexp near overflow or underflow; the unrelated HNSW edits are gone. Decimal deviation handling, resident/DISTINCT/merge execution, sample scaling, and the v30 rolling-upgrade gate/legacy state layout have focused regression coverage. I found no remaining correctness, performance, compatibility, or unhappy-path blocker. Exact-head CI is green. Local focused binaries compiled but could not run in this checkout because the host lacks thirdparties/install/lib/libmo.dylib; that is an environment limitation, not a PR failure.

@aunjgr aunjgr left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approved at exact head a1dd839498bbb584644b4e4db3a7a7b08d4f6d13 against base 77c9ae710c991b219d1aabfb245cb9109dc5cd3c.

The normalized Welford/Chan representation restores translation stability without retaining an overflow-prone M2. The exponent sidecar closes finite VAR results whose intermediate square/weighted sum overflows and finite STDDEV results whose variance itself exceeds float64; ordinary values remain on the direct arithmetic fast path. Decimal inputs retain an exact origin and convert only deviations, including the exact-subtraction overflow fallback. Resident, DISTINCT, merge, population/sample, overflow, underflow, and large-offset cases are covered.

The aggregate-state layout change is capability-gated: pre-v30 remote execution uses the legacy three-vector implementation, the coordinator prevents incompatible multi-stage/shuffle placement, and remote validation fails closed. Current-format spill and mixed-version remote ownership are therefore separated. I found no remaining correctness, performance, compatibility, cleanup, or growth blocker.

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-reviewed the complete diff and all historical reviews/threads at exact head c93d071, including the delta after my prior review of 0cea946 and the v32 protocol rebase.

The earlier Decimal128 subtraction, normalized-variance rescaling, exponent-scaled STDDEV, and mixed-version state-layout blockers are closed. The current v32 wire round trips and fails closed across mismatched layouts; resident, DISTINCT, merge, sample/population, spill-facing state serialization, and rolling-upgrade gates were checked. Full aggexec/group/compile tests, focused race suites, vet, build, and diff check pass.

One supported exact-numeric large-offset case remains silently wrong: integer inputs are converted to float64 before the new stable recurrence, so unit differences above 2^53 disappear. The inline operator-level counterexample returns zero instead of the exact representable variance 1.25.

Comment thread pkg/sql/colexec/aggexec/vardev2.go Resolved

@aptend aptend left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Deep re-review of exact head 28a1ac8, including the complete diff, all historical reviews/threads, and the delta since my previous review at c93d071. The exact native origin added for BIGINT, BIGINT UNSIGNED, and BIT closes the remaining >2^53 unit-offset failure in resident, DISTINCT, merge, and serialized-state continuation paths. The earlier decimal-deviation, scaled finite VAR/STDDEV, and rolling-upgrade state-layout findings remain closed behind the v35 gate. Owning-package build, vet, full tests, focused race tests (20 iterations), benchmark, and diff check pass; exact-head CI is green. I found no remaining blocker.

@Lundomn

Lundomn commented Aug 28, 2026

Copy link
Copy Markdown
Contributor Author

@Mergifyio queue

@mergify

mergify Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-08-28 07:31 UTC · Rule: main · triggered by @Lundomn with the @mergifyio queue command
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-08-28 07:57 UTC · at 32975b1efbe56376c92c9c6a5173ac3e806a3f9d

This pull request spent 25 minutes 42 seconds in the queue, with no time running CI.

Waiting for
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of: [🛡 GitHub branch protection]
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
All conditions
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / UT Test on Ubuntu/x86
    • check-skipped = Matrixone CI / UT Test on Ubuntu/x86
    • check-success = Matrixone CI / UT Test on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone CI / SCA Test on Linux/arm64
    • check-skipped = Matrixone CI / SCA Test on Linux/arm64
    • check-success = Matrixone CI / SCA Test on Linux/arm64
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-skipped = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
    • check-success = Matrixone Compose CI / multi cn e2e bvt test docker compose(PROXY)
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Utils CI / Coverage
    • check-skipped = Matrixone Utils CI / Coverage
    • check-success = Matrixone Utils CI / Coverage
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-skipped = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
    • check-success = Matrixone UT Coverage / UT Coverage on Ubuntu/x86
  • any of [🛡 GitHub branch protection]:
    • check-neutral = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-skipped = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
    • check-success = Matrixone Standlone CI / multi CN e2e BVT Test on Linux/x64(COMPOSE, PESSIMISTIC)
  • #review-threads-unresolved = 0 [🛡 GitHub branch protection]
  • github-review-approved [🛡 GitHub branch protection]

Reason

Pull request #27549 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Failing checks:

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

This branch was previously deployed

1 inactive deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kind/bug Something isn't working size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: VAR_POP / STDDEV_POP lose small variance under large numeric offsets

5 participants