diff --git a/internal/agent/compaction/compactor.go b/internal/agent/compaction/compactor.go index 8c7b9c93..2cc85a35 100644 --- a/internal/agent/compaction/compactor.go +++ b/internal/agent/compaction/compactor.go @@ -269,6 +269,14 @@ func (c *Compactor) streamSummary( if streamErr != "" { return "", finishReason, fmt.Errorf("summarization stream error: %s", streamErr) } + // A stream that closes because the call was cancelled is a + // cancelled call, not an empty successful summary. Checking the + // context here, and not only in the ctx.Done() arm above, also + // settles the race where a cancellation closes the stream while + // both arms are ready and select picks between them at random. + if err := ctx.Err(); err != nil { + return "", finishReason, err + } return sb.String(), finishReason, nil } stall.Reset(timeout) diff --git a/internal/agent/compaction/stream_test.go b/internal/agent/compaction/stream_test.go index c7be0240..5230cedd 100644 --- a/internal/agent/compaction/stream_test.go +++ b/internal/agent/compaction/stream_test.go @@ -50,6 +50,22 @@ func (p *pacedChat) ChatStream( return ch, nil } +// closedStreamChat hands back a stream that is already closed: a provider that +// gives up the instant the call is cancelled. Closing before ChatStream returns +// makes the closed-stream arm and the ctx.Done() arm of the select ready at the +// same moment, so the outcome cannot depend on which one select happens to pick. +type closedStreamChat struct { + stubChat +} + +func (c *closedStreamChat) ChatStream( + context.Context, []chat.Message, *chat.ChatOptions, +) (<-chan types.StreamResponse, error) { + ch := make(chan types.StreamResponse) + close(ch) + return ch, nil +} + func pacedSettings() Settings { s := testSettings() s.StallTimeout = 80 * time.Millisecond @@ -97,6 +113,19 @@ func TestSummarizationIsCancelledWhenItStalls(t *testing.T) { "a single live turn has only its prefix to summarize, attempted twice") } +// A stream that closes because the call was cancelled is a cancelled call, not +// an empty successful summary. Both the ctx.Done() arm and the closed-stream arm +// are ready at once here, so this pins down the answer instead of letting select +// choose it at random. +func TestSummarizationIsCancelledWhenTheStreamCloses(t *testing.T) { + c := New(&closedStreamChat{}, newEstimator(t), pacedSettings()) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + _, _, err := c.streamSummary(ctx, nil, &chat.ChatOptions{}) + require.True(t, errors.Is(err, context.Canceled), "got %v", err) +} + // An error reported inside the stream is a failed attempt, not a summary. func TestSummarizationStreamErrorIsAFailure(t *testing.T) { chatModel := &pacedChat{chunks: []types.StreamResponse{