Skip to content

fix: handle untyped NULL vectors during selection - #33058

Merged
XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/33056-any-null-shuffle
Nov 26, 2026
Merged

XuPeng-SH merged 6 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/33056-any-null-shuffle

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 22, 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:

Fixes #33056

What this PR does / why we need it:

A view containing NULL + (correlated scalar subquery ... LIMIT 0) could fail during ORDER BY with panic unexpect type ANY for function vector.Shuffle.

T_any can reach execution here because the binder folds the expression to an untyped NULL. It carries no unknown non-NULL value: batch duplication may flatten that NULL into a zero-width vector with row markers. Give selection and copying a defined contract for these payload-free rows, preserving the ordinary NULL and grouping bitmaps independently. The affected selection and copy paths reject a visible ANY row that has neither marker.

AllNull now asks whether every visible row is SQL NULL; this matters because SetLength can retain bitmap bits past the current length. Empty flat vectors and constant NULLs retain their existing different empty-length behavior. IsGrouping uses the same visible-prefix rule. Column projection and spool copying publish only visible grouping rows, including for shortened constants and reusable destinations.

The planner, client-visible type metadata, and wire format are unchanged. In particular, the fix does not eagerly convert an untyped NULL to BIGINT, which breaks existing UUID, vector and old-view coercion.

Validation

  • Go 1.27.1 on Linux: full -race for vector, batch, pSpool, partition, colexec, compare, sort, order, window, top, mergetop, mergeorder, filter and group. Focused regressions cover shortened rollup projection and flat/constant spool copies through the pipeline codec, mixed row markers, self-append, cache reuse, read-only windows and foreign pools.
  • Standalone, metadata-aware BVT: 169/169 original issue, related SQL/authorization and type-compatibility checks, plus 41/41 vector CASE checks; teardown verified.
  • Upgraded copies of data created by the official 4.2.8 binary with old CAST and COALESCE vector views: describe, read and write succeeded, and both views remained readable after a candidate restart.
  • Repository-selected SCA scope was the full graph (330/503 packages); default-config full-graph molint and golangci-lint, affected-package go vet, formatting, error policy and license headers passed. SIMD-enabled full-graph golangci-lint also passed. SIMD-enabled molint reported two unchanged metric files; the same two findings reproduce on clean main with the same tool and flags. Following the main merge, targeted analyzers on optools and pkg/tests/issues and the optools inventory race tests also passed.
  • A synthetic 8192-row predicate benchmark measured no allocations: 1.1 ns for a concrete type, 3.9 ns for all-NULL ANY, 40 ns with a retained bitmap tail, and 5.5 μs for mixed NULL/grouping. These measurements are not end-to-end SQL timings.
  • Independent design by gpt-6.2-astra/high and complete review by gpt-6.2-sol/xhigh. The standalone SQL/upgrade binary was built from f3be436; the subsequent main merge changed only UT fixtures/scripts and left the complete PR patch unchanged. Mixed-version execution and a new multi-CN run were not tested locally.

A pre-existing weak-NULL ROLLUP/GROUPING SETS case fails in the separate ANY function-result constructor, which this change does not alter. Separately, released v4.2.8 was observed to create an ANY column for CTAS SELECT NULL+1; in a separate isolated test, flushing the ANY table created from the correlated expression crashed the service. Durable schema admission and recovery for existing ANY schemas need a separate fix.

@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 22, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

@XuPeng-SH

XuPeng-SH commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 4289d59482ac0023c35a2e0fe11cf49396a60fc7

Review completed. Read the assessment.

@XuPeng-SH
XuPeng-SH marked this pull request as draft November 22, 2026 08:10

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: 4289d59482ac0023c35a2e0fe11cf49396a60fc7

Assessment: request_changes

The original ORDER BY query now returns the expected rows. A second transform can leave stale grouping bits after the first converts a NULL-only ANY vector to a constant. The pipeline decoder rejects the resulting batch.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/container/vector/vector.go:2391: Start with four NULL-only ANY rows and grouping bits at rows 0 and 2. Shrink to rows [1,2,3], then use ShrinkByMask with offset 1 to keep the middle row.
    Impact: The one-row result keeps grouping bit 1 instead of remapping it to bit 0. The pipeline decoder rejects the batch with pipeline grouping bit exceeds vector length. A chained shuffle also kept the original length after a shorter selection.
    Evidence: The first transform calls SetConstNull after remapping. The next transform takes the existing constant fast path and skips row-specific metadata. The ANY pipeline probe failed and the equivalent BIGINT control passed. Keep NULL-only ANY vectors flat through these transforms, or make the constant path remap their metadata and update their length. See composition.stdout and pipeline.stdout.

Validation:

  • All 294 top-level vector and partition tests passed. The base vector reproduced the original ANY shuffle panic.

  • The issue query and three sorting controls returned rows 2 and 20 with NULL values through the MySQL protocol.

  • Verified the frozen patch and pinned policy. Matched eight command receipts to retained logs and accounted for all three discussion entries.

Limitations:

  • SQL validation used one CN. The grouping defect was reproduced at the pipeline codec boundary. Separate SQL ROLLUP probes stopped during projection setup with an unsupported ANY function result.

@XuPeng-SH XuPeng-SH changed the title fix(vector): handle NULL-only ANY transformations fix(plan): preserve NULL arithmetic result types Nov 22, 2026
@XuPeng-SH
XuPeng-SH marked this pull request as ready for review November 22, 2026 09:03
@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 →

@XuPeng-SH
XuPeng-SH requested a review from aptend as a code owner November 22, 2026 09:03
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Nov 22, 2026
@XuPeng-SH

XuPeng-SH commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: d3a79dbf5edfe30698c01b0118d44dd2c18e72df

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: d3a79dbf5edfe30698c01b0118d44dd2c18e72df

Assessment: request_changes

The standalone MySQL check returned the expected rows for issue #33056. Reusing arithmetic overload resolution supplies concrete result types, but nested arithmetic loses the existing correlated-wrapper pruning. The earlier grouping defect also persists when a NULL-only ANY vector goes through two selections.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

  • P2 pkg/container/vector/vector.go:2391: Apply Shrink to a flat NULL-only ANY vector with grouping bits, then select from the resulting vector with ShrinkByMask.
    Impact: The second selection can leave grouping bits outside the new row range. The pipeline decoder rejects the batch.
    Evidence: The first selection converts the vector to constant NULL. The second takes the constant fast path at line 2503 and changes only the length. The probe retained bit 1 in a one-row vector and failed decoding. The BIGINT control moved the bit to row 0 and decoded successfully. Preserve row-aligned grouping metadata across chained selections and permutations.

  • P2 pkg/sql/plan/base_binder.go:8926: Use (NULL + 1) as the left operand of an addition whose right operand is a scalar wrapper containing a correlated LIMIT 0 subquery.
    Impact: The planner keeps a dead wrapper scan reachable and can schedule an unnecessary dependent scalar program. The authorization source is still retained.
    Evidence: The inner fold now produces a typed NULL, while isNullExpr recognizes only an untyped NULL literal. The candidate optimizer retained the customer scan. Both the bare-NULL control and the control using the pinned binder and overload code pruned it while retaining the privilege carrier. Public EXPLAIN also showed an extra dependent program for the nested form. Preserve this fold through nested arithmetic while keeping the resolved type and authorization tracking.

  • P3 test/distributed/cases/subquery/issue-32869-correlated-scalar-limit-zero.sql:79: The change repairs the SQL-visible result of sorting a view that projects untyped NULL arithmetic over a correlated LIMIT 0 subquery.
    Impact: The maintained BVT suite can miss a recurrence of the original query failure.
    Evidence: The pinned testing contract requires BVT proof for changed SQL-visible behavior. The existing sorted-view case uses CAST(NULL AS SIGNED), which already avoided the issue. Extend that fixture with the untyped projection and assert the ordered rows and NULL values.

Validation:

  • Verified the frozen source, patch, and pinned review policy. Isolation preflight passed.

  • The selected planner, vector, and partition tests passed, including the five-operator NULL arithmetic regression. See focused-exact.jsonl and receipt checks/1795340047032314921-3.json.

  • The standalone MySQL probe returned (2, NULL) and (20, NULL) for the issue query and three ordering or CAST controls. See sql-exact.jsonl and receipt checks/1795340049659377315-6.json.

  • The nested pruning assertion failed on the candidate and passed with the pinned binder and overload files restored through an overlay. See binder-retry.jsonl, nested-pruning-base.jsonl, and receipts checks/1795340000207402882-3.json and checks/1795340056929681007-5.json.

  • The exact-head pipeline round trip failed for ANY and passed for BIGINT. See pipeline.jsonl and receipt checks/1795338991690317216-11.json.

Limitations:

  • The pipeline failure was reproduced at the batch codec boundary. Distributed SQL, the full CI matrix, and the reported performance measurements were outside the completed local checks.

  • The validation ledger retains the timed-out attempts and the SQL retry that selected zero tests. The completed checks above supply the stated results.

@iamlinjunhong iamlinjunhong 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 867f792911e0c496469ff0d696e87c5f441dbcb3 against main at cc2c82dc4a6cb2cbcc046ef9caebde50c6004b15. The BVT fixture now covers the untyped ordered view, direct query, typed control, and window partitioning. The planner diff is empty at this head, which removes the earlier changes to scalar pruning and contextual NULL coercion. Issue #33056

  • [P2] Trim grouping bits when projecting a shortened same-type constant NULL. At pkg/sql/colexec/evalExpression.go:1951, shorten a four-row NewRollupConst(INT32, ...) to two rows with batch.SetLength, then evaluate an INT32 column reference. The same-type path returns the input with grouping bits [0, 1, 2, 3]. The pipeline decoder rejects that two-row result with pipeline grouping bit exceeds vector length. Use the existing cache when grouped bits fall outside the visible rows and retain bits [0, 1].
  • [P2] Keep the spool copy's grouping bitmap within the copied rows. At pkg/container/pSpool/copy.go:162, copy a flat all-NULL ANY vector shortened from four rows to two, with grouping bits [1, 3]. The newly supported GetUnionAllFunction path copies only bit 1, but the spool then overwrites that bitmap with the source's full bitmap. The resulting two-row batch fails the pipeline round trip with the same decoder error. Extend TestCachedBatchCopiesAllNullAny with a shortened source and check the cached result retains only bit 1.

The two open design questions concern the runtime type and the null bitmap's bounds. The existing evaluator and batch copy can materialize a zero-width ANY vector for the issue query. Its visible rows are represented entirely by NULL bits. SetLength changes the visible length while retaining bitmap storage and bits. After shortening four NULL rows to two, the old Count() == Length() test returns false. The current predicate tests for NULLs within the visible prefix, while the flat-vector paths still reject ANY with a visible non-NULL row. The captured discussion contains no explicit author reply to either question. AllNull discussion · Runtime ANY discussion

The frozen CI snapshot has 29 completed checks for this head. Thirteen succeeded, including CI Required, the Ubuntu/x86 unit tests, and two multi-CN BVT jobs. Fourteen were skipped and two Mergify checks were neutral. No check failed. CI run

I cross-checked the full diff and both grouping paths against the source and the prior exact-head component probes. The artifact and diff whitespace checks passed locally. I skipped local test reruns because the source establishes both failure paths and the captured review reports the exact-head probes. SQL-level reproduction of the grouping failures remains unverified. This is my first review, so the prior-reply exception for P2/P3 does not apply. Exact-head probes

Comment thread pkg/sql/colexec/evalExpression.go Outdated
if vec.IsConstNull() && !vec.IsGrouping() {
// Grouping is row-specific even for a constant NULL. A typed cache is
// still required when the input's type differs from the bound column.
if vec.IsConstNull() && (!vec.HasGrouping() || vec.GetType().Oid != expr.typ.Oid ||

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.

[P2] Shorten a four-row INT32 rollup constant to two rows with batch.SetLength, then project it through an INT32 column reference. This branch returns the input with grouping bits [0, 1, 2, 3], and the pipeline decoder rejects the result with pipeline grouping bit exceeds vector length. Route constants with out-of-range grouping bits through the cache and retain only the visible bits [0, 1].

Comment thread pkg/container/pSpool/copy_test.go Outdated
cache := initCachedBatch(mp, 1)
t.Cleanup(cache.free)
for range 2 {
copied, useCache, cacheID, err := cache.GetCopiedBatch(source)

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.

[P2] Add a case where batch.SetLength shortens a four-row flat all-NULL ANY source to two rows with grouping bits [1, 3]. The new union path copies bit 1, but pkg/container/pSpool/copy.go:162 overwrites the destination with both bits. The pipeline decoder then rejects the cached batch. Keep the row-bounded grouping from the append and assert the shortened copy retains only bit 1.

@XuPeng-SH

XuPeng-SH commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 867f792911e0c496469ff0d696e87c5f441dbcb3

New discussion was assessed; the previous review remains unchanged.

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: f3be436145421d71e7833926fb6da894c32a02b9

"interrupted"

@XuPeng-SH

XuPeng-SH commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 6ebbacb4ee63ed107508601ad965b6b69763744c

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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

Assessment: approve

The ordered view returns both expected rows with NULL values. The fix extends the existing vector selection and copy paths, preserves weak-NULL coercion, and resolves both prior pipeline decoding failures by keeping grouping bits within visible rows.

Model: gpt-6.2-sol / xhigh

Session: 01a1f0a0-5126-78f3-9ab8-ef4e87f2f119 · slot 0 · generation 3

Validation:

  • Verified the frozen patch, pinned policy, native inputs, and isolation preflight. The merge from main affected only test tooling and unrelated test fixtures, so the prior execution evidence still applies.

  • Matched receipts and logs for ten passing race-enabled suites, including chained ANY selection, shortened spool copies, and shortened rollup projection through the pipeline codec.

  • The retained single-CN MySQL probe passed the ordered view, direct query, LIMIT/OFFSET, typed CAST, and window partitioning controls.

Limitations:

  • The full BVT and released-binary upgrade results were author-reported. Independent SQL validation covered one CN, and the frozen CI snapshot still showed build and unit checks in progress.

Resolve arithmetic overloads before folding literal NULL operands so the result no longer leaks ANY metadata. Return a typed NULL literal after resolution to preserve correlated LIMIT 0 pruning and authorization retention, and let division adopt a single NULL operand's peer domain.
@XuPeng-SH

XuPeng-SH commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 64ecfe423f482609a337392115645872b2e79db5

discussion changed before publication

@XuPeng-SH

Copy link
Copy Markdown
Contributor Author

Independent QA for issue #33056

Tested the rebased PR head 64ecfe423f482609a337392115645872b2e79db5 against base 2b0038fbd1070494008bd50362b53d2667d6cae6 (macOS arm64, Go 1.27.1), using fresh temporary SQL and white-box probes rather than only the tests already in this PR.

Black-box results

  • The exact issue SQL reproduces on base with ERROR 20101: panic unexpect type ANY for function vector.Shuffle.
  • The same SQL succeeds on the PR and returns (2, NULL), (20, NULL).
  • Direct/view reads, typed/untyped controls, with/without ORDER BY, empty input, duplicate/permuted rows, and prepared execution all passed.
  • 50 repeated executions plus 80 queries from 8 concurrent clients completed with zero failures and no ANY panic in the PR server log.

White-box, correctness, and error paths

  • New selection probes covered lengths 0/1/2/63/64/65/130, Shuffle, ShuffleWithBuf, Shrink, masks with non-zero offsets, and flat/constant vectors.
  • Partition results were checked differentially against equivalent typed-NULL vectors.
  • Spool probes covered mixed ANY+INT64 batches, cache reuse, and source/copy independence.
  • Nil/foreign pools, read-only windows, non-NULL ANY, self/empty union, and length overflow were rejected without corrupting the input state.
  • The new probes passed with -race for pkg/container/vector, pkg/container/pSpool, and pkg/partition, with final memory-pool usage checks at zero.
  • Running the same independent selection probe on base produced the intended vector.Shuffle ANY panic, confirming that the probe distinguishes the fix.

Focused performance comparison (8 samples, -benchtime=300ms, -cpu=1)

Benchmark Base PR
INT64 Shuffle, 1024 rows 603.0 ns/op 600.4 ns/op
AllNull, ordinary visible prefix 1.7 ns/op 1.9 ns/op
AllNull, stale bitmap bits beyond visible prefix 1.7 ns/op 7.8 ns/op
ANY NULL Shuffle, 1024 rows panics 2076.5 ns/op, 0 B/op, 0 allocs/op

The typed Shuffle and ordinary AllNull paths showed no material regression or added allocation. The stale-prefix case intentionally performs more work because the old result was incorrect.

Scope / response to the design questions

  • SetLength changes only the logical length; it does not trim later NULL bitmap bits. Thus, after four NULL rows are shortened to two, the old Count() == length check evaluates 4 == 2 even though both visible rows are NULL. The new AllNull explicitly checks the visible prefix.
  • This PR does not attempt to eliminate every runtime T_any. It defines behavior for payload-free NULL/empty ANY vectors on the affected paths and rejects non-NULL ANY. A global runtime-type redesign is outside this issue's scope.

These results support the fix for #33056; they are not a claim of full-system performance coverage or completion of CI/reviewer approval.

@XuPeng-SH

XuPeng-SH commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: 64ecfe423f482609a337392115645872b2e79db5

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor Author

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: 64ecfe423f482609a337392115645872b2e79db5

Assessment: approve

The fix extends the existing vector selection, copy, and partition paths for payload-free NULL values without changing planner coercion. The visible-prefix AllNull check addresses stale bitmap bits after shortening. Earlier grouping and planner findings concern implementations absent from this head; the current evaluator can produce runtime ANY NULL vectors, so eliminating all runtime ANY values is a separate design question.

Model: gpt-6.1-terra / max

Session: 01a2139c-d96f-7c90-931f-8f9ea168e77f · slot 2 · generation 4

Validation:

  • Isolation preflight passed. Focused changed tests and short owning-package suites passed for vector, pSpool, and partition; see focused-tests.log, packages-short.log, and receipts 1795635471630348533-5.json and 1795635522861036394-5.json.

  • A freshly built, provenance-verified exact-head service passed the changed mo-tester case twice on one CN: 169/169 comparisons each time, including the tagged metadata check. Database, user, and role teardown checks passed after each run; see bvt-probe-v3.log, both bvt-tester-v3 reports, and receipt 1795637191806969420-17.json.

  • The complete discussion was assessed in discussion-assessment.json. The exact-head QA report and the local checks support the reported SQL fix.

Limitations:

  • The first fixture attempts stopped before executing SQL because of a client readiness warning and mo-tester's absolute-path resolution. The successful runs used a relative path to the same frozen fixture.

  • An additional time-window query returned the expected row, but its separate cleanup command exceeded a five-second limit; the task-owned service was then stopped.

  • SQL validation used the frozen head on one CN; it did not test a synthesized merge with the newer target branch or rerun the full CI matrix. The PR description still describes earlier grouping paths and validation from f3be436.

This branch was successfully deployed

No deployments
ci — a0a9a0ed Deployed Nov 26, 2026 by XuPeng-SH
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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: ORDER BY a view with untyped correlated LIMIT 0 NULL panics in vector.Shuffle

4 participants