Skip to content

discovery: fix keyspaceState leak for keyspaces missing in localCell#19993

Merged
mattlord merged 5 commits into
vitessio:mainfrom
HubSpot:upstream-keyspace-status-oom-fix
May 14, 2026
Merged

discovery: fix keyspaceState leak for keyspaces missing in localCell#19993
mattlord merged 5 commits into
vitessio:mainfrom
HubSpot:upstream-keyspace-status-oom-fix

Conversation

@corbantek
Copy link
Copy Markdown
Contributor

@corbantek corbantek commented Apr 29, 2026

Description

Fixes a keyspaceState leak in KeyspaceEventWatcher for any keyspace whose SrvKeyspace does not exist in the local cell (common in multi-cell vtgate deployments where some keyspaces are only served from a subset of cells).

The leak grows by one orphan keyspaceState per healthcheck event for the missing keyspace. At fleet healthcheck rates (>1k/sec for an active keyspace) this manifests as steady RSS + CPU growth on vtgate over hours.

Root cause

  1. processHealthCheckgetKeyspaceStatus allocates a fresh keyspaceState via newKeyspaceState.
  2. newKeyspaceState calls WatchSrvKeyspace. srvtopo.watchEntry.addListener (in go/vt/srvtopo/watch.go) unconditionally appends the callback to entry.listeners and synchronously fires it with the cached NoNode. onSrvKeyspace sets kss.deleted = true and returns false.
  3. newKeyspaceState then calls WatchSrvVSchema. onSrvVSchema always returns true, so its listener is never reaped from the listeners slice.
  4. getKeyspaceStatus removes the kss from kew.keyspaces (the kss.deleted branch), but the SrvVSchema watcher still holds the orphan reference.
  5. The next healthcheck for that keyspace repeats step 2, pinning another orphan. Forever.

Fix

Two pieces in go/vt/discovery/keyspace_events.go:

  • Skip the WatchSrvVSchema registration when WatchSrvKeyspace synchronously reported NoNode (i.e. kss.deleted is already true after the call returns). With no onSrvVSchema listener attached, no orphan reference exists.
  • Negative cache (missingKeyspaces, 30s TTL). Once a keyspace is confirmed missing in localCell, subsequent healthchecks short-circuit in getKeyspaceStatus before allocating a new keyspaceState. 30s balances suppressing the storm vs. recovering quickly when the keyspace becomes locally served.

Also adds a small isDeleted() accessor mirroring the existing isConsistent() helper from #16683 — both kss.deleted reads in newKeyspaceState and getKeyspaceStatus now take kss.mu rather than racing with the watcher goroutine's writes in onSrvKeyspace.

Regression test

TestKeyspaceEventWatcherMissingKeyspaceCache drives 100 lookups against a fake topo where WatchSrvKeyspace returns NoNode for the target keyspace, asserts:

  • WatchSrvKeyspace is invoked exactly once within missingKeyspaceTTL.
  • WatchSrvVSchema is never invoked (the original leak vector).
  • After expiring the negative cache, the next lookup re-probes exactly once and WatchSrvVSchema still isn't called.

This passes under go test -race.

Related Issue(s)

Fixes #19992

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

The fix is request-path-relevant in any multi-cell vtgate deployment, so I'm requesting backport to release-22.0 (the only currently-supported release where I've personally validated the fix). If maintainers want it in older releases too, the patch should apply with no conflicts — the affected functions haven't changed substantively in several releases.

Deployment Notes

No flags, no migrations. Behavior change is limited to a 30s window where a SrvKeyspace that becomes available in localCell will be picked up at the next healthcheck after TTL expiry rather than the very next one. Note this is a fixed 30s window — unlike srv-topo-cache-ttl (default 1s, configurable), the negative cache here is hard-coded. The 30s value was chosen to suppress the per-event allocation storm without delaying recovery materially when a keyspace becomes locally served.

AI Disclosure

The code, tests, and PR/issue text were drafted with Claude Code; I (the author) reviewed each change and the diagnostic chain end-to-end before submitting.

In multi-cell deployments, healthchecks for a keyspace whose SrvKeyspace
does not exist in the local cell would allocate a new keyspaceState per
event, register a SrvVSchema watcher whose callback always returns true
(never reaped), and immediately discard the keyspaceState — pinning an
orphan reference in the SrvVSchema watcher's listeners slice on every
event.

Two changes:

  - Skip the SrvVSchema registration when WatchSrvKeyspace already
    reported NoNode synchronously via the cached value. With no
    onSrvVSchema listener attached, no orphan reference exists.

  - Add a 30s negative cache (missingKeyspaces) keyed by keyspace name,
    populated when getKeyspaceStatus discards a deleted keyspaceState
    and consulted before allocating a new one. This prevents a per-event
    allocation storm when healthchecks for the same missing keyspace
    arrive at >1k/sec.

Also adds an isDeleted() accessor mirroring the existing isConsistent()
helper from vitessio#16683, so both kss.deleted reads in newKeyspaceState and
getKeyspaceStatus take kss.mu rather than racing with the watcher
goroutine's writes in onSrvKeyspace.

Signed-off-by: Kyle Johnson <kyjohnson@hubspot.com>
Copilot AI review requested due to automatic review settings April 29, 2026 20:10
@github-actions github-actions Bot added this to the v25.0.0 milestone Apr 29, 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 Apr 29, 2026
@vitess-bot
Copy link
Copy Markdown
Contributor

vitess-bot Bot commented Apr 29, 2026

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.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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 keyspaceState leak in KeyspaceEventWatcher when a keyspace has no SrvKeyspace in localCell (common in multi-cell vtgate deployments), preventing unbounded listener growth and associated RSS/CPU drift.

Changes:

  • Avoids registering WatchSrvVSchema when WatchSrvKeyspace synchronously returns NoNode (keyspace missing in local cell).
  • Adds a missingKeyspaces negative cache (30s TTL) to short-circuit repeated lookups for missing keyspaces.
  • Adds a regression test asserting WatchSrvKeyspace is probed once per TTL and WatchSrvVSchema is never registered for missing keyspaces.

Reviewed changes

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

File Description
go/vt/discovery/keyspace_events.go Skips SrvVSchema watch on synchronous NoNode, adds negative cache + locked isDeleted() accessor to avoid races and repeated allocations.
go/vt/discovery/keyspace_events_test.go Adds regression test covering missing-keyspace negative caching and ensuring no SrvVSchema watch registration occurs.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 29, 2026

Codecov Report

❌ Patch coverage is 96.15385% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 67.98%. Comparing base (70c7a72) to head (098f2b8).
⚠️ Report is 258 commits behind head on main.

Files with missing lines Patch % Lines
go/vt/discovery/keyspace_events.go 96.15% 1 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##             main   #19993       +/-   ##
===========================================
- Coverage   69.67%   67.98%    -1.69%     
===========================================
  Files        1614       12     -1602     
  Lines      216793     1846   -214947     
===========================================
- Hits       151044     1255   -149789     
+ Misses      65749      591    -65158     
Flag Coverage Δ
partial 67.98% <96.15%> (?)

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

☔ View full report in Codecov by Sentry.
📢 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 added Type: Bug Component: Cluster management 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 Apr 29, 2026
Copy link
Copy Markdown
Member

@mattlord mattlord left a comment

Choose a reason for hiding this comment

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

Thanks, @corbantek !

There's a linter error (modernize) that you will need to address. Beyond that, I only have a tiny nit in that the deployment note says this is equivalent to existing srvtopo cache TTLs, but srv-topo-cache-ttl defaults to 1s and is configurable, while this adds a fixed 30s negative-cache window. The 30s tradeoff seems reasonable, but I’d make that wording a little more explicit.

The CI golangci-lint `modernize` rule flagged `for i := 0; i < lookups; i++`
where `i` is unused. Switch to `for range lookups` to clear the warning
without changing semantics.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Signed-off-by: Kyle Johnson <kylej@hubspot.com>
@corbantek
Copy link
Copy Markdown
Contributor Author

Thanks @mattlord, this was a crazy one here at HubSpot when we starting deploying Vitess 22 to our larger environments with 2000+ keyspaces--vtgates were OOMing all over the place 😄

Can we also mark this one for backport to 22+ if possible?

@mattlord mattlord added Backport to: release-23.0 Needs to be backport to release-23.0 Backport to: release-24.0 Needs to be backport to release-24.0 labels May 1, 2026
@mattlord
Copy link
Copy Markdown
Member

mattlord commented May 1, 2026

@corbantek v22 is EOL as of this past week so we won't backport it that far (no more releases anyway). But we can backport it to v23.

@corbantek
Copy link
Copy Markdown
Contributor Author

Good to know, we were waiting for v24 to officially release and then we were going to move our upgrade target to v23

This was referenced May 4, 2026
@corbantek
Copy link
Copy Markdown
Contributor Author

Is there anything waiting on me for this fix to merge?

Comment thread go/vt/discovery/keyspace_events.go
The original fix handled the case where SrvKeyspace returns NoNode
synchronously inside newKeyspaceState: we skip WatchSrvVSchema entirely,
so the SrvVSchema listener is never registered for a keyspace that has
no SrvKeyspace in localCell.

A second path is still leaky. When a keyspace exists in localCell at
allocation time, newKeyspaceState registers both onSrvKeyspace and
onSrvVSchema. If the keyspace is later removed from localCell, the
SrvKeyspace watcher fires onSrvKeyspace with NoNode, which sets
kss.deleted = true and returns false to reap itself. The SrvVSchema
watcher is never told — onSrvVSchema always returns true, so the
resilient watcher keeps the closure (and the orphan *keyspaceState it
captures) in its listeners slice forever, and re-runs the callback's
work on every SrvVSchema update.

Return false from onSrvVSchema once kss.deleted is set so the watcher
reaps the listener. The leak is bounded — one orphan per "appeared then
disappeared in localCell" cycle, not per healthcheck event like the
original — but a leak nonetheless, flagged by @mhamza15 in review of
the original PR.

Signed-off-by: Kyle Johnson <kylej@hubspot.com>
Copilot AI review requested due to automatic review settings May 14, 2026 15:33
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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 1 comment.

Comments suppressed due to low confidence (1)

go/vt/discovery/keyspace_events.go:660

  • The error check here uses the function parameter err instead of the local kerr returned from getMoveTablesStatus, so failures from getMoveTablesStatus can be silently ignored (or logged based on an unrelated incoming watcher error). This should check kerr != nil to reflect the call you just made.
	var kerr error
	if kss.moveTablesState, kerr = kss.getMoveTablesStatus(vs); err != nil {
		log.Error(fmt.Sprintf("onSrvVSchema: keyspace %s failed to get move tables status: %v", kss.keyspace, kerr))
	}

Comment thread go/vt/discovery/keyspace_events_test.go
@corbantek corbantek requested a review from mhamza15 May 14, 2026 15:49
Copy link
Copy Markdown
Collaborator

@mhamza15 mhamza15 left a comment

Choose a reason for hiding this comment

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

LGTM! I've approved, but I also left a comment for a change that wasn't introduced in your PR but could be good to have anyway.

Comment thread go/vt/discovery/keyspace_events.go Outdated
@mhamza15
Copy link
Copy Markdown
Collaborator

Also I think you'll need to merge in main to get this job to pass: https://github.com/vitessio/vitess/actions/runs/25869133670/job/76028121188?pr=19993

@mattlord mattlord self-requested a review May 14, 2026 16:35
Copy link
Copy Markdown
Member

@mattlord mattlord left a comment

Choose a reason for hiding this comment

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

We should check kerr from getMoveTablesStatus in go/vt/discovery/keyspace_events.go:657-660. onSrvVSchema stores the getMoveTablesStatus error in kerr, but checks the watcher callback parameter err instead. Normal SrvVSchema updates have err == nil, so topo/shard lookup failures can be silently treated as a successful {MoveTablesNone, Unknown} update, masking MoveTables state during a topo blip. Please check kerr != nil and avoid updating moveTablesState from the error result.

We should reap deleted listeners even when SrvVSchema payload is nil in go/vt/discovery/keyspace_events.go:641-655. The new deleted-state reaper sits after if vs == nil { return true }. If onSrvKeyspace has marked the keyspace deleted and the SrvVSchema watcher later invokes this callback with a nil value/error, the callback keeps returning true and the orphan listener survives. Since deleted should always mean this listener is done, check kss.deleted before the nil fast path and add a nil-payload regression.

corbantek added 2 commits May 14, 2026 13:00
Two issues raised by @mattlord on the original onSrvVSchema body, plus
an order-of-operations bug in our deleted-state reaper:

1. Reorder the kss.deleted check before the "vs == nil" fast-path. Our
   prior commit added the deleted-state reaper after the nil-payload
   early-return, so a SrvVSchema watcher firing onSrvVSchema(nil, _) for
   an already-deleted keyspace would still return true and the orphan
   listener would survive. Lock acquisition is uncontended on this path
   and cheap; deleted always means the listener is done.

2. Use a local variable for getMoveTablesStatus's result and only assign
   into kss.moveTablesState on success. The previous form
       if kss.moveTablesState, kerr = kss.getMoveTablesStatus(vs); err != nil
   had two latent bugs: it checked the watcher callback's outer err
   parameter (always nil for normal updates) instead of kerr, and the
   multi-assignment silently clobbered the previously-tracked
   MoveTables state to nil whenever getMoveTablesStatus errored. So a
   transient topo blip during a MoveTables workflow could mask the
   workflow's state until the next successful update.

3. Extend the regression test into a table covering both the non-nil
   and nil SrvVSchema payloads, since the reorder is what makes the
   nil case correct.

Signed-off-by: Kyle Johnson <kylej@hubspot.com>
@mattlord mattlord merged commit e3cc812 into vitessio:main May 14, 2026
109 checks passed
mattlord pushed a commit that referenced this pull request May 14, 2026
…g in localCell (#19993) (#20109)

Signed-off-by: Kyle Johnson <kyjohnson@hubspot.com>
Signed-off-by: Kyle Johnson <kylej@hubspot.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Kyle Johnson <kyjohnson@hubspot.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
mattlord added a commit that referenced this pull request May 15, 2026
…g in localCell (#19993) (#20108)

Signed-off-by: Matt Lord <mattalord@gmail.com>
Co-authored-by: vitess-bot[bot] <108069721+vitess-bot[bot]@users.noreply.github.com>
Co-authored-by: Matt Lord <mattalord@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Backport to: release-23.0 Needs to be backport to release-23.0 Backport to: release-24.0 Needs to be backport to release-24.0 Component: Cluster management Type: Bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Bug Report: KeyspaceEventWatcher leaks keyspaceState objects for keyspaces missing in localCell

4 participants