Skip to content

frontend: fix result save/scan chain issues (#30552 #30553 #30571) - #30641

Merged
XuPeng-SH merged 7 commits into
mainfrom
fix-result-scan-chain-305xx
Oct 22, 2026
Merged

XuPeng-SH merged 7 commits into
mainfrom
fix-result-scan-chain-305xx

Conversation

@aptend

@aptend aptend commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

What this PR does / why we need it:

Fixes three issues in the save-result / result_scan / MODUMP chain:

  1. [Bug]: MODUMP max_file_size panics with 'cannot create context from nil parent' when splitting large results #30552 — modump query_result ... max_file_size panics with cannot create context from nil parent on the first file rotation. ExportConfig only sets Ctx, while the rotation path passes ep.ctx (nil). Fixed both ends: openNewFile now falls back ep.ctx -> ep.Ctx -> context.Background, and doDumpQueryResult propagates the statement ctx to exportParam.ctx. Regression UT Test_openNewFile_nilCtx added (fails with the exact panic on the old code).

  2. [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 by saveMeta, but zero-row results save no data blocks, leaving ResultPath empty. saveQueryResult2 finalization now persists one typed empty block first when the query produced zero rows (mirroring the cursor path's FinishStage), so the saved result stays scannable and returns an empty set.

  3. [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 in vector.unionT / unsafe slice cast, because ZonemapReader used the prune-affected ColIndex as the file column index while RESULT_SCAN never populated TbColToDataCol. buildResultScan now fills TbColToDataCol from a dedicated copy of the name->file-column map (kept separate from Name2ColIndex, which later optimizer passes may rewrite), and getBatchFromZonemapFile locates file columns via ColFieldIndex, matching the CSV/parquet readers.

Validation

  • New UT Test_openNewFile_nilCtx: red/green (old code panics with the exact issue message).
  • pkg/frontend targeted tests and pkg/sql/colexec/external full package: pass.
  • Live e2e on this branch: MODUMP with forced rotation (max_file_size 1) produces 3 split files with intact rows and no server panic; empty result_scan returns an empty set; single-column projections, count/sum/min/max/avg, and filtered queries over result_scan all return correct results; server log contains zero panics.

Special notes

None.

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-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 →

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.
@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: a89434c6bac3280362474e06b7c946d572de3a94

"interrupted"

@XuPeng-SH

XuPeng-SH commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

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

Commit: a89434c6bac3280362474e06b7c946d572de3a94

Review completed. Read the assessment.

@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-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
aunjgr previously requested changes Oct 20, 2026

@aunjgr aunjgr 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.

REQUEST_CHANGES at a89434c6bac3280362474e06b7c946d572de3a94.

Two findings from independently tracing the complete five-file delta:

  1. [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 builds Filter.columnMap from the pruned param.Cols positions; ZonemapReader.needRead passes 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), then SELECT b FROM result_scan('<saved-query-id>') AS r WHERE b IS NULL. Pruning keeps only b: its output position is 0 and its file position is 1. The new vector mapping records 1, but the filter map records 0. GetExprZoneMap's ISNULL branch (evalExpression.go:2882-2887) consequently reads file column a's persisted null count (0), returns false, and ReadBatch skips 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.

  2. [P2] Close and join each async writer in the new nil-context test. export_test.go:139-144 calls openNewFile twice on the same ep without the production rotation path's intervening Close(ep), and installs no cleanup for either call. Each open creates io.Pipe and starts an errgroup goroutine; with Header:false, a fresh writable local path, and context.Background(), LocalETLFS.write -> io.CopyBuffer -> ioEntriesReader.Read -> PipeReader.Read waits 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.
@aptend

aptend commented Oct 20, 2026

Copy link
Copy Markdown
Contributor Author

Review findings addressed in the new head commit:

P1 (filtered result_scan pruning, reader_zonemap.go): new translateZonemapFilterColumnMap rewrites the filter columnMap from the (possibly pruned) output schema to physical file indexes. Live repro of the review case: saved result (42,NULL),(10,1), select b from result_scan(Q) as r where b is null now returns exactly 1 NULL row (was 0); where a=42, full projection, and cross-column filter probes all correct.

P2 (Test_openNewFile_nilCtx race): the test now closes each async writer and joins its group BEFORE reopening, uses a distinct file for the second open (a completed rotation really creates the file and ETL write refuses overwrite), and removes both on setup/teardown. Passes -race -count=1 twice in a row.

Regression after the fixes: #30571 count/sum + filter probes, #30552 forced rotation (max_file_size 1 → 3 split files), #30553 empty-result scan (0 rows) all green; pkg/frontend (-race) and pkg/sql/colexec/external targeted runs pass.

@XuPeng-SH

XuPeng-SH commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-xupeng · superseded

Commit: 0838c77eab1fc6e1443a809bb49d31bfdd44c8ae

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

@mergify

mergify Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-22 06:32 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🚫 Left the queue — 2026-10-22 06:57 UTC · at 0838c77eab1fc6e1443a809bb49d31bfdd44c8ae

This pull request spent 25 minutes 42 seconds in the queue, with no time running CI.

Reason

The pull request cannot be checked because of an incompatibility with branch protections

'Require a pull request before merging' branch protections are enabled on fix-result-scan-chain-305xx, Mergify cannot check the pull request inplace.

Tick the box to put this pull request back in the merge queue (same as @mergifyio queue).

  • Requeue this pull request

@mergify mergify Bot added dequeued and removed queued labels Oct 22, 2026
@mergify mergify Bot removed the dequeued label Oct 22, 2026
@XuPeng-SH
XuPeng-SH merged commit 9f7fe43 into main Oct 22, 2026
XuPeng-SH added a commit to XuPeng-SH/matrixone that referenced this pull request Nov 16, 2026
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)
XuPeng-SH added a commit that referenced this pull request Nov 16, 2026
…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>
@XuPeng-SH
XuPeng-SH deleted the fix-result-scan-chain-305xx branch November 30, 2026 13:07

This branch was previously deployed

1 inactive deployment
ci — 8894cf79 Deployed Oct 22, 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.

4 participants