refactor(coderd/x/chatd/chatdebug): share one finalize-once lifecycle between the stream wrappers (#30981)

`wrapStreamSeq` and `wrapObjectStreamSeq` each carried a copy of the
same finalize-once lifecycle. This PR moves it into a private
`streamStep` (the once-only gate and the context safety net) and a
`streamOutcome` (finish and error bookkeeping, and the early-stop and
missing-finish status rules), and rewrites both wrappers on them. Each
wrapper keeps its own part switch and payload type. It also deletes a
`stop != nil` check that is never false and a `seq != nil` check that
`Stream` and `StreamObject` make before they wrap a sequence.

**Why it is safe:** the PR changes no test. #30980 pins both wrappers'
status rules, and the chatdebug package and the chatd debug-run tests
pass before and after. All 39 mutants of the new lifecycle and of each
wrapper's wiring fail the package's tests, and a copy of `model.go` with
garbage in it fails to build. One more mutant drops the `finalized`
check from the safety net, so a step can be written twice; #30980's race
case kills it in 50 of 50 runs without `-race` and in 45 to 49 of 50
with `-race`. Two details keep their values: the response usage
normalizes a zero `fantasy.Usage` when no finish part arrived, which
gives the same zero value as before, and the summary's error count and
last error are copied from `streamOutcome` when the step finalizes
instead of being counted inline.

**Review focus:** the once-only gate stays per iterator (`streamStep`),
not on `stepHandle`, because `stepHandle.finish` lets a retry overwrite
an earlier result. `finish` builds the payload only when its call
finalizes the step, under the same lock as before.

**Moved onto the deletion stack:** #30988 deletes the stream heartbeats,
so the merge commit that moved this layer (no force push) also drops
them from the new lifecycle: `heartbeatDone`, `startHeartbeat`, the
channel close in `finalizeLocked`, both `step.startHeartbeat()` calls
and `launchHeartbeat`, and with them the heartbeat blocks in
`debugModel.Generate` and `GenerateObject`. The rest of the diff is
unchanged.

Validation:
- `go test -race -count=1 -p 4 -parallel 4
./coderd/x/chatd/chatdebug/...` passes before and after.
- `go test -race -count=1 -p 4 -parallel 4 ./coderd/x/chatd/ -run
'^(TestActiveServer_ChatTurnDebugRun.*|TestRunnerDebugTurn.*|TestProposeChatTitle_DebugRun|TestArchiveChatDeletesDebugRuns|TestEditMessageDebugCleanup.*|TestQuickgen.*|TestMaybeGenerateChatTitle.*|TestPrepareManualTitleDebugRunCreateFailure)$'`:
the same 25 tests pass before and after.
- `golangci-lint run --fix=false ./coderd/x/chatd/chatdebug/...` reports
0 issues, and the pre-commit hook passed.

## Stack

This stack deletes the stale debug-run sweep, then simplifies the
chatdebug debug-run, stream wrapper and step numbering code, drops the
indexes the sweep used, and last deletes a runner debug field that lost
its only reader with the heartbeats. The debug-run and stream wrapper
refactors each sit on a test-only layer that pins the behavior they
keep.

1. #30988 Delete the chat debug run and step heartbeats
2. #30989 Delete `FinalizeStale` and the stale threshold
3. #30995 Delete the `FinalizeStaleChatDebugRows` query
4. #30933 Pin the debug runs that turns, titles and status labels record
5. #30934 Create and finalize debug runs through one helper
6. #30980 Table the stream wrapper tests and cover their status rules
7. This PR: Share one finalize-once lifecycle between the stream
wrappers
8. #31007 Number chat debug steps in the database
9. #31008 Delete the process-global step counters
10. #31009 Drop the chat debug stale-sweep indexes
11. #31010 Drop the unused `runnerCtx` from the runner debug turn

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
This commit is contained in:
Michael Suchacz authored and GitHub committed 2026-10-21 07:45:19 +00:00
1 parent d14631df1a
commit 95e6a73f5c
1 file changed
+183 -248
+183 -248
View File
@@ -337,167 +337,174 @@ func (d *debugModel) Model() string {
return d.inner.Model()
}
type streamStep struct {
ctx context.Context
handle *stepHandle
// A mutex rather than sync.Once lets cancellation defer to the iterator
// when complete is set, preserving the response and usage payloads.
mu sync.Mutex
finalized bool
complete atomic.Bool
stop func() bool
}
func newStreamStep(ctx context.Context, handle *stepHandle) *streamStep {
s := &streamStep{ctx: ctx, handle: handle}
// Finalize a dropped or abandoned stream when ctx ends so the step
// does not stay in progress.
s.stop = context.AfterFunc(ctx, func() {
s.mu.Lock()
defer s.mu.Unlock()
if s.finalized || s.complete.Load() {
return
}
s.finalizeLocked(StatusInterrupted, nil, nil, nil, nil)
})
return s
}
func (s *streamStep) finish(status Status, out *streamOutcome, payload func() (resp, metadata any)) {
s.stop()
s.mu.Lock()
defer s.mu.Unlock()
if s.finalized {
return
}
resp, metadata := payload()
var usage any
if out.finished {
usage = &out.usage
}
s.finalizeLocked(status, resp, usage, out.err, metadata)
}
func (s *streamStep) finalizeLocked(status Status, resp, usage, errPayload, metadata any) {
s.finalized = true
s.handle.finish(s.ctx, status, resp, usage, errPayload, metadata)
}
type streamOutcome struct {
status Status
finished bool
finishReason fantasy.FinishReason
usage fantasy.Usage
err any
errorCount int
lastError string
}
// Mark completion before yielding so cancellation while the consumer holds
// the finish part leaves finalization to the iterator.
func (o *streamOutcome) observeFinish(step *streamStep, reason fantasy.FinishReason, usage fantasy.Usage) {
o.finished = true
o.finishReason = reason
o.usage = usage
step.complete.Store(true)
}
func (o *streamOutcome) observeError(ctx context.Context, err error) {
o.errorCount++
if err != nil {
o.lastError = err.Error()
o.err = normalizeError(ctx, err)
} else {
o.lastError = "stream error part with nil error"
o.err = map[string]string{"error": "stream error part with nil error"}
}
o.status = streamErrorStatus(o.status, err)
}
// Stopping at the finish part is not an interruption.
func (o *streamOutcome) stoppedStatus() Status {
switch {
case o.status == StatusError:
return StatusError
case o.finished:
return StatusCompleted
default:
return StatusInterrupted
}
}
// A clean iterator exit without a finish part can still mean truncated output.
func (o *streamOutcome) endedStatus() Status {
if o.status == StatusCompleted && !o.finished {
return StatusInterrupted
}
return o.status
}
func wrapStreamSeq(
ctx context.Context,
handle *stepHandle,
seq iter.Seq[fantasy.StreamPart],
) fantasy.StreamResponse {
// mu and finalized guard both the normal finalization path
// inside the iterator and the safety-net AfterFunc below.
// This ensures handle.finish is called exactly once regardless
// of whether the caller iterates, drops the stream, or the
// context is canceled mid-flight. We use a mutex rather than
// sync.Once so the AfterFunc can yield to the normal path
// when the stream already received its terminal chunk
// (streamComplete), preventing the AfterFunc from clobbering
// completed stream data with nil.
var (
mu sync.Mutex
finalized bool
streamComplete atomic.Bool
)
// Safety net: if the caller drops the returned iterator without
// consuming it (or abandons mid-stream and the context is
// canceled), finalize the step so it does not remain permanently
// in_progress once persistence lands in later branches.
stop := context.AfterFunc(ctx, func() {
mu.Lock()
defer mu.Unlock()
// If the stream already received a finish chunk, let
// finalize handle it; it has the real response payload
// and usage data that we would otherwise clobber.
if finalized || streamComplete.Load() {
return
}
finalized = true
handle.finish(ctx, StatusInterrupted, nil, nil, nil, nil)
})
step := newStreamStep(ctx, handle)
return func(yield func(fantasy.StreamPart) bool) {
var (
summary streamSummary
latestUsage fantasy.Usage
usageSeen bool
finishSeen bool
finishReason fantasy.FinishReason
out = streamOutcome{status: StatusCompleted}
content []normalizedContentPart
currentText *strings.Builder
currentTextIdx int
argBuilders = make(map[string]*strings.Builder)
warnings []normalizedWarning
streamDebugBytes int
streamError any
streamStatus = StatusCompleted
)
finalize := func(status Status) {
// Cancel the safety net since we're finalizing.
if stop != nil {
stop()
}
mu.Lock()
defer mu.Unlock()
if finalized {
return
}
finalized = true
summary.FinishReason = string(finishReason)
materializeStreamContent(content, currentText, currentTextIdx, argBuilders)
resp := normalizedResponsePayload{
Content: content,
FinishReason: string(finishReason),
Warnings: warnings,
}
if usageSeen {
resp.Usage = normalizeUsage(latestUsage)
}
var usage any
if usageSeen {
usage = &latestUsage
}
handle.finish(ctx, status, resp, usage, streamError, map[string]any{
"stream_summary": summary,
step.finish(status, &out, func() (any, any) {
summary.FinishReason = string(out.finishReason)
summary.ErrorCount = out.errorCount
summary.LastError = out.lastError
materializeStreamContent(content, currentText, currentTextIdx, argBuilders)
resp := normalizedResponsePayload{
Content: content,
FinishReason: string(out.finishReason),
Usage: normalizeUsage(out.usage),
Warnings: warnings,
}
return resp, map[string]any{"stream_summary": summary}
})
}
if seq != nil {
seq(func(part fantasy.StreamPart) bool {
summary.PartCount++
summary.WarningCount += len(part.Warnings)
if len(part.Warnings) > 0 {
warnings = append(warnings, normalizeWarnings(part.Warnings)...)
}
seq(func(part fantasy.StreamPart) bool {
summary.PartCount++
summary.WarningCount += len(part.Warnings)
if len(part.Warnings) > 0 {
warnings = append(warnings, normalizeWarnings(part.Warnings)...)
}
switch part.Type {
case fantasy.StreamPartTypeTextDelta:
summary.TextDeltaCount++
case fantasy.StreamPartTypeReasoningStart,
fantasy.StreamPartTypeReasoningDelta:
case fantasy.StreamPartTypeToolCall:
summary.ToolCallCount++
case fantasy.StreamPartTypeToolResult:
case fantasy.StreamPartTypeSource:
summary.SourceCount++
case fantasy.StreamPartTypeFinish:
finishReason = part.FinishReason
latestUsage = part.Usage
usageSeen = true
finishSeen = true
// Signal that the stream received its terminal
// chunk so the AfterFunc safety net yields to
// finalize, which has the real response payload.
streamComplete.Store(true)
}
switch part.Type {
case fantasy.StreamPartTypeTextDelta:
summary.TextDeltaCount++
case fantasy.StreamPartTypeReasoningStart,
fantasy.StreamPartTypeReasoningDelta:
case fantasy.StreamPartTypeToolCall:
summary.ToolCallCount++
case fantasy.StreamPartTypeToolResult:
case fantasy.StreamPartTypeSource:
summary.SourceCount++
case fantasy.StreamPartTypeFinish:
out.observeFinish(step, part.FinishReason, part.Usage)
}
content, currentText, currentTextIdx = appendNormalizedStreamContent(
content, currentText, currentTextIdx, argBuilders, part, &streamDebugBytes)
content, currentText, currentTextIdx = appendNormalizedStreamContent(
content, currentText, currentTextIdx, argBuilders, part, &streamDebugBytes)
if part.Type == fantasy.StreamPartTypeError || part.Error != nil {
summary.ErrorCount++
if part.Error != nil {
summary.LastError = part.Error.Error()
streamError = normalizeError(ctx, part.Error)
} else {
summary.LastError = "stream error part with nil error"
streamError = map[string]string{"error": "stream error part with nil error"}
}
streamStatus = streamErrorStatus(streamStatus, part.Error)
}
if part.Type == fantasy.StreamPartTypeError || part.Error != nil {
out.observeError(ctx, part.Error)
}
if !yield(part) {
// When the consumer stops iteration after
// receiving a finish part, the stream completed
// successfully; the consumer simply has nothing
// left to read. Only mark as interrupted when the
// consumer exits before the provider finished.
switch {
case streamStatus == StatusError:
finalize(StatusError)
case finishSeen:
finalize(StatusCompleted)
default:
finalize(StatusInterrupted)
}
return false
}
return true
})
}
// If the stream ended without a finish part and
// without an explicit error, the provider closed
// the connection prematurely. Record this as
// interrupted so debug runs surface incomplete
// output instead of falsely reporting success.
if streamStatus == StatusCompleted && !finishSeen {
streamStatus = StatusInterrupted
}
finalize(streamStatus)
if !yield(part) {
finalize(out.stoppedStatus())
return false
}
return true
})
finalize(out.endedStatus())
}
}
@@ -506,131 +513,59 @@ func wrapObjectStreamSeq(
handle *stepHandle,
seq iter.Seq[fantasy.ObjectStreamPart],
) fantasy.ObjectStreamResponse {
// Same safety-net pattern as wrapStreamSeq: a mutex rather
// than sync.Once lets the AfterFunc yield to the normal
// finalization path when the stream has already completed.
var (
mu sync.Mutex
finalized bool
streamComplete atomic.Bool
)
stop := context.AfterFunc(ctx, func() {
mu.Lock()
defer mu.Unlock()
if finalized || streamComplete.Load() {
return
}
finalized = true
handle.finish(ctx, StatusInterrupted, nil, nil, nil, nil)
})
step := newStreamStep(ctx, handle)
return func(yield func(fantasy.ObjectStreamPart) bool) {
var (
summary = objectStreamSummary{StructuredOutput: true}
latestUsage fantasy.Usage
usageSeen bool
finishSeen bool
finishReason fantasy.FinishReason
out = streamOutcome{status: StatusCompleted}
rawTextLength int
warnings []normalizedWarning
streamError any
streamStatus = StatusCompleted
)
finalize := func(status Status) {
if stop != nil {
stop()
}
mu.Lock()
defer mu.Unlock()
if finalized {
return
}
finalized = true
summary.FinishReason = string(finishReason)
resp := normalizedObjectResponsePayload{
RawTextLength: rawTextLength,
FinishReason: string(finishReason),
Warnings: warnings,
StructuredOutput: true,
}
if usageSeen {
resp.Usage = normalizeUsage(latestUsage)
}
var usage any
if usageSeen {
usage = &latestUsage
}
handle.finish(ctx, status, resp, usage, streamError, map[string]any{
"structured_output": true,
"stream_summary": summary,
step.finish(status, &out, func() (any, any) {
summary.FinishReason = string(out.finishReason)
summary.ErrorCount = out.errorCount
summary.LastError = out.lastError
resp := normalizedObjectResponsePayload{
RawTextLength: rawTextLength,
FinishReason: string(out.finishReason),
Usage: normalizeUsage(out.usage),
Warnings: warnings,
StructuredOutput: true,
}
return resp, map[string]any{"structured_output": true, "stream_summary": summary}
})
}
if seq != nil {
seq(func(part fantasy.ObjectStreamPart) bool {
summary.PartCount++
summary.WarningCount += len(part.Warnings)
if len(part.Warnings) > 0 {
warnings = append(warnings, normalizeWarnings(part.Warnings)...)
}
seq(func(part fantasy.ObjectStreamPart) bool {
summary.PartCount++
summary.WarningCount += len(part.Warnings)
if len(part.Warnings) > 0 {
warnings = append(warnings, normalizeWarnings(part.Warnings)...)
}
switch part.Type {
case fantasy.ObjectStreamPartTypeObject:
summary.ObjectPartCount++
case fantasy.ObjectStreamPartTypeTextDelta:
summary.TextDeltaCount++
rawTextLength += utf8.RuneCountInString(part.Delta)
case fantasy.ObjectStreamPartTypeFinish:
finishReason = part.FinishReason
latestUsage = part.Usage
usageSeen = true
finishSeen = true
streamComplete.Store(true)
}
switch part.Type {
case fantasy.ObjectStreamPartTypeObject:
summary.ObjectPartCount++
case fantasy.ObjectStreamPartTypeTextDelta:
summary.TextDeltaCount++
rawTextLength += utf8.RuneCountInString(part.Delta)
case fantasy.ObjectStreamPartTypeFinish:
out.observeFinish(step, part.FinishReason, part.Usage)
}
if part.Type == fantasy.ObjectStreamPartTypeError || part.Error != nil {
summary.ErrorCount++
if part.Error != nil {
summary.LastError = part.Error.Error()
streamError = normalizeError(ctx, part.Error)
} else {
summary.LastError = "stream error part with nil error"
streamError = map[string]string{"error": "stream error part with nil error"}
}
streamStatus = streamErrorStatus(streamStatus, part.Error)
}
if part.Type == fantasy.ObjectStreamPartTypeError || part.Error != nil {
out.observeError(ctx, part.Error)
}
if !yield(part) {
// Same as the regular stream wrapper: if a
// finish part was already seen, the consumer
// exited normally after completion.
switch {
case streamStatus == StatusError:
finalize(StatusError)
case finishSeen:
finalize(StatusCompleted)
default:
finalize(StatusInterrupted)
}
return false
}
return true
})
}
// Same as the regular stream wrapper: treat a
// stream that ended without a finish part as
// interrupted rather than falsely completed.
if streamStatus == StatusCompleted && !finishSeen {
streamStatus = StatusInterrupted
}
finalize(streamStatus)
if !yield(part) {
finalize(out.stoppedStatus())
return false
}
return true
})
finalize(out.endedStatus())
}
}