Skip to content

fix(sql): preserve COLLATE expressions and resolve coercibility (C04) - #29892

Merged
XuPeng-SH merged 45 commits into
matrixorigin:mainfrom
ck89119:issue-25096-main
Oct 16, 2026
Merged

XuPeng-SH merged 45 commits into
matrixorigin:mainfrom
ck89119:issue-25096-main

Conversation

@ck89119

@ck89119 ck89119 commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

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

Which issue(s) this PR fixes:

Implements C04 for #25096 under #29479, including the explicit-conflict cases from #25303. The original issue remains open for the other collation workstreams and release gates.

What this PR does / why we need it:

The parser discarded expression COLLATE clauses, so binding could lose explicit precedence and silently accept incompatible explicit collations. This change preserves the clause in the AST and resolves one effective domain before comparison or result-type inference.

  • Apply coercibility before merging equal-priority candidates. Report MySQL errors 1267 for incompatible explicit mixes or equal-priority semantic-version conflicts, 1273 for unknown rules, and 1253 for charset mismatches. Typed NULL keeps its static CAST domain; the consumer integration distinguishes rejected cross-version mixes from valid ordinary and native-domain NULLs.
  • Carry the resolved domain through comparisons, IN/BETWEEN, casts, CASE/IF/COALESCE, concatenation, UNION/VALUES, folding, variables, and prepared parameters. Type inference respects deferred evaluation and keeps source nodes and cached plans intact.
  • Use the resolved text comparator for LEAST/GREATEST while returning the original selected value. Preserve COLLATE through qualification, window traversal, and ROLLUP rewriting.
  • Cover indexed access, View/CTAS, scalar/vector execution, NULL, operand reversal, and repeated prepared execution with changing text/binary/NULL parameters.
  • Preserve scalar subquery projection provenance and explicit precedence through implicit width and PAD SPACE comparison casts, including CHAR window keys. Validate COLLATE against its operand charset before VALUES assignment conversion.
  • Validate functional index metadata using value-bearing type fields across catalog round-trips; match fully bound expressions across old/new provenance without disabling historical indexes.
  • Accept COLLATE-qualified NAME_CONST literal values while retaining its non-literal rejection rules.
  • Traverse COLLATE operands in frontend database remapping, prepared SET scalar-subquery collection, and sidecar table rewriting. A collated scalar subquery now reads the remapped database and can be materialized by EXECUTE SET without a subquery-count mismatch.
  • Select the numeric domain for numeric IN/NOT IN/BETWEEN before checking text-rule conflicts. Keep string-left IN and all-text BETWEEN conflict checks, and preserve numeric typed NULL and repeated prepared execution.
  • Validate COLLATE against the source string encoding from its effective identity/revision. Cross-charset utf8/utf8mb3 and utf8mb4 requests return 1253; matching encodings, numeric operands, direct markers, and source metadata retain their existing contracts.

The existing admission and semantic-version boundaries remain in force. Already admitted UCA400 domains demonstrate native behavior; revision-0 general_ci and historical 0900 aliases retain their legacy semantics. This change does not activate additional table collations or alter key/protocol formats. Broader activation remains subject to C11/C12 (#29490 / #29491).

The latest main merge regenerates the parser from the combined grammar and adapts the newly added JSON EXPLAIN reader to the current IndexSearchScan metadata model (QueryPayload, opaque algorithm options, and named algorithm expressions). The existing query-identity, settings, and distance-bound controls are retained.

Validation after merging main at 35c8dd5854 (Go 1.27.1, macOS arm64, repository CGo wrapper):

  • The two new regressions fail at ef289f3ee5 and pass after the fix. Numeric IN/NOT IN/BETWEEN, a numeric bound with a text left operand, numeric typed NULL, charset mismatch in both directions, matching charset controls, and source-table non-mutation are covered. Existing explicit-string conflict and numeric/direct-marker admission controls remain in place.
  • Full normal tests pass for pkg/common/moerr, pkg/frontend, pkg/sql/parsers/tree, pkg/sql/parsers/dialect/mysql, pkg/sql/plan/function, and pkg/sql/plan, plus the affected pkg/sql/plan/explain package. Frontend: 57.470s / 69.8% coverage; planner: 25.015s / 84.3%; EXPLAIN: 5.271s / 71.7%.
  • TestUnicodeCollationConsumerContract and TestFunctionalIndexLifecycle pass (9.970s). Cross-version typed NULL remains rejected with 1267; valid NULL controls and the merged consumer metadata checks still pass.
  • Normal C04 mo-tester execution: 152/152; complete charset/collation group: 886/886 (28s), including another C04 execution at 152/152 on the same owned instance. No failures, ignored, or abnormal cases. Teardown was checked after both runs. New numeric results and charset errors were independently checked against MySQL 8.4.11. String-conflict controls retain C04's established 1267 contract; MySQL may report 1270 for a three-operand mix.
  • The affected JSON EXPLAIN BVT passes 68/68, preserving independent query payload, probe-setting, range-bound, and first-round-limit controls.
  • Formatting, go vet, and configured golangci-lint 2.14.0 pass for the eight affected Go packages (0 lint issues).
  • This repair's changed-production statement coverage: 42/50 (84%); whole PR after merge compatibility repair: 329/359 (91.64%). The JSON EXPLAIN adapter has 20/20 (100%) changed-statement coverage. Generated parser line mappings are excluded and retain parser generation/round-trip evidence.
  • CPU/release arm64 native provenance is verified; the default SIMD service build passes with those artifacts. SQL validation used an isolated port and tester directory. Fixtures were cleaned up and the owned service stopped.

Earlier complete consumer-suite, parser-generation, NAME_CONST and frontend-walker evidence remains historical validation. The checks above validate the current merged source and keep the existing collation admission/version boundaries.

@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 a403a221d5cc5795c72a7289b9876a60d9f1c7cc against declared base/merge-base fab7b5c0430a475bf64ad1619ce4d5249013a138, comparing the previously reviewed cca18b2e7dad8668f81b92030d2b75f4914c179e and integrating the full 57-file diff. Read all eight historical reviews, five inline comments, three conversation comments and all five threads (all resolved; no omitted pagination).

The session-ID finding is CLOSED. The final commit changes only the inherited-role directive from 10 to unused 11; its result file is unchanged. The entire committed role_rule.sql runs as the intended user and passes 232/232 in both native rounds, with no new grant, edited result or script overlay. All prior production findings remain closed. Of the 57 PR files, only query_builder.go and that SQL directive changed since my last review; the query-builder change is the upstream shared-CTE fallback-demand correction, not a change to this PR's collation logic. The other collation, protocol, frontend and parser inputs are byte-identical; qualifying earlier lifecycle/race/parser evidence is reused for those closures.

One VALIDATION-ONLY blocker remains, not a new alleged production collation defect: the merged baseline BVT result no longer matches the intentionally enforced NULL charset contract.

Location: test/distributed/cases/charset_collation/issue_28164_legacy_native_gate.sql:14, expected result at issue_28164_legacy_native_gate.result:12–14.

SELECT NULL COLLATE utf8mb4_general_ci AS legacy_null;

The result file expects a NULL row. Current bindCollateExpr treats an untyped NULL as binary and rejects a non-binary COLLATE with 1253, matching the existing NULL admission regression in this PR (collation_expression_test.go:75). Actual native error: COLLATION 'utf8mb4_general_ci' is not valid for CHARACTER SET 'binary'.

Independently ran the COMPLETE unchanged 16-case script twice with canonical mo-tester against an owned exact-head native CN: 15/16 each time, with exactly this row-14 error, no ignored/abnormal cases, and teardown checked. A review-only copy retains the identical SQL and changes only this one expected NULL result to the intended charset-mismatch error: 16/16 twice. This diagnoses an outdated characterization oracle; it does not justify removing the NULL admission guard or blindly regenerating the entire result file. Reconcile the one baseline BVT expectation with the intended NULL semantics and complete the mandatory validation.

This matches the live exact-head failure, not an unrelated/pending-CI guess: run 38551373893, Pessimistic job 115813259319, reports 46,014 total, one failure, in issue_28164_legacy_native_gate.sql (15/16); role_rule.sql is 232/232. Coverage job 115830456187 stops at prerequisites because a required producer did not publish a complete profile; NO coverage verdict was calculated, so this is not a claimed below-75% result. Branch protection requires CI Required and strict current-base validation. I did not rerun CI or change repository gates.

Additional independent current-head validation: full planner/frontend suites 6,175 roots / 21,029 named passes with three existing skips; parser/grammar unchanged, generated SHA-256 4993ee82eb9e391f6a9b8437dcd5243fd99d0e463aafd4e858db5a2732fcfe07. Reused the prior complete consumer/remote-identity/lifecycle closure only where source and semantic inputs are unchanged; no newly repeated mixed-version cluster or performance claim. Native role log SHA-256 1d4cba93518e30e92db45fe2931e094a75a0acf6568cb3697197f98106706951.

Decision: REQUEST_CHANGES solely for this demonstrated mandatory BVT/evidence closure. The earlier session collision and all reported production defects are closed. Temporary diagnostics and the detached worktree are removed after submission.

@XuPeng-SH

XuPeng-SH commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: a3a1624594f655f0561ef88492e20cfa63e2d561

Review completed. Read the assessment.

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

mo-bot review · mo-bot-local · review

Commit: a3a1624594f655f0561ef88492e20cfa63e2d561

Assessment: approve

Reviewed all 58 changed files and affected callers. The design coherently preserves COLLATE syntax, resolves precedence in the binder, reuses existing casts/comparators, and fences changed LEAST/GREATEST semantics with a new overload and protocol floor. Earlier findings are addressed; no actionable defect remains in the assigned scope.

Model: gpt-6-astra / xhigh

Session: 01a12d8f-7dea-77c2-a565-38d45b5564e4 · slot 0 · generation 0

Validation:

  • Reused the frozen exact-head CI successes for build, Ubuntu unit tests, static analysis, coverage, and proxy/pessimistic BVT. Skipped checks were not counted as passes.

  • Isolation preflight passed. Verified 192 native inputs and 62 retained artifacts against build-owner provenance and receipts.

  • TestExplicitCollationConflicts and TestExpressionCollationSemantics passed. Additional planner diagnostics confirmed mixed binary/native UNION and VALUES domains.

  • A targeted prepared-regexp probe passed text, binary, and NULL bindings, execution, and cached-plan nonmutation checks.

  • Reconciled commands, source fingerprints, exit receipts, and retained logs in /home/xupeng/.local/state/mo-bot/jobs/6a8976d03681a6754c483097/attempt-1/validation-summary.json. Complete review map: review-analysis.json. Frozen patch matched; source remained unchanged.

Limitations:

  • Linked issue bodies and raw CI logs were absent; review used the supplied PR contracts, source, and frozen CI snapshot. local_validation contained no retained worker gates.

  • No local full-suite, service BVT, deployed mixed-version cluster, or performance benchmark was repeated. Binding scans and native comparison costs were assessed qualitatively; no throughput claim is made.

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

REQUEST_CHANGES — deep re-review of exact head a3a1624594f655f0561ef88492e20cfa63e2d561, base/merge-base 43ae1edafafa5749315d567a3f18a38ff53d3eaa, compared with my last reviewed a403a221d5cc5795c72a7289b9876a60d9f1c7cc.

The previous validation blocker is CLOSED. The one NULL-COLLATE golden is corrected without weakening the source guard or changing SQL. Current-head actual Pessimistic logs show legacy gate 16/16, C04 159/159, user-variable matrix 96/96 and full role_rule 292/292; LOAD in the proxy lane is 19/19. The main merge reused session 11 for another user, so the collated inherited-role request now correctly uses independent ID 22. Earlier remapdb, prepared SET, role merge, nested INTO and old-112 overload fencing findings remain closed.

One NEW compatibility blocker is independently confirmed below: the previously valid v113 fence became insufficient after #30228 actually merged into main. A current-main 113 reader admits the PR's saved v113 view and silently recomputes opposite LEAST/GREATEST results. This is not a request to renumber merely because another unmerged PR uses 113, and not a recycled failed-BVT concern.

Scope/evidence:

  • Read all ten historical reviews, all five inline comments/threads (resolved, no omitted pagination), four conversation comments, current PR body and full change inventory. Reconciled the complete 58-file map with the prior full review: 50 files are byte-identical to the previous reviewed head; read the eight changed-file increments and distinguished upstream role-lifecycle/parser/vector changes from this PR's actual delta. Prior qualifying proof is reused only for unchanged closures. This remains an existing-contract correction, not a new design-approval-label blocker.
  • Verified exact-head run 38585018225: build, Ubuntu UT, SCA, coverage, proxy/Pessimistic BVT and CI Required succeed. The original UT checkpoint proves all eight planner shards finish status 0; its summary records committed Unicode consumer and functional-index lifecycle PASS. Inspected actual case-level BVT logs, not only green badges. Existing skipped unrelated cases are not passes.
  • Fresh local repository goyacc generation is byte-identical: 39ead384f3c074b5ac221fce79a23bac6879766a2e0cbad2a3342b76492d2cc6. Historical parser hashes are not relabeled current. Trailing-space result rows remain intentional semantic fixtures; handwritten code whitespace checks pass.
  • Local committed TestLeastGreatestCollationPersistedAdmissionAndViewRead passes (one selected root, native CGo wrapper). That suite only checks an old-112 local version and thus does not close the newly committed main-113 boundary.
  • New native cross-revision probe: exact PR-head writer passes, emits its actual serialized view definitions, then exact freshly fetched main 17a6200f59e764729e5544908fffd5480ae88279 decodes them and fails exactly four value-preservation assertions (LEAST/GREATEST × two rounds). Its saved-floor-114 rejection controls pass. Native dependencies for main were built independently through the top-level build owner because its Makefile differs; no stamp bypass or main-workspace rebuild was used. This is actual planner/view-reader/evaluator evidence, not a claimed deployed mixed-version cluster or new performance benchmark.
  • Probe source SHA256 eedbe7f9e78b80593e9762d58826828fe12667a9a21ab740a2318ec593b6ee48. No production fix/push/merge/CI rerun made. Temporary probes, native artifacts and owned detached worktrees are cleaned after submission verification. Head rechecked immediately before POST.

Comment thread pkg/sql/plan/persisted_ip.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.

APPROVE — deep re-review of exact head ec4e50910b4d785e48c9b14280efb8a803cef8e7, base/merge-base 17a6200f59e764729e5544908fffd5480ae88279, compared with my previous a3a1624594f655f0561ef88492e20cfa63e2d561.

The previous v113 compatibility blocker is CLOSED. Main's DECIMAL statistical-result capability remains v113; collation-aware ordering now independently requires v114 at placement, actual-destination/source/receiver validation and persisted-expression/view admission. Constant-folded views save the pre-fold v114 requirement. Main-113 local readers and pre-fence authoring are rejected; historical overload 0 retains its existing domain, and mixed owners take the maximum without dropping main's decimal contract. Fresh main 501c85ecdd6eee0195172743c6d8aaf125cb252d still advertises 113. The old main reader's saved-floor rejection boundary is unchanged from the independently verified cross-revision counterexample in my previous review; this review does not claim a newly deployed mixed-version cluster.

Read all 11 historical reviews, all inline comments/replies and four conversation comments; all six threads are resolved with no omitted pagination or author replies. Reconciled the complete 58-file change map: 43 files are byte-identical to the last reviewed head; read all 15 changed-file increments and merge resolutions, separating upstream binder/ROLLUP/frontend/aggregate changes from this correction. Earlier remapdb, prepared SET, role-rule merging, nested INTO, session-ID and NULL-COLLATE golden findings remain closed. This repairs existing contracts; no separate feature-design approval gate is required.

Validation in an isolated exact-head detached worktree, Linux/amd64, Go 1.27.1:

  • Independently built CPU native artifacts with the top-level build owner because primary-worktree inputs differ; used the repository CGo wrapper. All seven selected TestLeastGreatestCollation roots across planner/compiler/functions/protobuf pass with -count=1, including v112/v113 negative and v114 positive admission, persisted/folded view requirements, nulls, overload selection and legacy controls. No production changes or temporary probe tests were added.
  • Reused verified exact-head CI 38677765567: actual checkout is this SHA; build, UT, SCA, coverage, proxy/Pessimistic BVT and CI Required succeed. Original checkpoint has all eight planner shards and light/embedded/heavy test stages status 0. Actual Pessimistic case logs show C04 159/159, legacy gate 16/16, user-variable matrix 96/96 and complete role_rule 292/292. Skips are not counted as passes.
  • Grammar/generated parser and comparator/AST inputs are byte-identical to the previously independently verified versions; that qualified evidence is reused, not relabeled as a fresh generation or broad local rerun. No new full-suite, race-stress, GPU or performance claim.

No remaining blocking finding. Exact head rechecked immediately before submission; owned worktree/native artifacts are removed after verification.

@mergify

mergify Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-16 06:15 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-16 08:28 UTC · at 387f5e84784a7e3b53448b364d0ea925dbc51f2a

This pull request spent 2 hours 12 minutes 57 seconds in the queue, with no time running CI.

Reason

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

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

  • Requeue this pull request

Copy link
Copy Markdown
Contributor

最近24小时合并项复核:在最新 main aa4b6eddfdad54d11be6fd75a5675eb9801f6690 上,本 PR 对应的 COLLATE 绑定/冲突回归通过;原始 #25096 场景仍返回 0,0,0,0(大小写、重音、尾空格、显式 general_ci 比较)。这与本 PR 声明的 C04 局部交付范围一致,不能将 #25096 / #29479 作为整体已解决。#25096 继续由开发负责人处理;无需新建重复 issue。

Copy link
Copy Markdown
Contributor

本轮合并功能审计更新(2026-10-19,main 2ad1d7e5c2baafdee0b8fa097ce02ca32feb3a7b,本轮重新构建native、真实两 CN/MySQL TCP):#25096 general_ci等价比较仍返回0/预期1;#28164 general_ci UNIQUE+ODKU仍保留3行/预期1;#30339 unicode_ci重复键诊断仍泄露物理排序键;#30340 大小写等价父键更新仍未级联。每项两个 CN 均复现,已在原issue更新本轮证据,保持开发指派。这里报告相邻语义仍未闭环,不把metadata/session修复本身归因为这些旧问题,也不要求无关4.2回移。

可复查命令、最小SQL及未弱化断言:pr-audit-continue21/followup_sql_test.go、followup-overlay.json、logs/unresolved-public.{log,command,exit},整体exit1;同命令4项已修复对照PASS。

This branch was previously deployed

1 inactive deployment
ci — 387f5e84 Deployed Oct 16, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants