Skip to content

[fix]: core - scope the stream terminal marker to the active attempt - #10290

Open
ahmedabdou14 wants to merge 3 commits into
maximhq:devfrom
ahmedabdou14:fix/10202-attempt-scoped-terminal
Open

ahmedabdou14 wants to merge 3 commits into
maximhq:devfrom
ahmedabdou14:fix/10202-attempt-scoped-terminal

Conversation

@ahmedabdou14

@ahmedabdou14 ahmedabdou14 commented Nov 21, 2026 •

Copy link
Copy Markdown

Summary

Fixes #10202. Follow-up to the stream panic recovery from #9791.

A stream attempt that fails on its first chunk (an error event in a 200 stream, or a TTFT cut) sends its error through ProcessAndSendBifrostError, which marks the shared context as having handled its terminal chunk. Retries and fallbacks reuse that context and clear the other per-stream flags, but not this marker. If the next attempt's provider goroutine then panics, RecoverStreamPanic sees the old marker and sends nothing. The client stream ends with no error and no post-hook runs for the attempt that served the request, so logging, governance and usage tracking never see it end.

Changes

  • ResetStreamAttemptState in core/providers/utils clears the per-attempt stream state: StreamEndIndicator, StreamBodyExhausted, StreamParkedAfterFinish and the terminal marker.
  • The retry block in executeRequestWithRetries and clearCtxForFallback both call it instead of keeping their own lists, so a new flag cannot be missed in one of them. Both run after the previous attempt's stream has drained, so no late write can race the reset.
  • Changelog entry in core/changelog.md.

Not taken: keying the marker to the attempt's response channel. It needs every provider to pass the same channel to the send helpers and to RecoverStreamPanic, and a mismatch would send a second terminal after a good final chunk.

Type of change

  • Bug fix
  • Feature
  • Refactor
  • Documentation
  • Chore/CI

Affected areas

  • Core (Go)
  • Transports (HTTP)
  • Providers/Integrations
  • Plugins
  • UI (React)
  • Docs

How to test

cd core
go test -run 'TestStreamPanicAfterRetryOrFallbackReachesPostHooks|TestClearCtxForFallback' .
go test -run TestRecoverStreamPanic ./providers/utils/

TestStreamPanicAfterRetryOrFallbackReachesPostHooks has a retry and a fallback case: the first attempt fails with an SSE rate-limit event, and a test tracer panics on the served attempt's second chunk. It expects one client error chunk and one error post-hook with ErrStreamPanicMessage. Both cases fail on dev and pass here; each fails when only its own call site is reverted.

The CI core unit set (go test over every core package except the llmtests ones) passes, apart from internal/memtest (TestEveryLoopBoundJSONMutationIsReviewed) and the internal/mcptests STDIO cases, which fail the same way on unmodified dev locally (Go 1.27.4, darwin/arm64).

No provider-harness case: the change only shows on the wire when a provider goroutine panics, which no well-formed HTTP request can trigger.

Cost (BenchmarkClearCtxForFallback, -benchmem, Go 1.27.4, Apple M4 Max, median of 6): 290 ns/op before, 315 ns/op after, 0 allocs/op and 0 B/op both. The extra cost is one context value write, paid only on a retry or fallback attempt, never on a request served by its first attempt. No memory is retained.

Screenshots/Recordings

N/A

Breaking changes

  • Yes
  • No

Related issues

Fixes #10202

Security considerations

None.

Checklist

  • I added/updated tests where appropriate
  • I verified Go builds succeed (no UI change)
  • I ran the core unit tests locally

A stream attempt that failed on its first chunk left the terminal marker
set on the shared context. If a retry or fallback attempt then panicked,
RecoverStreamPanic treated the stream as already ended, so neither the
client nor the post-hooks saw the served attempt end. The marker is now
cleared wherever the other per-attempt stream flags are.

Affected packages:
- core/providers/utils/utils.go
- core/bifrost.go
- core/utils.go
- core/streamfallback_test.go, core/bifrost_test.go
- core/changelog.md

Fixes maximhq#10202
@coderabbitai

coderabbitai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Automatic approval withheld

CodeRabbit could not verify the path filters used for the saved review. Run a full review using the repository's approval configuration.

A reviewer can post @coderabbitai approve as a new top-level comment to request approval.

Commit: 406db3ca6141.

No actionable comments were generated in the recent review.

Summary

Summary by CodeRabbit

  • Bug Fixes
    • Streaming requests that retry or fall back after an earlier failure now consistently report a later stream panic as an error, including when the earlier attempt fails immediately.
    • The panic error is delivered once to the client and reported once through plugin notifications, reducing missing or duplicate error notifications.
    • Stream errors are handled consistently across retry and fallback attempts, so failures are surfaced reliably regardless of which attempt encounters them.

Retry and fallback paths now use a shared utility to reset stream-attempt state. Regression tests check that a panic on the served attempt produces one client error chunk and one matching plugin error post-hook.

Changes: Stream attempt state

Layer / File(s) Summary
Reset stream state between attempts
core/providers/utils/utils.go, core/bifrost.go, core/utils.go
A new utility clears five stream-attempt context values after the prior stream drains. Retry and fallback paths use it. Fallback handling still clears the connection-closed value separately.
Validate retry and fallback panic handling
core/streamfallback_test.go, core/bifrost_test.go, core/changelog.md
Regression tests check that a panic on the served attempt produces one client error chunk and one matching plugin error post-hook. A benchmark and changelog entry are added.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related issues

Suggested reviewers: impoiler

Merge Risk: Minimal · up to 406db

The fix makes a panic on a retried or fallback stream attempt produce an error chunk and an error post-hook. No concrete merge-blocking risk remains in the reviewed change.

Pre-merge checks: Passed 5

Check name Status Explanation
Title check Passed The title names the core fix: the stream terminal marker is scoped to the active attempt. The changeset adds ResetStreamAttemptState, which clears the terminal-handled marker on retries and fallbacks,…
Description check Passed The description follows the repository template. It includes Summary, Changes, Type of change (Bug fix checked), Affected areas (Core checked), How to test with commands and expected outcomes, Screens…
Linked Issues check Passed Issue #10202 requires that, after a recovered provider stream error, the active attempt reports its terminal outcome to PostLLMHook exactly once, and that a previous attempt's notification stays with …
Out of Scope Changes check Passed Every changed area relates to the fix for #10202. The changes are: the ResetStreamAttemptState helper in core/providers/utils/utils.go; its call sites in clearCtxForFallback (core/utils.go, verified) …
Audit Commit Point Passed The check applies only to changed handlers under transports/bifrost-http/handlers/. The reviewed range (refs/coderabbit/pre-merge-check/base..head) changes six files, all under core/: core/bifrost.go,…
Full details: Title check

Explanation

The title names the core fix: the stream terminal marker is scoped to the active attempt. The changeset adds ResetStreamAttemptState, which clears the terminal-handled marker on retries and fallbacks, so the title matches the main change. The title is specific and uses the repository's [fix] convention.

Full details: Description check

Explanation

The description follows the repository template. It includes Summary, Changes, Type of change (Bug fix checked), Affected areas (Core checked), How to test with commands and expected outcomes, Screenshots (N/A), Breaking changes (No), Related issues (Fixes #10202), Security considerations, and a Checklist. It explains the root cause, the fix, the design alternative not taken, and the benchmark cost. The description is complete. Minor gap: it does not list the repository's full checklist items (for example, the documentation item), but the required sections are present.

Full details: Linked Issues check

Explanation

Issue #10202 requires that, after a recovered provider stream error, the active attempt reports its terminal outcome to PostLLMHook exactly once, and that a previous attempt's notification stays with that attempt. The root cause is the streamTerminalHandled marker surviving into a later attempt. At head, core/providers/utils/utils.go adds ResetStreamAttemptState, which clears StreamEndIndicator, StreamBodyExhausted, StreamParkedAfterFinish, StreamProviderJob, and the streamTerminalHandledKey marker. The diff of core/utils.go confirms that clearCtxForFallback calls this helper in place of the individual clears. The diff of core/bifrost.go could not be read (changed blob unavailable). The retry call site in executeRequestWithRetries is supported only by the AI-generated raw summary, which reports the same helper replacing four individual clears. With the marker cleared, a later attempt's RecoverStreamPanic can send its own terminal error. The regression test TestStreamPanicAfterRetryOrFallbackReachesPostHooks is described in the PR, but its result was not run here.

Full details: Out of Scope Changes check

Explanation

Every changed area relates to the fix for #10202. The changes are: the ResetStreamAttemptState helper in core/providers/utils/utils.go; its call sites in clearCtxForFallback (core/utils.go, verified) and executeRequestWithRetries (core/bifrost.go, per raw summary); the regression tests in core/streamfallback_test.go; the BenchmarkClearCtxForFallback benchmark in core/bifrost_test.go, which measures the cost of the reset; and the changelog entry in core/changelog.md. The benchmark, test, and changelog support the fix and do not change runtime behavior beyond the reset. No unrelated change was found in the inspected diffs.

Full details: Audit Commit Point

Explanation

The check applies only to changed handlers under transports/bifrost-http/handlers/. The reviewed range (refs/coderabbit/pre-merge-check/base..head) changes six files, all under core/: core/bifrost.go, core/bifrost_test.go, core/changelog.md, core/providers/utils/utils.go, core/streamfallback_test.go, and core/utils.go. A path-limited diff of transports/bifrost-http/handlers/ returned no changes. No changed handler exists, so the failure condition cannot apply, and the check passes. PR context: #10290 by ahmedabdou14 (base dev, head fix/10202-attempt-scoped-terminal). The PR adds ResetStreamAttemptState and uses it in the retry and fallback paths. None of that code is an HTTP handler or an audit record path.

Finishing Touches

Generate unit tests (beta)

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts
Recent review info

Run configuration

Commits

Reviewing files that changed from the base of the PR and between 4293741 and 406db3c.

Files selected for processing: 6

  • core/bifrost.go
  • core/bifrost_test.go
  • core/changelog.md
  • core/providers/utils/utils.go
  • core/streamfallback_test.go
  • core/utils.go
Files skipped from review as they are similar to previous changes: 1

  • core/changelog.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 21, 2026

@akshaydeo akshaydeo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this, it is a clean, well-scoped fix. I confirmed red before green: with either reset removed, the matching TestStreamPanicAfterRetryOrFallbackReachesPostHooks case fails (no client error chunk, no panic post-hook), and both pass at this head, also under -race. The reset is safe because both call sites run only after the previous attempt's channel has been drained (<-drainDone in executeRequestWithRetries), and nothing marks the terminal after close(responseChan). The cost statement and the harness exemption in the PR body read fine to me. Two small nits inline, neither blocks merge.

Comment thread core/bifrost.go Outdated
ctx.ClearValue(schemas.BifrostContextKeyStreamEndIndicator)
ctx.ClearValue(schemas.BifrostContextKeyStreamBodyExhausted)
ctx.ClearValue(schemas.BifrostContextKeyStreamParkedAfterFinish)
providerUtils.ResetStreamTerminalHandled(ctx)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (follow-up is fine): this block and clearCtxForFallback (core/utils.go:463-468) now keep two hand-copied lists of the same per-attempt stream state (StreamEndIndicator, StreamBodyExhausted, StreamParkedAfterFinish, and now the terminal marker). This bug happened because a marker was added to neither list. A small shared helper, for example resetStreamAttemptState(ctx), called from both places would keep the next stream flag from being missed in one of them.

Comment thread core/changelog.md Outdated
@@ -1,3 +1,4 @@
- fix: a retry or fallback stream that panics now ends with an error chunk and an error post-hook, even after an earlier attempt failed on its first chunk (#10202) [@ahmedabdou14](https://github.com/ahmedabdou14)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: other credited entries in this file use (thanks [@user](https://github.com/user)!). Could you match that, e.g. ... on its first chunk (#10202) (thanks [@ahmedabdou14](https://github.com/ahmedabdou14)!)?

…and fallback

The retry block in executeRequestWithRetries and clearCtxForFallback each
kept their own list of per-attempt stream flags to clear. Both now call
ResetStreamAttemptState, which replaces ResetStreamTerminalHandled, so a
new flag cannot be added to one list and missed in the other. No behavior
change. The changelog credit now matches the file's style.

Affected packages:
- core/providers/utils/utils.go
- core/bifrost.go
- core/utils.go
- core/changelog.md
@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Confidence Score: 4/5RetriggerView in Greptile

[Medium impact] The change affects streaming requests that enter a retry or fallback.

The code change appears sound, but the test comment must follow the repository’s explicit comment rule before merging.

Findings

  1. P2 Test comment describes old behavior ▶

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Attempt fails before useful output] --> B[Drain the old stream]
  B --> C[Choose retry or fallback]
  C --> D[Reset stream attempt state]
  D --> E[Start the next attempt]
  E --> F{Provider goroutine panics?}
  F -->|Yes| G[Send error through post-hooks]
  G --> H[Client receives terminal error]
  F -->|No| I[Continue the stream]
Loading

Reviews (2) · Last reviewed commit: "merge dev into fix/10202-attempt-scoped-..." · Reviewed by Greptile

coderabbitai[bot]
coderabbitai Bot previously approved these changes Nov 25, 2026
Comment on lines +2166 to +2168
// earlier attempt's terminal bookkeeping belongs to that attempt; before the fix it
// survived the retry or fallback, so the recovered panic sent nothing and plugins never
// saw the served attempt end.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Test comment describes old behavior

The new comment explains what happened “before the fix.” AGENTS.md requires test comments to describe the behavior they check, not the incident or previous implementation. Remove the historical explanation and keep the expected behavior. This repository requirement must be satisfied before merging.

Suggested change
// earlier attempt's terminal bookkeeping belongs to that attempt; before the fix it
// survived the retry or fallback, so the recovered panic sent nothing and plugins never
// saw the served attempt end.
// earlier attempt's terminal bookkeeping belongs to that attempt.

File Used: AGENTS.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Scope provider stream terminal notifications to the active attempt

2 participants