Skip to content

fix(frontend): preserve SQL source through policy rewrite - #29600

Merged
XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-29597-rewrite-source
Oct 4, 2026
Merged

XuPeng-SH merged 4 commits into
matrixorigin:mainfrom
XuPeng-SH:codex/fix-29597-rewrite-source

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Oct 4, 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:

Fixes #29597

What this PR does / why we need it:

SQL provenance was indexed by block-comment position instead of statement position. A generated policy hint could hide a save_result marker; in multi-statement requests a marker on the second SELECT could save the unmarked first SELECT instead. Restricted queries returned correct rows, but result persistence was absent or attached to the wrong query UUID.

Bind the existing source vector at the computation-wrapper boundary using the grammar-aligned scheduling fragments. Use the existing whole-stream lexer when source-tag candidates exist so quoted text, ordinary comments, compound statements and executable-comment wrappers retain their real boundaries. Discard blank fragments together with their source entries. This applies to fresh parsing, cache hits and SQL-mode staged execution, without another full SQL parse or persistent state.

Exact tag-text absence is a conservative fast path, not a raw-text classifier: any candidate, including one inside a string, still requires lexical validation. Authoritative internal provenance bypasses source scanning using one shared predicate and is rechecked when publishing every source slot. Fragment validation remains unconditional; fragment-end arrays are allocated only for source scanning and the fresh source vector is compacted in place.

Policy materialization copies the input and refreshes SQL/hash. Generated hints do not become source markers. SQL PREPARE captures the current statement's source rather than all siblings; decoded string/variable bodies retain explicit nonuser protection. Syntax-error diagnostics keep their lexical boundaries and do not publish an executable source vector.

Tags remain case-sensitive. Real inline/trailing ordinary block markers count; marker-looking literals and line comments do not. Conflicting tags resolve to cloud_nonuser regardless of order. Existing result-saving and saved-result authorization gates remain unchanged.

Validation:

  • Reproduced the original failure on clean main through the frontend boundary and MySQL protocol: restricted SELECT succeeds, saved-result lookup fails with error 20440.
  • Source/lexer tests cover sparse markers, literals, comments, conflicts, empty fragments, compounds, executable wrappers and scanner reuse. Current frontend tests additionally verify fast-path fragment validation, all internal predicates, fresh/cache publication, and an escaped PREPARE tag that appears only after decoding.
  • Real single-CN MySQL matrix validates no/row/column/combined policies, exact returned and saved rows/columns, metadata, sparse multi-statements, non-saving controls, hidden-column failure/recovery and privilege revocation. Two lifecycles reuse one CN and names with checked cleanup.
  • Additional protocol QA passes for SQLMode lexical transitions, native/text/variable PREPARE, executable-comment wrappers, NULL/UTF8 values and partial batch failure followed by recovery.
  • Full current frontend tests, scoped go vet and incremental lint pass (0 issues). Unchanged parser/lexer suites passed on the preceding revision and were reused. Local platform: Darwin/arm64, Go 1.26.4.

Performance: normal-mode, single-CPU microbenchmarks with five samples per cell and reversed run order compare exact base and fixed code. Marker-free 64 KiB source binding is about 145–146 us on both, with identical 67,960 B/op and 23 allocations; the former extra payload-sized allocation is removed. Plain native EXECUTE source classification is about 62 ns (previous PR revision about 423 ns; base about 40 ns). Candidate-containing external input still uses precise lexical classification; marked multi-statement workloads retain its additional cost compared with the old inaccurate classifier. These are source-binding/parsing measurements, not end-to-end query throughput claims.

No persisted format/protocol change, new execution path, cache or state flag. Historical saved-result snapshot/refilter semantics are unchanged. Remote CI is not awaited or claimed to pass.

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

Resolved by 023be960e5d81c024bf4ca0b307622f40482a882. This historical review concerned head 140c54431235090d18bdfb8ce59ff87bb1a2a544; it is superseded by the final whole-PR review.

The confirmed P2 finding was a sparse-marker COM_QUERY (select ...; /* save_result */ select ...) saving the first unmarked SELECT instead of the marked second SELECT. The old producer indexed block comments rather than statements. Clean-base comparison established that the general no-policy bug predated the PR, while the original patch newly exposed wrong saving under mandatory policy.

The correction binds source slots to existing grammar-aligned statement fragments, handles real comments through the SQL lexer, and isolates PREPARE/error provenance. Real protocol regression now passes for both no-policy and mandatory row/column-policy requests: first result missing with20440, second result and metadata readable with exact authorized rows/columns. Astra/xhigh final review reports no material blockers; relevant packages, public matrix and scoped static checks pass. This remains a self-authored COMMENT, not a formal GitHub approval. Remote CI was not awaited.

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

Resolved — superseded by final head review

The performance P2 on this reviewed commit (023be960e5d8) is fixed by 3dae3634fbe759bd69688f7edf83f45835b8b231. See the final head-bound review.

Historical finding: marker-free 64 KiB SQL was redundantly tokenized solely for source classification, adding about 65,568 B/op and 90–129% binding time; authoritative internal input paid the same cost before its source override. Functional QA passed but the unconditional approval recommendation was withdrawn pending this correction.

Resolution: conservative tag-absence prefilter and authoritative internal bypass, preserving grammar/fragment validation, exact lexer fallback and final all-slot protection. Fixed binding allocation matches base (67,960 B/op, 23 allocations); five-sample runs in both orders show worst median timing difference about +0.6% from base. Current frontend/public QA/vet/lint pass; final gpt-6-astra/xhigh overall review reports no unresolved material blockers. This historical COMMENT is no longer an outstanding request for changes.

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

Final review: no unresolved material blockers

Re-reviewed latest head 3dae3634fbe759bd69688f7edf83f45835b8b231 against base 1a2e591d95489fdb51fe2b0c5c0bf012201c7c1e. This additional deep review was performed directly, without subagents or a delegated model run. Every changed hunk, producer/consumer boundary, implementation/test/document increment and historical review finding was reconciled; prior model-gate and current-code test evidence were reused where source/fixture fingerprints match.

Additional independent QA: 384 deterministic lexer pairs passed (0.503 s), combining three SQL modes, quoted/escaped/Unicode expressions, real/line/hint/incomplete comments and executable wrappers. Projecting COMMENT tokens out of ScanWithComments produces the unchanged parser-facing token/value stream; every comment's reported byte range matches original SQL. This specifically challenges the observer API and byte positions used for statement-source binding. No tracked source was changed.

Historical sparse-source and performance P2 findings are both closed by code plus consumer evidence. GitHub review threads contain no unresolved code comments; the Qodo subscription notice is not a code finding.

Unhappy-path audit Result
Ownership/cleanup Scanner borrows have deferred returns; source compaction only touches new request-owned slices; existing prepared ownership preserved.
Termination Input-bounded scans/fragment loops, no new asynchronous owner or blocking dependency.
Growth/reuse Per-request bounded arrays and unchanged scanner pool reset/oversize handling; no new cache or persistent state.

Technical recommendation: APPROVE. Submitted as COMMENT because this account owns the PR; this is not a GitHub formal approval.

The previous performance P2 is resolved. The complete PR and corrective delta were reviewed with gpt-6-astra / xhigh, with actual model/effort verified from the design and final-review session metadata. No collaboration subagents were used.

  • Design: conservative tag-absence prefilter, unchanged centralized internal provenance predicate, early source-scan bypass and final all-slot protection. No new lexer/state/cache. Ordered fragment validation and statement counts remain unconditional; fresh source arrays are compacted without mutating inherited vectors.
  • Correctness/unhappy paths: source alignment remains correct across rewrite, cache, SQLMode staging, executable comments and prepared execution. Decoded PREPARE bodies are classified independently, including escaped tags absent from outer text. Existing saved-result and authorization gates remain intact; diagnostic classification preserves lexical-error boundaries.
  • Validation: current complete frontend tests PASS; maintained real-MySQL saved-result matrix plus lexical, SQLMode, native/text/variable PREPARE, executable wrapper and partial-batch failure/recovery QA PASS. Scoped vet PASS; incremental lint 0 issues. Unchanged parser/lexer evidence reused.
  • Performance: five samples per case, normal mode, one CPU, both run orders. Marker-free 64 KiB binding is about 145–146 us on fixed code and base, worst median difference about +0.6%; both allocate 67,960 B/op in 23 allocations. The earlier extra 65,568-byte allocation is gone. Ordinary native EXECUTE classification is about 62 ns versus 423 ns before this correction. Candidate-containing internal SQL also avoids redundant literal decoding.
  • Scope/quality: implementation, tests and documentation reviewed separately. Tests extend existing fixtures with independent literal results and public save/no-save checks. No persisted data/protocol format change, asynchronous owner or unbounded state.

Limitations: candidate-containing external SQL retains exact lexical work; marked multi-statement classification can still cost more than the old inaccurate baseline. These are local Darwin/arm64 source-binding/parsing measurements, not an end-to-end throughput claim. Remote CI was not awaited or claimed to pass.

@XuPeng-SH
XuPeng-SH merged commit 21f711a into matrixorigin:main Oct 4, 2026
@XuPeng-SH
XuPeng-SH deleted the codex/fix-29597-rewrite-source branch October 4, 2026 13:15
XuPeng-SH added a commit that referenced this pull request Oct 4, 2026
…29605)

## What type of PR is this?

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

## Which issue(s) this PR fixes:

Refs #29597. Backport of #29600 to `4.2-dev`, including the complete
final source range through `3dae3634fbe759bd69688f7edf83f45835b8b231`
(three source commits).

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

Policy rewrite prepends optimizer comments. The old comment-indexed
source classifier consequently shifts `save_result` / `cloud_nonuser`
away from their executable statement. On clean 4.2-dev, a role-filtered
query returns the correct live row but `result_scan` fails with 20440.

- Bind sources at the existing computation-wrapper owner, using grammar
statement boundaries and the SQLMode-aware lexer. Compact SQL/source
slots together, including fresh/cache, staged SQLMode and prepared
paths.
- Preserve source provenance when copying rewritten input; derive
prepared nonuser state from its owner statement and decoded
string/variable body, not a sibling statement.
- Keep parse-failure records paired with diagnostic sources; do not
infer markers from quoted data or beyond lexical failure.
- Preserve internal protection and conservatively skip source lexing
when exact tag candidates are absent. No new cache, state machine or
parser.
- Close 4.2's saved-result eligibility gap for nonuser SHOW results,
using the same existing guard as internal results.

### Branch adaptations and compatibility

Preserves 4.2's existing `enable_remap_hint` semantics, rewrite policy
structure, native PREPARE envelope and lexical rules. Does not bring
main's mandatory-role switch behavior, new snapshot fields, native
wrapper refactoring or single-CN fixture. Existing
saved-result/data/wire formats are unchanged. Mixed-version upgrade is
outside this backport.

### Validation

Target base: `6d4569bce66acb67e6d0fe746ee537da7955bffd`; macOS arm64 /
Go 1.26.4; freshly built target-native libraries.

- Clean-target white-box and real SQL reproduction both fail for the
expected old source-alignment cause.
- Full frontend and all SQL parser package tests pass.
- Maintained public regression passes two cleanup/recreation rounds on
the same existing 3-CN fixture, with two-row row/column/combined
policies, sparse/mixed markers, error recovery, privilege revocation,
switch-off control, saved contents/metadata and nonuser SHOW absence.
- Independent public QA passes NULL/UTF-8/empty/alias, lexical
marker/literal controls, repeated cached execution,
native/text/string/variable PREPARE, executable comments, staged SQLMode
and partial-batch failure/recovery.
- Owning/dependent `go vet` passes; incremental golangci-lint reports 0
issues.

### Performance

Same target-native/toolchain, sequential baseline/candidate benchmarks.
Marker-free binding allocations unchanged. After background compilation
ended, the final interleaved pair showed plain 64 KiB / internal /
escaped 64 KiB / 1000-row INSERT medians within the 10% budget
(candidate approximately 1–3% lower). Earlier loaded-machine timings
were noisy and are not used to claim speedup.

Ordinary EXECUTE source classification is 39.04 → 62.86 ns (same 16 B, 1
allocation). A literal containing a tag candidate still pays lexical
validation (approximately 152 → 292 µs and 75,888 → 149,632 B for the
synthetic 64 KiB case); this is the correctness fallback, not the
marker-free path. No end-to-end workload speedup claim.

### Design and final review

Both required gates used actual `gpt-6.1-sol` / `xhigh`: design ACCEPT
and complete-change review ACCEPT, followed by accepted test-ownership
delta review. Final reviewed staged diff SHA-256:
`0ba62e50b7848de20fe62eb63e72589af76a125dcb886a27ea12e7a487edf40e`. No
unresolved delivery blocker. Target-specific cached AST test cleanup was
corrected and the entire frontend suite/static checks rerun afterward.

CI has not been waited for.

This branch was previously deployed

1 inactive deployment
ci — cba815a5 Deployed Oct 4, 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/L Denotes a PR that changes [500,999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Row/column policy rewrite drops save_result SQL source classification and prevents result_scan

2 participants