Skip to content

fix: preserve repeated Top ordering keys on 4.2 - #32402

Merged
XuPeng-SH merged 2 commits into
4.2-devfrom
codex/fix-32396-4.2-dev
Nov 9, 2026
Merged

XuPeng-SH merged 2 commits into
4.2-devfrom
codex/fix-32396-4.2-dev

Conversation

@XuPeng-SH

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 #32396

What this PR does / why we need it:

ORDER BY b DESC, b ASC LIMIT 2 could return the smallest rows because Top and MergeTop configured the comparator for a repeated physical column from the last ordering specification. The first specification determines the order; a later occurrence of the same value cannot break ties left by the first.

Preserve the first specification when the resident Top or MergeTop comparator is shared by a physical column. Spill Top stores a separate vector per logical key, so construct each comparator from its corresponding specification. Expression evaluation, logical key order, row ownership, and the leading-key scan-pruning protocol are unchanged. This ports the corresponding comparator fix from #32239 to 4.2-dev while using this branch's ordering comparator.

Validation:

  • Reproduced the original and reverse-direction failures on the base and confirmed the new Top/MergeTop regression tests fail there. The fixed version returns the correct ordered rows for both directions, NULL placement, offset, repeated keys separated by another key, and real spill writes/reads, including a full-heap replacement past the spill threshold.
  • Ran both affected Go packages in normal and -race modes, plus incremental gofmt, go vet, repository molint, and golangci-lint on the complete Go delta.
  • Ran the existing UNION/typed-NULL and leading-key-pruning SQL cases twice each on an isolated two-CN instance: 41/41 and 63/63 statements per run. A physical plan confirmed local Top on both CNs and coordinator MergeTop. An independent 36-case comparison against MySQL 8.0.44 matched exact ordered rows across resident, spill, NULL, offset, computed-key, and execution-mode controls.
  • The reported pruning witness now returns the same correct answer with the message enabled or disabled; EXPLAIN ANALYZE confirmed one input block with pruning and two without.
  • Interleaved local A/B runs on 100,000 identical rows showed median changes of +0.4% and -3.0% for non-repeated and repeated-leading-key resident Top (30 pairs), and -0.1% and +0.9% for their spill counterparts (8 pairs). These small shared-host samples cannot exclude small regressions. Existing Go benchmarks showed comparable allocations. No per-row work is added; the spill path no longer builds the position map.

@XuPeng-SH
XuPeng-SH requested a review from aunjgr as a code owner November 9, 2026 04:44
@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 Nov 9, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Commit: caa08b2dacadbb58bee5ee2548d1ebbeb88f60c4

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

Assessment: approve

No blocking findings remain. The first ORDER BY specification now governs comparators shared by repeated physical columns, while spill comparators retain each logical key's flags. This narrow backport reuses the existing ordering owners, preserves expression evaluation and resource cleanup, and aligns heap ordering with leading-key pruning without adding per-row work or new mechanisms.

Model: gpt-6.1-sol / max

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

Validation:

  • Reviewed the complete eight-file delta, relevant Top/MergeTop and pruning consumers, both discussion entries and linked issue #32396; discussion-assessment.json has exact key coverage and source-closure.md records contract and design closure.

  • Fresh branch-compatible native prerequisites were built through make cgo from 173 qualified tracked inputs; native-inputs.json and native-outputs.json retain input provenance and 44 output hashes.

  • Go 1.26.6 with production GOEXPERIMENT=simd and GOAMD64=v3: full Top and MergeTop normal and race suites each passed 29 top-level tests / 64 test and subtest outcomes, with no failures or skips. Owner go vet, changed-Go formatting and diff checks passed; see owners-normal.jsonl, owners-race.jsonl, vet.log and source-audit.json.

  • All three new regression tests passed on the candidate and failed for wrong ordering/NULL placement with exact frozen-base production-file overlays. baseline-summary.json, overlay input hashes and recovery logs retain the discriminating control. An initial setup timeout produced no test events; the missing control was subsequently completed.

  • Independently calculated tuple/NULL ordering matched all ten added SQL expected-result sections; public-oracles.json records these source-level oracles, not a local SQL execution.

  • validation-review.json and validation-review.log reconcile all 12 product/setup claims with local check-run command/source/exit receipts, timed test events and retained logs. The final audit exited zero and confirmed the frozen checkout remained unchanged.

Limitations:

  • No local cluster, BVT, two-CN, MySQL or full-query performance run was performed. The supplied author reports describe repeated two-CN SQL runs, a MySQL 8.0.44 ordering comparison and bounded performance comparisons; their raw execution logs are unavailable locally.

  • The frozen CI snapshot includes unfinished and queued checks, so it is not treated as a completed green run. Reported small timing variations do not establish performance equivalence; the reviewed change is limited to bounded comparator initialization.

@XuPeng-SH
XuPeng-SH merged commit fa6bc2b into 4.2-dev Nov 9, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/fix-32396-4.2-dev branch November 9, 2026 08:45
XuPeng-SH added a commit that referenced this pull request Nov 10, 2026
## What type of PR is this?

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

## Which issue(s) this PR fixes:

Related to matrixorigin/matrixflow#20285

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

Adapt the simple ZoneMap-filter admission fix from #32012 to `4.2-dev`,
including the reader compatibility fixes needed to preserve query
results on this branch.

- Admit safe direct-column comparisons and ranges independently of
estimated block selectivity, including unavailable statistics. Retain
ZoneMap safety checks, residual row predicates, cost estimates, explicit
disabling, and composite-key filters.
- Preserve comparison direction for constant-left inequalities in both
ZoneMap and primary-key reader filters without mutating shared
expressions or function IDs. A planner-only backport returned no rows
for `100 < k` where `[150, 200, 201]` was expected; this PR includes the
consumer fix rather than shipping that unsafe backport.
- Conservatively retain objects/blocks with uninitialized ZoneMaps for
the newly admitted simple predicates, including sorted-key
early-stop/seek paths.
- Fail open for initialized legacy FLOAT/DOUBLE ZoneMaps containing NaN
bounds, which may hide ordinary values. Reuse the existing NaN-bound
guard in scalar equality, strict comparison, and range interfaces; cover
both object/block pruning and sorted seek/early-stop consumers,
including single-end NaN summaries and ordinary-summary controls.
- Add planner/reader regressions and a small SQL BVT covering
clustered/interleaved layouts, commuted comparisons, primary-key
controls, prepared-statement NULL/reuse, and disabled-filter controls.
Preserve existing composite-key assertions without relying on predicate
ordering.

Additional correctness fixes after rebase:

- Preserve pre-existing block filters when statistics are unavailable,
and only newly admit simple predicates in that case. Keep the existing
cost, index and hint policy when statistics are available.
- Treat folded values that cannot safely become literals as unprunable
for range, hash and list partitions. Keep shared expressions unchanged
and retain normal pruning for representable bounds.
- Avoid ordered-block seeking and early termination for FLOAT/DOUBLE
sort keys because NaNs can make the physical block order non-monotonic.
Keep object and per-block ZoneMap checks; avoid raw-byte Bloom and fast
PK row filters for scalar floating-point primary keys so signed zero and
NaN do not lose rows.

Validation on rebased `4.2-dev` (`c6606110e8`):

- Complete `pkg/partitionprune`, `pkg/sql/plan`,
`pkg/vm/engine/readutil` and `pkg/vm/engine/tae/index` tests passed in
normal and `-race` modes on Linux/amd64 with Go 1.26.6 and the
repository CGo wrapper.
- Gofmt, incremental go vet, repository molint, and golangci-lint 2.6.2
passed for those owners and direct consumers `pkg/vm/engine/disttae` and
`pkg/sql/compile` (0 lint issues).
- A private single-CN SQL probe passed the range-partition prepared
sequence `11 → NULL → 11` with default and disabled block filters. The
normal `optimizer/non_primary_zonemap.sql` BVT passed twice (77/77
each), with database teardown checked between runs.
- The four-block floating-point counterexample and legacy NaN summaries
are covered by injected metadata tests; the test establishes the reader
boundary, not an end-to-end default-sized legacy object reproduction.

The float safeguard may examine every block summary in a sorted float
object and leaves scalar float primary-key filtering to the residual
predicate. It does not claim to resolve separate pre-existing float
upsert-probe behavior. Real customer-scale performance and the new
remote CI run remain unverified.

Historical author validation on earlier revisions:

- On then-current `4.2-dev` base `fa6bc2bcd9`: complete `pkg/sql/plan`
and `pkg/vm/engine/readutil` tests pass with Go 1.26.4 and the
repository CGo wrapper; gofmt, incremental go vet, and golangci-lint
2.6.2 built with Go 1.26.4 pass (0 issues).
- The same candidate also passed both complete packages and an actual
binary build on deployed source baseline `10d204b876`.
- On that deployment-baseline binary,
`optimizer/non_primary_zonemap.sql` passed normal mo-tester comparison
twice (60/60 each); generated expectations were checked against
independent expected rows before comparison. Cleanup was verified
between runs.
- The three original source SQL statements, including explicit
permission predicates and request variables, returned the expected
results on a 15-row synthetic fixture. Default scans fell from 6
blocks/15 rows to 2 blocks/6, 3, and 4 rows respectively. The extra
retained all-NULL block is intentional conservative handling, not a
correctness failure. No forced `blockFilter=1` was used.
- Changed-line-intersecting coverage blocks: 55/56; statement-weighted
coverage of those blocks: 104/105 (99.05%). This is not branch or
whole-package coverage.

Evidence reuse: the only change between previously validated
`a860d63a97` and current base `fa6bc2bcd9` is the repeated Top/mergeTop
ordering-key fix (#32402). It does not change the planner/readutil
implementation or this BVT fixture; current-base package/static checks
were rerun, while deployment-baseline SQL/BVT evidence is retained with
its original revision attribution.

Limitations: local validation was macOS/arm64, single-node CPU mode.
Real 96-million-row latency, Linux/multi-CN, original-tenant permission
integration, the full BVT/EXPLAIN baseline suite, and full CI are not
claimed as validated. IDC Dev was not upgraded, restarted, or modified.
Real-data acceptance still requires a suitable environment.

Review follow-up validation: the new legacy-NaN regressions failed
before the fix and pass afterward. Complete `pkg/vm/engine/tae/index`,
`pkg/vm/engine/readutil`, and `pkg/sql/plan` tests pass with Go 1.26.4;
incremental vet/lint pass. New production changed-line-intersecting
coverage blocks are 8/8 (100%). The compatibility fixture injects
historical summary bytes into a valid object metadata layout: the
current writer no longer emits this legacy state, so no new-write SQL
test is presented as a reproduction. Existing integer BVT evidence is
reused; it is not a NaN SQL acceptance claim.

CI follow-up (run 42600602130): the BVT failures comprised stale EXPLAIN
expectations and a range-partition pruning consumer that passed
materialized Fold constants directly to the general expression executor.
Normalize the already-copied partition expressions using the existing
hash/list conversion helper; preserve original filters and partition
metadata. The new UT fails with the original executor error before the
fix. Refresh only generated EXPLAIN checkpoints for the new block
filters; all SQL row results and UPDATE/DELETE expectations remain
unchanged.

After merging `mo/4.2-dev` at `e4f70a7268`, the four complete owning
packages (`partitionprune`, `plan`, `readutil`, `tae/index`),
incremental vet/lint, and two local normal mo-tester runs of all 11
failed files passed (1187/1187 each), with database teardown checked
between runs. Changed-line-intersecting statement-weighted coverage is
116/118 (98.31%). The earlier CI coverage job was blocked by failed BVT
prerequisites and did not compute a verdict. These local checks do not
claim the next remote multi-CN run is green.

CI and rebase follow-up:

- Rebased onto 4.2-dev `5dc6dec013`. Restore the existing index-table
ZoneMap admission rule when optimizer statistics are unavailable, still
requiring a zonemappable expression and honoring `blockFilter=2`.
Default costs and residual row filters remain unchanged. This removes
the missing-prefix-filter plan differences seen in run 42726120209;
unavailable statistics is a source-supported explanation, though that
run did not log its stats state.
- Added nil/error-stats, disabled-hint, ordinary-table and
volatile-expression controls; a real index-only rewrite now checks
prepared and NULL `prefix_eq`/`prefix_in` block filters. Both focused
tests reproduce the missing-filter behavior before the change.
- Go 1.26.4 Linux/amd64: `plan`, `partitionprune`, `readutil`, and
`tae/index` owning packages passed normal and race tests. Final planner
tests were rerun after the test additions. Incremental gofmt, vet and
configured golangci-lint passed for these packages plus `disttae` and
`sql/compile`.
- Using the exact CI mo-tester revision `309a0ca650` against a private
three-CN embedded cluster through one CN, the four affected BVT files
passed: decimal 625/625, index 134/134, index-cast 73/73 and non-primary
ZoneMap 77/77. A persisted secondary-index SQL probe also verified
equality and unordered prepared `IN` with NULL, with block pruning
enabled and disabled. These local runs do not replace the remote Proxy
and multi-CN BVT jobs.

---------

Co-authored-by: XuPeng-SH <[email protected]>
XuPeng-SH added a commit that referenced this pull request Nov 21, 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 #32396. Related to #32897 item 1 and the 4.2-dev fix #32402.

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

With repeated physical columns in ORDER BY, resident Top and heap
MergeTop configured the shared comparator from the last occurrence. This
could reverse a LIMIT result and give scan pruning a cutoff inconsistent
with the leading key. Resident Top and heap MergeTop now use the first
ordering specification for each physical slot, including its NULL
placement.

Spill Top stores one vector per logical sort key. Direct spill and
resident-to-spill migration now give each logical key an independent
comparator. This also prevents repeated keys from aliasing mutable
comparator bindings during migration. The change adds no work to row
comparison and avoids building a physical-slot map on direct spill.

### Validation

- On the exact main base, 13 of 16 independent SQL checks returned wrong
rows. The candidate matched all 17 checks, covering directions, NULLs,
aliases, intervening keys, OFFSET, pruning on and off, SQL PREPARE and
binary prepared reuse.
- An isolated two-CN probe verified remote execution and actual Top
spill. EXPLAIN ANALYZE reported 40,001 spilled rows and 318.13 KiB in
the spilling Top.
- Both owning Go packages passed normal and race suites. Regression
checks cover repeated keys, migration bindings, cutoff publication,
Reset and reuse, and NULL placement.
- The leading-key-pruning BVT passed 94/94 statements. Incremental
gofmt, diff check, err-check, vet, golangci-lint, and molint passed.

This branch was successfully deployed

No deployments
ci — f7ec09b9 Deployed Nov 9, 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/M Denotes a PR that changes [100,499] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants