Skip to content

txthrottler: don't cancel the state context when restarting the healthcheck stream - #20561

Closed
mightbeanshuu wants to merge 2 commits into
vitessio:mainfrom
mightbeanshuu:fix-txthrottler-healthcheck-restart-cancels-state
Closed

mightbeanshuu wants to merge 2 commits into
vitessio:mainfrom
mightbeanshuu:fix-txthrottler-healthcheck-restart-cancels-state

Conversation

@mightbeanshuu

Copy link
Copy Markdown
Contributor

Description

When the transaction throttler discovers its cells from the topology (no --tx-throttler-healthcheck-cells), the first change to the topology cell list silently stops it from ever monitoring replication lag again.

healthChecksProcessor runs on the state context ts.ctx and periodically calls updateHealthCheckCells. When the cell list changes it restarts the healthcheck stream via closeHealthCheckStream + initHealthCheckStream. The trouble is closeHealthCheckStream called ts.cancel(), which cancels the state context, not a per-stream one. So after the first refresh:

  • initHealthCheckStream re-created the healthcheck bound to the already-cancelled ts.ctx, and
  • healthChecksProcessor returned on case <-ts.ctx.Done() and never ran again.

From then on StatsUpdate / RecordReplicationLag stop, the cached lag goes stale, and the throttler fails open. No panic, no error logged.

The fix gives the healthcheck stream its own child context derived from ts.ctx, so restarting it only tears down the stream and leaves the state context alive. deallocateResources now cancels the state context explicitly, which closeHealthCheckStream previously did as a side effect on the teardown path.

I think this is worth backporting: it's a silent reliability regression on the topology-cells path (introduced in #12477), the fix is small and self-contained, and there's no behavior change for anyone who is not on that path.

Related Issue(s)

Fixes #20560

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

None. Behavior only changes for tablets running --enable-tx-throttler without --tx-throttler-healthcheck-cells, which will now keep monitoring lag across topology cell changes instead of silently going quiet.

AI Disclosure

This PR was written with Claude Code; I reviewed the change, the reasoning, and the test, and I can defend them.

…hcheck stream

closeHealthCheckStream cancelled ts.cancel(), the state context that
healthChecksProcessor runs on. That is fine on the deallocate path, but
updateHealthCheckCells also calls closeHealthCheckStream to restart the
stream when the topology cell list changes. So the first cell-list change
cancelled the state context: the re-created healthcheck was bound to a
dead context and healthChecksProcessor returned on ts.ctx.Done(), leaving
the throttler unable to see replication lag for the life of the tablet.

Give the healthcheck stream its own child context so restarting it no
longer tears down the state. deallocateResources now cancels the state
context explicitly, which closeHealthCheckStream used to do implicitly.

Fixes vitessio#20560

Signed-off-by: Anshu <amananshu2004@gmail.com>
Copilot AI review requested due to automatic review settings July 10, 2026 15:56
@github-actions github-actions Bot added this to the v25.0.0 milestone Jul 10, 2026
@vitess-bot

vitess-bot Bot commented Jul 10, 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.

@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 Jul 10, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7b744d48db

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

ts.healthCheck = nil

// Stop healthChecksProcessor, which runs for the lifetime of ts.ctx.
ts.cancel()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Cancel state before closing healthcheck

When Close() runs with the real HealthCheckImpl, closeHealthCheckStream() closes the subscriber channel before this line cancels ts.ctx; healthChecksProcessor can then wake on ts.healthCheckChan, receive the zero nil value from the closed channel, and panic in StatsUpdate while the tablet is shutting down. Previously the state context was canceled before the channel was closed, so the processor had a chance to exit first; cancel the state context before closing the stream or make the receive handle a closed channel.

Useful? React with 👍 / 👎.

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.

Good catch, this is a real one I introduced. Since closeHealthCheckStream no longer cancels the state context, the teardown path could close the real HealthCheckImpl subscriber channel while healthChecksProcessor was still selecting on it, and it would then receive a nil TabletHealth and pass it to StatsUpdate.

Fixed in 31f3430 two ways: deallocateResources now cancels the state context before closing the stream, and healthChecksProcessor returns if the receive from healthCheckChan reports the channel is closed. Added TestHealthChecksProcessorReturnsOnClosedChannel, which spins up the processor and closes its channel; it hangs on the old code (nil StatsUpdate loop) and returns cleanly now.

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.

Pull request overview

Fixes a reliability bug in the vttablet transaction throttler where restarting the healthcheck stream (triggered by topology-discovered cell list changes) accidentally canceled the throttler’s long-lived state context, causing replication-lag monitoring to stop permanently.

Changes:

  • Introduces a dedicated per-healthcheck-stream child context/cancel so stream restarts don’t cancel the throttler’s state context.
  • Moves state-context cancellation to deallocateResources() to keep shutdown semantics explicit.
  • Adds a regression test ensuring stream restart does not cancel the state context.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go Splits stream lifetime from state lifetime by adding a per-stream cancel; adjusts teardown to cancel state context explicitly.
go/vt/vttablet/tabletserver/txthrottler/tx_throttler_test.go Adds a test to verify restarting the healthcheck stream does not cancel the state context.

Comment on lines +314 to 318
hcCtx, hcCancel := context.WithCancel(ts.ctx)
ts.healthCheck, err = healthCheckFactory(hcCtx, topoServer, target.Cell, target.Keyspace, target.Shard, ts.healthCheckCells)
if err != nil {
hcCancel()
return err

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.

Thanks. The StatsUpdate(nil) panic you describe is handled by 31f3430 (pushed after this review): healthChecksProcessor now does th, ok := <-ts.healthCheckChan and returns on !ok, so a receive from a closed channel can't reach StatsUpdate.

On the retry point: initHealthCheckStream can only fail if healthCheckFactory fails, and the factory only errors when discovery.NewFilterByShard rejects the keyspace|shard filter. That filter is built from the tablet's keyspace/shard, which don't change between topo cell refreshes, so once the throttler has opened successfully a re-init during a cell refresh won't fail in practice. Worth noting main was actually worse on this path: there closeHealthCheckStream cancelled the state context, so a failed re-init killed the processor outright.

Comment on lines 325 to 330
func (ts *txThrottlerStateImpl) closeHealthCheckStream() {
if ts.healthCheck == nil {
return
}
ts.cancel()
ts.healthCheckCancel()
ts.healthCheck.Close()

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.

Same as the other thread: 31f3430 makes healthChecksProcessor return when the receive reports the channel is closed, so reading the previous (closed) channel after Close() no longer risks a nil StatsUpdate. healthCheckCancel is only ever called when healthCheck != nil (the guard above it), and both are set together in initHealthCheckStream, so it can't be nil there.

…ardown

Reordered deallocateResources to cancel ts.ctx before closeHealthCheckStream
closes the subscriber channel, and made healthChecksProcessor return when that
channel is closed. Without this, teardown could close the real HealthCheckImpl
channel before the state context was cancelled, so the processor would receive
a nil TabletHealth and forward it to StatsUpdate.

Signed-off-by: Anshu <amananshu2004@gmail.com>
Copilot AI review requested due to automatic review settings July 10, 2026 16:06

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@mattlord mattlord added Type: Bug and removed NeedsDescriptionUpdate The description is not clear or comprehensive enough, and needs work NeedsWebsiteDocsUpdate What it says 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 Jul 29, 2026
@codecov

codecov Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 88.88889% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 78.14%. Comparing base (70c7a72) to head (31f3430).
⚠️ Report is 515 commits behind head on main.

Files with missing lines Patch % Lines
.../vttablet/tabletserver/txthrottler/tx_throttler.go 88.88% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main   #20561       +/-   ##
===========================================
+ Coverage   69.67%   78.14%    +8.47%     
===========================================
  Files        1614        1     -1613     
  Lines      216793      183   -216610     
===========================================
- Hits       151044      143   -150901     
+ Misses      65749       40    -65709     
Flag Coverage Δ
partial 78.14% <88.88%> (?)

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.

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

The core cancellation fix looks correct, but I think two issues remain:

  • Wait for healthChecksProcessor before closing its resources
    go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go:408

ts.cancel() only signals the processor; waitForTermination currently tracks only updateMaxLag. If the processor already selected the topology-refresh case, it can continue after cancellation. fetchKnownCells converts the canceled request into the local-cell fallback, which can trigger another close/reinitialize cycle. I reproduced this on the current head: updateHealthCheckCells installed a new healthcheck after ts.ctx was canceled.

During teardown that can race with HealthCheck.Close, leak the replacement healthcheck, or let StatsUpdate call RecordReplicationLag after throttler.Close has closed its input channel. I think we should track and join healthChecksProcessor: cancel the state, stop both processors, wait for them, and only then close the current healthcheck and throttler. A regression test could block a refresh during teardown and verify that no replacement stream is created.

  • Move healthcheck observability to the replacement instance
    go/vt/vttablet/tabletserver/txthrottler/tx_throttler.go:315

The restart replaces ts.healthCheck, but RegisterStats runs only for the initial instance. Those metric callbacks remain bound to the first healthcheck after it has been closed. NewHealthCheck similarly registers /debug/gateway through a package-level sync.Once, so that handler remains bound to the closed instance too. Replication-lag events now continue correctly, but HealthcheckConnections, topology-watcher metrics, and the debug endpoint become empty or stale after the first cell change.

I think we should either restart the watchers without replacing the registered healthcheck or make the published callbacks dereference the current instance, with a test confirming observability follows the replacement. No?

@github-actions

Copy link
Copy Markdown
Contributor

This PR is being marked as stale because it has been open for 30 days with no activity. To rectify, you may do any of the following:

  • Push additional commits to the associated branch.
  • Remove the stale label.
  • Add a comment indicating why it is not stale.

If no action is taken within 7 days, this PR will be closed.

@github-actions github-actions Bot added the Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. label Aug 30, 2026
@github-actions

github-actions Bot commented Sep 6, 2026

Copy link
Copy Markdown
Contributor

This PR was closed because it has been stale for 7 days with no activity.

@github-actions github-actions Bot closed this Sep 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Component: Throttler Component: VTTablet Stale Marks PRs as stale after a period of inactivity, which are then closed after a grace period. Type: Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: txthrottler stops monitoring replication lag after a topology cell change (fails open)

3 participants