Skip to content

Commit 618b286

Browse files
committed
fix: replace time.Sleep with context-aware select in MCP tryRestart
Assisted-By: docker-agent
1 parent e5f7cfa commit 618b286

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

pkg/tools/mcp/mcp.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,14 @@ func (ts *Toolset) tryRestart(ctx context.Context) bool {
309309
for attempt := range maxAttempts {
310310
backoff := time.Duration(1<<uint(attempt)) * time.Second
311311
slog.Debug("Restarting MCP server", "server", ts.logID, "attempt", attempt+1, "backoff", backoff)
312-
time.Sleep(backoff)
312+
313+
timer := time.NewTimer(backoff)
314+
select {
315+
case <-timer.C:
316+
case <-ctx.Done():
317+
timer.Stop()
318+
return false
319+
}
313320

314321
ts.mu.Lock()
315322
if ts.stopping {

pkg/tools/mcp/mcp_race_test.go

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
package mcp
22

33
import (
4+
"context"
45
"sync"
56
"testing"
7+
"time"
8+
9+
"github.com/stretchr/testify/assert"
610
)
711

812
func TestInstructions_Concurrent(t *testing.T) {
@@ -30,3 +34,31 @@ func TestInstructions_Concurrent(t *testing.T) {
3034
}
3135
wg.Wait()
3236
}
37+
38+
func TestTryRestart_RespectsContextCancellation(t *testing.T) {
39+
t.Parallel()
40+
41+
ts := &Toolset{
42+
logID: "test",
43+
mcpClient: &mockMCPClient{},
44+
}
45+
46+
ctx, cancel := context.WithCancel(t.Context())
47+
48+
done := make(chan bool, 1)
49+
go func() {
50+
done <- ts.tryRestart(ctx)
51+
}()
52+
53+
// Cancel almost immediately; tryRestart should return promptly
54+
// instead of sleeping through the full backoff.
55+
time.Sleep(50 * time.Millisecond)
56+
cancel()
57+
58+
select {
59+
case result := <-done:
60+
assert.False(t, result, "tryRestart should return false on cancellation")
61+
case <-time.After(2 * time.Second):
62+
t.Fatal("tryRestart did not return promptly after context cancellation")
63+
}
64+
}

0 commit comments

Comments
 (0)