Skip to content

Commit 0fdbc4d

Browse files
committed
fix(upstream): make ListTools coalescing deadlock-safe + tidy snapshot lifecycle
Address review feedback on PR smart-mcp-proxy#446: 1. acquireListToolsContext now ALWAYS allocates listToolsWaitCh and resets the cached last-result when electing a leader. Previously the helper was used by the health-check (client.go:750) and tool-count refresh (client.go:1224) without setting up a wait channel, so a concurrent ListTools waiter would block on a nil channel for up to 30s (ctx.Done()) instead of being unblocked when the holder finished. 2. The two non-coalescing callers (health check, tool-count refresh) now call publishListToolsResult so any ListTools waiter coalesced behind them receives the real tools list rather than nil/stale data. 3. ListTools is split into a leader path (runListToolsAsLeader) that goes through acquireListToolsContext and a wait path that loops on a genuine race (rare: holder released between the failed acquire and the re-check) before parking on the wait channel. Single source of truth for leader bookkeeping. 4. Runtime: prune r.lastGoodTools entries for servers no longer in GetAllServerNames() to prevent unbounded growth on config churn. 5. Demote the "reusing last-good tool snapshot" log from Warn to Info - it's benign self-healing that can fire repeatedly during reconnect storms and was noisy. 6. New regression tests in listtools_coalescing_test.go: - TestListTools_MultipleWaitersUnblockedByLeader: real leader/multi-waiter goroutine interaction. - TestListTools_HealthCheckLeaderDoesNotDeadlockWaiters: directly reproduces the nil-channel hang the old code allowed. - TestListTools_LeaderErrorPropagatedToWaiters: error fan-out. - TestListTools_AcquireContextResetsCachedResult: leader election clears stale per-call state. Tests pass with -race on internal/upstream/managed and internal/runtime. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 1f83fef commit 0fdbc4d

3 files changed

Lines changed: 247 additions & 43 deletions

File tree

‎internal/runtime/lifecycle.go‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -302,13 +302,28 @@ func (r *Runtime) DiscoverAndIndexTools(ctx context.Context) error {
302302
toolsByServer[tool.ServerName] = append(toolsByServer[tool.ServerName], tool)
303303
}
304304

305-
// Persist fresh snapshots for discovered servers
305+
// Snapshot the set of currently-known servers so we can prune entries for
306+
// servers that have been removed from config and avoid an unbounded map.
307+
knownServers := r.upstreamManager.GetAllServerNames()
308+
knownServerSet := make(map[string]struct{}, len(knownServers))
309+
for _, name := range knownServers {
310+
knownServerSet[name] = struct{}{}
311+
}
312+
313+
// Persist fresh snapshots for discovered servers and prune stale entries.
314+
// ToolMetadata values are treated as immutable post-discovery; if that ever
315+
// changes, switch to a deep copy here.
306316
r.lastGoodToolsMu.Lock()
307317
for serverName, serverTools := range toolsByServer {
308318
cp := make([]*config.ToolMetadata, len(serverTools))
309319
copy(cp, serverTools)
310320
r.lastGoodTools[serverName] = cp
311321
}
322+
for serverName := range r.lastGoodTools {
323+
if _, ok := knownServerSet[serverName]; !ok {
324+
delete(r.lastGoodTools, serverName)
325+
}
326+
}
312327
r.lastGoodToolsMu.Unlock()
313328

314329
// Apply differential update for each server with fallback to last-good snapshots
@@ -325,7 +340,7 @@ func (r *Runtime) DiscoverAndIndexTools(ctx context.Context) error {
325340

326341
// For connected servers that were temporarily missing from discovery results,
327342
// re-apply last-good snapshot to avoid transient index shrink.
328-
for _, serverName := range r.upstreamManager.GetAllServerNames() {
343+
for _, serverName := range knownServers {
329344
if _, ok := processedServers[serverName]; ok {
330345
continue
331346
}
@@ -342,7 +357,9 @@ func (r *Runtime) DiscoverAndIndexTools(ctx context.Context) error {
342357
continue
343358
}
344359

345-
r.logger.Warn("Server missing from discovery result; reusing last-good tool snapshot",
360+
// Logged at Info: this can fire repeatedly during reconnect storms and
361+
// is benign self-healing, not a warning condition.
362+
r.logger.Info("Server missing from discovery result; reusing last-good tool snapshot",
346363
zap.String("server", serverName),
347364
zap.Int("snapshot_tools", len(snapshot)))
348365

‎internal/upstream/managed/client.go‎

Lines changed: 67 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -421,6 +421,13 @@ func (mc *Client) SetToolDiscoveryCallback(callback func(ctx context.Context, se
421421
mc.toolDiscoveryCallback = callback
422422
}
423423

424+
// acquireListToolsContext claims the in-progress flag for an upstream ListTools
425+
// call. When successful it also allocates listToolsWaitCh and resets the cached
426+
// last-result, so any concurrent ListTools waiter can safely block on the
427+
// channel and read the published result regardless of which caller is the
428+
// leader. release() must be called exactly once; it cancels the timeout,
429+
// publishes any result via publishListToolsResult (if the caller wrote one),
430+
// and closes the wait channel so coalesced waiters wake up.
424431
func (mc *Client) acquireListToolsContext(ctx context.Context, timeout time.Duration) (context.Context, func() bool, bool) {
425432
mc.listToolsMu.Lock()
426433
if mc.listToolsInProgress {
@@ -429,6 +436,9 @@ func (mc *Client) acquireListToolsContext(ctx context.Context, timeout time.Dura
429436
}
430437

431438
mc.listToolsInProgress = true
439+
mc.listToolsWaitCh = make(chan struct{})
440+
mc.listToolsLastResult = nil
441+
mc.listToolsLastErr = nil
432442
listCtx, cancel := context.WithTimeout(ctx, timeout)
433443
mc.listToolsCancel = cancel
434444
mc.listToolsMu.Unlock()
@@ -438,14 +448,31 @@ func (mc *Client) acquireListToolsContext(ctx context.Context, timeout time.Dura
438448
mc.listToolsMu.Lock()
439449
mc.listToolsCancel = nil
440450
mc.listToolsInProgress = false
451+
if mc.listToolsWaitCh != nil {
452+
close(mc.listToolsWaitCh)
453+
mc.listToolsWaitCh = nil
454+
}
441455
mc.listToolsMu.Unlock()
442456
return mc.IsConnected()
443457
}
444458

445459
return listCtx, release, true
446460
}
447461

448-
// ListTools retrieves tools with concurrency control and coalesces concurrent calls.
462+
// publishListToolsResult records the outcome of an upstream ListTools call so
463+
// that coalesced waiters in ListTools() can read it once the wait channel is
464+
// closed. All call sites that go through acquireListToolsContext (ListTools,
465+
// the health check, and the tool-count refresh) must publish their result so
466+
// that an arriving ListTools waiter never reads stale or zero data.
467+
func (mc *Client) publishListToolsResult(tools []*config.ToolMetadata, err error) {
468+
mc.listToolsMu.Lock()
469+
mc.listToolsLastResult = tools
470+
mc.listToolsLastErr = err
471+
mc.listToolsMu.Unlock()
472+
}
473+
474+
// ListTools retrieves tools with concurrency control and coalesces concurrent
475+
// callers onto a single in-flight upstream call.
449476
func (mc *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error) {
450477
mc.logger.Debug("🔍 ListTools called",
451478
zap.String("server", mc.Config.Name),
@@ -459,12 +486,29 @@ func (mc *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error)
459486
return nil, fmt.Errorf("client not connected (state: %s)", mc.StateManager.GetState().String())
460487
}
461488

462-
// Coalesce concurrent ListTools calls: one caller fetches, others wait for shared result.
463-
mc.listToolsMu.Lock()
464-
if mc.listToolsInProgress {
489+
for {
490+
listCtx, release, ok := mc.acquireListToolsContext(ctx, 30*time.Second)
491+
if ok {
492+
return mc.runListToolsAsLeader(listCtx, release)
493+
}
494+
495+
mc.listToolsMu.Lock()
465496
waitCh := mc.listToolsWaitCh
497+
inProgress := mc.listToolsInProgress
466498
mc.listToolsMu.Unlock()
467499

500+
if !inProgress {
501+
// Race: holder released between the failed acquire and our re-check.
502+
// Try to become the leader again.
503+
continue
504+
}
505+
if waitCh == nil {
506+
// Defensive fallback: every leader path is supposed to allocate a
507+
// wait channel via acquireListToolsContext, so this should be
508+
// unreachable. Fail fast rather than block forever on a nil channel.
509+
return nil, fmt.Errorf("ListTools operation already in progress for server %s", mc.Config.Name)
510+
}
511+
468512
mc.logger.Debug("🔍 ListTools already in progress, waiting for shared result",
469513
zap.String("server", mc.Config.Name))
470514

@@ -482,31 +526,24 @@ func (mc *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error)
482526
return res, nil
483527
}
484528
}
529+
}
485530

486-
mc.listToolsInProgress = true
487-
mc.listToolsWaitCh = make(chan struct{})
488-
listCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
489-
mc.listToolsCancel = cancel
490-
mc.listToolsMu.Unlock()
491-
531+
// runListToolsAsLeader performs the upstream ListTools call as the elected
532+
// leader and publishes the result before release() closes the wait channel,
533+
// so coalesced waiters always see a consistent result.
534+
func (mc *Client) runListToolsAsLeader(listCtx context.Context, release func() bool) ([]*config.ToolMetadata, error) {
492535
defer func() {
493-
cancel()
494-
mc.listToolsMu.Lock()
495-
mc.listToolsCancel = nil
496-
mc.listToolsInProgress = false
497-
if mc.listToolsWaitCh != nil {
498-
close(mc.listToolsWaitCh)
499-
mc.listToolsWaitCh = nil
536+
if release() {
537+
mc.logger.Debug("🔍 ListTools operation completed, flag reset",
538+
zap.String("server", mc.Config.Name))
539+
} else {
540+
mc.logger.Debug("🔍 ListTools operation completed while disconnected",
541+
zap.String("server", mc.Config.Name))
500542
}
501-
mc.listToolsMu.Unlock()
502543
}()
503544

504545
tools, err := mc.coreClient.ListTools(listCtx)
505-
506-
mc.listToolsMu.Lock()
507-
mc.listToolsLastResult = tools
508-
mc.listToolsLastErr = err
509-
mc.listToolsMu.Unlock()
546+
mc.publishListToolsResult(tools, err)
510547

511548
if err != nil {
512549
mc.logger.Error("ListTools operation failed",
@@ -522,9 +559,7 @@ func (mc *Client) ListTools(ctx context.Context) ([]*config.ToolMetadata, error)
522559
return nil, fmt.Errorf("ListTools failed: %w", err)
523560
}
524561

525-
// Cache the latest tool count for non-blocking stats consumers
526562
mc.setToolCountCache(len(tools))
527-
528563
return tools, nil
529564
}
530565

@@ -788,7 +823,10 @@ func (mc *Client) performHealthCheck() {
788823

789824
defer release()
790825

791-
_, err := mc.coreClient.ListTools(listCtx)
826+
// Capture and publish the full result so any concurrent ListTools waiter
827+
// (coalesced via the wait channel) receives a real list rather than nil.
828+
tools, err := mc.coreClient.ListTools(listCtx)
829+
mc.publishListToolsResult(tools, err)
792830

793831
if err != nil {
794832
// Only mark as error if it's a real connection issue, not timeout during high activity
@@ -1267,8 +1305,10 @@ func (mc *Client) GetCachedToolCount(ctx context.Context) (int, error) {
12671305
zap.Bool("cache_expired", !cachedTime.IsZero()),
12681306
zap.Duration("cache_age", time.Since(cachedTime)))
12691307

1270-
// Fetch fresh tool count with timeout
1308+
// Fetch fresh tool count with timeout. Publish the result so any concurrent
1309+
// ListTools waiter coalesced behind us receives the real tools list.
12711310
tools, err := mc.coreClient.ListTools(listCtx)
1311+
mc.publishListToolsResult(tools, err)
12721312
if err != nil {
12731313
mc.logger.Debug("Tool count fetch failed, returning cached value",
12741314
zap.String("server", mc.Config.Name),

0 commit comments

Comments
 (0)