Skip to content

fix(frontend): invalidate prepared row-rule statements after policy refresh - #29195

Merged
XuPeng-SH merged 11 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/issue-29148-prepared-row-rule
Oct 14, 2026
Merged

XuPeng-SH merged 11 commits into
matrixorigin:mainfrom
iamlinjunhong:codex/issue-29148-prepared-row-rule

Conversation

@iamlinjunhong

@iamlinjunhong iamlinjunhong commented Sep 21, 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 #29148

What this PR does / why we need it:

A prepared statement can retain an old row-rule policy after cache invalidation, including a failed SET ROLE, allowing execution outside the current tenant scope.

This change:

  • checks prepared-policy generations at publication, cache reload, execution, and migration, including failed role switches and mandatory rules with optional rewrite disabled;
  • preserves the harmless disabled-to-disabled control and requires fresh PREPARE for stale active or unknown policies;
  • fails closed with ER_NEED_REPREPARE before binding, rebuild, execution, or cursor fetch;
  • discards invalidated LONG_DATA uploads without a response and keeps explicit close/deallocate available;
  • prevents invalidated or unvalidated stale handles from being replayed during migration;
  • adds frontend unit coverage and a distributed regression for direct versus prepared execution.

Affected clients must explicitly PREPARE the statement again after the policy refresh.

Validation

Local Go 1.26.4, Darwin/arm64, native prerequisites built from this checkout:

  • frontend focused regressions and full package with mo-cgo-test -vet=all -count=1 -timeout=600s ./pkg/frontend
  • frontend full package with -race; 5040 passing test/subtest events, no race warnings
  • adaptive race stress: TestConcurrentRuleCacheAccess passed 100 repetitions
  • authenticated protocol lifecycle regression and full pkg/tests/issues with -short -tags matrixone_test -count=1 -timeout=900s
  • pkg/common/moerr, incremental golangci-lint (0 issues), gofmt, and diff checks
  • cmd/mo-service build; role_rule_prepared.sql passed 26/26 twice on the same clean local instance, with teardown checked after each round

@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

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES at exact head 0beb73e.\n\n[P1] PREPARE after refresh within the same request can publish an executable stale-policy handle. With rewrite enabled, if a session sends one COM_QUERY containing SET ROLE followed by PREPARE, ExecRequest can materialize the old policy before either statement runs; SET ROLE invalidates only handles already registered, and the subsequent PREPARE can register a new handle with the old policy and no invalidation flag. Later EXECUTE can retain the old tenant scope. Relevant paths: pkg/frontend/session.go:2232, prepareStringStatement:2736, SetPrepareStmt:2526, ExecRequest:6337. Associate captured policies/handles with a session policy generation or refresh/reject stale publication, and add a multi-statement protocol regression with execution in a later request.\n\n[P2] Invalidated handles can cause unsolicited responses to COM_STMT_SEND_LONG_DATA. After policy invalidation, parseStmtSendLongData reaches getPrepareStmt and returns ER_NEED_REPREPARE; ExecRequest writes an error response. COM_STMT_SEND_LONG_DATA has no response, so a conforming client proceeds to EXECUTE without reading it and becomes protocol-desynchronized. Discard uploads for invalidated handles without emitting a packet; report 1615 on EXECUTE. Add a wire test covering uploads, one execute error, close/reprepare, and a subsequent successful command.\n\nReviewed exact head: 0beb73e

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

Reviewed the complete diff and current review history at exact head 0beb73eee1df6b7323d319dc772e20e6b43e577e. The single-statement stale-handle path is closed, but two blocking paths remain: a multi-statement COM_QUERY can publish a stale-policy handle after the refresh invalidation, and invalidation can make COM_STMT_SEND_LONG_DATA emit a forbidden response packet and desynchronize the connection. Both need protocol-level regression coverage.

Comment thread pkg/frontend/session.go Resolved
Comment thread pkg/frontend/session.go Resolved
@iamlinjunhong
iamlinjunhong force-pushed the codex/issue-29148-prepared-row-rule branch from 0beb73e to b5349a5 Compare September 21, 2026 13:45
@matrix-meow matrix-meow added size/L Denotes a PR that changes [500,999] lines and removed size/M Denotes a PR that changes [100,499] lines labels Sep 21, 2026
@iamlinjunhong
iamlinjunhong force-pushed the codex/issue-29148-prepared-row-rule branch from b5349a5 to 1a8c0b7 Compare September 23, 2026 02:18
@iamlinjunhong

Copy link
Copy Markdown
Contributor Author

Updated this PR onto the current official main (ffcce7ecba) so the branch is no longer behind the base.

The fix now covers:

  • generation checks at prepared-handle publication after multi-statement SET ROLE; PREPARE;
  • failed SET ROLE cache refreshes, including disabled-to-mandatory role-rule transitions;
  • checked binary COM_STMT_EXECUTE and COM_STMT_FETCH lookups;
  • silent discard of COM_STMT_SEND_LONG_DATA for an invalidated handle, leaving ER_NEED_REPREPARE for EXECUTE;
  • migration rejection for stale or unknown prepared policy state.

Validation at the rebased head:

  • go test ./pkg/frontend -run 'Test(Session|Rewrite|Routine|MySQLCmdExecutor).*' -count=1
  • go test -race ./pkg/frontend -run 'Test(Session|Rewrite|Routine|MySQLCmdExecutor).*' -count=1
  • go test ./pkg/tests/issues -run TestIssue29148PreparedRowRuleProtocolLifecycle -count=1

All passed locally. The authenticated issue regression exercises direct SQL EXECUTE, binary EXECUTE before direct policy reload, failed-role-switch empty-to-mandatory transitions, multi-statement publication, and long-data protocol alignment.

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

Deep review completed at exact head d51e23b41d1bd282ac5397aaa2ca27bbe8a27240, against base/merge-base ffcce7ecbab771d78edf8415db32880b133cce71. All 16 changed files/hunks were reviewed; no subagents or production changes.

Decision: REQUEST_CHANGES.

The original reported multi-statement publication, LONG_DATA response alignment, and non-migrated failed-SET-ROLE reproductions are addressed. However, the policy-generation contract still misses the actual migration replay producer: authenticated two-CN export/replay followed by a policy refresh reproduces an access-control bypass. RESET also inherits the new execution rejection and skips its cleanup responsibilities. See inline findings; the dead prepared-list API is a separate non-blocking cleanup item.

Design: session-owned policy generations and monotonic rejection of an already-materialized stale AST are justified. The incomplete integration is the optional capture marker: a real producer can omit it and thereby bypass all later validation. Cleanup operations must also be distinguished from operations that consume the retained plan. No new parallel policy store is needed.

Evidence: exact-head CI is green and its authenticated TestIssue29148PreparedRowRuleProtocolLifecycle passed (3.47s). Locally, five existing focused tests (publication transitions, reload, failed/unknown/current policy checks, FETCH cleanup, migration export) passed. The additional real migration probe failed on expected [1] versus actual [1,2]; the RESET probe failed on the retained cursor. The initial migration-probe attempt used an empty configured address and never reached migration; only the corrected discovery-based run is reproduction evidence. Local mode: Go 1.27.1, Darwin/arm64, native prerequisites built/verified for this checkout; issues probe used -short -tags matrixone_test -count=1.

Performance: steady-generation lookups add no catalog I/O or per-execution prepared-map scan. A review-only microbenchmark comparing the exact base getter with the head getter measured approximately 9.9 vs 17.9 ns/lookup, both 0 B/op and 0 allocs/op (3 samples). This is helper cost, not an end-to-end QPS result; the extra binary guard repeats a checked lookup and refresh helpers also repeat invalidation scans on slow paths.

Change accounting: implementation +300/-18 (net +282); tests, including BVT/results, +753/-1 (net +752); documentation 0. Shared authenticated-cluster reuse and two-row oracles are appropriate, but coverage must include the actual migration producer and RESET consumer rather than only manually initialized handle states.

Comment thread pkg/frontend/mysql_cmd_executor.go Resolved
Comment thread pkg/frontend/session.go Resolved
Comment thread pkg/frontend/session.go Resolved

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

Deep review at exact head 5b4ca7a22ecd0e2867e078a9e8184450600f411c, against base/merge-base 64b715a8234e272794185e2acc98ad58a8346c65: REQUEST_CHANGES.

All 17 changed files/hunks were reviewed, with the policy/cache owner, SQL and binary execution, background/procedure PREPARE, migration export/replay, LONG_DATA, RESET/CLOSE/FETCH, errors, test oracles and hot-path costs traced. No subagents or production changes were used.

Design: session-owned generations and monotonic invalidation of retained plans are justified; there is no need for a second policy store or state machine. The remaining flaw is that participation in this security contract is optional at handle creation. Fixing migration's caller does not close the shared owner boundary: a procedure creates an untagged handle that both refresh and execution exempt. The inline P1 is an authenticated, real-entry reproduction, not a speculative concern or a claim that this PR introduced the original authorization defect.

Prior comments: the multi-statement stale publication, LONG_DATA response alignment, ordinary failed-role-refresh, migration replay, RESET cleanup and retired GetPrepareStmts API cases are addressed in source. The previous real two-CN migration reproducer now passes (9.57s test body). RESET cleanup passes its focused regression and preserves execution invalidation. However, the requested real migration export/replay -> policy refresh regression is still absent from the committed tests; checking captured=true in a mocked replay is narrower evidence. The same integration class remains broken for procedures. GitHub thread resolution flags were not treated as proof of fixes.

Evidence: exact-head CI run 38069313654 is green, including TestIssue29148PreparedRowRuleProtocolLifecycle (3.98s); this evidence was reused. Locally, the real procedure probe failed with direct SELECT [1] versus prepared EXECUTE [1,2] after a mandatory policy refresh (0.17s test body, package exit 1). The same run's real two-CN migration control passed. Focused refresh/generation/export-rejection and RESET tests passed. Restoring the deleted pending-isolation PREPARE fixture, with two empty catalog mock results, makes TestSession_Migrate/typed_user_variables pass (package exit 0); see the inline test-quality finding. Local mode: Go 1.27.1, Darwin/arm64, checkout-specific native prerequisites built through make cgo; authenticated probes used -short -tags matrixone_test -count=1. No new full-suite or local race claim is made.

Performance: unchanged-generation lookup adds locks/generation/atomic checks, with no catalog query or prepared-map scan. A review-only benchmark comparing the exact base getter with this head measured 10.79 vs 18.54 ns/op, both 0 B/op and 0 allocs/op. This single helper measurement is not an end-to-end TP throughput result. Cache refresh is the slow path and scans existing handles; catalog I/O stays outside the session/cache locks. There is no new unbounded queue, goroutine or persistent store; cleanup remains owned by the existing prepared handle/session lifecycle.

Change accounting: implementation +326/-25; tests/BVT/results +811/-19; documentation 0. The two-row authenticated protocol oracle and shared cluster reuse are useful, but they do not excuse missing producer coverage or deleting an existing behavioral regression. The inline P2 preserves a concrete migration contract, rather than adding test volume.

Comment thread pkg/frontend/mysql_cmd_executor.go Resolved
Comment thread pkg/frontend/session_test.go Resolved

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

Reviewed f77ae8ca55b4afe190bbd365e06c176d9130d8ad against merge-base 64b715a8234e272794185e2acc98ad58a8346c65, including the delta from my previous review at 5b4ca7a. No remaining blocking finding.

The latest change closes the producer boundary: procedure/background PREPARE captures the owning session's effective policy and rewrites raw SQL before planning. Already-captured frontend requests retain their frozen policy. String, variable and typed producers converge on the existing planner/publication path; the common constructor now rejects missing provenance. Temporary input/remap state is restored on failure. This is a justified distinction between raw and already-materialized input, without adding another policy store or execution engine.

Previous review findings are addressed:

  • Stale publication after a policy-changing statement in one COM_QUERY: generation validation remains at publication and checked consumption.
  • LONG_DATA: invalidated uploads remain response-free; the following EXECUTE reports 1615 and the connection remains usable.
  • Failed SET ROLE / previously empty policy: reload and binary lookup validate existing handles; empty-to-empty refresh remains usable.
  • Migration: untagged/stale or unprovable materialized handles fail closed; replay captures target policy. Committed authenticated tests now exercise real two-CN export/replay followed by refresh, for both SQL- and procedure-created handles.
  • RESET/CLOSE: cleanup remains reachable without granting execution to invalidated handles.
  • Replaced GetPrepareStmts API and its orphan assertion: removed.
  • Procedure-created handles: all three producer forms now participate before planning, with actual row-result/reprepare assertions.
  • Pending-isolation migration regression: PREPARE replay is restored in the typed-variable case, followed by both the pending-isolation and actual prepared-handle assertions.

Validation: exact-head Linux CI job 114403283431 checked out this SHA and reports PASS for TestIssue29148PreparedOwnerPolicyLifecycle (10.47s, all five subcases) and TestIssue29148PreparedRowRuleProtocolLifecycle (4.30s). Locally, TestPreparedOwnerPolicyBeforePlanning, TestCaptureRewritePolicyValidatesExistingPreparedHandlesOnReload and TestSession_Migrate passed with the complete Go delta overlaid onto the previously built checkout; native inputs are unchanged. The independent previous SQL reproducer was selected but could not enter the scenario because another local process occupies port 10060; those attempts are not counted as passing evidence. No new local full-suite or race-run claim.

Design/performance: Session remains the policy/cache owner, PrepareStmt remains the resource owner, and invalidation is monotonic. Catalog I/O stays outside session/cache locks. Stable prepared execution adds bounded lock/generation checks, without catalog reads or scanning the handle map. Refresh performs O(number of prepared handles) validation; the new raw-policy rewrite/reparse is on background PREPARE. No TP throughput benchmark was performed, so this approval does not assert zero TP impact.

Change accounting, reviewed separately: implementation +398/-26; tests (including SQL/results) +1164/-20; documentation 0. Since the previous reviewed head: implementation +72/-1, tests +357/-5. The added tests cover distinct producer, migration, policy-transition and failure contracts using the existing authenticated fixture.

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

APPROVE after deep re-review of exact head f77ae8c, against declared base/merge-base 64b715a. No confirmed blocking finding remains.

Read all 13 historical reviews, 14 inline comments/replies, both conversation comments and all eight resolved/unresolved thread records (currently unresolved flags do not themselves prove a defect). Reviewed the complete 17-file diff and the changes since my 0beb73e review, with particular attention to the latest 5b4ca7a -> head producer fix. This is corrective bug work, not a new-feature design approval.

Closure: session-generation capture and publication checks reject old-policy handles published after SET ROLE within one frozen COM_QUERY. Invalid LONG_DATA is discarded without a response; later EXECUTE reports 1615/HY000 and the next command stays aligned. Empty-to-mandatory reloads and unknown/load-error paths fail closed, including failed SET ROLE and binary EXECUTE before a direct query. Empty-to-empty remains executable. Procedure typed/string/variable producers now capture/apply owner policy before planning; the common constructor rejects absent provenance instead of blessing a materialized old plan. Migration export rejects unproven/stale handles; replay captures destination policy and refuses materialized hints. The real two-CN export/replay regressions cover SQL and procedure-created handles. Pending-isolation PREPARE coverage is restored rather than removed.

Audit Owner/boundary Result
Q1 cleanup PrepareStmt retains plan/cursor/upload ownership; RESET, CLOSE and DEALLOCATE remain reachable after invalidation Cleanup does not revive execution; FETCH rejection releases cursor budget
Q2 waits/generation ses.mu -> ruleCacheMu; catalog I/O outside both, generation rechecked at publication/reload No new lock-held catalog wait; frozen request policy is not silently replaced
Q3 retained growth Existing bounded session handle map, monotonic invalidation bit, normal replacement/session teardown No per-refresh history or unbounded new owner container

Local validation at this exact head, Linux/amd64 Go1.27.1, independent detached worktree and matching make cgo native generation:

  • 12 focused frontend roots PASS, including all seven owner-admission subcases, migration/pending isolation, stale publication, RESET/FETCH and no-response LONG_DATA.
  • Actual authenticated OwnerPolicyLifecycle (five producer/migration subcases) and RowRuleProtocolLifecycle PASS twice in one shared cluster. Successful RPC exports/restores were observed on distinct CNs both rounds; fresh schema/principal creation in round two also verifies prior fixture cleanup.
  • TestConcurrentRuleCacheAccess measured race-root T=0, then exact-root -race -count=100 PASS; PreparedOwnerPolicyBeforePlanning T=0.01s, then -race -count=100 PASS.
  • Whole frontend -race was NOT all-green: 2360 root passes, eight RETURNING-spool failures, one skip, no data-race report. Independently rebuilt clean base 64b715a reproduces the identical eight failures and exact requested/used/cap signatures (106/114/98, used=0, cap=1) under the same race command/toolchain/native inputs. These unchanged-path failures are not attributed to this PR.

Exact-head CI run 38116822926 is successful (required, Ubuntu UT, SCA, coverage, build and active BVT). Independently inspected its public protocol roots (10.47s / 4.30s) and compose role_rule_prepared.sql artifact: 41/41, zero failure/ignore/abnormal. CI evidence is reused, not described as a local full-suite pass.

Cross-session policy refresh timing remains the existing reconnect/SET ROLE contract; no broader cache-coherence or TP-throughput claim. Head/state rechecked immediately before submission.

@mergify

mergify Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Merge Queue Status

  • ✅ Entered queue — 2026-10-14 04:10 UTC · Rule: main · triggered by rule Automatic queue on approval for main
  • 🟠 Checks running · in-place
  • 🚫 Left the queue — 2026-10-14 05:29 UTC · at 189c29dc6a2d881f0d41121ef814a9056c03ee8f

This pull request spent 1 hour 19 minutes 29 seconds in the queue, with no time running CI.

Reason

Pull request #29195 has been dequeued

Pull request from fork cannot be queued. This pull request comes from a fork, and Mergify needs the author's permission to update its branch.

The author needs to enable "Allow edits from maintainers" on this pull request.

Hint

You should look at the reason for the failure and decide if the pull request needs to be fixed or if you want to requeue it.
If you do update this pull request, it will automatically be requeued once the queue conditions match again.
If you think this was a flaky issue instead, you can requeue the pull request, without updating it, by posting a @mergifyio queue comment.

Waiting for any of
  • check-neutral = CI Required
  • check-skipped = CI Required
  • check-success = CI Required
All conditions

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

  • Requeue this pull request

This branch was successfully deployed

No deployments
ci — 189c29dc Deployed Oct 14, 2026 by mergify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dequeued kind/bug Something isn't working size/XL Denotes a PR that changes [1000, 1999] lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: prepared statement keeps old row-rule result after SET ROLE refresh

4 participants