Skip to content

vtgate: retry buffered queries on a recovered primary - #22169

Open
ZainnQureshii wants to merge 1 commit into
vitessio:mainfrom
ZainnQureshii:fix/vtgate-buffer-recovered-primary
Open

ZainnQureshii wants to merge 1 commit into
vitessio:mainfrom
ZainnQureshii:fix/vtgate-buffer-recovered-primary

Conversation

@ZainnQureshii

Copy link
Copy Markdown
Contributor

Description

With VTGate buffering enabled, an in-flight primary query can reach the old primary during PlannedReparentShard and receive CLUSTER_EVENT while the tablet is shutting down. On main, VTGate records that alias in the request's exclusion map (go/vt/vtgate/tabletgateway.go:449). When demotion fails and the same primary resumes serving, the candidate filter still drops it (go/vt/vtgate/tabletgateway.go:466), and the MySQL client receives the original SHUTTING_DOWN error.

Clear the request's tablet exclusions when the buffer hands back a retry callback (go/vt/vtgate/tabletgateway.go:385). VTGate then selects from current health data (go/vt/vtgate/tabletgateway.go:396), so the recovered primary can serve the retry.

The gateway wrapper at go/vt/vtgate/tabletgateway.go:157 leads to the sole production call to WaitForFailoverEnd. Both balancer paths share its candidate filter. The other references exercise the buffer directly in tests and benchmarks, outside the gateway's exclusion map. Direct-by-alias calls use a specified tablet and the shard-error wrapper (go/vt/vtgate/tabletgateway.go:236).

Motivation

How do you use Vitess?

  • In production
  • In staging or development
  • Evaluating it
  • I don't use Vitess

Did you run this change against a real Vitess deployment? Yes. A local Linux/arm64 cluster used MySQL 8.4.11, etcd 3.6.7, a primary and replica, and VTGate with buffering enabled. A MySQL table lock made PlannedReparentShard time out setting super_read_only in both runs. With base VTGate the buffered SELECT returned SHUTTING_DOWN (errno 1105). With patched VTGate the query returned the expected row after the original primary resumed serving.

Both regressions were adapted from mhamza15's reproductions. The gateway test synchronizes the initial health events and checks both attempts against the same tablet (go/vt/vtgate/tabletgateway_flaky_test.go:274). The cluster test checks that the request entered and left the buffer and received the expected row (go/test/endtoend/tabletgateway/buffer/reparent_rollback_test.go:75). Issue #21395

With the Vitess binaries, MySQL, and etcd configured, the cluster test was built and run with:

go test -p=6 -trimpath -c -o bin/buffer.test ./go/test/endtoend/tabletgateway/buffer
./bin/buffer.test -test.timeout=4m -test.count=1 -test.run '^TestBufferPlannedReparentRollback$' -test.v

The gateway regression failed on the base code with CLUSTER_EVENT after the buffer drained and passed 100 runs with the fix. The package and style checks passed locally with Go 1.27.4 and golangci-lint 2.15.0.

go test -timeout=2m -count=100 -run '^TestGatewayBufferedQueryRetriesSamePrimary$' ./go/vt/vtgate
go test -timeout=5m -count=1 ./go/vt/vtgate ./go/vt/vtgate/buffer ./go/vt/discovery ./go/vt/vttablet/queryservice
scripts/fmt go/vt/vtgate/tabletgateway.go go/vt/vtgate/tabletgateway_flaky_test.go \
  go/test/endtoend/tabletgateway/buffer/buffer_test_helpers.go \
  go/test/endtoend/tabletgateway/buffer/reparent_rollback_test.go
go run -trimpath -modfile=tools/golangci-lint/go.mod github.com/golangci/golangci-lint/v2/cmd/golangci-lint \
  run --timeout 10m ./go/vt/vtgate ./go/test/endtoend/tabletgateway/buffer ./go/test/endtoend/tabletgateway/buffer/reparent
go run ./go/tools/ci-config

Related Issue(s)

Fixes #21395

Checklist

  • "Backport to:" labels have been added if this change should be back-ported to release branches
  • If this change is to be back-ported to previous releases, a justification is included in the PR description
  • Tests were added or are not required
  • Did the new or modified tests pass consistently locally and on CI?
  • Documentation was added or is not required

Deployment Notes

No migration or configuration changes are required.

AI Disclosure

Codex wrote the code change, adapted the tests, ran verification, and drafted this description. Claude Code coordinated the investigation and review.

Prepared with AI assistance (Codex and Claude Code) and reviewed with GitHub Copilot.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Zain Qureshi <43629888+ZainnQureshii@users.noreply.github.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 10:54
@github-actions github-actions Bot added this to the v25.0.0 milestone Nov 25, 2026
@vitess-bot vitess-bot Bot added NeedsWebsiteDocsUpdate What it says NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsBackportReason If backport labels have been applied to a PR, a justification is required labels Nov 25, 2026
@vitess-bot

vitess-bot Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Review Checklist

Hello reviewers! 👋 Please follow this checklist when reviewing this Pull Request.

General

  • Ensure that the Pull Request has a descriptive title.
  • Ensure there is a link to an issue (except for internal cleanup and flaky test fixes), new features should have an RFC that documents use cases and test cases.

Tests

  • Bug fixes should have at least one unit or end-to-end test, enhancement and new features should have a sufficient number of tests.

Documentation

  • Apply the release notes (needs details) label if users need to know about this change.
  • New features should be documented.
  • There should be some code comments as to why things are implemented the way they are.
  • There should be a comment at the top of each new or modified test to explain what the test does.

New flags

  • Is this flag really necessary?
  • Flag names must be clear and intuitive, use dashes (-), and have a clear help text.

If a workflow is added or modified:

  • Each item in Jobs should be named in order to mark it as required.
  • If the workflow needs to be marked as required, the maintainer team must be notified.

Backward compatibility

  • Protobuf changes should be wire-compatible.
  • Changes to _vt tables and RPCs need to be backward compatible.
  • RPC changes should be compatible with vitess-operator
  • If a flag is removed, then it should also be removed from vitess-operator and arewefastyet, if used there.
  • vtctl command output order should be stable and awk-able.

Copilot AI 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.

🟡 Changes recommended

The test can pass without exercising the fix because a health-update race may buffer the query before it reaches the old primary; it must synchronize with shutdown and verify the initial tablet-side CLUSTER_EVENT rejection.

1 open issue
What changed in this PR

Fixes #21395 by allowing buffered VTGate queries to retry the same primary after a failed reparent restores it to service.

Changes:

  • Clear request-local tablet exclusions when buffering releases a query for retry.
  • Add gateway and end-to-end regressions for recovery of the original primary.
  • Support tablet argument overrides in the test helper and include the new test package in CI.
File Description
test/​config.json Adds the buffer package to the reparent CI suite.
go/​vt/​vtgate/​tabletgateway.go Clears tablet exclusions after buffering.
go/​vt/​vtgate/​tabletgateway_flaky_test.go Tests retrying the same primary after recovery.
go/​test/​endtoend/​tabletgateway/​buffer/​reparent_rollback_test.go Adds a failed-reparent cluster regression.
go/​test/​endtoend/​tabletgateway/​buffer/​buffer_test_helpers.go Allows per-test tablet argument overrides.

Review effort: Balanced

Comment on lines +79 to +81
result, queryErr = conn.ExecuteFetch("select id from buffer where id = 1", 1, false)
buffered, _ := cluster.VtgateProcess.GetVars()["BufferRequestsBuffered"].(map[string]any)
return queryErr != nil || buffered[statsLabel] == float64(1)

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.

Fair point that buffered == 1 on its own doesn't prove the query reached the old primary first, but I don't think that race can realistically happen in this test, so I've left it as is. The old primary only reports itself as not serving on the 20s health tick or once unserveCommon finishes and setState broadcasts (go/vt/vttablet/tabletserver/state_manager.go:510 and :752), and that drain is held up by the open transaction, while the test sends the SELECT every 100ms from the moment PRS starts. A false pass would need a 20s tick to land inside the single 100ms gap after the tablet starts shutting down. The run against main without the fix also failed on the tablet's own rejection, operation not allowed in state SHUTTING_DOWN with code 17 (CLUSTER_EVENT), which is the initial rejection this asks to verify, and the gateway unit test covers the same path deterministically. I can tighten the polling if a maintainer would rather have that.

@mattlord mattlord left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good to me. Thanks!

@mattlord
mattlord requested a review from a team November 25, 2026 18:36
@codecov

codecov Bot commented Nov 25, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.31%. Comparing base (70c7a72) to head (89eb46e).
⚠️ Report is 844 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main   #22169       +/-   ##
===========================================
+ Coverage   69.67%   85.31%   +15.64%     
===========================================
  Files        1614      310     -1304     
  Lines      216793    48199   -168594     
===========================================
- Hits       151044    41122   -109922     
+ Misses      65749     7077    -58672     
Flag Coverage Δ
partial 85.31% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Component: VTGate NeedsBackportReason If backport labels have been applied to a PR, a justification is required NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsIssue A linked issue is missing for this Pull Request NeedsWebsiteDocsUpdate What it says Type: Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: buffered queries fail when a failover ends with the same primary

3 participants