Skip to content

fix: stabilize Top layout for typed NULL batches (#30708) - #30714

Merged
mergify[bot] merged 3 commits into
matrixorigin:mainfrom
Lundomn:codex/issue-30708-union-null-top
Oct 21, 2026
Merged

mergify[bot] merged 3 commits into
matrixorigin:mainfrom
Lundomn:codex/issue-30708-union-null-top

Conversation

@Lundomn

@Lundomn Lundomn commented Oct 21, 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:

Related to #30708

What this PR does / why we need it:

Top previously chose an ORDER BY slot by comparing the runtime vector pointer returned by expression evaluation. A direct column expression can instead return an executor-owned typed-NULL vector, so the pointer does not identify the input column's logical slot. Across UNION ALL batches this made the comparison and retained-batch layouts drift, causing an index-out-of-range failure.

Keep evaluating each ordering expression, but assign direct-column expressions to their planned column position and append computed expressions in a stable trailing order. This changes only the Top scratch-batch layout and preserves expression-cache ownership.

Candidate provenance: base 04fe057bd73520cdf30754f79f66f6505060ad1f; head 13ff05f0e2e271000d618622237f7ea218ed3ef8. The service binary and BVT inputs were built/run from d0acfe26d; the only later delta at the frozen head is the reviewed Top unit-test addition, so production source and BVT inputs are identical.

The report SQL reproduced on fresh main before the fix; the literal-only NULL UNION control remained green. The final SQL BVT passed 32/32 twice on the same service instance, with database teardown confirmed after each run. The targeted isolated two-CN test confirmed that a distinct peer CN was selected and hosted the query-owned remote TableScan.

Commands run from the repository root:

make build-with-prebuilt-native
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 ./pkg/sql/colexec/top
.agents/skills/mo-dev/scripts/mo-cgo-test -count=1 -run '^TestIssue30708UnionNullTopExecutesOnPeerCN$' ./pkg/tests/issues/isolated

MO_TESTER_CONFIG=/Users/ljy/.codex/issue-to-pr/matrixone/issue-30708/artifacts/mo-tester-isolated/mo.yml \
  /Users/ljy/Documents/Codex/shared-dependencies/matrixone/bin/mo-tester -m run -n \
  -p /Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/test/distributed/cases/union/issue_30708_union_null_top.sql
# The normal-comparison command above was run twice on the same service instance.

GOWORK=off \
CGO_CFLAGS="-I/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/cgo -I/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/thirdparties/install/include" \
CGO_LDFLAGS="-L/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/thirdparties/install/lib" \
DYLD_LIBRARY_PATH="/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/cgo:/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/thirdparties/install/lib" \
  go vet -mod=readonly ./pkg/sql/colexec/top ./pkg/tests/issues/isolated

GOWORK=off \
CGO_CFLAGS="-I/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/cgo -I/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/thirdparties/install/include" \
CGO_LDFLAGS="-L/Users/ljy/Documents/Codex/2026-09-07/matrixone-qa-monitor/work/issue-30708/thirdparties/install/lib" \
  /Users/ljy/.codex/issue-to-pr/matrixone/issue-30677/artifacts/tools/golangci-lint run \
  -c .golangci.yml --new-from-rev 04fe057bd73520cdf30754f79f66f6505060ad1f \
  ./pkg/sql/colexec/top ./pkg/tests/issues/isolated
gofmt -d pkg/sql/colexec/top/top.go pkg/sql/colexec/top/top_test.go pkg/tests/issues/isolated/issue_30708_test.go
git diff --check origin/main...HEAD

The Top package coverage includes both typed-NULL batch orders, K/EOF and reset/reuse, partial-Eval cleanup, computed key, bounded resident, direct spill, and typed-NULL-triggered resident-to-spill migration. go vet exited 0 with no diagnostics; pinned golangci-lint v2.14.0 reported 0 issues; formatting and diff checks were clean.

Limits: the full repository suite was not run. Remote CI is not covered by this local validation and must be tracked after publication. No performance benchmark was run. The fix removes the runtime pointer scan used to assign key slots and adds no per-row work, but no performance non-regression claim is made. The peer evidence proves selected-worker identity, a query-owned Remote scope/address and table source with no coordinator-local scan fallback, root Top runtime rows, and SQL output; per-operator counters from the remote worker were unavailable and are not claimed. Native NULLS FIRST/LAST syntax is rejected by the parser; the BVT instead covers the supported explicit NULL-first expression ORDER BY x IS NULL DESC, x DESC.

@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 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · done

Commit: 13ff05f0e2e271000d618622237f7ea218ed3ef8

Review completed. Read the assessment.

@XuPeng-SH

XuPeng-SH commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: 13ff05f0e2e271000d618622237f7ea218ed3ef8

Review belongs to an older commit; it is not a review of the current head.

@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-xupeng · review

Commit: 13ff05f0e2e271000d618622237f7ea218ed3ef8

Assessment: approve

Reviewed the complete five-file delta and affected callers, ownership, spill, cleanup and reuse paths. Planned ordering slots resolve the layout drift while preserving vector ownership. No actionable defects remain.

Model: gpt-6-astra / xhigh

Session: 01a14d34-4e51-79a3-a62d-6c9c16279dc8 · slot 0 · generation 0

Validation:

  • Full pkg/sql/colexec/top tests passed with -count=1: 26.839s.

  • TestIssue30708UnionNullTopExecutesOnPeerCN passed: 90.07s. Logs confirm distinct peer placement, query-owned table scan, Top runtime rows, SQL results and teardown.

  • Isolation preflight, repository-owned native provenance verification and git diff --check passed. Source remained unchanged.

  • Commands, source fingerprints, exit receipts, logs and retained artifacts reconciled in /home/xupeng/.local/state/mo-bot/jobs/9fda1553f66899491710a86e/attempt-1/validation-manifest.json.

Limitations:

  • No local full-repository, full isolated-package, race, performance or standalone SQL BVT rerun.

  • Supplied CI statuses and author validation descriptions lacked case-level logs; those executions were not independently verified.

  • The linked issue body was not supplied; its reported SQL contract was reviewed through the frozen PR description and regression cases.

@mergify mergify Bot added the queued label Oct 21, 2026
@mergify

mergify Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-21 06:07 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • ✅ Checks passed · in-place
  • ✅ Merged — 2026-10-21 12:11 UTC · at 32591dcf3757a0ae4c2dec52cfd8d98761bd3454 · squash

This pull request spent 6 hours 3 minutes 50 seconds in the queue, including 1 hour 52 seconds running CI.

Required conditions to merge

@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 review completed at exact head 13ff05f0e2e271000d618622237f7ea218ed3ef8; base/merge-base 04fe057bd73520cdf30754f79f66f6505060ad1f. No blocking findings.

Read all five changed files, issue #30708 and the complete available review/discussion/inline/thread history. This is a focused Top scratch-layout correction; the ordinary bug-fix design exemption applies.

Change/closure map:

  • R2/R3 Top key identity and ownership: direct-column slots now come from the planned ColPos, while computed expressions receive stable trailing slots. Every expression still executes. Traced the ColumnExpressionExecutor typed-NULL cache, original input batch, shallow scratch batch, retained winner batch and comparator owners. Only the scratch vector slice is replaced; input vectors are not overwritten or freed through that borrowed slice.
  • R3 lifecycle/spill: checked ordinary heap/K replacement/EOF, partial Eval failure, Reset/reuse, varlena bounded-resident mode, direct spill, resident-to-spill migration and output trimming to the original width. Same planned key positions reach resident comparisons, key retention and spill serialization.
  • R1 tests/public contract: reviewed both batch orders, computed-first/direct-second keys, pointer/type preservation, zero-account cleanup and named spill migration assertions. SQL/result cases preserve result metadata, NULL placement, LIMIT 0/1/>input/OFFSET, prepared reuse, non-LIMIT/UNION DISTINCT/ordinary-Top controls and same-session health.
  • R3 topology fixture: private two-CN cluster, authoritative peer placement with query-owned physical profile and output assertions, bounded condition polling, restored global force flag/work state, rows/connection/database/cluster cleanup. No new product worker or synchronization protocol.

Q1-Q3:

Scope Closure
Q1 vectors/executors borrowed scratch references; executor exclusively owns typed-NULL cache; retained batch owns copied values; existing Reset/Free and spill cleanup retained
Q2 completion/error existing child cancellation, EOF and terminal budget-error paths; no new waits; peer fixture uses observable bounded membership conditions
Q3 layout/storage fixed original-column + computed-key width for every batch; existing heap/account/spill bounds; no new per-row allocation or retained queue

Verified/reused raw exact-head CI 39546948294, not just check badges:

  • UT job 119047215618, checkpoint: full Top package selected in unfiltered -race -short -tags matrixone_test light stage, terminal exit 0. All isolated embedded race batches exit 0; named active-case record confirms TestIssue30708UnionNullTopExecutesOnPeerCN was actually selected.
  • Normal coverage job 119047253592: producer exit 0, 83,517 pass events, no package/test failure events.
  • SCA job 119047215516: exact checkout, pinned golangci-lint 2.14.0, 0 issues.
  • Pessimistic multi-CN BVT job 119050091365: issue_30708_union_null_top.sql 32/32, zero failed/ignored/abnormal.
  • Isolated exact-head worktree: full diff and git diff --check passed. Also verified d0acfe26d..HEAD contains only the 55-line Top test addition, consistent with the author's older-binary provenance statement.

No redundant local native/Go/cluster suite was run; author-reported same-instance repetitions and another reviewer's local timing are supplemental, not independently rerun evidence. No wire/catalog/API-format or security boundary changed; no benchmark or remote per-operator counter claim is made.

@mergify
mergify Bot merged commit 32591dc into matrixorigin:main Oct 21, 2026
@mergify mergify Bot removed the queued label Oct 21, 2026
XuPeng-SH pushed a commit that referenced this pull request Nov 5, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes matrixorigin/matrixflow#20795

## What this PR does / why we need it:

Backport the stable Top ordering layout from #30714 to `4.1.6-hotfix`.
Direct-column sort keys use their planned slots instead of vector
pointer identity, preventing typed-NULL batches from changing the
retained column layout and causing an index-out-of-range panic.

Also clear stale borrowed data/area references when
`Vector.UnmarshalBinary` reads empty payloads. The spill regression
reproduced this independent wrong-result bug on the unmodified hotfix
baseline: a NULL row could retain the previous batch's value. Encoding
and ownership contracts are unchanged.

Preserve the first ordering specification for repeated columns in
resident Top and MergeTop; spill Top uses each ordering position's own
flags. This closes the pre-existing comparator defect identified during
review: `ORDER BY x DESC, x ASC` must not behave as ascending order. The
fix covers direction and NULL-placement flags without changing operator
lifecycle or adding a new fixture.

Validation (Go 1.26.4, branch-local native libraries):
- Reproduced the Top panic and six vector-reuse failures before their
respective fixes.
- All 24 new repeated-key UT scenarios failed on the previous PR head
and pass after the comparator fix, covering ordinary/typed-NULL input,
opposite directions, explicit NULL placement, resident/spill Top and
MergeTop.
- Top and MergeTop package tests passed; changed comparator coverage
blocks are 100% covered. Earlier Vector/Batch evidence remains valid
because their inputs are unchanged.
- Incremental formatting/static checks and service build passed.
- SQL BVT passed twice on the same owned instance: 46/46 each, including
order-sensitive comparison and cleanup checks.
- A query-owned EXPLAIN ANALYZE confirmed three-row spilling for the
repeated-key query; results were `2, 1, NULL`.

Spill integration tests do not assume map-driven reload order; the
Vector reuse UT provides the deterministic empty-payload transition
oracle. Validation uses minimal reproductions, not an independent replay
of the customer's complete executed statement. No production deployment
was performed.
XuPeng-SH pushed a commit that referenced this pull request Nov 6, 2026
## What type of PR is this?

- [ ] API-change
- [x] BUG
- [ ] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

Fixes matrixorigin/matrixflow#20795

## What this PR does / why we need it:

Backport the stable Top ordering layout from #30714 to `4.2-dev`. A
column expression may return an executor-owned typed-NULL vector, so
pointer identity cannot identify its logical column. Use the planned
column slot and append only computed sort expressions, keeping the
layout stable across batches.

Preserve this branch's cancellation checks and ordering comparators; do
not import unrelated main memory-management changes.

Validation (Go 1.26.4, branch-local native libraries):
- Reproduced the original index-out-of-range panic before the fix.
- Top package tests passed, including both typed-NULL batch orders,
computed keys, heap replacement, reset/reuse, partial evaluation failure
and spill cleanup.
- Changed production statements have 100% coverage; Top package coverage
is 76.0%.
- Incremental formatting/static checks, vet and service build passed.
- SQL BVT passed twice on the same owned instance: 36/36 each, with
order-sensitive comparison and database/service cleanup checks.

The complete production SQL was truncated, so validation uses minimal
reproductions rather than a replay of the full production statement. No
production deployment was performed.

This branch was previously deployed

1 inactive deployment
ci — 5f077276 Deployed Oct 21, 2026 by mergify[bot]
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.

4 participants