discovery: fix keyspaceState leak for keyspaces missing in localCell#19993
Conversation
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>
Review ChecklistHello reviewers! 👋 Please follow this checklist when reviewing this Pull Request. General
Tests
Documentation
New flags
If a workflow is added or modified:
Backward compatibility
|
There was a problem hiding this comment.
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
WatchSrvVSchemawhenWatchSrvKeyspacesynchronously returnsNoNode(keyspace missing in local cell). - Adds a
missingKeyspacesnegative cache (30s TTL) to short-circuit repeated lookups for missing keyspaces. - Adds a regression test asserting
WatchSrvKeyspaceis probed once per TTL andWatchSrvVSchemais 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 Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
mattlord
left a comment
There was a problem hiding this comment.
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>
|
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? |
|
@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. |
|
Good to know, we were waiting for v24 to officially release and then we were going to move our upgrade target to v23 |
|
Is there anything waiting on me for this fix to merge? |
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>
There was a problem hiding this comment.
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
errinstead of the localkerrreturned fromgetMoveTablesStatus, so failures fromgetMoveTablesStatuscan be silently ignored (or logged based on an unrelated incoming watcher error). This should checkkerr != nilto 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))
}
mhamza15
left a comment
There was a problem hiding this comment.
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.
|
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
left a comment
There was a problem hiding this comment.
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.
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>
…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>
Description
Fixes a
keyspaceStateleak inKeyspaceEventWatcherfor any keyspace whoseSrvKeyspacedoes 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
keyspaceStateper 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
processHealthCheck→getKeyspaceStatusallocates a freshkeyspaceStatevianewKeyspaceState.newKeyspaceStatecallsWatchSrvKeyspace.srvtopo.watchEntry.addListener(ingo/vt/srvtopo/watch.go) unconditionally appends the callback toentry.listenersand synchronously fires it with the cachedNoNode.onSrvKeyspacesetskss.deleted = trueand returnsfalse.newKeyspaceStatethen callsWatchSrvVSchema.onSrvVSchemaalways returnstrue, so its listener is never reaped from the listeners slice.getKeyspaceStatusremoves the kss fromkew.keyspaces(thekss.deletedbranch), but the SrvVSchema watcher still holds the orphan reference.Fix
Two pieces in
go/vt/discovery/keyspace_events.go:WatchSrvVSchemaregistration whenWatchSrvKeyspacesynchronously reportedNoNode(i.e.kss.deletedis already true after the call returns). With noonSrvVSchemalistener attached, no orphan reference exists.missingKeyspaces, 30s TTL). Once a keyspace is confirmed missing inlocalCell, subsequent healthchecks short-circuit ingetKeyspaceStatusbefore allocating a newkeyspaceState. 30s balances suppressing the storm vs. recovering quickly when the keyspace becomes locally served.Also adds a small
isDeleted()accessor mirroring the existingisConsistent()helper from #16683 — bothkss.deletedreads innewKeyspaceStateandgetKeyspaceStatusnow takekss.murather than racing with the watcher goroutine's writes inonSrvKeyspace.Regression test
TestKeyspaceEventWatcherMissingKeyspaceCachedrives 100 lookups against a fake topo whereWatchSrvKeyspacereturnsNoNodefor the target keyspace, asserts:WatchSrvKeyspaceis invoked exactly once withinmissingKeyspaceTTL.WatchSrvVSchemais never invoked (the original leak vector).WatchSrvVSchemastill isn't called.This passes under
go test -race.Related Issue(s)
Fixes #19992
Checklist
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.