diff --git a/internal/container/pool.go b/internal/container/pool.go index cd7d95e14..18d3e583f 100644 --- a/internal/container/pool.go +++ b/internal/container/pool.go @@ -174,8 +174,9 @@ func NewPool(ctx context.Context, cfg Config, log *slog.Logger) (*Pool, error) { // Acquire creates and starts a container with the given mounts and // environment variables. Mounts are provided by the caller (typically -// from a storage.Backend). If MaxUptime is set, the container is -// created with a deadline -- Docker kills it when the time elapses. +// from a storage.Backend). If MaxUptime is set, the pool schedules a hard +// stop and remove of the container once that lifetime cap elapses, +// regardless of task state. func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string) (*Container, error) { p.mu.Lock() if p.cfg.MaxConcurrency > 0 && p.active >= p.cfg.MaxConcurrency { @@ -185,13 +186,6 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string p.active++ p.mu.Unlock() - // Enforce MaxUptime via container-level timeout. - if p.cfg.MaxUptime > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, p.cfg.MaxUptime) - defer cancel() - } - name := fmt.Sprintf("archie-agent-%d", time.Now().UnixNano()) hostConfig := &container.HostConfig{ @@ -235,10 +229,33 @@ func (p *Pool) Acquire(ctx context.Context, mounts []storage.Mount, env []string return nil, fmt.Errorf("container start: %w", err) } + if p.cfg.MaxUptime > 0 { + p.armMaxUptime(ctx, resp.ID) + } + p.log.Info("container started", "id", resp.ID[:12], "name", name) return &Container{ID: resp.ID}, nil } +// armMaxUptime schedules a hard stop and remove for a container once its +// lifetime cap elapses. The timer is keyed to the container ID and never +// touches p.active: Release (or Close) remains the only owner of the active +// slot. Docker stop and remove are idempotent, so a timer that fires after +// Release has already removed the container only logs a warning. +func (p *Pool) armMaxUptime(ctx context.Context, id string) { + time.AfterFunc(p.cfg.MaxUptime, func() { + zero := 0 + stopCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second) + defer cancel() + if _, err := p.cli.ContainerStop(stopCtx, id, client.ContainerStopOptions{Timeout: &zero}); err != nil { + p.log.Warn("max uptime stop failed", "id", id[:12], "err", err) + } + if _, err := p.cli.ContainerRemove(context.WithoutCancel(ctx), id, client.ContainerRemoveOptions{Force: true}); err != nil { + p.log.Warn("max uptime remove failed", "id", id[:12], "err", err) + } + }) +} + // releaseDecision reports how Release should tear a container down: whether // to honour the configured post-completion grace period, and what Docker // stop timeout to request (nil means the container's configured timeout or diff --git a/internal/container/pool_test.go b/internal/container/pool_test.go index f358ae7de..645d21114 100644 --- a/internal/container/pool_test.go +++ b/internal/container/pool_test.go @@ -3,10 +3,16 @@ package container import ( "context" "encoding/json" + "net/http" + "net/http/httptest" "os" "path/filepath" + "strings" + "sync/atomic" "testing" "time" + + "github.com/moby/moby/client" ) // ── regression: Gap 2 -- post-completion grace period ──────────────── @@ -290,3 +296,74 @@ func TestWriteTaskJSONMinimalPayload(t *testing.T) { t.Error("minimal payload ID mismatch") } } + +// TestAcquireEnforcesMaxUptime pins the MaxUptime lifetime cap: a container +// acquired with MaxUptime > 0 must be stopped and removed once that cap +// elapses, independent of any later Release call. +func TestAcquireEnforcesMaxUptime(t *testing.T) { + const containerID = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + + var stopCalls, removeCalls atomic.Int32 + stopped := make(chan struct{}, 1) + removed := make(chan struct{}, 1) + + dockerAPI := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case strings.HasSuffix(r.URL.Path, "/containers/create"): + writeDockerJSON(t, w, map[string]any{"Id": containerID, "Warnings": []string{}}) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/start"): + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID+"/stop"): + stopCalls.Add(1) + select { + case stopped <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + case strings.HasSuffix(r.URL.Path, "/containers/"+containerID): + removeCalls.Add(1) + select { + case removed <- struct{}{}: + default: + } + w.WriteHeader(http.StatusNoContent) + default: + http.Error(w, "unexpected Docker API path "+r.URL.Path, http.StatusNotFound) + } + })) + t.Cleanup(dockerAPI.Close) + + dockerClient, err := client.New(client.WithHost(dockerAPI.URL), client.WithAPIVersion("1.55")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = dockerClient.Close() }) + + pool := &Pool{ + cli: dockerClient, + cfg: Config{Image: "test/image", MaxUptime: 50 * time.Millisecond}, + log: discardLogger(), + } + + c, err := pool.Acquire(context.Background(), nil, nil) + if err != nil { + t.Fatalf("Acquire: %v", err) + } + if c.ID != containerID { + t.Fatalf("Acquire returned container ID %q, want %q", c.ID, containerID) + } + + select { + case <-stopped: + case <-time.After(2 * time.Second): + t.Fatal("max uptime timer did not stop the container") + } + select { + case <-removed: + case <-time.After(2 * time.Second): + t.Fatal("max uptime timer did not remove the container") + } + if stopCalls.Load() == 0 || removeCalls.Load() == 0 { + t.Fatalf("expected at least one stop and remove, got stop=%d remove=%d", stopCalls.Load(), removeCalls.Load()) + } +} diff --git a/internal/store/store.go b/internal/store/store.go index 3688dd98e..82d4ad348 100644 --- a/internal/store/store.go +++ b/internal/store/store.go @@ -160,7 +160,7 @@ CREATE TABLE IF NOT EXISTS tasks ( title TEXT NOT NULL DEFAULT '', body TEXT NOT NULL DEFAULT '', labels TEXT NOT NULL DEFAULT '', - status TEXT NOT NULL DEFAULT 'queued', + status TEXT NOT NULL DEFAULT '` + workflow.StatusQueued + `', workflow TEXT NOT NULL DEFAULT '', stage TEXT NOT NULL DEFAULT '', branch TEXT NOT NULL DEFAULT '', @@ -285,12 +285,13 @@ func (s *Store) EnqueueBindingTask(ctx context.Context, owner, repo, title, body // returns it; nil when the queue is empty. func (s *Store) ClaimNext(ctx context.Context) (*workflow.Task, error) { row := s.db.QueryRowContext(ctx, ` - UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now') - WHERE id = (SELECT id FROM tasks WHERE status='queued' ORDER BY id LIMIT 1) + UPDATE tasks SET status=?, attempt=attempt+1, updated_at=datetime('now') + WHERE id = (SELECT id FROM tasks WHERE status=? ORDER BY id LIMIT 1) RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, retry_count, - source, identity, binding_id, binding_version, created_at, updated_at`) + source, identity, binding_id, binding_version, created_at, updated_at`, + workflow.StatusRunning, workflow.StatusQueued) t, err := scanTask(row) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -318,12 +319,13 @@ func scanTask(row *sql.Row) (*workflow.Task, error) { // inserted via EnqueueIssue and needs an immediate targeted claim. func (s *Store) ClaimByIssue(ctx context.Context, owner, repo string, number int) (*workflow.Task, error) { row := s.db.QueryRowContext(ctx, ` - UPDATE tasks SET status='running', attempt=attempt+1, updated_at=datetime('now') - WHERE owner=? AND repo=? AND issue_number=? AND status='queued' + UPDATE tasks SET status=?, attempt=attempt+1, updated_at=datetime('now') + WHERE owner=? AND repo=? AND issue_number=? AND status=? RETURNING id, owner, repo, issue_number, title, body, labels, status, workflow, stage, branch, plan, notes, pr_number, tokens_used, iterations, attempt, park_reason, watch_comment_id, retry_count, - source, identity, binding_id, binding_version, created_at, updated_at`, owner, repo, number) + source, identity, binding_id, binding_version, created_at, updated_at`, + workflow.StatusRunning, owner, repo, number, workflow.StatusQueued) t, err := scanTask(row) if errors.Is(err, sql.ErrNoRows) { return nil, nil @@ -427,7 +429,7 @@ func (s *Store) TaskByID(ctx context.Context, taskID int64) (*workflow.Task, err // current status matches fromStatus. If no row matches, ErrStaleTransition // is returned and no audit row is written. Both statements execute in a // single transaction. -func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow string) error { +func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, wf string) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err @@ -435,10 +437,10 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow defer func() { _ = tx.Rollback() }() res, err := tx.ExecContext(ctx, ` - UPDATE tasks SET status='queued', + UPDATE tasks SET status=?, workflow=CASE WHEN ?='' THEN workflow ELSE ? END, stage='', park_reason='', updated_at=datetime('now') - WHERE id=? AND status=?`, workflow, workflow, taskID, fromStatus) + WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus) if err != nil { return err } @@ -451,8 +453,8 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow } _, err = tx.ExecContext(ctx, - `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, 'queued', ?)`, - taskID, fromStatus, "requeued "+workflow) + `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`, + taskID, fromStatus, workflow.StatusQueued, "requeued "+wf) if err != nil { return err } @@ -463,7 +465,7 @@ func (s *Store) Requeue(ctx context.Context, taskID int64, fromStatus, workflow // RetryTask requeues a task and increments retry_count in the same guarded // transaction. A queued task with an uncounted retry would make max_retries a // suggestion rather than a cap. -func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, workflow string) error { +func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, wf string) error { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return err @@ -471,10 +473,10 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, workflo defer func() { _ = tx.Rollback() }() res, err := tx.ExecContext(ctx, ` - UPDATE tasks SET status='queued', retry_count=retry_count+1, + UPDATE tasks SET status=?, retry_count=retry_count+1, workflow=CASE WHEN ?='' THEN workflow ELSE ? END, stage='', park_reason='', updated_at=datetime('now') - WHERE id=? AND status=?`, workflow, workflow, taskID, fromStatus) + WHERE id=? AND status=?`, workflow.StatusQueued, wf, wf, taskID, fromStatus) if err != nil { return err } @@ -486,8 +488,8 @@ func (s *Store) RetryTask(ctx context.Context, taskID int64, fromStatus, workflo return ErrStaleTransition } if _, err := tx.ExecContext(ctx, - `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, 'queued', ?)`, - taskID, fromStatus, "retried "+workflow); err != nil { + `INSERT INTO transitions (task_id, from_status, to_status, detail) VALUES (?, ?, ?, ?)`, + taskID, fromStatus, workflow.StatusQueued, "retried "+wf); err != nil { return err } return tx.Commit() @@ -533,7 +535,8 @@ func (s *Store) ArchiveTask( // RecoverStale re-queues tasks left running by a crashed daemon. func (s *Store) RecoverStale(ctx context.Context) (int64, error) { res, err := s.db.ExecContext(ctx, - `UPDATE tasks SET status='queued', updated_at=datetime('now') WHERE status='running'`) + `UPDATE tasks SET status=?, updated_at=datetime('now') WHERE status=?`, + workflow.StatusQueued, workflow.StatusRunning) if err != nil { return 0, err } @@ -544,7 +547,7 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) { func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr error) { rows, err := s.db.QueryContext(ctx, ` SELECT id, owner, repo, issue_number, pr_number, status, source, identity - FROM tasks WHERE status='pr_open'`) + FROM tasks WHERE status=?`, workflow.StatusPROpen) if err != nil { return nil, err } @@ -566,7 +569,8 @@ func (s *Store) OpenPRs(ctx context.Context) (tasks []workflow.Task, retErr erro // deliberately excluded because it is recoverable. func (s *Store) ClearTerminalTasks(ctx context.Context) (int64, error) { res, err := s.db.ExecContext(ctx, - `DELETE FROM tasks WHERE status IN ('merged','rejected','dead','closed_wont_do')`) + `DELETE FROM tasks WHERE status IN (?, ?, ?, ?)`, + workflow.StatusMerged, workflow.StatusRejected, workflow.StatusDead, workflow.StatusClosedWontDo) if err != nil { return 0, err } diff --git a/internal/tools/builtin/edit.go b/internal/tools/builtin/edit.go index 4918bedd7..b6a18cee0 100644 --- a/internal/tools/builtin/edit.go +++ b/internal/tools/builtin/edit.go @@ -131,9 +131,6 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { return Result{Content: "at least one edit is required", IsError: true}, nil } - _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) - defer cancel() - path := resolvePath(cwd, p.Path) if !isConfined(cwd, path) { @@ -147,63 +144,85 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor { } } - // Check file size before reading to avoid OOM on large files. - info, err := os.Stat(path) + editCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + var result Result + err = runWithContext(editCtx, func() error { + result = performEdit(path, p, mq) + return nil + }) if err != nil { - return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true}, nil - } - if info.Size() > maxReadBytes { - return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}, nil - } - - release := mq.Acquire(path) - defer release() - - data, err := os.ReadFile(path) - if err != nil { - return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}, nil - } - - // Strip a UTF-8 BOM and normalise CRLF to LF before matching - the - // model never includes an invisible BOM or carriage returns in - // old_text. Both are restored on write. - raw := string(data) - bom := "" - if strings.HasPrefix(raw, utf8BOM) { - bom = utf8BOM - raw = strings.TrimPrefix(raw, utf8BOM) - } - hadCRLF := strings.Contains(raw, "\r\n") - content := strings.ReplaceAll(raw, "\r\n", "\n") - - newContent, err := applyEdits(content, p.Edits) - if err != nil { - errorKind := "invalid_arguments" - if strings.Contains(err.Error(), "old_text not found") { - errorKind = "stale_edit" + if errors.Is(err, context.DeadlineExceeded) { + return Result{Content: fmt.Sprintf("edit timed out after %v", DefaultToolTimeout), IsError: true}, nil } - return Result{ - Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying", - IsError: true, - ErrorKind: errorKind, - }, nil - } - if newContent == content { - return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true}, nil + return Result{Content: fmt.Sprintf("edit failed: %v", err), IsError: true}, nil } - if hadCRLF { - newContent = strings.ReplaceAll(newContent, "\n", "\r\n") - } + return result, nil + } +} - if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil { - return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true}, nil - } +// performEdit loads, mutates, and writes path according to the edits in p. +// Every failure is returned as a Result with IsError set, never a non-nil +// error, so the executor keeps a single error envelope. +func performEdit(path string, p EditParams, mq *MutationQueue) Result { + // Check file size before reading to avoid OOM on large files. + info, err := os.Stat(path) + if err != nil { + return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true} + } + if info.Size() > maxReadBytes { + return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true} + } + release := mq.Acquire(path) + defer release() + + data, err := os.ReadFile(path) + if err != nil { + return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true} + } + + // Strip a UTF-8 BOM and normalise CRLF to LF before matching - the + // model never includes an invisible BOM or carriage returns in + // old_text. Both are restored on write. + raw := string(data) + bom := "" + if strings.HasPrefix(raw, utf8BOM) { + bom = utf8BOM + raw = strings.TrimPrefix(raw, utf8BOM) + } + hadCRLF := strings.Contains(raw, "\r\n") + content := strings.ReplaceAll(raw, "\r\n", "\n") + + newContent, err := applyEdits(content, p.Edits) + if err != nil { + errorKind := "invalid_arguments" + if strings.Contains(err.Error(), "old_text not found") { + errorKind = "stale_edit" + } return Result{ - Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path), - Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent}, - }, nil + Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying", + IsError: true, + ErrorKind: errorKind, + } + } + if newContent == content { + return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true} + } + + if hadCRLF { + newContent = strings.ReplaceAll(newContent, "\n", "\r\n") + } + + if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil { + return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true} + } + + return Result{ + Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path), + Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent}, } } diff --git a/internal/tools/builtin/edit_test.go b/internal/tools/builtin/edit_test.go index 4058ded0c..a5d59daf4 100644 --- a/internal/tools/builtin/edit_test.go +++ b/internal/tools/builtin/edit_test.go @@ -7,6 +7,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func TestApplyEdits(t *testing.T) { @@ -329,3 +330,36 @@ func TestEdit_NotFoundWithNoPlausibleMatchStaysGeneric(t *testing.T) { t.Fatalf("expected the generic error, got:\n%s", res.Content) } } + +// TestEditToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout +// contract: when the caller's context is already expired, edit must not +// ignore that deadline and mutate the file anyway. +func TestEditToolHonoursDeadlineOnExpiredContext(t *testing.T) { + tmp := t.TempDir() + path := filepath.Join(tmp, "f.txt") + if err := os.WriteFile(path, []byte("hello\n"), 0o644); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + tool := NewEditTool(tmp, NewMutationQueue(), nil) + res, err := tool.Execute(ctx, json.RawMessage( + `{"path":"f.txt","edits":[{"old_text":"hello","new_text":"hi"}]}`, + ), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("edit on an expired context must not succeed; got content %q", res.Content) + } + + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(after) != "hello\n" { + t.Fatalf("file was mutated despite the expired context: %q", after) + } +} diff --git a/internal/tools/builtin/read.go b/internal/tools/builtin/read.go index 94f51788d..a7e9f0513 100644 --- a/internal/tools/builtin/read.go +++ b/internal/tools/builtin/read.go @@ -15,6 +15,7 @@ package builtin import ( "context" "encoding/json" + "errors" "fmt" "io/fs" "os" @@ -222,28 +223,42 @@ func makeReadExecutor(cwd string, rt *ReadTracker) Executor { return *terminal, nil } - _, cancel := context.WithTimeout(ctx, DefaultToolTimeout) - defer cancel() - path := resolvePath(cwd, p.Path) if !isReadConfined(cwd, path) { return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil } - info, err := os.Stat(path) - if err != nil { - msg := fmt.Sprintf("error stating file: %v", err) - if hint := suggestPaths(cwd, path); hint != "" { - msg += "\n" + hint + readCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout) + defer cancel() + + var result Result + err = runWithContext(readCtx, func() error { + info, statErr := os.Stat(path) + if statErr != nil { + msg := fmt.Sprintf("error stating file: %v", statErr) + if hint := suggestPaths(cwd, path); hint != "" { + msg += "\n" + hint + } + result = Result{Content: msg, IsError: true, ErrorKind: "not_found"} + return nil } - return Result{Content: msg, IsError: true, ErrorKind: "not_found"}, nil + + state, terminal := readFileContent(cwd, path, p, info, rt) + if terminal != nil { + result = *terminal + return nil + } + result = serveReadContent(cwd, path, p, info, state, rt) + return nil + }) + if err != nil { + if errors.Is(err, context.DeadlineExceeded) { + return Result{Content: fmt.Sprintf("read timed out after %v", DefaultToolTimeout), IsError: true}, nil + } + return Result{Content: fmt.Sprintf("read failed: %v", err), IsError: true}, nil } - state, terminal := readFileContent(cwd, path, p, info, rt) - if terminal != nil { - return *terminal, nil - } - return serveReadContent(cwd, path, p, info, state, rt), nil + return result, nil } } diff --git a/internal/tools/builtin/read_test.go b/internal/tools/builtin/read_test.go index 7cad3e74c..598325fa7 100644 --- a/internal/tools/builtin/read_test.go +++ b/internal/tools/builtin/read_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "testing" + "time" ) func execRead(t *testing.T, cwd, params string) Result { @@ -210,3 +211,23 @@ func TestReadTool_NotFoundListsExistingParentDir(t *testing.T) { t.Fatalf("expected the existing directory to be listed, got:\n%s", res.Content) } } + +// TestReadToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout +// contract: when the caller's context is already expired, read must not +// ignore that deadline and read the file anyway. +func TestReadToolHonoursDeadlineOnExpiredContext(t *testing.T) { + tmp := t.TempDir() + writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n") + + ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second)) + defer cancel() + + tool := NewReadTool(tmp, nil) + res, err := tool.Execute(ctx, json.RawMessage(`{"path":"f.txt"}`), nil) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if !res.IsError { + t.Fatalf("read on an expired context must not succeed; got content %q", res.Content) + } +} diff --git a/internal/tools/mcp/transport_sse.go b/internal/tools/mcp/transport_sse.go index 9a1b99200..0d1f2879b 100644 --- a/internal/tools/mcp/transport_sse.go +++ b/internal/tools/mcp/transport_sse.go @@ -75,6 +75,12 @@ type SSETransport struct { // stopCh is closed by Stop(). Background goroutines select on this. stopCh chan struct{} + // lifecycleCancel cancels the lifecycle context handed to the background + // reader and reconnect goroutines. Stop calls it so an in-flight reconnect + // HTTP request can be interrupted immediately instead of blocking Stop + // until the OS-level connect/read gives up. + lifecycleCancel context.CancelFunc + // The SSE reader goroutine. readerWg sync.WaitGroup // Track HTTP response body so Stop can close it. @@ -101,10 +107,12 @@ func (t *SSETransport) Start(ctx context.Context) error { } t.state = StateStarting t.stopCh = make(chan struct{}) + lifecycleCtx, cancel := context.WithCancel(ctx) + t.lifecycleCancel = cancel t.messageEndpoint = t.config.MessageEndpoint // fallback; endpoint event overrides t.mu.Unlock() - return t.connect(ctx) + return t.connect(lifecycleCtx) } // Stop closes the SSE connection, fails pending requests, and transitions @@ -123,6 +131,9 @@ func (t *SSETransport) Stop(_ context.Context) error { close(t.stopCh) } } + if t.lifecycleCancel != nil { + t.lifecycleCancel() + } if t.respBody != nil { _ = t.respBody.Close() t.respBody = nil @@ -335,14 +346,24 @@ func (t *SSETransport) reconnect(ctx context.Context) { backoff = nextBackoff(backoff, t.config.effectiveMaxReconnectBackoff()) continue } + + // Guarded commit: Stop may have won while the reconnect GET was in + // flight. Do not install a reader (or a response body Stop has already + // missed) once Stop has closed stopCh. t.mu.Lock() + if t.isStopped() || t.state != StateRunning { + t.state = StateStopped + t.mu.Unlock() + _ = resp.Body.Close() + return + } if msgURL != "" { t.messageEndpoint = msgURL } t.respBody = resp.Body + t.readerWg.Add(1) t.mu.Unlock() - t.readerWg.Add(1) go t.runReader(ctx, resp.Body, reader) return } diff --git a/internal/tools/mcp/transport_sse_test.go b/internal/tools/mcp/transport_sse_test.go index 5dd68c312..47cb637d8 100644 --- a/internal/tools/mcp/transport_sse_test.go +++ b/internal/tools/mcp/transport_sse_test.go @@ -9,6 +9,7 @@ import ( "net/http/httptest" "strings" "sync" + "sync/atomic" "testing" "time" ) @@ -275,3 +276,57 @@ func TestSSETransportConcurrentSendsGetCorrectResponses(t *testing.T) { t.Error(e) } } + +// TestSSETransportStopCancelsInFlightReconnect pins the Stop contract: when +// the SSE stream drops and reconnect is blocked on an unreachable endpoint, +// Stop must cancel that in-flight HTTP request instead of waiting for the +// OS-level connect/read to time out. +func TestSSETransportStopCancelsInFlightReconnect(t *testing.T) { + var requests atomic.Int32 + reconnectStarted := make(chan struct{}) + + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch requests.Add(1) { + case 1: + // Initial connect: deliver the endpoint event, then return so the + // client reader sees EOF and drops into reconnect. + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = fmt.Fprintf(w, "event: endpoint\ndata: http://127.0.0.1:1/messages\n\n") + if f, ok := w.(http.Flusher); ok { + f.Flush() + } + default: + // Reconnect: block until the client cancels the request (via Stop). + close(reconnectStarted) + <-r.Context().Done() + } + })) + defer srv.Close() + + tr := NewSSETransport(SSETransportConfig{ + SSEEndpoint: srv.URL + "/sse", + ReconnectBackoff: time.Millisecond, + MaxReconnectBackoff: time.Millisecond, + }) + if err := tr.Start(context.Background()); err != nil { + t.Fatalf("Start: %v", err) + } + + select { + case <-reconnectStarted: + case <-time.After(2 * time.Second): + t.Fatal("reconnect request never started") + } + + done := make(chan error, 1) + go func() { done <- tr.Stop(context.Background()) }() + select { + case err := <-done: + if err != nil { + t.Fatalf("Stop: %v", err) + } + case <-time.After(2 * time.Second): + t.Fatal("Stop did not cancel the in-flight reconnect request") + } +}