Skip to content

vstreamer: stop the throttle goroutine when parseEvents returns - #22171

Open
goingforstudying-ctrl wants to merge 3 commits into
vitessio:mainfrom
goingforstudying-ctrl:fix/vstreamer-throttler-goroutine-leak
Open

goingforstudying-ctrl wants to merge 3 commits into
vitessio:mainfrom
goingforstudying-ctrl:fix/vstreamer-throttler-goroutine-leak

Conversation

@goingforstudying-ctrl

Copy link
Copy Markdown
Contributor

Description

parseEvents launches throttleEvents on the caller's context but returns on its own — io.EOF at a stop position, or any error from the binlog connection — and nothing cancelled the goroutine. Two ways that bites, from #22118:

  • a goroutine that already read the next binlog event stays blocked forwarding it to throttledEvents until the caller's context ends, holding the event the whole time;
  • a goroutine sitting in the fully-throttled branch sends on throttlerErrs after fullyThrottledTimeout — but parseEvents already closed the channel via defer, so the send panics and crashes vttablet. The copy-phase fast-forward vstreamer can hit this one: it ends with io.EOF at its stop position and its app is the non-exempt "vstreamer".

Since #21887 the leak also has a production trigger: a DDL that stays uncommitted past --schema-change-reload-timeout fails the schema tracker's and messager's vstreams on each retry (~35s), and every retry leaves one more goroutine behind.

The change derives a context for the goroutine that is cancelled when parseEvents returns, and stops closing throttlerErrs — it has a buffer of one and at most one send, so leaving it unclosed is safe while the late send can no longer panic on a closed channel. Behavior when the caller's context ends first is unchanged.

I think this should be back-ported to release-23.0 and release-24.0 together with #21887, per the issue.

Motivation

How do you use Vitess? (pick one)

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

Did you run this change against a real Vitess deployment?

No deployment involved; the bug reproduces in the vstreamer package alone. The new TestParseEventsStopsThrottlerGoroutine drives parseEvents without MySQL: a nil-throttler client plus throttlerapp.TestingAlwaysThrottledName parks the goroutine in the fully-throttled branch, then the errs channel ends parseEvents while the caller's context stays alive. On main the test binary panics with send on closed channel at vstreamer.go:434 — the orphaned goroutine reporting fully-throttled after the channel was closed. With the change the goroutine observes the derived cancellation and the test passes. Also ran the existing TestHeartbeat, TestFullyThrottledTimeout and TestVStreamerThrottledCounts against the change, all green, plus gofmt and go vet.

Related Issue(s)

Fixes #22118

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.

AI Disclosure

The investigation, the change and the regression test were done with an AI coding assistant, under my direction and review.

parseEvents starts throttleEvents on the caller's context, but returns on
its own: io.EOF at a stop position, or any error from the binlog
connection. Nothing cancelled the goroutine, so it outlived parseEvents:

- a goroutine that had already read the next binlog event stayed blocked
  forwarding it to throttledEvents until the caller's context ended,
  holding the event the whole time;
- a goroutine sitting in the fully-throttled branch sent on throttlerErrs
  after fullyThrottledTimeout, but parseEvents had already closed the
  channel via defer. The send panicked and crashed vttablet. The copy-phase
  fast-forward vstreamer hits this: it ends with io.EOF at its stop
  position, and its app is the non-exempt "vstreamer".

Since vitessio#21887, a DDL that stays uncommitted past --schema-change-reload-timeout
fails the schema tracker's and messager's vstreams on each retry (~35s),
leaving one more leaked goroutine behind every time.

Derive a context for the goroutine that is cancelled when parseEvents
returns, and stop closing throttlerErrs: it has a buffer of one and gets at
most one send, so leaving it unclosed is safe, while a late send can no
longer panic on a closed channel. The regression test drives parseEvents
without MySQL and panics on the old code as the orphaned goroutine reports
fully-throttled after parseEvents has returned.

Fixes vitessio#22118

Signed-off-by: goingforstudying-ctrl <goingforstudying@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 25, 2026 16:01
Copilot stopped reviewing on behalf of goingforstudying-ctrl due to an error November 25, 2026 16:14
@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.

@github-actions github-actions Bot added this to the v25.0.0 milestone Nov 25, 2026

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 regression test can pass without the cancellation fix and lacks an explicit worker-exit assertion, while its background context can leave workers running after test failure or timeout.

2 open issues
What changed in this PR

This PR addresses #22118 by tying the vstreamer throttle worker’s lifetime to parseEvents, preventing leaks and late-send panics when parsing ends before the caller’s context.

Changes:

  • Cancel a derived context when parseEvents returns.
  • Leave the buffered throttler error channel open to avoid racing with a late send.
  • Add a regression test for parsing ending while the worker is fully throttled.
File Description
go/​vt/​vttablet/​tabletserver/​vstreamer/​vstreamer.go Adds worker cancellation and removes error-channel closure.
go/​vt/​vttablet/​tabletserver/​vstreamer/​vstreamer_throttler_goroutine_test.go Adds a regression scenario with a caller context that outlives parsing.

Review effort: Balanced

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

  1. Blocking: I agree with Copilot's thread that the test should assert that the throttler goroutine exits, and cover the goroutine blocked forwarding an event. I ran the mutation: with context.WithCancel and defer cancel() removed from vstreamer.go:420-421, TestParseEventsStopsThrottlerGoroutine still passes without -race. Under -race it fails only because the race detector catches the leaked goroutine reading fullyThrottledTimeout at vstreamer.go:442 while the test's cleanup restores it, so only the Unit Test (Race) job would notice, and only by accident. The blocked-forwarding leak, which #22118 lists first, isn't exercised at all. I think that we should check the goroutine directly while the parent context is still live, for example with assert.Never that the test engine's throttledCounts grows by more than one after parseEvents returns, with fullyThrottledTimeout left at its default so that the timeout can't end the goroutine instead. That would also replace the 6.5s of sleeps. And then add a case where the goroutine has read an event that the main loop never takes. What do you think?

  2. I agree with Copilot's thread on using a context derived from t.Context() in vstreamer_throttler_goroutine_test.go:91.

  3. I think that we should pass empty names to stats.NewCounter and stats.NewCountersWithSingleLabel in vstreamer_throttler_goroutine_test.go:73-74, as wraperror_test.go:52 does. Named stats are published to expvar, so go test -count=2 -run TestParseEventsStopsThrottlerGoroutine panics on the second run with Reuse of exported var name: TestParseEventsVstreamerThrottledCounts.

Thanks!

@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 81.76%. Comparing base (70c7a72) to head (ed2bde3).
⚠️ Report is 844 commits behind head on main.

Additional details and impacted files
@@             Coverage Diff             @@
##             main   #22171       +/-   ##
===========================================
+ Coverage   69.67%   81.76%   +12.09%     
===========================================
  Files        1614       14     -1600     
  Lines      216793     3055   -213738     
===========================================
- Hits       151044     2498   -148546     
+ Misses      65749      557    -65192     
Flag Coverage Δ
partial 81.76% <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.

The previous test passed even without the derived context: the worker
sent into the buffered throttlerErrs and left at its timeout, so nothing
failed. Drive parseEvents from a t.Context-derived context, wait for the
worker to reach the fully-throttled branch on the throttled counter
instead of sleeping, and assert the counter stays frozen once
parseEvents returns, inside a window shorter than fullyThrottledTimeout.

Also cover the second leak path: a worker blocked forwarding an event
cannot leave through fullyThrottledTimeout at all. Park parseEvents in
vs.send on the heartbeat path, hand the worker an event it cannot
forward, and assert the parseEvents goroutines are gone while the
caller's context is still alive.

Signed-off-by: goingforstudying-ctrl <goingforstudying@gmail.com>
Copilot AI balanced review requested due to automatic review settings November 26, 2026 02:13

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 regression tests can fail spuriously on a post-cancellation counter increment and panic under repeated execution because they register fixed process-wide metric names.

2 open issues
2 resolved since last review

Review effort: Balanced

Copilot AI balanced review requested due to automatic review settings November 26, 2026 05:59

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.

🟢 Approval recommended

No active review issues are recorded for the vstreamer throttle-worker lifecycle fix.

No open issues 🎉

2 resolved since last review

Review effort: Balanced

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

  1. Blocking: The DCO check fails because the two new commits, c4052c1 and 4f8589a, have no Signed-off-by: trailer (the first commit has one). I think that git rebase --signoff HEAD~2 and a force-push will fix it.

  2. Thanks for the test rework. All three earlier points look addressed to me. With context.WithCancel and defer cancel() removed from vstreamer.go:420-421, both tests now fail without -race, and -count=2 passes. In TestParseEventsStopsThrottlerGoroutine, the wait for the worker to exit is fullyThrottledTimeout/2, which is 1s. With the fix, the worker should exit within one throttle check (about 250ms), so the margin is fine locally, but it seems like it could flake on a loaded race runner, and the repo's guideline is CI timeouts of at least 30 seconds. I wonder if we should raise fullyThrottledTimeout in the test to something like 2 minutes and wait up to 30s for parseEventsGone. A leaked worker would still be caught long before its timeout. Once parseEventsGone holds, the assert.Never on the counter seems redundant too, so the test could drop it and save a second.

Thanks!

The tests registered counters under fixed process-wide names, so a
second run under -count=2 panicked on the duplicate expvar publish.
Keep them unnamed.

Cancellation is delivered to the throttle worker's select but the
worker can still have an increment in flight when parseEvents returns,
so an immediate counter freeze check could flap. Wait for the worker
to actually be gone, with a deadline under fullyThrottledTimeout,
before asserting the counter stays frozen.

Signed-off-by: goingforstudying-ctrl <goingforstudying@gmail.com>
@goingforstudying-ctrl
goingforstudying-ctrl force-pushed the fix/vstreamer-throttler-goroutine-leak branch from 4f8589a to ed2bde3 Compare November 26, 2026 13:11
Copilot AI balanced review requested due to automatic review settings November 26, 2026 13:11

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.

🟢 Approval recommended

No active review issues were identified for the throttle-worker lifecycle fix.

No open issues 🎉

Review effort: Balanced

@goingforstudying-ctrl

Copy link
Copy Markdown
Contributor Author

All addressed in the latest push:

  1. Both new commits carry the Signed-off-by trailer and DCO is green now.
  2. fullyThrottledTimeout is 2 minutes in the test.
  3. The test waits up to 30s for parseEventsGone, and the counter assert.Never is dropped.

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

Thanks for the updates! The DCO check passes now, and the test changes look good to me. With the derived context and defer cancel() removed, both tests still fail, -race -count=2 passes at this head, and the full vstreamer package passes too.

Looks good to me.

@mattlord
mattlord requested a review from a team November 26, 2026 23:59

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: VTTablet 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: vstreamer's throttler goroutine outlives parseEvents, and can send on a closed channel

3 participants