diff --git a/internal/channels/email/email.go b/internal/channels/email/email.go index 81c83e24c..e9cae9c49 100644 --- a/internal/channels/email/email.go +++ b/internal/channels/email/email.go @@ -87,7 +87,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error { g.log.Error("email accept", "err", err) continue } - go g.handleSMTP(conn) + go g.handleSMTP(ctx, conn) } } @@ -103,7 +103,7 @@ func (g *Gateway) Stop(ctx context.Context) error { } // handleSMTP processes one SMTP session. -func (g *Gateway) handleSMTP(conn net.Conn) { +func (g *Gateway) handleSMTP(ctx context.Context, conn net.Conn) { defer func() { _ = conn.Close() }() r := bufio.NewReader(conn) w := bufio.NewWriter(conn) @@ -136,7 +136,7 @@ func (g *Gateway) handleSMTP(conn net.Conn) { case inData: if line == "." { // End of DATA — process the message. - g.processMessage(mailFrom, rcptTo, dataBuf.String()) + g.processMessage(ctx, mailFrom, rcptTo, dataBuf.String()) write(250, "OK: message accepted") return } @@ -185,7 +185,7 @@ func extractAddr(line string) string { // processMessage extracts text from the raw email and routes it through // the gateway router. Replies are sent back via SMTP. -func (g *Gateway) processMessage(from, to, raw string) { +func (g *Gateway) processMessage(ctx context.Context, from, to, raw string) { g.mu.Lock() router := g.router g.mu.Unlock() @@ -204,7 +204,7 @@ func (g *Gateway) processMessage(from, to, raw string) { From: from, Text: text, } - reply, err := router.Route(context.Background(), msg) + reply, err := router.Route(ctx, msg) if err != nil { g.log.Error("email route", "err", err, "from", from) return diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index cdad5a043..70963f344 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -140,11 +140,11 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error { select { case <-ctx.Done(): cancel() - return g.Stop(context.Background()) + return g.Stop(context.WithoutCancel(ctx)) case req := <-g.restartCh: g.log.Info("restarting telegram gateway", "requested_by", req.chatID) cancel() - if err := g.Stop(context.Background()); err != nil { + if err := g.Stop(context.WithoutCancel(ctx)); err != nil { g.log.Warn("stop during restart failed", "error", err) } if g.Reload != nil { diff --git a/internal/channels/webhook/webhook.go b/internal/channels/webhook/webhook.go index c8ceea4d9..93d6e551a 100644 --- a/internal/channels/webhook/webhook.go +++ b/internal/channels/webhook/webhook.go @@ -84,7 +84,7 @@ func (g *Gateway) Start(ctx context.Context, router *gateway.Router) error { g.log.Info("webhook gateway listening", "addr", addr) go func() { <-ctx.Done() - shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer cancel() _ = g.server.Shutdown(shutdownCtx) }() diff --git a/internal/container/pool.go b/internal/container/pool.go index 0c01ea2b0..74d0a35e2 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -191,7 +191,7 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string if _, err := p.cli.ContainerStart(ctx, resp.ID, client.ContainerStartOptions{}); err != nil { // Best-effort cleanup. - if _, rmErr := p.cli.ContainerRemove(context.Background(), resp.ID, client.ContainerRemoveOptions{Force: true}); rmErr != nil { + if _, rmErr := p.cli.ContainerRemove(context.WithoutCancel(ctx), resp.ID, client.ContainerRemoveOptions{Force: true}); rmErr != nil { p.log.Warn("container remove after start failure", "id", resp.ID[:12], "err", rmErr) } p.mu.Lock() @@ -208,7 +208,7 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string // GracePeriod is configured, the container stays alive for that duration // before being killed -- the agent can handle follow-ups (gate re-runs, // human replies) during this window. PRD section 1. -func (p *Pool) Release(c *Container) { +func (p *Pool) Release(ctx context.Context, c *Container) { if c == nil { return } @@ -218,13 +218,13 @@ func (p *Pool) Release(c *Container) { time.Sleep(p.cfg.GracePeriod) } - ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + stopCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() - if _, err := p.cli.ContainerStop(ctx, c.ID, client.ContainerStopOptions{}); err != nil { + if _, err := p.cli.ContainerStop(stopCtx, c.ID, client.ContainerStopOptions{}); err != nil { p.log.Warn("container stop failed", "id", c.ID[:12], "err", err) } - if _, err := p.cli.ContainerRemove(context.Background(), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { + if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), c.ID, client.ContainerRemoveOptions{Force: true}); err != nil { p.log.Warn("container remove failed", "id", c.ID[:12], "err", err) } diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 5b11116ae..96696bd63 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -947,7 +947,7 @@ func (d *Daemon) process(ctx context.Context, task *store.Task) { _ = d.Store.Transition(ctx, task.ID, store.StatusRunning, store.StatusParked, "container acquire failed: "+err.Error()) return } - defer d.ContainerPool.Release(ctr) + defer d.ContainerPool.Release(ctx, ctr) } // Set the working label only after successful container setup (or when no diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c8c48ea2d..01755da41 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -144,14 +144,14 @@ type TaskController interface { // responder. Gateway implementations call Route on every inbound // message. type Router struct { - Store StatusReader - Models ModelManager // nil = /model not configured + Store StatusReader + Models ModelManager // nil = /model not configured // ModelPersist persists the active model selection so it survives // restarts (e.g. writing back to identity config). nil = not configured. ModelPersist func(ctx context.Context, modelRef string) error // Personas holds the available personality registry for /personality. - Personas *PersonaRegistry - Tasks TaskCreator // nil = /spawn not configured + Personas *PersonaRegistry + Tasks TaskCreator // nil = /spawn not configured Controller TaskController // nil = /approve and /cancel not configured LLM LLMResponder // nil = LLM not wired yet // LLMStream is the optional streaming responder. When set, adapters @@ -169,7 +169,7 @@ type Router struct { // /undo, /retry, /compress) are available. When nil, those // commands report "not configured". Sessions SessionStore - Agents AgentReader // nil = /agents not configured + Agents AgentReader // nil = /agents not configured sessionTracker *sessionTracker gatewayName string } diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index cbdf32d57..f34a5dc71 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -758,7 +758,8 @@ func TestRouteResumeNotConfigured(t *testing.T) { func TestRouteResumeNoMatch(t *testing.T) { r := NewRouter(nil, nil, "test-gw") - r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore(), + r.Sessions = &fakeSessionLister{ + fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "session-1"}, }, @@ -774,7 +775,8 @@ func TestRouteResumeNoMatch(t *testing.T) { func TestRouteResumeAmbiguous(t *testing.T) { r := NewRouter(nil, nil, "test-gw") - r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore(), + r.Sessions = &fakeSessionLister{ + fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "abc-123"}, {SessionID: "abc-456"}, @@ -791,7 +793,8 @@ func TestRouteResumeAmbiguous(t *testing.T) { func TestRouteResumeExactMatch(t *testing.T) { r := NewRouter(nil, nil, "test-gw") - r.Sessions = &fakeSessionLister{fakeSessionStore: newFakeSessionStore(), + r.Sessions = &fakeSessionLister{ + fakeSessionStore: newFakeSessionStore(), sessions: []SessionContext{ {SessionID: "abc-123"}, {SessionID: "abc-456"}, diff --git a/internal/memory/manager.go b/internal/memory/manager.go index 21d8e9921..4516b1c94 100644 --- a/internal/memory/manager.go +++ b/internal/memory/manager.go @@ -486,6 +486,15 @@ func (m *Manager) Prefetch(query string) (string, error) { // (18.8). Results from successful prefetches are stored and included in // SystemPromptBlock() output. func (m *Manager) PrefetchContext(ctx context.Context, query string) (string, error) { + // Apply the manager's default timeout if the caller hasn't set a + // shorter deadline. Derived before the loop so we never nest a + // context inside a loop (fatcontext). + if _, hasDeadline := ctx.Deadline(); !hasDeadline { + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout) + defer cancel() + } + m.mu.RLock() providers := m.activeProvidersLocked() m.mu.RUnlock() @@ -508,17 +517,6 @@ func (m *Manager) PrefetchContext(ctx context.Context, query string) (string, er } defer flag.Store(false) - // Apply the manager's default timeout if the caller hasn't set a - // shorter deadline. - if _, hasDeadline := ctx.Deadline(); !hasDeadline { - var cancel context.CancelFunc - // Assignment, not declaration: `:=` here would scope the - // timeout-bearing ctx to this if-block, so the deadline would - // silently never apply to the call below. - ctx, cancel = context.WithTimeout(ctx, m.prefetchTimeout) - defer cancel() - } - start := time.Now() // Run Prefetch in a goroutine so we can respect the context deadline. diff --git a/internal/storage/storage_test.go b/internal/storage/storage_test.go index e6ee1945f..4cc486f67 100644 --- a/internal/storage/storage_test.go +++ b/internal/storage/storage_test.go @@ -555,10 +555,15 @@ func dockerTestClient(t *testing.T, roundTrip func(*http.Request) (*http.Respons srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { resp, err := roundTrip(req) if err != nil { + // roundTrip may return a partial response alongside the error. + if resp != nil { + resp.Body.Close() + } t.Errorf("Docker test handler: %v", err) http.Error(w, err.Error(), http.StatusInternalServerError) return } + defer resp.Body.Close() for key, values := range resp.Header { for _, value := range values { w.Header().Add(key, value) diff --git a/internal/tools/mcp/transport.go b/internal/tools/mcp/transport.go index 8cdb0df5b..ec4a87bb7 100644 --- a/internal/tools/mcp/transport.go +++ b/internal/tools/mcp/transport.go @@ -103,9 +103,8 @@ type StdioTransport struct { // pending maps message IDs (as raw JSON) to response channels. pending map[string]chan []byte - // ctx is cancelled by Stop(). Background goroutines select on this. - ctx context.Context - cancel context.CancelFunc + // stopCh is closed by Stop(). Background goroutines select on this. + stopCh chan struct{} // readerWg tracks the reader goroutine so Stop can wait for it. readerWg sync.WaitGroup @@ -164,18 +163,22 @@ func (t *StdioTransport) Start(ctx context.Context) error { return fmt.Errorf("mcp: stop in progress") } t.state = StateStarting - // Create a fresh context for this lifecycle. If we're restarting from - // Error state, the previous context was already cancelled; make a new one. - if t.ctx != nil { - t.cancel() + // Create a fresh stop channel for this lifecycle. If we're restarting + // from Error state, the previous stop channel is already closed. + if t.stopCh != nil { + select { + case <-t.stopCh: + default: + close(t.stopCh) + } } - t.ctx, t.cancel = context.WithCancel(context.Background()) + t.stopCh = make(chan struct{}) // Reset crash and failure counters on explicit user start. t.crashCount = 0 t.startupFailures = 0 t.mu.Unlock() - return t.startSubprocess() + return t.startSubprocess(context.WithoutCancel(ctx)) } // stopSubprocess kills the current subprocess and waits for it to exit. @@ -225,8 +228,12 @@ func (t *StdioTransport) Stop(_ context.Context) error { // opens a window where a concurrent Start() could see a state it isn't // guarding against and race a fresh subprocess against this shutdown. t.state = StateStopping - if t.cancel != nil { - t.cancel() + if t.stopCh != nil { + select { + case <-t.stopCh: + default: + close(t.stopCh) + } } t.mu.Unlock() @@ -345,22 +352,22 @@ func (t *StdioTransport) Notify(ctx context.Context, body []byte) error { // startSubprocess spawns the MCP server subprocess and starts the reader // goroutine. Must be called without t.mu held. -func (t *StdioTransport) startSubprocess() error { - cmd, stdin, stdout, err := t.spawnProcess() +func (t *StdioTransport) startSubprocess(ctx context.Context) error { + cmd, stdin, stdout, err := t.spawnProcess(ctx) if err != nil { t.mu.Lock() t.state = StateError t.mu.Unlock() return err } - return t.commitSpawnedProcess(cmd, stdin, stdout, false) + return t.commitSpawnedProcess(ctx, cmd, stdin, stdout, false) } // commitSpawnedProcess installs a freshly spawned subprocess as the // transport's active one and starts its reader goroutine. spawnProcess runs // without t.mu held (it performs a real fork/exec), so a concurrent Stop() -// can cancel t.ctx and commit StateStopped while a spawn is still in -// flight. commitSpawnedProcess re-checks t.ctx under the lock immediately +// can close t.stopCh and commit StateStopped while a spawn is still in +// flight. commitSpawnedProcess re-checks stopCh under the lock immediately // before committing: if Stop() already won, the just-spawned subprocess is // discarded (killed and reaped) instead of clobbering the Stopped state // Stop() already reported to its own caller. Both startSubprocess (a fresh @@ -370,9 +377,9 @@ func (t *StdioTransport) startSubprocess() error { // resetStartupFailures resets the spawn-failure counter on success; it is // true only for attemptRestart, since Start() already resets both crash and // startup-failure counters itself before the first spawn attempt. -func (t *StdioTransport) commitSpawnedProcess(cmd *exec.Cmd, stdin io.WriteCloser, stdout *bufio.Reader, resetStartupFailures bool) error { +func (t *StdioTransport) commitSpawnedProcess(ctx context.Context, cmd *exec.Cmd, stdin io.WriteCloser, stdout *bufio.Reader, resetStartupFailures bool) error { t.mu.Lock() - if t.ctx.Err() != nil { + if t.isStopped() { t.state = StateStopped t.mu.Unlock() _ = stdin.Close() @@ -380,7 +387,7 @@ func (t *StdioTransport) commitSpawnedProcess(cmd *exec.Cmd, stdin io.WriteClose _ = cmd.Process.Kill() _ = cmd.Wait() } - return t.ctx.Err() + return errTransportStopped } t.cmd = cmd t.stdin = stdin @@ -392,15 +399,15 @@ func (t *StdioTransport) commitSpawnedProcess(cmd *exec.Cmd, stdin io.WriteClose // Start the reader goroutine. t.readerWg.Add(1) - go t.runReader(stdout) + go t.runReader(ctx, stdout) return nil } // spawnProcess creates and starts the subprocess. Returns the cmd, // stdin writer, and buffered stdout reader. -func (t *StdioTransport) spawnProcess() (*exec.Cmd, io.WriteCloser, *bufio.Reader, error) { - cmd := exec.CommandContext(t.ctx, t.config.Command, t.config.Args...) +func (t *StdioTransport) spawnProcess(ctx context.Context) (*exec.Cmd, io.WriteCloser, *bufio.Reader, error) { + cmd := exec.CommandContext(ctx, t.config.Command, t.config.Args...) cmd.Env = append(os.Environ(), t.config.Env...) cmd.Dir = t.config.Dir @@ -428,7 +435,7 @@ func (t *StdioTransport) spawnProcess() (*exec.Cmd, io.WriteCloser, *bufio.Reade // subprocess's stdout, routing responses to the matching pending // channels. On error (process crash, pipe close), it initiates the // auto-restart sequence. -func (t *StdioTransport) runReader(reader *bufio.Reader) { +func (t *StdioTransport) runReader(ctx context.Context, reader *bufio.Reader) { defer t.readerWg.Done() for { @@ -437,7 +444,7 @@ func (t *StdioTransport) runReader(reader *bufio.Reader) { // The subprocess is dead or the pipe is broken. Attempt restart // if we weren't asked to stop. t.mu.Lock() - cancelled := t.ctx.Err() != nil + cancelled := t.isStopped() shuttingDown := t.state == StateStopping || t.state == StateStopped t.mu.Unlock() @@ -445,7 +452,7 @@ func (t *StdioTransport) runReader(reader *bufio.Reader) { return } - t.handleProcessDeath() + t.handleProcessDeath(ctx) return } @@ -486,7 +493,7 @@ func (t *StdioTransport) deliverResponse(body []byte) { // handleProcessDeath is called when the reader detects the subprocess // has died. It increments crashCount for backoff, transitions to Starting, // closes pending channels, and initiates the auto-restart sequence. -func (t *StdioTransport) handleProcessDeath() { +func (t *StdioTransport) handleProcessDeath(ctx context.Context) { t.mu.Lock() if t.state != StateRunning { t.mu.Unlock() @@ -508,7 +515,7 @@ func (t *StdioTransport) handleProcessDeath() { } // Attempt restart (outside lock because it waits). - t.attemptRestart() + t.attemptRestart(ctx) } // failAllPendingLocked closes all pending response channels with an error. @@ -528,11 +535,11 @@ func (t *StdioTransport) failAllPendingLocked() { // Crash loops where the process starts but immediately dies are bounded // by exponential backoff growing up to MaxBackoff. Spawn failures // (binary not found, permissions, etc.) count against MaxRetries. -func (t *StdioTransport) attemptRestart() { +func (t *StdioTransport) attemptRestart(ctx context.Context) { for { // Check preconditions under lock. t.mu.Lock() - if t.ctx.Err() != nil { + if t.isStopped() { t.state = StateStopped t.mu.Unlock() return @@ -563,7 +570,7 @@ func (t *StdioTransport) attemptRestart() { // Wait for the backoff period, but abort if the transport is stopped. timer := time.NewTimer(backoff) select { - case <-t.ctx.Done(): + case <-t.stopCh: timer.Stop() t.mu.Lock() t.state = StateStopped @@ -573,7 +580,7 @@ func (t *StdioTransport) attemptRestart() { } // Try to start the subprocess. - cmd, stdin, stdout, err := t.spawnProcess() + cmd, stdin, stdout, err := t.spawnProcess(ctx) if err != nil { t.mu.Lock() t.startupFailures++ @@ -585,7 +592,7 @@ func (t *StdioTransport) attemptRestart() { // so a concurrent Stop() that cancelled the context while // spawnProcess was in flight discards this subprocess instead of // clobbering the Stopped state Stop() already reported. - _ = t.commitSpawnedProcess(cmd, stdin, stdout, true) + _ = t.commitSpawnedProcess(ctx, cmd, stdin, stdout, true) return } } @@ -633,6 +640,22 @@ func writeMessageWithTimeout(w io.Writer, data []byte, timeout time.Duration) er // ── Helpers ───────────────────────────────────────────────────────────── +// isStopped returns true if the transport stop channel has been closed. +// Must be called with t.mu held or from a goroutine that doesn't need +// the lock for ordering. +func (t *StdioTransport) isStopped() bool { + select { + case <-t.stopCh: + return true + default: + return false + } +} + +// errTransportStopped is returned by the lifecycle context when the +// transport is stopped. +var errTransportStopped = errors.New("mcp: transport stopped") + // extractMessageID extracts the "id" field from a JSON body as a raw JSON // string. This is used as the key for correlating requests with responses. // A missing "id" returns an empty string (for notifications, which don't diff --git a/internal/tools/mcp/transport_sse.go b/internal/tools/mcp/transport_sse.go index c366b2dad..684e99cc2 100644 --- a/internal/tools/mcp/transport_sse.go +++ b/internal/tools/mcp/transport_sse.go @@ -72,8 +72,8 @@ type SSETransport struct { pending map[string]chan []byte - ctx context.Context - cancel context.CancelFunc + // stopCh is closed by Stop(). Background goroutines select on this. + stopCh chan struct{} // The SSE reader goroutine. readerWg sync.WaitGroup @@ -100,7 +100,7 @@ func (t *SSETransport) Start(ctx context.Context) error { return fmt.Errorf("mcp sse: already running") } t.state = StateStarting - t.ctx, t.cancel = context.WithCancel(context.Background()) + t.stopCh = make(chan struct{}) t.messageEndpoint = t.config.MessageEndpoint // fallback; endpoint event overrides t.mu.Unlock() @@ -116,8 +116,12 @@ func (t *SSETransport) Stop(_ context.Context) error { return nil } t.state = StateStopping - if t.cancel != nil { - t.cancel() + if t.stopCh != nil { + select { + case <-t.stopCh: + default: + close(t.stopCh) + } } if t.respBody != nil { _ = t.respBody.Close() @@ -240,13 +244,13 @@ func (t *SSETransport) connect(ctx context.Context) error { // Start the background SSE event reader. t.readerWg.Add(1) - go t.runReader(resp.Body, reader) + go t.runReader(ctx, resp.Body, reader) return nil } // runReader loops reading SSE events from the stream, routing // "message" events to the corresponding pending channel. -func (t *SSETransport) runReader(body io.Closer, reader *bufio.Reader) { +func (t *SSETransport) runReader(ctx context.Context, body io.Closer, reader *bufio.Reader) { defer t.readerWg.Done() defer func() { _ = body.Close() }() @@ -255,13 +259,13 @@ func (t *SSETransport) runReader(body io.Closer, reader *bufio.Reader) { if err != nil { // Stream closed or errored. Attempt reconnect. t.mu.Lock() - cancelled := t.ctx.Err() != nil + cancelled := t.isStopped() stopping := t.state == StateStopping || t.state == StateStopped t.mu.Unlock() if cancelled || stopping { return } - t.reconnect() + t.reconnect(ctx) return } switch event { @@ -283,11 +287,11 @@ func (t *SSETransport) runReader(body io.Closer, reader *bufio.Reader) { // reconnect attempts to re-establish the SSE connection with exponential // backoff. On success, the reader goroutine restarts. -func (t *SSETransport) reconnect() { +func (t *SSETransport) reconnect(ctx context.Context) { backoff := t.config.effectiveReconnectBackoff() for { t.mu.Lock() - if t.ctx.Err() != nil { + if t.isStopped() { t.state = StateStopped t.mu.Unlock() return @@ -300,13 +304,13 @@ func (t *SSETransport) reconnect() { timer := time.NewTimer(backoff) select { - case <-t.ctx.Done(): + case <-t.stopCh: timer.Stop() return case <-timer.C: } - req, err := http.NewRequestWithContext(t.ctx, http.MethodGet, t.config.SSEEndpoint, nil) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, t.config.SSEEndpoint, nil) if err != nil { backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff()) continue @@ -339,7 +343,7 @@ func (t *SSETransport) reconnect() { t.mu.Unlock() t.readerWg.Add(1) - go t.runReader(resp.Body, reader) + go t.runReader(ctx, resp.Body, reader) return } } @@ -485,5 +489,15 @@ func readSSEEvent(r *bufio.Reader) (event, data string, err error) { } } +// isStopped returns true if the transport stop channel has been closed. +func (t *SSETransport) isStopped() bool { + select { + case <-t.stopCh: + return true + default: + return false + } +} + // Compile-time interface check. var _ Transport = (*SSETransport)(nil) diff --git a/internal/tools/mcp/transport_test.go b/internal/tools/mcp/transport_test.go index 5b578580d..a01acbdda 100644 --- a/internal/tools/mcp/transport_test.go +++ b/internal/tools/mcp/transport_test.go @@ -601,7 +601,7 @@ func TestStdioTransportConcurrentStartDuringStop(t *testing.T) { // regression test for a race where startSubprocess (the path Start() uses // to commit a freshly spawned subprocess) could clobber a StateStopped // already committed and reported by a concurrent Stop(): spawnProcess runs -// without t.mu held (it's a real fork/exec), so Stop() can cancel t.ctx and +// without t.mu held (it's a real fork/exec), so Stop() can close t.stopCh and // return Stopped to its own caller while a spawn is still in flight. The // commit path used to unconditionally set state = StateRunning afterward, // wedging the transport in a Running state no caller of Stop() would ever @@ -623,21 +623,21 @@ func TestStdioTransportCommitSpawnedProcessDiscardsWhenContextRacesAhead(t *test tr.mu.Lock() tr.state = StateStarting - tr.ctx, tr.cancel = context.WithCancel(context.Background()) + tr.stopCh = make(chan struct{}) tr.mu.Unlock() - cmd, stdin, stdout, err := tr.spawnProcess() + cmd, stdin, stdout, err := tr.spawnProcess(context.Background()) if err != nil { t.Fatalf("spawnProcess: %v", err) } // Simulate a concurrent Stop() winning the race between spawn and - // commit: it would have cancelled this exact context. + // commit: it would have closed this exact stop channel. tr.mu.Lock() - tr.cancel() + close(tr.stopCh) tr.mu.Unlock() - err = tr.commitSpawnedProcess(cmd, stdin, stdout, false) + err = tr.commitSpawnedProcess(context.Background(), cmd, stdin, stdout, false) if err == nil { t.Fatal("expected error when context was cancelled before commit") } diff --git a/internal/webui/webui.go b/internal/webui/webui.go index 841276e27..8da4e8c97 100644 --- a/internal/webui/webui.go +++ b/internal/webui/webui.go @@ -61,7 +61,7 @@ func (s *Server) Run(ctx context.Context, listen string) error { srv := &http.Server{Addr: listen, Handler: s.Handler(), ReadHeaderTimeout: 5 * time.Second} go func() { <-ctx.Done() - shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + shutdownCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second) defer cancel() _ = srv.Shutdown(shutdownCtx) }()