Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

test(agent): stop pkg/agent tests racing fixture startup under load (MUL-9179) (#10537)

Jiayuan Zhang603156fff0d3
diff --git a/server/pkg/agent/agent_test_executable_test.go b/server/pkg/agent/agent_test_executable_test.go
index 1e584a1276..7e620342de 100644
--- a/server/pkg/agent/agent_test_executable_test.go
+++ b/server/pkg/agent/agent_test_executable_test.go
@@ -1,11 +1,63 @@
package agent
import (
+ "context"
+ "os"
"path/filepath"
+ "sync"
"testing"
+ "time"
)
+// testFallbackTimeout bounds waits that only exist so a broken test fails
+// instead of hanging. It is not part of any behavior under test: fixture
+// processes can take seconds to start on a loaded machine (macOS scans every
+// new executable before its first exec), so a timeout that a fixture has to
+// beat must be this one, never a few-second budget.
+const testFallbackTimeout = 60 * time.Second
+
func missingAgentExecutable(tb testing.TB, name string) string {
tb.Helper()
return filepath.Join(tb.TempDir(), name)
}
+
+// waitForTestFile blocks until a fixture creates path.
+func waitForTestFile(tb testing.TB, path string) {
+ tb.Helper()
+ deadline := time.Now().Add(testFallbackTimeout)
+ for {
+ if _, err := os.Stat(path); err == nil {
+ return
+ }
+ if time.Now().After(deadline) {
+ tb.Fatalf("fixture never created %s", path)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+}
+
+// expirableContext reports context.DeadlineExceeded once expire is called, so
+// a test can end the caller's budget after the fixture reaches a known point
+// instead of racing a wall-clock deadline against fixture startup.
+type expirableContext struct {
+ context.Context
+ done chan struct{}
+ once sync.Once
+}
+
+func newExpirableContext() *expirableContext {
+ return &expirableContext{Context: context.Background(), done: make(chan struct{})}
+}
+
+func (c *expirableContext) Done() <-chan struct{} { return c.done }
+
+func (c *expirableContext) Err() error {
+ select {
+ case <-c.done:
+ return context.DeadlineExceeded
+ default:
+ return nil
+ }
+}
+
+func (c *expirableContext) expire() { c.once.Do(func() { close(c.done) }) }
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index db7998c275..532eee1444 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -2614,6 +2614,10 @@ type pendingRPC struct {
type rpcResult struct {
result json.RawMessage
err error
+ // processExited marks the error codexClient.markProcessExited hands to
+ // every pending request. It is not an answer from the server, so a caller
+ // whose context has already ended reports that instead.
+ processExited bool
}
type codexHandshakeTimeoutError struct {
@@ -2769,11 +2773,16 @@ func (c *codexClient) request(ctx context.Context, method string, params any) (j
select {
case res := <-pr.ch:
+ if res.processExited && requestCtx.Err() != nil {
+ return nil, codexRequestContextError(requestCtx)
+ }
return res.result, res.err
case <-processDone:
select {
case res := <-pr.ch:
- return res.result, res.err
+ if !res.processExited {
+ return res.result, res.err
+ }
default:
}
c.mu.Lock()
@@ -2852,7 +2861,7 @@ func (c *codexClient) markProcessExited(err error) {
}
}
for id, pr := range c.pending {
- pr.ch <- rpcResult{err: err}
+ pr.ch <- rpcResult{err: err, processExited: true}
delete(c.pending, id)
}
}
diff --git a/server/pkg/agent/codex_cleanup_unix_test.go b/server/pkg/agent/codex_cleanup_unix_test.go
index 336264ebde..25cae11545 100644
--- a/server/pkg/agent/codex_cleanup_unix_test.go
+++ b/server/pkg/agent/codex_cleanup_unix_test.go
@@ -6,11 +6,9 @@ import (
"context"
"fmt"
"log/slog"
- "os"
"path/filepath"
"strings"
"testing"
- "time"
)
// TestCodexInitializeParentDeadlineDoesNotPersistOpaqueEnv is the other half of
@@ -27,11 +25,10 @@ import (
// Canceled arm only.
//
// The fake writes the secret to stderr before reading the handshake, so the
-// redaction check never depends on racing our own initialize write. The budget
-// is sized against measurement: reaching the app-server's first line costs
-// ~430-465ms here (version probe plus launch), so 2s keeps ~4x headroom, and
-// the ready-file guard below fails loudly rather than vacuously if a slower
-// machine ever misses it.
+// redaction check never depends on racing our own initialize write. The
+// caller's deadline expires only once the fake has written it, and the
+// handshake bound is the fallback timeout, so the deadline is the only thing
+// that can end the run no matter how slowly the fake starts.
func TestCodexInitializeParentDeadlineDoesNotPersistOpaqueEnv(t *testing.T) {
t.Parallel()
@@ -41,7 +38,7 @@ func TestCodexInitializeParentDeadlineDoesNotPersistOpaqueEnv(t *testing.T) {
`echo "$OPAQUE_AUTH_VALUE" >&2`+"\n"+
`touch "`+readyFile+`"`+"\n"+
`read line`+"\n"+
- `sleep 5`+"\n")
+ `sleep 300`+"\n")
var logs strings.Builder
backend, err := New("codex", Config{
@@ -52,10 +49,9 @@ func TestCodexInitializeParentDeadlineDoesNotPersistOpaqueEnv(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- // Below the 4s handshake bound, so the parent deadline is what ends the run.
- ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
- defer cancel()
- session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: 10 * time.Second, HandshakeTimeout: 4 * time.Second})
+ ctx := newExpirableContext()
+ defer ctx.expire()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: testFallbackTimeout, HandshakeTimeout: testFallbackTimeout})
if err != nil {
t.Fatal(err)
}
@@ -63,10 +59,9 @@ func TestCodexInitializeParentDeadlineDoesNotPersistOpaqueEnv(t *testing.T) {
for range session.Messages {
}
}()
+ waitForTestFile(t, readyFile)
+ ctx.expire()
result := <-session.Result
- if _, err := os.Stat(readyFile); err != nil {
- t.Fatalf("fake app-server never wrote the secret to stderr, so the redaction check would pass vacuously: %v", err)
- }
persisted := fmt.Sprintf("%+v\n%s", result, logs.String())
if strings.Contains(persisted, secret) {
t.Fatalf("opaque env persisted after the parent deadline: %s", persisted)
@@ -85,7 +80,7 @@ func TestCodexInitializeParentCancellationDoesNotPersistOpaqueEnv(t *testing.T)
`read line`+"\n"+
`echo "$OPAQUE_AUTH_VALUE" >&2`+"\n"+
`touch "`+readyFile+`"`+"\n"+
- `sleep 5`+"\n")
+ `sleep 300`+"\n")
var logs strings.Builder
backend, err := New("codex", Config{
@@ -98,7 +93,7 @@ func TestCodexInitializeParentCancellationDoesNotPersistOpaqueEnv(t *testing.T)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: 10 * time.Second, HandshakeTimeout: 4 * time.Second})
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{Timeout: testFallbackTimeout, HandshakeTimeout: testFallbackTimeout})
if err != nil {
t.Fatal(err)
}
@@ -106,21 +101,9 @@ func TestCodexInitializeParentCancellationDoesNotPersistOpaqueEnv(t *testing.T)
for range session.Messages {
}
}()
- deadline := time.Now().Add(3 * time.Second)
- for {
- if _, err := os.Stat(readyFile); err == nil {
- break
- }
- if time.Now().After(deadline) {
- t.Fatal("fake app-server did not write stderr before cancellation")
- }
- time.Sleep(20 * time.Millisecond)
- }
+ waitForTestFile(t, readyFile)
cancel()
result := <-session.Result
- if _, err := os.Stat(readyFile); err != nil {
- t.Fatalf("fake app-server never wrote the secret to stderr, so the redaction check would pass vacuously: %v", err)
- }
persisted := fmt.Sprintf("%+v\n%s", result, logs.String())
if strings.Contains(persisted, secret) {
t.Fatalf("opaque env persisted after parent context ended: %s", persisted)
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 2b917a0fa9..76623aa192 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -2196,31 +2196,27 @@ func TestCodexRequestFailsImmediatelyAfterProcessExit(t *testing.T) {
func TestCodexRequestPrefersContextCancellationOverProcessExit(t *testing.T) {
t.Parallel()
- c, fs, _ := newTestCodexClient(t)
- processExitMarked := make(chan error, 1)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- go func() {
- deadline := time.Now().Add(2 * time.Second)
- for {
- if len(fs.Lines()) >= 1 {
- cancel()
- c.markProcessExited(errCodexProcessExited)
- processExitMarked <- nil
- return
- }
- if time.Now().After(deadline) {
- processExitMarked <- fmt.Errorf("timed out waiting for request write")
- return
- }
- time.Sleep(5 * time.Millisecond)
- }
- }()
+ // Both endings land after the write and before request waits, so it sees
+ // them together and has to choose.
+ var c *codexClient
+ fs := &fakeStdinWithHook{}
+ fs.afterWrite = func() {
+ cancel()
+ c.markProcessExited(errCodexProcessExited)
+ }
+ c = &codexClient{
+ cfg: Config{Logger: slog.Default()},
+ stdin: fs,
+ pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
+ }
_, err := c.request(ctx, "thread/start", map[string]any{})
- if markErr := <-processExitMarked; markErr != nil {
- t.Fatal(markErr)
+ if len(fs.Lines()) != 1 {
+ t.Fatalf("request wrote %d lines, want 1", len(fs.Lines()))
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("request error = %v, want context.Canceled", err)
@@ -3676,9 +3672,9 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
// Post-fix, drainAndWait does graceful-then-cancel in two bounded phases
// (see codex.go), and cmd.Cancel group-SIGKILLs the codex tree so the
// process exits even when stdin EOF isn't sufficient. We verify the
- // failed Result reaches the caller within a small bound and carries an
- // empty SessionID so the outer daemon's PriorSessionID-with-empty-
- // SessionID fallback can retry a fresh session.
+ // failed Result reaches the caller and carries an empty SessionID so the
+ // outer daemon's PriorSessionID-with-empty-SessionID fallback can retry a
+ // fresh session.
codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))
t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })
@@ -3698,20 +3694,38 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
// hangs cmd.Wait() because codex never sees stdin EOF (it isn't
// in a read syscall) and the stdout pipe stays full. Cleanup must
// fall back to the group-SIGKILL path to make progress.
- `sleep 30`+"\n")
+ `sleep 300`+"\n")
- start := time.Now()
- result := executeFakeCodex(t, fakePath, ExecOptions{
+ backend, err := New("codex", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Neither the caller nor the run timeout may end this run, so the Result
+ // can only come from the overflow cleanup itself. Pre-fix it never came.
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ session, err := backend.Execute(ctx, "prompt", ExecOptions{
Cwd: t.TempDir(),
ResumeSessionID: "thr_prior",
- Timeout: 30 * time.Second,
- SemanticInactivityTimeout: 5 * time.Second,
+ Timeout: 10 * testFallbackTimeout,
+ SemanticInactivityTimeout: 10 * testFallbackTimeout,
})
- elapsed := time.Since(start)
+ if err != nil {
+ t.Fatal(err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ var result Result
+ select {
+ case result = <-session.Result:
+ case <-time.After(testFallbackTimeout):
+ t.Fatal("cleanup never completed without the caller cancelling (bug regressed?)")
+ }
if result.Status != "failed" {
- t.Fatalf("expected status=failed, got %q (error=%q, elapsed=%s)",
- result.Status, result.Error, elapsed)
+ t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
}
if !strings.Contains(result.Error, "token too long") {
t.Fatalf("expected error to surface scanner overflow cause, got %q",
@@ -3742,15 +3756,6 @@ func TestCodexExecuteCleansUpWhenScannerOverflowsOnResume(t *testing.T) {
if !CodexResumeOverflowError(result.Error) {
t.Fatalf("predicate missed the error the backend actually produced: %q", result.Error)
}
- // With the shrunken 100 ms grace, pushing the oversized line plus two
- // bounded phases and the SIGKILL round-trip should complete in ~1 s.
- // Pre-fix this test would block until the executeFakeCodex 10 s outer
- // timeout and fail with "timeout waiting for result". We assert a much
- // tighter bound so a future regression cannot quietly slip back up to 10 s.
- if elapsed > 5*time.Second {
- t.Fatalf("cleanup took %s, expected < 5s with shrunken grace (bug regressed?)",
- elapsed)
- }
}
func TestCodexExecuteDoesNotClaimResumeRejectedWhenOverflowIsNotAResume(t *testing.T) {
@@ -3778,13 +3783,13 @@ func TestCodexExecuteDoesNotClaimResumeRejectedWhenOverflowIsNotAResume(t *testi
`printf '{"jsonrpc":"2.0","id":2,"result":{"big":"'`+"\n"+
fmt.Sprintf(`head -c %d /dev/zero | tr '\0' 'x'`, agentStreamMaxLineBytes+1024*1024)+"\n"+
`printf '"}}\n'`+"\n"+
- `sleep 30`+"\n")
+ `sleep 300`+"\n")
- result := executeFakeCodex(t, fakePath, ExecOptions{
+ result, _ := executeFakeCodexCollectingMessages(t, fakePath, ExecOptions{
Cwd: t.TempDir(),
- Timeout: 30 * time.Second,
- SemanticInactivityTimeout: 5 * time.Second,
- })
+ Timeout: testFallbackTimeout,
+ SemanticInactivityTimeout: testFallbackTimeout,
+ }, testFallbackTimeout)
if result.Status != "failed" {
t.Fatalf("expected status=failed, got %q (error=%q)", result.Status, result.Error)
diff --git a/server/pkg/agent/exec_fixture_unix_test.go b/server/pkg/agent/exec_fixture_unix_test.go
index f73bf3945a..dbc7591c87 100644
--- a/server/pkg/agent/exec_fixture_unix_test.go
+++ b/server/pkg/agent/exec_fixture_unix_test.go
@@ -3,7 +3,12 @@
package agent
import (
+ "bytes"
+ "errors"
+ "io/fs"
"os"
+ "os/exec"
+ "runtime"
"syscall"
"testing"
)
@@ -14,7 +19,26 @@ import (
// the sibling's fork child inherits our still-open write fd and the
// subsequent exec of the file sees "text file busy" (seen on CI as
// TestKimiBackendInvokesACPSubcommand: fork/exec ... text file busy).
+//
+// On macOS the first exec of every new file is held while XProtect scans it:
+// ~0.4s on an idle machine and several seconds once parallel tests and other
+// builds queue behind the same scanner. The scan is cached per inode and is
+// not repeated when the file is rewritten in place, so a new script is first
+// written as a no-op, executed once, then truncated to its real content. That
+// moves the scan out of the test's own timeouts. Only scripts take this path:
+// rewriting an executed Mach-O in place invalidates its code signature.
func writeTestExecutable(tb testing.TB, path string, content []byte) {
+ tb.Helper()
+ if runtime.GOOS == "darwin" && bytes.HasPrefix(content, []byte("#!")) {
+ if _, err := os.Lstat(path); errors.Is(err, fs.ErrNotExist) {
+ writeTestExecutableContent(tb, path, []byte("#!/bin/sh\nexit 0\n"))
+ _ = exec.Command(path).Run()
+ }
+ }
+ writeTestExecutableContent(tb, path, content)
+}
+
+func writeTestExecutableContent(tb testing.TB, path string, content []byte) {
tb.Helper()
syscall.ForkLock.RLock()
defer syscall.ForkLock.RUnlock()
diff --git a/server/pkg/agent/grok_test.go b/server/pkg/agent/grok_test.go
index 491202c89b..59b2b1df95 100644
--- a/server/pkg/agent/grok_test.go
+++ b/server/pkg/agent/grok_test.go
@@ -165,9 +165,9 @@ func TestGrokSupplementTargetsActivePrompt(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: 5 * time.Second, EnableTaskSupplement: true})
+ session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
if err != nil {
t.Fatal(err)
}
@@ -177,7 +177,7 @@ func TestGrokSupplementTargetsActivePrompt(t *testing.T) {
if session.SupplementReady() {
t.Fatal("supplement became ready before session/prompt started")
}
- deadline := time.Now().Add(3 * time.Second)
+ deadline := time.Now().Add(testFallbackTimeout)
for !session.SupplementReady() && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
@@ -246,11 +246,11 @@ func TestGrokSupplementTimesOutIndependentlyAndAllowsNextMessage(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: time.Minute, EnableTaskSupplement: true})
+ session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: 10 * testFallbackTimeout, EnableTaskSupplement: true})
if err != nil {
t.Fatal(err)
}
- deadline := time.Now().Add(3 * time.Second)
+ deadline := time.Now().Add(testFallbackTimeout)
for !session.SupplementReady() && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
@@ -259,18 +259,19 @@ func TestGrokSupplementTimesOutIndependentlyAndAllowsNextMessage(t *testing.T) {
t.Fatal("supplement never became ready during active prompt")
}
- started := time.Now()
+ // ctx has no deadline and the run timeout is far away, so a
+ // DeadlineExceeded here can only come from grokSupplementTimeout.
firstSupplement := make(chan error, 1)
go func() {
firstSupplement <- session.Supplement(ctx, "The first interjection will not be acknowledged.")
}()
select {
case err = <-firstSupplement:
- case <-time.After(time.Second):
+ case <-time.After(testFallbackTimeout):
cancel()
select {
case <-session.Result:
- case <-time.After(3 * time.Second):
+ case <-time.After(testFallbackTimeout):
t.Fatal("Grok run did not stop after its parent context was canceled")
}
t.Fatal("supplement did not return within its independent timeout")
@@ -279,10 +280,6 @@ func TestGrokSupplementTimesOutIndependentlyAndAllowsNextMessage(t *testing.T) {
cancel()
t.Fatalf("first supplement error=%v, want context deadline exceeded", err)
}
- if elapsed := time.Since(started); elapsed > time.Second {
- cancel()
- t.Fatalf("first supplement took %s to time out, want under 1s", elapsed)
- }
if !session.SupplementReady() {
cancel()
t.Fatal("an interject timeout ended the active Grok prompt")
@@ -297,7 +294,7 @@ func TestGrokSupplementTimesOutIndependentlyAndAllowsNextMessage(t *testing.T) {
if result.Status != "completed" {
t.Fatalf("turn status=%q error=%q", result.Status, result.Error)
}
- case <-time.After(3 * time.Second):
+ case <-time.After(testFallbackTimeout):
cancel()
t.Fatal("Grok prompt did not complete after the second interjection")
}
@@ -317,9 +314,9 @@ func TestGrokSupplementReportsACPRejection(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: 5 * time.Second, EnableTaskSupplement: true})
+ session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
if err != nil {
t.Fatal(err)
}
@@ -329,7 +326,7 @@ func TestGrokSupplementReportsACPRejection(t *testing.T) {
for range session.Messages {
}
}()
- deadline := time.Now().Add(3 * time.Second)
+ deadline := time.Now().Add(testFallbackTimeout)
for !session.SupplementReady() && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
@@ -372,9 +369,9 @@ func TestGrokSupplementHandlesObservedNestedResultStatus(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: 5 * time.Second, EnableTaskSupplement: true})
+ session, err := backend.Execute(ctx, "continue working", ExecOptions{Timeout: testFallbackTimeout, EnableTaskSupplement: true})
if err != nil {
t.Fatal(err)
}
@@ -382,7 +379,7 @@ func TestGrokSupplementHandlesObservedNestedResultStatus(t *testing.T) {
for range session.Messages {
}
}()
- deadline := time.Now().Add(3 * time.Second)
+ deadline := time.Now().Add(testFallbackTimeout)
for !session.SupplementReady() && time.Now().Before(deadline) {
time.Sleep(5 * time.Millisecond)
}
@@ -413,10 +410,10 @@ func TestGrokBackendStreamsAndCompletes(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -483,9 +480,9 @@ func TestGrokPromptStopReasons(t *testing.T) {
if err != nil {
t.Fatal(err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "say pong", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatal(err)
}
@@ -535,11 +532,11 @@ func TestGrokBlockedArgsFiltering(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := backend.Execute(ctx, "task", ExecOptions{
- Timeout: 5 * time.Second,
+ Timeout: testFallbackTimeout,
ThinkingLevel: "high",
// Users must not strip ACP mode, disable auto-approve, or switch
// into print/headless transports.
@@ -606,10 +603,10 @@ func TestGrokSetModelFailureFailsTask(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "task", ExecOptions{Model: "bogus-model", Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "task", ExecOptions{Model: "bogus-model", Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -644,12 +641,12 @@ func TestGrokUsesSessionLoadForResume(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := backend.Execute(ctx, "continue", ExecOptions{
ResumeSessionID: "ses_existing",
- Timeout: 5 * time.Second,
+ Timeout: testFallbackTimeout,
})
if err != nil {
t.Fatalf("execute: %v", err)
@@ -709,12 +706,12 @@ func TestGrokAuthenticatesBeforeSession(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := backend.Execute(ctx, "task", ExecOptions{
ResumeSessionID: tc.resume,
- Timeout: 5 * time.Second,
+ Timeout: testFallbackTimeout,
})
if err != nil {
t.Fatalf("execute: %v", err)
@@ -780,10 +777,10 @@ func TestGrokAuthFailureFailsTask(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
- session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -820,7 +817,7 @@ func TestGrokNoUsableAuthMethodFailsBeforeSession(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -861,7 +858,7 @@ func TestGrokUsesAdvertisedAPIKeyMethod(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -893,7 +890,7 @@ func TestGrokDrainsNotificationsAfterPromptResponse(t *testing.T) {
if err != nil {
t.Fatalf("new grok backend: %v", err)
}
- session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -927,7 +924,7 @@ func TestGrokPropagatesMCPAndUsage(t *testing.T) {
t.Fatalf("new grok backend: %v", err)
}
session, err := backend.Execute(context.Background(), "task", ExecOptions{
- Timeout: 5 * time.Second,
+ Timeout: testFallbackTimeout,
McpConfig: json.RawMessage(`{"mcpServers":{"fetch":{"command":"uvx","args":["mcp-server-fetch"]}}}`),
})
if err != nil {
@@ -990,7 +987,7 @@ func TestGrokAttributesUsageOnResumeWithoutConfiguredModel(t *testing.T) {
// MULTICA_GROK_MODEL pins one (see daemon.go resolveModel).
session, err := backend.Execute(context.Background(), "continue", ExecOptions{
ResumeSessionID: "ses_existing",
- Timeout: 5 * time.Second,
+ Timeout: testFallbackTimeout,
})
if err != nil {
t.Fatalf("execute: %v", err)
@@ -1036,7 +1033,7 @@ func TestGrokCancellation(t *testing.T) {
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: 5 * time.Second})
+ session, err := backend.Execute(ctx, "task", ExecOptions{Timeout: testFallbackTimeout})
if err != nil {
t.Fatalf("execute: %v", err)
}
@@ -1044,7 +1041,7 @@ func TestGrokCancellation(t *testing.T) {
for range session.Messages {
}
}()
- deadline := time.Now().Add(3 * time.Second)
+ deadline := time.Now().Add(testFallbackTimeout)
for {
raw, _ := os.ReadFile(requestsFile)
if strings.Contains(string(raw), `"method":"session/prompt"`) {
@@ -1061,7 +1058,7 @@ func TestGrokCancellation(t *testing.T) {
if result.Status != "aborted" {
t.Fatalf("status=%q error=%q, want aborted", result.Status, result.Error)
}
- case <-time.After(4 * time.Second):
+ case <-time.After(testFallbackTimeout):
t.Fatal("grok child was not terminated and reaped")
}
}
diff --git a/server/pkg/agent/muse_lifecycle_test.go b/server/pkg/agent/muse_lifecycle_test.go
index e0cbafbb60..2a748e843a 100644
--- a/server/pkg/agent/muse_lifecycle_test.go
+++ b/server/pkg/agent/muse_lifecycle_test.go
@@ -5,7 +5,6 @@ import (
"os"
"strings"
"testing"
- "time"
)
func rewriteFakeMuseServe(t *testing.T, path, old, replacement string) {
@@ -26,7 +25,7 @@ func TestMuseHostExitAfterTurnStart(t *testing.T) {
t.Parallel()
bin, _, _ := writeFakeMuseServe(t, false)
rewriteFakeMuseServe(t, bin, " sleep 0.02", " exit 17")
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := newFakeMuseBackend(t, bin).Execute(ctx, "work", ExecOptions{Cwd: t.TempDir()})
if err != nil {
@@ -45,7 +44,7 @@ func TestMuseTerminalSurvivesSessionCloseAndEOF(t *testing.T) {
printf '{"jsonrpc":"2.0","method":"session/closed","params":{}}\n'
exit 0
#`)
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := newFakeMuseBackend(t, bin).Execute(ctx, "work", ExecOptions{Cwd: t.TempDir()})
if err != nil {
@@ -69,7 +68,7 @@ func TestMuseResumeAppliesSelectedModel(t *testing.T) {
if reject {
rewriteFakeMuseServe(t, bin, `"result":{"sessionId":"`+fakeMuseSessionID+`","modelId":"new-model"}`, `"error":{"code":-32602,"message":"model unavailable"}`)
}
- ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), testFallbackTimeout)
defer cancel()
session, err := newFakeMuseBackend(t, bin).Execute(ctx, "continue", ExecOptions{
Cwd: t.TempDir(), ResumeSessionID: fakeMuseSessionID, Model: "new-model",
diff --git a/server/pkg/agent/qwen_test.go b/server/pkg/agent/qwen_test.go
index 3a9e8419d0..a2d46242ba 100644
--- a/server/pkg/agent/qwen_test.go
+++ b/server/pkg/agent/qwen_test.go
@@ -263,15 +263,14 @@ func TestQwenBackendFailureTimeoutAndCancellation(t *testing.T) {
} {
t.Run(tc.name, func(t *testing.T) {
ctx, cancel := tc.ctx()
- if tc.name == "cancel" {
- go func() { time.Sleep(20 * time.Millisecond); cancel() }()
- } else {
- defer cancel()
- }
+ defer cancel()
session, err := newFakeQwenBackend(t, tc.env).Execute(ctx, "task", tc.opts)
if err != nil {
t.Fatalf("Execute: %v", err)
}
+ if tc.name == "cancel" {
+ cancel()
+ }
_, result := awaitQwenResult(t, session)
if result.Status != tc.status || !strings.Contains(result.Error, tc.needle) || result.SessionID != tc.wantSession {
t.Fatalf("result = %+v, want status=%q error containing %q session=%q", result, tc.status, tc.needle, tc.wantSession)