Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Bound Assistant stream chunk stalls

rcourtmana7854bf34179
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 5cf170adc6..1a013c4c48 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -275,12 +275,18 @@ runtime cost control, and shared AI transport surfaces.
marker arrives; it must not flash as run-on prose such as
`I'llcheckthedevicenodes...` while the actual governed tool row is still
being assembled.
- Streamed provider startup must be bounded by the configured Assistant request
- timeout, the OpenAI-compatible SSE response-header guard, and the first SSE
- body-read guard adapted from OpenCode's provider `wrapSSE` source; transient
- startup failures may retry once before surfacing failed-turn recovery, but a
- stalled route must not leave the user in an opaque first-token wait for the
- full provider timeout.
+ Streamed provider startup and mid-stream progress must be bounded by the
+ configured Assistant request timeout, the OpenAI-compatible SSE
+ response-header guard, and the per-chunk SSE body-read guard adapted from
+ OpenCode's provider `wrapSSE` source. The referenced OpenCode source at
+ fetched `origin/dev` commit `ba57718b0516c7a8670d1e820b1a24146a8b8262`
+ wraps `text/event-stream` responses in
+ `packages/opencode/src/provider/provider.ts` so each stream read either
+ yields a chunk or aborts within the configured `chunkTimeout`, distinct from
+ the response-header timeout. Pulse's OpenAI-compatible Assistant transport
+ follows that split: transient startup failures may retry once before
+ surfacing failed-turn recovery, but a stalled route must not leave the user
+ in an opaque first-token or mid-answer wait for the full provider timeout.
Assistant turn tool exposure is backend-owned runtime behavior, not a
provider whim or frontend polish concern. Normal diagnostic, log, command,
repair, and governed-action prompts keep the full governed tool manifest so
diff --git a/internal/ai/providers/openai.go b/internal/ai/providers/openai.go
index 318c5494cd..23069138d2 100644
--- a/internal/ai/providers/openai.go
+++ b/internal/ai/providers/openai.go
@@ -22,7 +22,7 @@ const (
openaiStreamMaxRetries = 1
openaiStreamInitialBackoff = 1 * time.Second
openaiStreamResponseHeaderTimeout = 12 * time.Second
- openaiStreamFirstEventTimeout = 12 * time.Second
+ openaiStreamChunkTimeout = 12 * time.Second
openrouterRefererURL = "https://pulse.app"
openrouterAppTitle = "Pulse"
// OpenRouter preflights affordability against the requested maximum
@@ -42,10 +42,10 @@ type OpenAIClient struct {
requestTimeout time.Duration
client *http.Client
streamClient *http.Client
- // OpenAI-compatible gateways can accept SSE headers and then stall before
- // the first body chunk. Bound that gap separately from the full turn timeout
- // so chat fallback can move before the drawer looks dead.
- streamFirstEventTimeout time.Duration
+ // OpenAI-compatible gateways can accept SSE headers and then stall between
+ // body chunks. Bound that gap separately from the full turn timeout so chat
+ // fallback can move before the drawer looks dead.
+ streamChunkTimeout time.Duration
}
// NewOpenAIClient creates a new OpenAI API client
@@ -83,13 +83,13 @@ func NewOpenAIClient(apiKey, model, baseURL string, timeout time.Duration) *Open
timeout = 300 * time.Second // Default 5 minutes
}
return &OpenAIClient{
- apiKey: apiKey,
- model: model,
- baseURL: baseURL,
- requestTimeout: timeout,
- client: &http.Client{Timeout: timeout},
- streamClient: newOpenAIStreamHTTPClient(timeout),
- streamFirstEventTimeout: boundedOpenAIStreamFirstEventTimeout(timeout),
+ apiKey: apiKey,
+ model: model,
+ baseURL: baseURL,
+ requestTimeout: timeout,
+ client: &http.Client{Timeout: timeout},
+ streamClient: newOpenAIStreamHTTPClient(timeout),
+ streamChunkTimeout: boundedOpenAIStreamChunkTimeout(timeout),
}
}
@@ -110,11 +110,11 @@ func boundedOpenAIStreamResponseHeaderTimeout(timeout time.Duration) time.Durati
return openaiStreamResponseHeaderTimeout
}
-func boundedOpenAIStreamFirstEventTimeout(timeout time.Duration) time.Duration {
- if timeout > 0 && timeout < openaiStreamFirstEventTimeout {
+func boundedOpenAIStreamChunkTimeout(timeout time.Duration) time.Duration {
+ if timeout > 0 && timeout < openaiStreamChunkTimeout {
return timeout
}
- return openaiStreamFirstEventTimeout
+ return openaiStreamChunkTimeout
}
type openAIStreamReadResult struct {
@@ -122,8 +122,8 @@ type openAIStreamReadResult struct {
err error
}
-func readOpenAIStreamChunk(ctx context.Context, body io.ReadCloser, buf []byte, timeout time.Duration, enforceTimeout bool) (int, error) {
- if !enforceTimeout || timeout <= 0 {
+func readOpenAIStreamChunk(ctx context.Context, body io.ReadCloser, buf []byte, timeout time.Duration) (int, error) {
+ if timeout <= 0 {
return body.Read(buf)
}
@@ -144,7 +144,7 @@ func readOpenAIStreamChunk(ctx context.Context, body io.ReadCloser, buf []byte,
return 0, ctx.Err()
case <-timer.C:
_ = body.Close()
- return 0, fmt.Errorf("stream first event timed out after %s", timeout)
+ return 0, fmt.Errorf("stream chunk timed out after %s", timeout)
}
}
@@ -986,7 +986,6 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
reader := resp.Body
buf := make([]byte, 4096)
var pendingData string
- firstStreamBytesSeen := false
toolCallBuilders := make(map[int]*openaiStreamToolCallBuilder)
var inputTokens, outputTokens int
var finishReason string
@@ -1094,9 +1093,8 @@ func (c *OpenAIClient) ChatStream(ctx context.Context, req ChatRequest, callback
}
for {
- n, err := readOpenAIStreamChunk(streamCtx, reader, buf, c.streamFirstEventTimeout, !firstStreamBytesSeen)
+ n, err := readOpenAIStreamChunk(streamCtx, reader, buf, c.streamChunkTimeout)
if n > 0 {
- firstStreamBytesSeen = true
pendingData += string(buf[:n])
lines := strings.Split(pendingData, "\n")
diff --git a/internal/ai/providers/openai_test.go b/internal/ai/providers/openai_test.go
index addc134339..006228db53 100644
--- a/internal/ai/providers/openai_test.go
+++ b/internal/ai/providers/openai_test.go
@@ -61,6 +61,36 @@ func (b *blockingReadCloser) Close() error {
return nil
}
+type readOnceThenBlockBody struct {
+ payload []byte
+ read bool
+ closed chan struct{}
+ once sync.Once
+}
+
+func newReadOnceThenBlockBody(payload string) *readOnceThenBlockBody {
+ return &readOnceThenBlockBody{
+ payload: []byte(payload),
+ closed: make(chan struct{}),
+ }
+}
+
+func (b *readOnceThenBlockBody) Read(p []byte) (int, error) {
+ if !b.read {
+ b.read = true
+ return copy(p, b.payload), nil
+ }
+ <-b.closed
+ return 0, io.ErrClosedPipe
+}
+
+func (b *readOnceThenBlockBody) Close() error {
+ b.once.Do(func() {
+ close(b.closed)
+ })
+ return nil
+}
+
func TestOpenAIClient_ChatStream_Success(t *testing.T) {
// Mock OpenAI SSE stream
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -156,19 +186,19 @@ func TestNewOpenAIClient_BoundsStreamResponseHeaderTimeout(t *testing.T) {
transport, ok := client.streamClient.Transport.(*http.Transport)
require.True(t, ok)
assert.Equal(t, openaiStreamResponseHeaderTimeout, transport.ResponseHeaderTimeout)
- assert.Equal(t, openaiStreamFirstEventTimeout, client.streamFirstEventTimeout)
+ assert.Equal(t, openaiStreamChunkTimeout, client.streamChunkTimeout)
shortTimeoutClient := NewOpenAIClient("sk-test", "gpt-4", "https://api.openai.com/v1", 2*time.Second)
shortTransport, ok := shortTimeoutClient.streamClient.Transport.(*http.Transport)
require.True(t, ok)
assert.Equal(t, 2*time.Second, shortTransport.ResponseHeaderTimeout)
- assert.Equal(t, 2*time.Second, shortTimeoutClient.streamFirstEventTimeout)
+ assert.Equal(t, 2*time.Second, shortTimeoutClient.streamChunkTimeout)
}
-func TestOpenAIClient_ChatStream_TimesOutWaitingForFirstStreamEvent(t *testing.T) {
+func TestOpenAIClient_ChatStream_TimesOutWaitingForFirstStreamChunk(t *testing.T) {
body := newBlockingReadCloser()
client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", time.Second)
- client.streamFirstEventTimeout = 10 * time.Millisecond
+ client.streamChunkTimeout = 10 * time.Millisecond
client.streamClient = &http.Client{
Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
return &http.Response{
@@ -188,11 +218,46 @@ func TestOpenAIClient_ChatStream_TimesOutWaitingForFirstStreamEvent(t *testing.T
})
require.Error(t, err)
- assert.Contains(t, err.Error(), "stream first event timed out")
+ assert.Contains(t, err.Error(), "stream chunk timed out")
assert.Less(t, time.Since(started), 200*time.Millisecond)
assert.Equal(t, 0, eventCount)
}
+func TestOpenAIClient_ChatStream_TimesOutWaitingForLaterStreamChunk(t *testing.T) {
+ body := newReadOnceThenBlockBody(`data: {"choices":[{"delta":{"content":"first"}}]}` + "\n\n")
+ client := NewOpenAIClient("sk-test", "gpt-4", "https://example.invalid/v1", time.Second)
+ client.streamChunkTimeout = 10 * time.Millisecond
+ client.streamClient = &http.Client{
+ Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) {
+ return &http.Response{
+ StatusCode: http.StatusOK,
+ Header: http.Header{"Content-Type": []string{"text/event-stream"}},
+ Body: body,
+ }, nil
+ }),
+ }
+
+ started := time.Now()
+ var content string
+ var doneCalled bool
+ err := client.ChatStream(context.Background(), ChatRequest{
+ Messages: []Message{{Role: "user", Content: "Hi"}},
+ }, func(event StreamEvent) {
+ switch event.Type {
+ case "content":
+ content += event.Data.(ContentEvent).Text
+ case "done":
+ doneCalled = true
+ }
+ })
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "stream chunk timed out")
+ assert.Less(t, time.Since(started), 200*time.Millisecond)
+ assert.Equal(t, "first", content)
+ assert.False(t, doneCalled)
+}
+
// TestOpenAIClient_ChatStream_OpenRouterReasoning guards the OpenRouter reasoning
// path. OpenRouter (and other OpenAI-compatible gateways) stream chain-of-thought
// in the "reasoning" delta field rather than DeepSeek's "reasoning_content". A