返回 DeepSeek-Reasonix
stall_test.go
根目录 / internal / provider / anthropic / stall_test.go
1 package anthropic
2
3 import (
4 "context"
5 "io"
6 "net/http"
7 "net/http/httptest"
8 "strings"
9 "testing"
10 "time"
11
12 "reasonix/internal/provider"
13 )
14
15 func TestDefaultStreamIdleTimeoutIsFiveMinutes(t *testing.T) {
16 if defaultStreamIdleTimeout != 300*time.Second {
17 t.Fatalf("default stream idle timeout = %s, want 5m", defaultStreamIdleTimeout)
18 }
19 }
20
21 // TestStreamStallTimesOut covers issue #3374 for the Anthropic provider: a
22 // half-open connection sends the SSE head then goes silent without an RST, which
23 // would hang scanner.Scan() forever. The idle watchdog must surface a stall error.
24 func TestStreamStallTimesOut(t *testing.T) {
25 release := make(chan struct{})
26 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
27 w.Header().Set("Content-Type", "text/event-stream")
28 w.WriteHeader(http.StatusOK)
29 if f, ok := w.(http.Flusher); ok {
30 f.Flush()
31 }
32 _, _ = io.WriteString(w, ": ping\n\n")
33 if f, ok := w.(http.Flusher); ok {
34 f.Flush()
35 }
36 <-release // stall: never send data, never close
37 }))
38 defer srv.Close()
39 defer close(release)
40
41 p, err := New(provider.Config{Name: "claude", BaseURL: srv.URL, Model: "claude-opus-4-8", APIKey: "k"})
42 if err != nil {
43 t.Fatalf("New: %v", err)
44 }
45 p.(*client).idleTimeout = 150 * time.Millisecond
46 ch, err := p.Stream(context.Background(), provider.Request{
47 Messages: []provider.Message{{Role: provider.RoleUser, Content: "hi"}},
48 MaxTokens: 16,
49 })
50 if err != nil {
51 t.Fatalf("Stream: %v", err)
52 }
53
54 deadline := time.After(5 * time.Second)
55 for {
56 select {
57 case chunk, ok := <-ch:
58 if !ok {
59 t.Fatal("stream closed without surfacing a stall error")
60 }
61 if chunk.Type == provider.ChunkError {
62 if !strings.Contains(chunk.Err.Error(), "stalled") {
63 t.Fatalf("error = %v, want a 'stalled' error", chunk.Err)
64 }
65 return
66 }
67 case <-deadline:
68 t.Fatal("stream did not time out on a stalled connection — it hung")
69 }
70 }
71 }
72
73 func TestReadStreamSendUnblocksOnContextCancel(t *testing.T) {
74 ctx, cancel := context.WithCancel(context.Background())
75 resp := &http.Response{Body: io.NopCloser(strings.NewReader("data: {\"type\":\"content_block_delta\",\"delta\":{\"type\":\"text_delta\",\"text\":\"hi\"}}\n\n"))}
76 out := make(chan provider.Chunk)
77 done := make(chan struct{})
78
79 go func() {
80 (&client{name: "anthropic"}).readStream(ctx, resp, out)
81 close(done)
82 }()
83
84 time.Sleep(50 * time.Millisecond)
85 cancel()
86
87 select {
88 case <-done:
89 case <-time.After(500 * time.Millisecond):
90 t.Fatal("readStream remained blocked sending to an abandoned reader after context cancellation")
91 }
92 }
93
93 lines GO