Skip to content

[Compatibility]: accept JSON operands in numeric aggregates - #28946

Merged
XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-28868-json-numeric-agg-20260915
Sep 29, 2026
Merged

XuPeng-SH merged 12 commits into
matrixorigin:mainfrom
VioletQwQ-0:codex/issue-28868-json-numeric-agg-20260915

Conversation

@VioletQwQ-0

@VioletQwQ-0 VioletQwQ-0 commented Sep 15, 2026 •

Copy link
Copy Markdown
Collaborator

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #28868

What this PR does / why we need it:

Numeric aggregates over JSON use a dedicated MySQL numeric-context conversion before the existing DOUBLE aggregate executors. JSON null, arrays and objects contribute zero with warnings; booleans contribute 1/0; numeric-prefix strings retain their numeric prefix and a truncation diagnostic. SQL NULL is skipped. Explicit numeric CAST retains its separate existing semantics and nullable metadata.

The CR repair preserves the warning for a JSON string such as "12x" (SUM=12; SHOW WARNINGS reports 1292), corrects window-plan assertions to check JSON_AGG_TO_DOUBLE, and fixes the sample-aggregate oracle: two contributing JSON nulls are two zeros, so VAR_SAMP/STDDEV_SAMP return zero, while fewer than two contributing values return SQL NULL.

Follow-up SQL planner regressions exposed that VARIANCE/STD/STDDEV bypassed the numeric-context conversion. Their names now enter the same existing coercion boundary as VAR_POP/STDDEV_POP. Regression tests exercise ordinary and window SQL binding, warning-sink precedence and diagnostic codes, SQL NULL versus JSON null, and effective sample cardinalities 0/1/2. No new function ID, executor, public API, storage format or configuration is added by this follow-up.

Validation at 3de957a54b433492d204802edb75e77d5ca21492 (base b9013dc6bb058ec74935a62ac3a35f57d13c2f98):

  • PASS: baseline focused tests at 092b7215ddb744f77863e1097c121f151cd72d8a.
  • Regression proof: the three alias tests fail in both ordinary and window SQL binding before the one-line binder repair (six failing subtests); the repaired focused suite passes.
  • PASS: CGo-enabled focused tests (52 planner and 94 function test items), complete pkg/sql/plan and pkg/sql/plan/function tests with -count=1, and go vet for both packages.
  • INCONCLUSIVE: supplemental local golangci-lint v2.6.2 built with Go 1.26.4 was stopped after approximately 35 minutes without a diagnostic/result; exit 143 is operator termination, not a lint pass or a reported source failure. New-head CI SCA is pending
  • PASS: the canonical func_aggr_json_numeric BVT ran twice on the same isolated local instance, 26/26 statements each time; independent post-run checks found zero residual test tables after both rounds
  • PASS: formatting and git diff --check.
  • CI: fresh checks for this head are tracked separately; local results do not imply CI approval.

The BVT execution also exposed stale DOUBLE metadata in the expected output: [8,54,0] was corrected to [8,53,31], with numeric values, NULL behavior, warning text/code, and explicit CAST control unchanged.

Canonical BVT: test/distributed/cases/function/func_aggr_json_numeric.sql and .result. It covers mixed numeric/JSON-null/SQL-NULL results (AVG=1.625), DISTINCT null-only groups, sibling aggregates, explicit CAST control, window SUM, the prefix warning, and alias equivalence.

QA required: yes. Prepared statements, View/CTAS, real spill, cross-CN warning transport, deployment QA, and complete MySQL diagnostic parity for other JSON values remain outside this scoped acceptance. Intermediate-state round-trip UT is not real spill/remote evidence. This PR remains Ready for re-review and does not close the issue.

@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 →

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Addressed XuPeng-SH's first P2 at exact head d691fc19b1272baf7a32159cf03e3abd11bef27e.

Changes:

  • Added json_agg_to_double as the MySQL warning-conversion boundary for numeric aggregates.
    • booleans become 1/0
    • numeric-prefix strings keep their numeric prefix ("12x" → 12)
    • JSON null / arrays / objects contribute 0 with a truncated-value warning (not SQL NULL)
    • SQL NULL is still skipped
  • Binder now rewrites SUM/AVG/VAR_POP/VAR_SAMP/STDDEV_POP/STDDEV_SAMP JSON operands through that function.
  • Explicit CAST(json AS DOUBLE) is unchanged and still uses the strict JSON-to-DOUBLE contract.
  • Public BVT func_aggr_json_numeric updated (AVG/VAR/STDDEV for JSON-null rows; NOT NULL JSON null now yields 0). Added boolean / numeric-prefix / composite cases.
  • Unit tests updated to the MySQL conversion boundary.

Validation:

  • Unit: json_numeric_agg_test.go expectations recomputed for 0-contributing JSON null; new TestJSONNumericAggMySQLWarningConversion covers bool/prefix/null/composite.
  • BVT: test/distributed/cases/function/func_aggr_json_numeric.sql / .result on this head. Exact-head CI (including Compose/Proxy and preferably Pessimistic) is required.

Remaining (not closed):

  • Second same-instance BVT execution and independent teardown evidence is a host-run acceptance item and is not claimed here.

Please re-review this head.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Local same-instance BVT acceptance evidence for exact head 0a4c46e993 (includes json_agg_to_double selectList fix b17d0626d1).

Environment: local single-CN mo-service built from this branch (codex/issue-28868-json-numeric-agg-20260915), one instance, database bvt_accept.

Two consecutive executions of test/distributed/cases/function/func_aggr_json_numeric.sql on the same instance (no restart):

Key MySQL-conversion results (identical in Run 1 and Run 2):

Query Result
grp=1 SUM/AVG/VAR_POP/VAR_SAMP/STDDEV_POP/STDDEV_SAMP 6.5 / 1.625 / 1.421875 / 1.8958333333333333 / 1.192424001771182 / 1.3768926368215255
grp=2 DISTINCT family 5 / 1.6666666666666667 / 2.888888888888889 / 4.333333333333333 / 1.699673171197595 / 2.0816659994661326
NOT NULL JSON null SUM/AVG DISTINCT 0 / 0 (not NULL)
bool + "12x" + composite + JSON null SUM=13, AVG=2.6

Independent teardown after both runs: information_schema.tables for json_numeric_agg% → 0.

Also fixed a real bug found in host run: empty non-nil selectList made json_agg_to_double return only NULLs; now follows ShouldEvalAllRow (pushed as b17d0626d1).

This closes the two same-instance BVT executions + independent teardown residue requirement.

@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 at exact head 0a4c46e against base/merge-base 5aa23ca: REQUEST_CHANGES. I read the prior reviews, inline thread, author replies, delta since my c2f5c81 review, and the full PR diff. The earlier strict-CAST result mismatch is addressed for SQL aggregate binding by json_agg_to_double; current public BVT and author same-instance teardown evidence cover those value cases. Two blockers remain:

  1. [P2] pkg/sql/plan/function/func_cast.go:3001-3008 drops numeric-prefix truncation warnings. parseStringToFloat("12x", SQLCompatibilityMySQL) returns 12 with nil error because it consumes the decimal prefix, so this branch returns 12 without calling emit. Reproducer: aggregate a JSON string '"12x"' and inspect SHOW WARNINGS: the numeric result is 12 but the truncation warning promised by this MySQL-compatible aggregate boundary is absent. The repo already has appendNumericCoercionWarning for precisely this consumed-prefix case (func_cast.go:7110+); use equivalent detection here and add a warning-sink assertion. MySQL documents JSON numeric aggregation and numeric conversion/truncation behavior at https://dev.mysql.com/doc/refman/8.4/en/json.html and https://dev.mysql.com/doc/refman/8.4/en/type-conversion.html.

  2. [P2 — exact-head validation] The new tests still assert the old contract, leaving required UT/coverage CI red. pkg/sql/plan/json_numeric_aggregate_test.go:259 demands a direct CAST for every window aggregate, but the new binder correctly places json_agg_to_double there; all six subtests fail. pkg/sql/plan/function/json_numeric_agg_test.go:167-168 unconditionally fails for sample aggregates even when the 'json-null-is-zero' case contains TWO contributing JSON nulls, so VAR_SAMP/STDDEV_SAMP validly return 0 rather than SQL NULL. Local CGO-enabled focused tests reproduced both failures, matching CI run 35810263731. Update those oracles to the new conversion and cardinality semantics and rerun the required jobs.

Local make thirdparties and git diff --check passed; the focused pkg/sql/plan and pkg/sql/plan/function tests failed only in the cases described above. No temporary test or main-worktree changes were retained.

VioletQwQ-0 and others added 9 commits September 28, 2026 14:21
Route SUM/AVG/VAR_*/STDDEV_* JSON operands through json_agg_to_double
so booleans become 1/0, numeric-prefix strings keep their prefix, and
JSON null/composites contribute 0 with warnings. Explicit CAST(json AS
DOUBLE) keeps the strict JSON-to-DOUBLE contract.
A non-nil FunctionSelectList with an empty SelectList made Contains
return false for every row, so the conversion appended only NULLs.
Follow ShouldEvalAllRow like the other unary templates.
@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Updated in 092b721:

  • Numeric-prefix JSON strings now use the existing numeric-coercion warning helper. The warning-sink regression checks that "12x" yields 12 and one warning, while complete numeric strings stay warning-free.
  • Window aggregate tests now assert json_agg_to_double; the sample-aggregate oracle correctly permits zero for two contributing JSON null values while preserving the singleton SQL NULL check.
  • Resolved the current base conflicts, retaining the persisted-expression observer and existing function IDs. Added a canonical SQL/expected-result check for SHOW WARNINGS after aggregating "12x".

Validation: focused JSON function/planner tests passed; the full pkg/sql/plan/function and pkg/sql/plan suites passed (21.781s and 14.908s), and git diff --check passed. Native dependencies were built in this checkout. The new SQL warning case has not yet been executed locally, and new-head CI remains pending; neither is claimed as PASS.

@VioletQwQ-0

VioletQwQ-0 commented Sep 28, 2026 •

Copy link
Copy Markdown
Collaborator Author

@XuPeng-SH CR follow-up at 3de957a54b433492d204802edb75e77d5ca21492:

  1. Nullable metadata / DISTINCT group preservation: the existing JSON numeric CAST fix remains in pkg/sql/plan/base_binder.go:10020 (appendCastBeforeExprWithOverload). TestJSONNumericAggregateCastDoesNotInheritJSONNotNull and TestNumericCastKeepsNotNullSourceContract pass. Aggregate numeric context now treats JSON null as zero; SQL NULL is skipped. The BVT retains the JSON-null-only group for single DISTINCT and sibling aggregates, and its explicit COUNT(CAST(j AS DOUBLE)) control still returns zero for JSON null.
  2. Numeric-context conversion: JSON aggregate inputs use the dedicated conversion before existing DOUBLE executors; prefix warning and sample/window repairs are retained. Added ordinary/window SQL regressions caught and fixed VARIANCE/STD/STDDEV bypassing conversion, with six failing subtests before the one-line repair.
  3. Repeatability and cleanup: PASS: the canonical func_aggr_json_numeric BVT ran twice on the same isolated local instance, 26/26 statements each time; independent post-run checks found zero residual test tables after both rounds. Each residue query is independent and occurs after the case's final DROP, before the next run's entry DROP IF EXISTS; the instance is not restarted between runs. The owned service subsequently exited normally and its ports were released.

Validation: focused tests (52 planner / 94 function test items), both full owning packages with -count=1, go vet, and diff checks PASS. INCONCLUSIVE: supplemental local golangci-lint v2.6.2 built with Go 1.26.4 was stopped after approximately 35 minutes without a diagnostic/result; exit 143 is operator termination, not a lint pass or a reported source failure. New-head CI SCA is pending. The stale BVT DOUBLE metadata was corrected without changing numeric/NULL/warning or explicit-CAST expectations.

The PR description now records this exact head and the remaining scope gaps. CI/reviewer approval, deployment QA, merge, and issue closure remain separate. Please re-review this head.

@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 at exact head 3de957a54b433492d204802edb75e77d5ca21492 against merge-base b9013dc6bb058ec74935a62ac3a35f57d13c2f98: APPROVE. I read the full 11-file PR diff, prior reviews, the resolved inline thread and all author replies, and compared the changes since my previous 0a4c46e993 review (accounting for the rebase).

The previous blockers are closed in code, not merely by the replies: pkg/sql/plan/function/func_cast.go:3036-3130 now routes JSON numeric-aggregate values through warning conversion; its string case uses appendNumericCoercionWarning, so a JSON string "12x" contributes 12 and emits diagnostic 1292 while SQL NULL is skipped and JSON null contributes zero. pkg/sql/plan/base_binder.go:3824-3850 applies this to ordinary and prepared/window aggregate binding, including VARIANCE/STD/STDDEV aliases that the prior candidate missed; explicit CAST remains on its separate strict path. pkg/sql/plan/base_binder.go:10030-10040 retains nullable metadata for JSON→numeric CAST in the DISTINCT rewrite. The new/updated function and planner UTs cover the previous warning-sink, window, sample-cardinality, and alias failures; the public BVT covers mixed values, DISTINCT null-only groups, explicit CAST control, and SHOW WARNINGS. The new function ID 584 is registered and below FUNCTION_END_NUMBER 585.

git diff --check passed. The author reports two same-instance BVT passes with independent teardown checks; I inspected the canonical SQL/result pair but did not independently run a service. The fresh exact-head CI UT, coverage, SCA, and two BVT topology jobs are still running at review time, so this approval does not claim those checks have passed. Prepared/View/CTAS, real spill/remote, and cross-CN warning propagation remain documented follow-up QA, not proven by this review. I found no remaining blocking defect in this PR's scoped implementation.

@VioletQwQ-0

Copy link
Copy Markdown
Collaborator Author

Conflict and exact-head coverage repair are published at 1df5f1a. The merge parent is current main d8152cb; the function-ID collision preserves main JSON_DEPTH=584 and assigns the new internal JSON_AGG_TO_DOUBLE function ID 585. Added branch-complete unit coverage for JSON numeric aggregate scalar kinds, malformed values, selection masks, all-null batches, and arity validation. With workspace-local third-party artifacts, focused function/planner tests pass; changed-function coverage is 100% for jsonAggToFloat64 and 83.3% for JsonAggToDouble. Fresh CI has started on this head. No re-review or merge is requested by this update.

@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 review at 1df5f1a: APPROVE within the stated numeric-aggregate scope. All 11 changed files, prior reviews, existing binder/aggregate/conversion owners and warning-aware constant folding reviewed. No CI wait.

Historical blockers are closed: explicit CAST nullability remains correct for DISTINCT; aggregate JSON coercion uses the dedicated warning conversion; numeric-prefix diagnostics use the existing warning owner; ordinary/prepared/window aliases converge on that boundary; sample cardinality and stale window test expectations are corrected. Author evidence for two BVT passes and independent same-instance teardown was reviewed, not rerun as a full BVT here.

Independent exact-head black-box challenge used a real embedded CN/TN cluster and MySQL client. Mixed JSON null, prefix string, array and SQL NULL produced SUM=12, AVG=4, VAR_POP=32 and VAR_SAMP=48, with 1265/1292 diagnostics. Checked window running totals, DISTINCT, empty input, repeat SQL PREPARE, and one binary prepared statement with null→2→array→3 parameters (0→8→0→12 over four rows), including diagnostics clearing on valid input. Explicit strict CAST still errors and the same connection immediately returns SELECT 1. Controlled-CGo integration run passed (scenario 11.51s).

Design: one conversion boundary before existing DOUBLE aggregate executors is proportionate; no new aggregate state machine or storage path is needed. The low-level direct type matcher still uses strict CAST, so future direct binder callers must not bypass the SQL coercion owner. I found no reachable new caller defect in this review.

Nonblocking cleanup: the unused diagnostic boolean returned by jsonAggToFloat64 is misleading when named gotNull in tests; simplify or give it a real owner. TestJSONNumericAggCastErrorsDoNotPoisonRetry currently exercises neither an error nor a retry; rename it to its actual NULL-control behavior or replace it with a real recovery assertion. Consolidate such tests instead of extending duplicate setup.

This review does not claim real spill/cross-CN warning transport, View/CTAS or deployment QA, and does not close #28868.

@mergify

mergify Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-09-29 09:03 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-09-29 10:24 UTC · at 089bdeb1b4bf93d590d0fe693e73f481fadcd4e0

This pull request spent 1 hour 20 minutes 59 seconds in the queue, with no time running CI.

Reason

Pull request #28946 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.

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.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

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 kind/test-ci size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants