Repository navigation
[4.1.6-hotfix] fix(index): fail open for NaN scalar ZoneMaps - #32431
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
|
mo-bot review · Commit: Review completed. Read the assessment. |
XuPeng-SH
left a comment
There was a problem hiding this comment.
mo-bot review · mo-bot-local · review
Commit: c5d722a17fc026e922ac78569293cf51bb78736c
Assessment: approve
The NaN guard belongs at the existing ZoneMap owner and conservatively protects scalar filtering, sorted seeks and early stops without changing persisted metadata or ordinary pruning. The INSERT fix reuses the established error-code helper and retains the fallback boundary. The small race dispatcher preserves inventory, flags, reports and failures while serializing embedded owners. These mechanisms are proportionate to the scoped safety fixes; no actionable defect or material unmet contract remains.
Model: gpt-6.1-sol / max
Session: 01a1a004-90c3-73b1-acc9-3d4636452003 · slot 0 · generation 0
Validation:
-
Reviewed the complete ten-file delta against ef9256e, the baseline NaN-producing writer, all scalar readutil consumers, error propagation/fallback and race-runner owners. source-review.md records the contract and design reasoning, finite/infinity/uninitialized controls and public SQL test oracle.
-
Read both chronological discussion entries and all linked context: matrixflow #20285 body plus 11 comments, and #32433 body plus its comment. discussion-assessment.json covers both PR keys exactly once. Earlier RPC incidents and broader CTAS latency reports were distinguished from this scoped fix.
-
Reused evidence.json eligibility_snapshot for the assessed head: Ubuntu/x86 UT, UT Coverage, Proxy and pessimistic multi-CN BVT, SCA and CI Required all record SUCCESS. The repository UT owner includes the changed index/readutil/planner/optools packages; skipped jobs were not treated as passes.
-
Local private-tmp/loopback preflight passed: preflight.log; checks/1794288253567875841-4.json. The initial optools command timed out fetching testify before test execution (optools-tests.log, checks/1794288384629107095-3.json, exit 124).
-
Recovered dependency fetching with GOPROXY=https://proxy.golang.org, reusing the same assigned caches, then ran the complete optools package through supplied test-exec: two top-level tests and 13 subtests passed with no skips/failures, package elapsed 0.144s. optools-direct-proxy.log; checks/1794288542441456608-3.json, exit 0.
-
Independent shell fixtures exercised the actual dispatcher and entry using mock external commands: 14 cases passed, including inventory/order, tags, ordinary/embedded failures, abnormal cancellation, empty scope and unchanged non-race execution; both Bash syntax checks passed. dispatcher-contract.log, dispatcher-contract-results.json; checks/1794288475282081615-5.json, exit 0. These fixtures did not run embedded clusters.
-
Final source fingerprints, 31 direct embedded importers, test terminal events, complete discussion coverage and command/source/exit receipts audited successfully: review-audit.log; checks/1794288643106206039-5.json. Frozen source remains clean.
Limitations:
-
Native libraries are absent from this read-only checkout; index/readutil/planner and the full Linux CI lane were not rerun locally. Their validation relies on the frozen current-head CI snapshot; author macOS and SQL run descriptions lack retained local receipts in this evidence bundle.
-
No business-data latency, production deployment or underlying RPC-stall root-cause validation is claimed. The scalar correctness fix does not change default planner admission or runtime-IN pruning; serial race admission is not proof of the earlier stall cause.
## 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 #32326 ## What this PR does / why we need it: Bare `NULL` projections are defaulted to text before set-operation type reconciliation. Consequently, numeric `UNION` queries and their CTAS consumers resolve to VARCHAR and sort lexicographically (`NULL, 10, 2` instead of `NULL, 2, 10`). - Preserve bare-NULL projection provenance in the binding context and exclude its default execution type from shared set-operation type reconciliation. - Exclude bare-NULL placeholders from CHAR/VARCHAR width reconciliation too, so their implementation width of 4 cannot widen declared CHAR(1)/VARCHAR(2) results. Preserve widening for real strings and explicitly typed NULLs, and retain the concrete all-NULL fallback. - Reconcile string widths after choosing the common type, for both implicit-cast and no-cast paths, before casting any arm. This prevents mixed VARCHAR/CHAR inputs from truncating long values, collapsing UNION DISTINCT rows, or persisting truncated CTAS data. Existing conservative implicit-conversion capacities remain lower bounds. - Keep concrete execution types for all-NULL branches, including nested set operations and branch-local ORDER BY/LIMIT; propagate provenance only through direct set-operation arms. - Preserve explicitly typed NULLs, real string branches, derived-table column types, and the existing set-operation/CTAS nullability rules. - Copy NULL AST literals rather than mutating them, so repeated CTE binding retains the original provenance. Handle parenthesized NULL projections consistently. - Preserve provenance through the internal `SELECT DISTINCT *` wrapper used when folding repeated parenthesized UNION arms. This is limited to the synthetic wrapper and does not relax user-written derived-table type boundaries. - Add 60 planner regression scenarios, each checking ordinary SELECT and CTAS types/nullability (including 20 string-width scenarios), plus an error-path check and SQL regression coverage for numeric ordering/arithmetic, COUNT, branch reversal, nesting, repeated-arm folding, NULL rows, declared-string controls, persisted string lengths, full string values, and DISTINCT cardinality. Validation on macOS arm64 with Go 1.26.4 and native libraries built in the isolated worktree: - Reproduced the original defect on the exact hotfix baseline `ef9256eca2c6436619272927e97f629af41ebd55`, which already includes #32085. The planner regression fails against unchanged baseline product code for numeric-versus-VARCHAR type mismatches. - Reproduced the repeated-arm folding omission on `aefc868bb0`, then verified numeric SELECT/CTAS types and ordering after the repair. Declared CHAR and genuine derived-table controls retain their existing string types. - Reproduced the bare-NULL width omission on `4d9e5d6566`: seven scenarios failed for SELECT and CTAS with expected width 1/2 versus actual width 4. Left/right NULLs, nesting/folding, typed-NULL widths, real-string widening, and the all-NULL fallback now pass. - Reproduced mixed-string truncation on `e8e06ba2b1`: the exact reported query returned NULL/a/a, CTAS stored VARCHAR(1), and DISTINCT produced only 2 rows. The original hotfix baseline and MySQL 8.0.45 retained abcdefgh and 3 rows. The repaired candidate matches MySQL for the exact witness, including full SELECT/CTAS values, VARCHAR(8) metadata, and DISTINCT cardinality. Seven of eight mixed-string planner scenarios failed before the repair; all eight now pass, including no-NULL, reversed-order, nested, folded-NULL, explicit-VARCHAR, and typed-NULL controls. - Merged the hotfix base `a5a8ed45fc` (#32431); it remains the current base. Focused regression, the full planner package, incremental static checks, service build, and SQL/BVT checks were rerun for the latest repair. - Focused regression and the full `pkg/sql/plan` unit-test package passed through the controlled CGo wrapper. Changed production statement-block coverage: 100% (27/27); overall planner package coverage: 61.3%. - Go 1.26.4 gofmt/vet and incremental golangci-lint v2.6.2 checks passed. - The new BVT case passed 86/86 statements on repeated same-instance runs after reviewing the generated result. Teardown checks confirmed the test database was removed. - The UNION BVT directory passed 182/182 statements, including the existing NULL/Top regression. The existing CTAS case passed 1176 statements with 0 failures and 30 existing ignored statements. - Numeric UNION/shared-contract SQL comparisons against MySQL 8.0.45 passed in earlier validation; the latest mixed-string witness was independently compared again. The explicit genuine-derived-table negative control intentionally retains MO's existing VARCHAR boundary, whereas MySQL optimizes that folded shape to BIGINT; this known difference is recorded separately and remains strictly asserted in planner and BVT tests. The expanded full SQL suite was not rerun against MySQL. This is a shared planner fix, not a CTAS-only cast workaround. No catalog/wire format or execution-operator changes are introduced. Validation used a single-CN instance; full CI, multi-CN testing, and exact MySQL 8.0.44 comparison were not run. Existing all-NULL fallback metadata differences, conservative conversion capacities in some branch orders, and broader derived-table compatibility are outside this repair; this PR does not claim complete MySQL schema-width equivalence.
…32550) ## 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#21333 ## What this PR does / why we need it: Adapt two complementary optimizations to `4.1.6-hotfix`: reduce repeated scalar CTE computation, and admit safe ZoneMap pruning independently of estimated block selectivity. This is **a target-branch adaptation, not a pure cherry-pick**. The branch lacks the CTE-sharing prerequisite used by #32522. This PR supplies a deliberately restricted prerequisite and adapts its non-truncating LIMIT proof, rather than importing main's general CTE materialization/spill subsystem. The ZoneMap portion adapts the admission work from #32012/#32419, preserves the existing #32431 protections, and does not import partition behavior changes. ### Two separate commits 1. **Safe ZoneMap admission and reader protections** (`ce71f6e3bf`) - Admit stable direct-column comparisons/ranges even with unhelpful or missing statistics; preserve residual predicates and `blockFilter=2` disabling. - Normalize constant-on-left comparisons without mutating shared expressions. Fail open for missing summaries and avoid unsafe floating-key seek, early-stop, and raw-byte filtering paths. - Retain the previous admission policy for partition tables. 2. **Bounded scalar CTE sharing and LIMIT proof** (`9f19e6fb7c`) - Match the same CTE declaration and actual bound source, including snapshots, types, and column mappings. Require deterministic, data-error-free producers with structurally at most one fixed-width row. - Bound each query to one shared producer, 64 readers, 256 output columns, and 64 KiB of fixed-width output. Unsupported, correlated/recursive, volatile, early-stop, or otherwise unsafe shapes remain inline. - Admit a positive literal LIMIT only when it covers a structural scalar/UNION ALL row bound. Statistics, OFFSET, and LIMIT itself do not tighten that bound. - Gather the final scalar result on the coordinator, project the compact published schema, and remap each reader after pruning. Give each reader a private copy through existing connector/spool machinery before evaluating expressions: decimal casts can mutate input vector metadata. - Preserve CTAS `HaveDDL=true` and same-transaction visibility. Do not force CTAS onto multiple CNs, change terminal protocols, or add a materialized source, spill store, or cross-query cache. ### Validation Local validation used **Go 1.26.4**, worktree-built native libraries, the CGo test wrapper, and golangci-lint 2.14.0 built with Go 1.26.4. - Both complete incident queries, with their original schema and **12 synthetic rows**: base-table scans changed from **8/4 to 1/1**. Actual CTAS produced 8/4 rows; business values and `SHOW CREATE TABLE` matched the optimization-disabled controls. Unordered row-number assignments were not used as an equality oracle. - Two independent local CN processes: both complete source SELECTs returned matching results from either coordinator. Actual remote contribution was verified by zero local scan rows on one coordinator, nonempty producer merge input, and matching business results—not merely an `AP_MULTICN` label or a remote placeholder in EXPLAIN. - ZoneMap fixture: clustered ranges read **1 block / 2 rows**, versus **3 blocks / 6 rows** with filtering disabled. Interleaved ranges correctly retained all three blocks. Commuted comparisons preserved results. - New BVT results were generated with mo-tester and verified twice: **41/41** for scalar CTEs and **60/60** for ZoneMaps. Adjacent ordinary/recursive CTE, recursive INSERT, and legacy NaN cases also passed (**54 + 124 + 31 checks**, including the new CTE case in the first group; none ignored). - Planner tests cover 2/4/8-branch LIMIT boundaries, structural unknown/overflow/cycle controls, source identity, pruning, and unsafe-inline cases. Compiler/operator tests cover local/remote-shaped producers, reader vector isolation, success/error/cancellation, partial preparation/publication, and zero residual mpool usage. Targeted race checks passed. - `go vet`, incremental lint, gofmt, and diff checks passed. Changed-line coverage mapped through Go coverage blocks is **519/616 = 84.25%**; affected-block statement coverage is **434/505 = 85.94%**. **Known baseline test failures:** the initial related-package run hit these three Parquet tests. The same failures were reproduced on a clean `54feca6423` worktree with matching Go/native inputs. The subsequent related-package run passed while explicitly excluding only these tests; no test was disabled or weakened in the committed code: - `TestCompileExternScanParquetLoadUsesRowGroupFanoutWithEmptyFiles` - `TestCompileExternScanParquetRowGroupFanoutValidatesEmptyFileColumnCount` - `TestCompileExternScanParquetLoadUsesFileFanoutMainPath` The package selection covered planner, compiler, readutil, TAE index, dispatch, merge, connector, pSpool, and process. This is not a claim that the unfiltered full suite or CI is green. ### Limits of the evidence No production deployment, production CTAS/DML, or production-scale latency/throughput/memory acceptance was performed. The small local fixtures establish plan, result, metadata, and lifecycle behavior; they do not establish a production wall-clock speedup. Customer SQL, local evidence, credentials, and build/data artifacts are not included in this PR. ### P2 review follow-up: concurrent copying of a broadcast batch Addressed in [`c8e4f588b7`](c8e4f58), after merging latest target `bf18d10904` (nullability inference). - Confirmed the review finding: `GetCopiedBatch` moved `ExtraBuf` out of its source, so multiple reader connectors copying a broadcast batch raced even with nil metadata. Both a minimal spool regression and the real compiler/connector path failed under `-race -count=1`. This proves a data race, not an observed wrong SQL result or crash. - Fix the common copy owner with `slices.Clone(src.ExtraBuf)`. Source metadata is read-only; destinations own independent backing. No reader serialization, if-nil workaround, or terminal-protocol change. Nonempty metadata copying costs O(metadata bytes); the scalar fixed-width output bound is not a general bound on serialized metadata. - Regressions now run the **copy phase concurrently** rather than only modifying completed copies concurrently. Cover nil/empty/nonempty metadata, source preservation, non-aliasing, cache reuse, 4/8 real readers, error/cancellation/partial preparation/publication, and zero residual mpool usage. Each exact concurrency test passed **100 race repetitions**. - Spool/compiler owning normal/race checks passed with the same three previously disclosed unrelated Parquet failures explicitly excluded from compiler selection. Unfiltered runs retain those failures; no repository test was disabled or weakened. Connector/dispatch/process race, merged plan/function/group normal tests, vet and incremental lint passed. Changed-production line coverage against the latest base is **520/617 = 84.28%**; the copy fix is **1/1 = 100%**. - On a fresh local service, complete scalar CTE, ZoneMap and CTAS fixtures passed twice: **41**, **60**, and **1,284** successful checks respectively per round, with **30 pre-existing CTAS ignores** and zero failures. An initial CTAS run with an inappropriate private default database was excluded; the final runs used no JDBC default database, preserving privilege/no-database assertions without changing SQL/results. - Rebuilt and revalidated both complete incident queries on the merged base: one base scan each, actual CTAS 8/4 rows, matching business values and table metadata versus disabled-optimization controls, plus two-CN remote contribution/result checks. No production access or production-scale performance acceptance. Post-push CI and maintainer design approval are not claimed. ### Versioned design and approval status - **Repository design document:** [v3-public.3 — scalar CTE sharing and safe ZoneMap admission](https://github.com/matrixorigin/matrixone/blob/c8e4f588b798984c2068802a1d20c2f682972e1e/docs/design/CLAUDE_32550_scalar_cte_zonemap_design.md) (`docs/design/CLAUDE_32550_scalar_cte_zonemap_design.md`). This commit-pinned repository file is the authoritative design; the earlier v3-public.1 PR comment is historical, not the formal document location. - The document binds base `54feca6423`, implementation `9f19e6fb7c`, and expectation-only fix `35edb87c48`. Revision v3-public.2 moved the document into the repository; v3-public.3 adds the source-immutable metadata-copy contract, review regression, and merged-base validation in section 10. - Approval provenance: the requester approved local v3 with “go ahead” before implementation and authorized delivery with “go on”. These are private-session scope/implementation authorizations, **not a maintainer design approval**; no public link to that private exchange is claimed. - **Maintainer design approval: pending.** XuPeng-SH is requested as reviewer. Please review **v3-public.3 at the pinned repository revision** and record approval/requested changes on GitHub. Publishing the document does not itself close the design-gate blocker. - Review item 1 (EXPLAIN expectations) was addressed in `35edb87c48`: the 10 affected cases passed twice locally, each with 999 successes, zero failures, and eight unchanged pre-existing decimal ignores.
What type of PR is this?
Which issue(s) this PR fixes:
Related to https://github.com/matrixorigin/matrixflow/issues/20285
What this PR does / why we need it:
Port the scalar NaN-ZoneMap safety fix identified during review of #32419 to
4.1.6-hotfix.The defect also exists on this branch independently of the new planner admission policy: its current writer can persist an initialized
[NaN, NaN]summary for a block containing[NaN, 7]. Scalar pruning then incorrectly rejects ordinary value7. Unlike4.2-dev, this branch also lacks the existing conservative>=/<=guards.index.ZMownership boundary.<,<=,>,>=, andBetween;InRangeinherits the safe comparisons for all open/closed bounds.This is a minimal scalar-pruning fix. It does not backport the #32012 planner-admission change, change the writer/storage format or row-level NaN semantics, or redesign runtime-IN pruning.
Validation on base
ef9256eca2(macOS/arm64, Go 1.26.4, CPU CGo):pkg/vm/engine/tae/index,pkg/vm/engine/readutil,pkg/sql/plan, andpkg/container/typestests pass using the repository CGo wrapper borrowed into the worktree (the older branch does not contain it).zm.go, to HEAD; no working-tree rollback or 4.2 native artifacts are involved.7in eight forced-block-filter cases across FLOAT/DOUBLE equality,>,>=, andBETWEEN; disabled controls return it. The small fixture's default mode does not reproduce the failure, so no default-mode reproduction claim is made.optimizer/legacy_nan_zonemap.sqlexpectations generated and reviewed, then normal mo-tester comparison passes twice on the same instance: 31/31, 31/31, with database teardown verified between runs.Linux/multi-CN, full CI, and real business-data acceptance are not claimed as validated. No IDC cluster was upgraded, restarted, or modified.
CI follow-up: error propagation and bounded embedded race execution
Related to #32433. The failed rerun exposed an independently reproducible panic: INSERT binding asserted every error as
*moerr.Error, so a standardcontext.DeadlineExceededtriggered a second panic. Use the existingmoerr.IsMoErrCodeguard and preserve the original error. Regression controls retain both permitted legacy fallback cases and reject fallback for other errors/upserts.The release-branch runner previously admitted all packages through one
go test -p8 -racecommand. Run ordinary race packages first at the requested parallelism, then execute embedded-cluster packages serially with no overlap. This includespkg/embed,pkg/tests/*, and the existingpkg/util/testembedded owner. Preserve race/short/tags/timeouts, the complete package inventory, concatenated JSON reports and nonzero exit status; do not retry, skip tests, weaken assertions, or increase timeouts. The non-race path is not split into stages.Follow-up validation (Go 1.26.4, macOS/arm64):
go listinventory contains 421 packages: a mock-command execution through the real dispatcher proves each appears exactly once (408 ordinary, 13 embedded). This inventory check is not a full UT run.-race -short -tags matrixone_test -count=1 -p1:TestPitrCases,TestDeleteAndSelect,TestClientDisconnectCancelsQueryAndRollsBack,TestAffectedRows, andTestPartitionBasedShardCanBeCreated. The cascade failureTestDataBranchDiffAsFilealso passes in a separate race run. Selected package execution took approximately 17–22 seconds each; the latter test took 33.81 seconds, excluding compilation.These changes fix the demonstrated error-type panic and enforce a bounded resource-admission contract. They do not prove the underlying runner CPU/I/O/HAKeeper stall cause, full Linux CI success, or full-lane timing acceptance. The original RPC incident remains tracked in #32433. The previous rerun passed Proxy BVT and coverage; CI for the new commits is pending.