Skip to content

fix: respect ci collations in ENUM/SET comparisons - #32874

Closed
gouhongshen wants to merge 2 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31364-main-8e482b24
Closed

gouhongshen wants to merge 2 commits into
matrixorigin:mainfrom
gouhongshen:agent/issue-31364-main-8e482b24

Conversation

@gouhongshen

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:

Related to #31364

What this PR does / why we need it:

ENUM and SET string comparisons under general_ci/unicode_ci can reach byte-sensitive equality because their declared collation is lost during planning. This PR makes ci ENUM case variants and ci SET member lists compare using the source column collation. For example, e = 'RED' matches stored Red, and s = 'A,B' matches stored a,b; binary collations remain case-sensitive.

Root causes

  • ENUM/SET DDL and display conversion dropped declared source collation, and scalar/materialized/dependent subquery lowering lost source identity.
  • CTE publication/readers and set-operation outputs carried storage-order metadata without independent equality-comparison provenance.
  • ProjectionBinder replaced grouped expressions with ColRefs whose storage-order resolver rejected explicit COLLATE adapters.
  • Logical SET metadata had to be separated from physical uint64 vector transport so remote batch admission retained the logical type without corrupting its physical representation.
  • Legacy catalogs can lack trustworthy declaration metadata, so recovery must use bounded declaration evidence and fail closed when that evidence is absent, ambiguous, stale, or unsupported.

Exact changes

  • Propagate ENUM/SET charset, collation, revision, and coercibility through DDL, logical plan/catalog types, and display wrappers; conservatively recover trustworthy legacy declarations without changing persisted state.
  • Add a PAD SPACE-aware, non-ordered general-ci equality key and rewrite ENUM/SET-provenance =, <=>, !=/<>, IN, and NOT IN string comparisons through an internal helper under general_ci/unicode_ci.
  • Preserve copy-on-write binding, SQL NULL behavior, numeric ordinals/bitmaps and temporal behavior, SET member order, assignments, and existing LIKE semantics. Register the helper as non-zonemappable.
  • Resolve permitted explicit COLLATE wrappers through context-aware scalar and derived provenance, including explicit-ci overrides on binary sources, while retaining arbitrary CAST coercion boundaries.
  • Keep comparison provenance separate from storage-order provenance. Resolve actual projected expressions for scalar, derived, and generated IN/NOT IN operands and carry bounded statement-local metadata through derived bindings.
  • Resolve CorrColRef provenance by walking exactly CorrColRef.Depth binder-owning lexical parents and reconstructing the owning relation/column identity there, covering direct, derived, and nested correlated predicates.
  • Carry comparison-specific provenance through CTE publication/readers and compatible set-operation outputs, including explicit-nil suppression. Require compatible definitions and effective charset/version across every non-NULL branch; clear provenance for mixed-collation or ordinary-string inputs.
  • Resolve grouped comparison operands through their owning group expressions with a self-reference guard, preserving explicit COLLATE adapters and arbitrary-CAST boundaries without changing grouping semantics.
  • Separate logical SET metadata from physical uint64 vectors after plan validation, retaining fail-closed raw decoding and ordinary uint64 admission checks.
  • Add planner/component regressions and the 182-statement test/distributed/cases/charset_collation/issue_31364_enum_set_comparison.sql BVT fixture with independently checked results.

Issue-to-test proof

  • On assigned base 7fcd9bdff8433d72983f0399fd5c10dcab91a00a, real SQL returned zero rows for the reported ci ENUM case variants and ci SET A,B; exact-case controls still matched. The primary planner regression also failed on that base. After the change, the ci predicates return the expected rows while binary and SET member-order controls retain their results.
  • The original comparison matrix covers happy/unhappy paths, NULL, empty SET, invalid labels, numeric and mixed IN, <=>, !=, NOT IN, explicit COLLATE, Unicode-ci, derived columns, LIKE, member order, and assignments. Scalar/materialized/dependent-subquery and legacy-recovery regressions provide their own red/green evidence.
  • The final CTE/set-operation/grouped-reference selection failed immediately before that repair with exactly 12 discriminating ci failures and nine passing binary/arbitrary-CAST/ordinary-string controls. The identical selection passes all 21 cases after the repair; its expanded 17-case CTE/set-operation selection also passes compatible multi-branch and mixed-collation negative controls.
  • Real SQL verifies materialized CTE and grouped ci matches, two-row compatible UNION ALL matches with row multiplicity preserved, explicit-ci overrides on binary sources, and zero matches for explicit-binary/arbitrary-CAST controls.
  • Physical transport regressions TestMySQLSpecialPhysicalVectorCollation and TestUnicodeSetRemoteBatchAdmission failed before the logical/physical boundary repair and passed afterward; native catalog controls passed. That transport code is unchanged in the final planner repair.
  • All 27 results added in the final fixture revision were independently checked; all 437 earlier result lines were preserved. Two normal mo-tester runs each passed 182/182 statements, and teardown after each run found zero issue databases.
  • Independent Challenger run 44175407291 completed PASS against the current source: all eight current regressions passed, including the exact reproduction and all 28 supported advanced assertions, with no coverage gaps and clean database audits. The retained historical exploratory nested-left quantified IN form reaches the pre-existing ERROR 20105 restriction; this PR does not change that unsupported form.

Validation commands and results

Assigned-base red reproduction (expected exit 1):

mo-cgo-test -mod=readonly -v -count=1 -timeout=5m \
  -run '^(TestBuildCreateTablePreservesEnumSetCollation|TestEnumSetStringComparisonUsesColumnCollation)$' \
  -o /tmp/issue-31364-red/plan.test ./pkg/sql/plan

Original fixed comparison/recovery selection (exit 0; all recovery/admission tests and 29 comparison subtests passed):

mo-cgo-test -v -count=1 -timeout=180s \
  -run '^(TestBuildCreateTablePreservesEnumSetCollation|TestRecoverLegacyEnumSetCollation|TestUnsupportedLegacyEnumSetIdentityDoesNotBlockTinyText|TestRecoverLegacyEnumSetCollationRejectsStaleEvidence|TestUnicodeEnumSetInsertPlanAdmission|TestEnumSetStringComparisonUsesColumnCollation)$' \
  -o /tmp/issue-31364-red/plan.test ./pkg/sql/plan

Final pre-repair red and post-repair green focused selection (red exit 1 with 12 discriminating failures; green exit 0 with all 21 cases passing):

mo-cgo-test -mod=readonly -v -count=1 -timeout=300s \
  -run '^(TestEnumSetCTEAndSetOperationComparisonUsesColumnCollation|TestEnumSetGroupedComparisonUsesColumnCollation)$' \
  -o /tmp/issue-31364-review-r4-red/plan.test ./pkg/sql/plan

Expanded compatible/mixed-collation selection (exit 0; all 17 cases passed):

mo-cgo-test -mod=readonly -v -count=1 -timeout=300s \
  -run '^TestEnumSetCTEAndSetOperationComparisonUsesColumnCollation$' \
  -o /tmp/issue-31364-review-r4-derived/plan.test ./pkg/sql/plan

Final planner package (exit 0, ok 194.191s):

mo-cgo-test -mod=readonly -count=1 -timeout=15m \
  -o /tmp/issue-31364-review-r4-red/plan.test ./pkg/sql/plan

Final build and static validation (all exit 0; go vet used the repository's documented CGo environment; selected molint and golangci-lint reported zero issues):

make build
go vet -mod=readonly ./pkg/sql/plan
make static-check-selected STATIC_CHECK_PACKAGES=./pkg/sql/plan

Public result generation (exit 0; independent result checking passed and final result SHA256 is c2824c9ea799c676ed16ff55551b24c23401d492dd34d507f60b0dc45ae91549):

java -Xms1024M -Xmx1024M \
  -cp '/Users/ghs-mo/MOWorkSpace/mo-tester:/Users/ghs-mo/MOWorkSpace/mo-tester/lib/*' \
  io.mo.Tester \
  path=/Users/ghs-mo/MOWorkSpace/tmp/issue-fix/issue-fix-loop/state/worktrees/issue-31364-main-8e482b24/test/distributed/cases/charset_collation/issue_31364_enum_set_comparison.sql \
  method=genrs rate=100 ignore nometa pprof

Normal public BVT (the same command with method=run was executed twice from isolated mo-tester working directories against the owned service; both exited 0 with total=182 success=182 failed=0):

java -Xms1024M -Xmx1024M \
  -cp '/Users/ghs-mo/MOWorkSpace/mo-tester:/Users/ghs-mo/MOWorkSpace/mo-tester/lib/*' \
  io.mo.Tester \
  path=/Users/ghs-mo/MOWorkSpace/tmp/issue-fix/issue-fix-loop/state/worktrees/issue-31364-main-8e482b24/test/distributed/cases/charset_collation/issue_31364_enum_set_comparison.sql \
  method=run rate=100 ignore nometa pprof

Supporting earlier-revision owning-package and race evidence for unchanged components (all exited 0; these are supporting evidence for this final revision):

mo-cgo-test -count=1 -timeout=15m \
  ./pkg/common/collation ./pkg/container/types ./pkg/container/vector \
  ./pkg/pb/plan ./pkg/sql/plan/function ./pkg/sql/plan ./pkg/frontend ./pkg/sql/compile
mo-cgo-test -race -count=1 -timeout=15m \
  -o /tmp/issue-31364-1794850561/plan.test ./pkg/sql/plan

Final delivery checks also passed: gofmt -l reported no files, git diff --check exited 0, and the complete 35-file patch matched the independently approved patch byte-for-byte with SHA256 3a1537e85913916fab7f85d23d84a6db3fe46747bab3744cb0ba75f5e334b3c7.

Residual risks and limits

  • The behavior change is scoped to equality-family string predicates. ORDER BY, BETWEEN, grouping, DISTINCT, CTE materialization policy, incompatible-source set-operation coercion, and assignment validation retain existing semantics.
  • Legacy recovery remains fail-closed when declaration evidence is missing or unsafe. Arbitrary CAST expressions retain their existing coercion boundary, and the existing nested-left quantified-subquery ERROR 20105 restriction remains unchanged.
  • Earlier race evidence predates the final provenance repairs and is supporting evidence only; no fresh race result is claimed for this revision. The full repository suite remains for CI.
  • Closed-service log classification found no panic, fatal, or runtime-error marker. Expected operator probes and dependent-not-ready messages matched the three fixture executions; the only shutdown SQL cancellation was the mo_logger statement_info flush after SIGTERM began.

Preserve ENUM/SET collation identity through DDL, expression binding,
subqueries, CTEs, compatible set operations, and grouped references.
Rewrite equality-family string predicates with a ci equality key while
retaining binary, numeric, NULL, CAST, LIKE, and assignment semantics.
Separate logical SET metadata from physical uint64 vector transport.

Add focused planner regressions and a 182-statement public BVT fixture.
The primary regression fails on the assigned base and passes after the
fix; the final planner package, build, vet, static checks, and two BVT
runs pass.

Related to matrixorigin#31364
@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 →

@mergify

mergify Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is closed, so it cannot be queued. Reopen it to get the box back.

@XuPeng-SH

XuPeng-SH commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 6ee34e6bbe31977297f5ec042d060ee3b71ea8d0

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: 6ee34e6bbe31977297f5ec042d060ee3b71ea8d0

Assessment: request_changes

The patch fixes the reported case-insensitive ENUM and SET comparisons and keeps comparison provenance separate from storage ordering. Three correctness gaps remain. Schema copies drop column collations, mixed IN lists lose existing numeric matches, and legacy recovery can mistake a later table default for the original column collation. The cross-component change also requires a versioned design that covers these contracts.

Model: gpt-6.2-sol / xhigh

Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0

  • P1 pkg/sql/plan/build_util.go:605: Run SHOW CREATE TABLE or CREATE TABLE LIKE on a table whose ENUM or SET column collation differs from the table default.
    Impact: The generated DDL drops the column override. A clone silently adopts the table default and can return different rows for the same data and predicates.
    Evidence: The binder now stores the column collation, but the shared formatter at pkg/sql/plan/build_show_util.go:953 skips ENUM and SET. CREATE TABLE LIKE reparses its output at pkg/sql/plan/build_ddl.go:3019. The MySQL-protocol probe reproduced both directions. Case-insensitive columns changed from 1,1 to 0,0 and binary columns changed from 0,0 to 1,1 in schema.jsonl. Preserve effective ENUM and SET collations through the shared DDL formatter and replay path.

  • P2 pkg/sql/plan/mysql_special_collation.go:255: Compare an ENUM display label such as '01' against a mixed list such as IN ('0', 1) under utf8mb4_general_ci.
    Impact: An existing match disappears because the integer arm becomes a string comparison against '1'.
    Evidence: The same MySQL-protocol probe returned 1 with the merge-base production code and 0 at the candidate head, in both list orders. Pure numeric ordinal and ordinary string controls were stable. The list rewrite converts numeric members to VARCHAR before the mixed comparison owner at pkg/sql/plan/base_binder.go:6594 can apply numeric coercion. Apply collation keys to string comparisons while preserving the existing numeric arm and NULL semantics.

  • P2 pkg/sql/plan/legacy_mysql_special_collation.go:86: After upgrading a 4.2 table whose stored CREATE omitted collation, change its table default to utf8mb4_general_ci without converting its existing columns.
    Impact: A default-only ALTER can make subsequent queries compare existing ENUM and SET labels case-insensitively even though the columns were never converted.
    Evidence: The v4.2.8 catalog retained CREATE SQL and table identity without a durable collation default. The current default-only ALTER updates the table default in place. The planner probe exercised that ALTER and then recovery, which changed both column identities from 0 to 3 at schema version 1. Equal physical and logical IDs do not establish the original default. Recover inherited collation only when creation-time evidence supports it, and retain legacy behavior otherwise.

  • P2 pkg/sql/plan/mysql_special_collation.go:60: The change introduces durable ENUM and SET collation semantics across catalog recovery, DDL replay, planner provenance, and vector transport.
    Impact: The repository's required design artifact is missing for the new ownership and compatibility rules. The schema-copy and legacy-default failures show concrete gaps at those boundaries.
    Evidence: The change touches 965 non-generated production lines. The scope triggers .agents/skills/mo-dev/references/feature-design-review.md:22 and :38 through its size, persistence changes, and cross-component ownership. The frozen submission contains implementation and test summaries but no linked versioned design. Supply the applicable design revision and close the DDL round-trip, legacy authority, and comparison coercion contracts together.

Validation:

  • Isolation preflight, frozen patch verification, diff --check, and native input verification passed. Receipts 1794956702959427454-2.json and 1794956736172013020-2.json.

  • Focused collation, type, vector, plan, compile, and embedded SQL tests passed. Additional cache, tuple-comparison, and function-registration controls passed. See candidate.jsonl and boundary-tests.jsonl with receipts 1794957122877667720-2.json and 1794957392081615076-2.json.

  • The public SQL probes reproduced the schema-copy failure and the mixed-list regression against the verified merge-base overlay. See schema.jsonl, base.jsonl, and candidate.jsonl with receipts 1794957275958140924-2.json, 1794957276008487601-2.json, and 1794957122877667720-2.json.

  • The legacy planner probe failed the default-only ALTER invariant. See legacy-default.jsonl and receipt 1794957367162875784-2.json. The evidence audit matched all seven receipts to retained logs and verified complete discussion coverage.

Limitations:

  • The legacy probe exercised the planner with a 4.2-shaped catalog fixture. A full stopped upgrade and the distributed BVT suite were not rerun locally. The author's BVT result checksum matches the frozen fixture, but raw logs for the reported runs were unavailable.

This branch was previously deployed

1 inactive deployment
ci — 6ee34e6b Deployed Nov 17, 2026 by gouhongshen
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.

3 participants