Repository navigation
frontend: fix result save/scan chain issues (#30552 #30553 #30571) - #30641
Conversation
1. MODUMP max_file_size rotation panics with a nil context (#30552): openNewFile now falls back to ExportParam.Ctx and then context.Background, and doDumpQueryResult also propagates the stmt ctx to exportParam.ctx. 2. Scanning a saved empty result set fails with an invalid input error (#30553): saveQueryResult2 finalization now persists one typed empty block before writing the meta when a query produced zero rows, so the meta always references a readable block, mirroring the cursor path. 3. Single-column projections over result_scan panic or read wrong data (#30571): buildResultScan now fills TbColToDataCol with the saved schema's name->file-column map, and ZonemapReader locates file columns by ColFieldIndex instead of the prune-affected ColIndex.
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? |
buildResultScan populated ExternScan.TbColToDataCol with the same map instance as TableDef.Name2ColIndex. Later optimizer passes may rewrite Name2ColIndex in place; the file-column mapping must stay fixed at the positions of the saved result schema. Keep a dedicated copy.
|
mo-bot review · Commit: "interrupted" |
|
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: a89434c6bac3280362474e06b7c946d572de3a94
Assessment: request_changes
Reviewed the complete five-file delta and its callers. The existing ownership and typed-empty-block approach are reasonable, but filtered result_scan projections remain incorrect, and the new export regression test introduces data races.
Model: gpt-6-astra / xhigh
Session: 01a13dcf-1517-7f90-b3f9-c5f9f9e7031b · slot 0 · generation 1
-
P1
pkg/sql/colexec/external/reader_zonemap.go:185: Save columns a=42 and b=NULL, then execute SELECT b FROM result_scan('') AS r WHERE b IS NULL.
Impact: The scan discards the matching row. Data loading uses physical column 1, but External.Prepare still constructs Filter.columnMap from the pruned schema, mapping b to physical column 0. Block pruning consequently checks a's null count. Propagate the physical mapping into metadata filtering and add a filtered-projection regression test.
Evidence: SQL planning confirmed the pruned schema contains only b, with file index 1 and filter ColPos 0. A real WriterQueryResult object scanned through External.Prepare/Call returned zero rows instead of one; both the unfiltered scan and a physical-filter-map control passed. See review-result-scan.log, receipt checks/1792478835440756166-5.json, and review-plan.log. This is a preexisting part of the projection/filter correctness problem left unresolved by this PR, not a newly introduced regression. -
P2
pkg/frontend/export_test.go:142: Test_openNewFile_nilCtx opens the same ExportConfig twice without closing and joining the first asynchronous writer.
Impact: The second open overwrites FileService and AsyncReader while the first writer accesses them, causing data races and abandoning writer resources. Close each writer before reopening and clean up the final writer; preferably exercise the actual max-size rotation path.
Evidence: The unmodified test failed with -race -count=1 -run '^Test_openNewFile_nilCtx$'. Race reports identify export.go:192 versus :211 and :199 versus :206, originating from export_test.go:142. See review-export-race.jsonl and receipt checks/1792479015979836505-3.json.
Validation:
-
Artifacts are retained under /home/xupeng/.local/state/mo-bot/jobs/2273d6876b677065c467c886/attempt-1. Preflight and native prerequisites passed; tests used the repository provenance-checking wrapper, assigned caches, and supplied test-exec.
-
Confirmed the filtered-projection failure with real saved-result storage and operator execution, plus passing controls. A separate SQL planner test confirmed reachability.
-
Typed empty-result finalization and readback passed, preserving both column types and zero rows. Existing Test_saveQueryResultMeta also passed. Two earlier diagnostic fixture failures were corrected and retained separately.
-
The new export test failed under the race detector. Receipt/log/source reconciliation passed and is recorded in review-evidence-audit.json. Assigned source remained unchanged.
-
Performance audit found an additional O(column-count) planning map and one object write for empty saved results; no additional ordinary SQL execution work when result saving is disabled.
Limitations:
-
No live SQL server run, full package rerun, or performance benchmark was performed. Planner and operator checks are distinct from end-to-end SQL execution.
-
Frozen CI reports success, but local_validation is empty and the author's live-test claims lack retained execution receipts. Linked issue contracts were assessed from the supplied PR description.
aunjgr
left a comment
There was a problem hiding this comment.
REQUEST_CHANGES at a89434c6bac3280362474e06b7c946d572de3a94.
Two findings from independently tracing the complete five-file delta:
-
[P2] Complete the file-column mapping fix for block pruning, not only vector loading. In reader_zonemap.go:180-190, vector loading correctly switches to
ColFieldIndex. However,External.Prepare(external.go:188-194) still buildsFilter.columnMapfrom the prunedparam.Colspositions;ZonemapReader.needReadpasses this map directly to physical block metadata before loading any vectors.A concrete remaining counterexample to #30571 is a saved two-column result with one row
(a=0, b=NULL), thenSELECT b FROM result_scan('<saved-query-id>') AS r WHERE b IS NULL. Pruning keeps onlyb: its output position is 0 and its file position is 1. The new vector mapping records 1, but the filter map records 0.GetExprZoneMap'sISNULLbranch (evalExpression.go:2882-2887) consequently reads file column a's persisted null count (0), returns false, andReadBatchskips the block. Expected: one NULL row; actual source path: empty result. This does not depend on initialized min/max zonemaps: the object writer explicitly persists column null counts (writer.go:900).This is an unclosed consumer of the same mapping invariant addressed by this PR, not a claim that this PR introduced the original pruning defect. Derive RESULT_SCAN's pruning map from the same immutable file-column mapping, or conservatively disable pruning when it cannot be established. Add a public SQL regression with different null distributions across the omitted/projected columns; successful ordinary equality filters do not cover this case.
-
[P2] Close and join each async writer in the new nil-context test. export_test.go:139-144 calls
openNewFiletwice on the sameepwithout the production rotation path's interveningClose(ep), and installs no cleanup for either call. Each open createsio.Pipeand starts an errgroup goroutine; withHeader:false, a fresh writable local path, andcontext.Background(),LocalETLFS.write -> io.CopyBuffer -> ioEntriesReader.Read -> PipeReader.Readwaits indefinitely for data/EOF. The second open overwrites the first pipe/group ownership, and the test returns without closing the second writer either. The blocked writers also retain their temporary file descriptors/buffers. Repetition accumulates these resources; this is a test-lifecycle defect, not a claimed new production leak.Use a test-private path, register cleanup immediately, close/join the current writer before reopening (as real rotation does), and close/join the final writer even when an assertion fails. The closure also captures mutable
ep, so generations must not overlap. Verify the focused test under the race detector after fixing its ownership.
Lifecycle audit:
| Check | Closure/result |
|---|---|
| Q1 ownership | The new typed empty batch is cleaned on save success/error. Production rotation closes the old writer before reuse. The new test loses the first writer/group and never cleans the final one: finding 2. |
| Q2 waits | A background-context pipe read in that test has neither EOF nor a remaining cleanup owner: finding 2. |
| Q3 bounds | No new persistent cache/queue; one empty block is guarded by zero rows/zero blocks. Test repetitions retain writers/FDs until process exit: finding 2. |
The nil-context propagation and independent saved-file column map otherwise address their stated root causes. Existing query-result format, permission checks and result-file cleanup ownership remain unchanged. Ordinary bug fixes do not require a feature-design gate.
Validation: complete source/consumer review plus green exact-head CI and the author's reported focused/live-SQL checks. The two findings above are source-backed; I did not claim a fresh local frontend/race/BVT run. The reported live cases do not close the NULL-pruning counterexample or the new test's missing teardown.
- colexec/external: translate the zonemap filter columnMap from the (possibly pruned) output schema to physical file indexes in ZonemapReader.Open, so result_scan block pruning checks the right column's zone map / null count. Without this, a saved schema [a,b] with 'select b ... where b is null' prunes blocks by a's stats and wrongly drops matching rows. Add Test_translateZonemapFilterColumnMap covering pruned projection, identity, and nil filter cases. - frontend: make Test_openNewFile_nilCtx race-free and hermetic: close and join each async export writer before reopening the config, use distinct output files per open, and remove them on setup/teardown (the previous version was caught by -race). Verified live: the filtered projection now returns the expected NULL row, #30571/#30552/#30553 regression probes stay green, and targeted -race / unit runs of pkg/frontend and pkg/sql/colexec/external pass.
|
Review findings addressed in the new head commit: P1 (filtered result_scan pruning, P2 ( Regression after the fixes: #30571 count/sum + filter probes, #30552 forced rotation ( |
|
mo-bot review · Commit: Review belongs to an older commit; it is not a review of the current head. |
Merge Queue Status
This pull request spent 25 minutes 42 seconds in the queue, with no time running CI. ReasonThe pull request cannot be checked because of an incompatibility with branch protections
Tick the box to put this pull request back in the merge queue (same as
|
Backport the empty-result persistence and result-scan projection fixes from matrixorigin#30641. The MODUMP context lifetime is already handled by matrixorigin#30742 on 4.2-dev. (cherry picked from commit 9f7fe43)
…32803) ## What type of PR is this? - [ ] API-change - [x] BUG - [ ] Improvement - [ ] Documentation - [ ] Feature - [x] Test and CI - [ ] Code Refactoring ## Which issue(s) this PR fixes: Related to #30553 and #30571. Related to matrixorigin/matrixflow#18267. ## What this PR does / why we need it: Backport the saved-result fixes from #30641 to `4.2-dev`: - Persist a typed empty block before the metadata for a successful zero-row query, so a newly saved empty result can be read by `result_scan` and exported. - Preserve the mapping from projected result columns and filter columns to their physical positions in the saved result file. - Retain the upstream result-scan regression cases and adapt their types and fixtures to the 4.2 branch. - Update the existing direct-reader test fixture with physical column indexes, and preserve ENUM metadata when creating an empty result block. The MODUMP rotation context addressed by #30641 is already handled by the 4.2 export lifecycle in #30742, so this backport retains that existing implementation. ### Validation - Go 1.26.4, macOS arm64: `gofmt`, `git diff --check`, and `go vet` passed for the changed Go packages. - The `pkg/frontend`, `pkg/sql/colexec/external`, and `pkg/sql/plan` test binaries compiled with `-race`; they were not executed locally. - The backported UT and SQL regression cases and the full CI have not yet been executed on this revision. Previously saved results without data blocks are not repaired by this change. End-to-end verification requires a newly executed query. --------- Co-authored-by: Codex <codex@localhost>
What type of PR is this?
What this PR does / why we need it:
Fixes three issues in the save-result / result_scan / MODUMP chain:
[Bug]: MODUMP max_file_size panics with 'cannot create context from nil parent' when splitting large results #30552 —
modump query_result ... max_file_sizepanics withcannot create context from nil parenton the first file rotation.ExportConfigonly setsCtx, while the rotation path passesep.ctx(nil). Fixed both ends:openNewFilenow falls backep.ctx -> ep.Ctx -> context.Background, anddoDumpQueryResultpropagates the statement ctx toexportParam.ctx. Regression UTTest_openNewFile_nilCtxadded (fails with the exact panic on the old code).[Bug]: empty result set marked /* save_result */ is not persisted — result_scan/modump report 'query id not found' #30553 — scanning a saved EMPTY query result errors with
invalid input: empty query result. The meta is written bysaveMeta, but zero-row results save no data blocks, leavingResultPathempty.saveQueryResult2finalization now persists one typed empty block first when the query produced zero rows (mirroring the cursor path'sFinishStage), so the saved result stays scannable and returns an empty set.[Bug]: aggregating a column over result_scan() panics with 'index out of range [16] with length 12' #30571 — single-column projections / aggregates over
result_scan(...)panic invector.unionT/unsafe slice cast, becauseZonemapReaderused the prune-affectedColIndexas the file column index whileRESULT_SCANnever populatedTbColToDataCol.buildResultScannow fillsTbColToDataColfrom a dedicated copy of the name->file-column map (kept separate fromName2ColIndex, which later optimizer passes may rewrite), andgetBatchFromZonemapFilelocates file columns viaColFieldIndex, matching the CSV/parquet readers.Validation
Test_openNewFile_nilCtx: red/green (old code panics with the exact issue message).pkg/frontendtargeted tests andpkg/sql/colexec/externalfull package: pass.max_file_size 1) produces 3 split files with intact rows and no server panic; emptyresult_scanreturns an empty set; single-column projections,count/sum/min/max/avg, and filtered queries overresult_scanall return correct results; server log contains zero panics.Special notes
None.