Commit Graph
3 Commits
Author SHA1 Message Date
yetone 2683123c7e gateway: TestClientGoneRecordedAsCanceled waits for the run's words, and takes either end of a killed run's stream (#5388)
The red on macOS CI (runs 42012262661 and 42354008450) was not the
fixed 200ms wait the issue's title names. Both logs have "thinking it
over" in the reply; what is missing is message_stop, and in its place
is `event: error` "Claude Code was ended by magpie before it ended its
reply". When the client leaves, letGo aborts the fake Claude Code run:
abort sends SIGTERM (Tree.Stop) and then r.finish() closes the run's
segment. Two goroutines race from there. If finish() closes the segment
first, relay sees its events end and enc.finish() writes message_stop.
If readOutput reaches the end of the dead process's output first, the
reply is still unended and, since a8e98e1ab (#4822), it emits KError,
which relay writes as the stream's error event, with no message_stop.
The test required message_stop, so on a slow runner (-race on macOS)
it went red. Neither end is the reply made whole, and h.ended stays
false in both; the test's guarantee (a stream end written after the
agent left is not taken as whole) holds either way.

The 200ms wait was a second, separate fault: with the fake's words
slower than 200ms the test canceled before the reply began.

- TestClientGoneRecordedAsCanceled: cancels once "thinking it over"
  reached the writer (saidRecorder closes said on it), not 200ms after
  hang.pid; accepts message_stop or the "ended by magpie before it
  ended its reply" error event as the stream's end; h.ended is checked
  as before.
- Sibling, same file family and helper: TestClaudeRunEndsWhenTheClientLeaves
  slept the same 200ms "its reply under way" after hang.pid. It now
  waits on the same state (saidRecorder), so it tests a client leaving
  mid-reply, not before the reply began. No other test of
  fakeClaudeCalling's hang uses a fixed wait (claude_runs_test waits on
  runsUntil).

Reproduced by injecting the delay, on mote, at 191f3c0af:
- time.Sleep(300ms) between t.Stop and r.finish() in abort (readOutput
  first): old test 3 of 3 red with CI's exact reply (the error event);
  new test 3 of 3 green.
- `sleep 0.5` in the fake after hang.pid (words slower than the wait):
  old TestClientGoneRecordedAsCanceled 3 of 3 red ("ended without an
  answer"), old TestClaudeRunEndsWhenTheClientLeaves passed while
  canceling before the reply; new tests 3 of 3 green.
Broken by hand: holdWriter.see without its ctx check makes
TestClientGoneRecordedAsCanceled red 3 of 3 (its first half).

Run at this tree, on origin/main 191f3c0af, on mote:
- go test -race -count=50 -run 'TestClientGoneRecordedAsCanceled$|TestClaudeRunEndsWhenTheClientLeaves$' ./internal/gateway: ok
- go vet ./internal/gateway, GOOS=linux and GOOS=windows go vet -tags
  nogui ./internal/gateway: ok; gofmt -l clean
- go test -tags nogui -timeout 45m ./internal/gateway: red on TestBurstTellsNoSpeed/responses_from_chat_burst alone (5000 tokens in 823ms read 6075 tok/s; a TTFT timing test this change doesn't touch), which passes -count=10 alone; recorded on #2719, its open issue
- full suite, go test -tags nogui -timeout 45m ./... under suite.lock: ok, every package (88), internal/gateway ok in 941s

Rebased onto origin/main f2412fd59 (8 commits since 191f3c0af, none
touching held_keepalive_test.go, claude_subscription_park_test.go,
claude_subscription.go or fallback.go). At that pushed head, on mote:
go test -race -count=5 -run 'TestClientGoneRecordedAsCanceled$|TestClaudeRunEndsWhenTheClientLeaves$'
./internal/gateway ok; go vet (darwin) and GOOS=linux/windows go vet
-tags nogui ./internal/gateway ok; gofmt -l clean. The full suite and
gateway runs above are at 191f3c0af, not again at this head.

Not changed: which end a killed run's stream gets stays a race in
abort (SIGTERM before finish); for a gone client nothing reaches it.
Not tried on Windows (fakeClaudeCalling skips there) or on CI before
the push.

Fixes #5388
2026-11-07 19:29:43 +08:00
yetone 76321e3b42 gateway: a lone provider's Claude or GPT reasoning streams as it comes, not held for a refusal no one else could answer (iTianbao on X: 请加一个开关,让思考实时透传; through a relay Claude Code showed the thinking only all at once with the text, Codex none until then) — holdWriter held Claude's, GPT's and Gemini's reasoning (refusesAfterThinking, up to holdThinking) on every candidate, so a refusal after it could go to the next one (#248), but a refusal on the last candidate is never asked again (the !last checks in serve), so there it only delayed the thinking. On the last candidate Claude's and GPT's reasoning is now shown at once (thinkingShown), and a refusal after it reaches the agent as the vendor's own stop; Gemini's stays held there, for a reply that only reasoned to be asked again (#667, TestGeminiEmptyRepliesAskedAgain). A group with members after it still holds as before. Before: on a slow fake relay (4 thoughts 300ms apart, then text) every relay shape (Messages, Chat with reasoning_content and reasoning, Responses) for claude-sonnet-4-5 and gpt-5.1 gave Claude Code's thinking_delta and Codex's reasoning_summary_text.delta all at ~1.2–1.5s with the text; after, 0/300/600/900ms. TestThinkingStreamsWithNoOneElse (Messages, Chat for Claude and GPT, Responses; each asked from /v1/messages and /v1/responses) fails without the change in every case and passes; TestHeldThinkingKeepsTheAgentAlive's nobody-left case now expects the thinking and Claude's refusal rather than a held error. -race -count=5 on TestThinking*, TestRefusal*, TestHeld*, TestGeminiEmpty*; go test -tags nogui ./internal/gateway, go vet, gofmt -l, linux and windows (nogui) builds pass. Not tried with the reporter's relay: whether it sends GPT's reasoning at all (OpenAI's Chat API doesn't) is unknown, and no switch was added. docs/subsystems/gateway-routing.md says it. 2026-10-06 19:34:24 +08:00
yetone 3eae3ee7fb gateway: a Claude stream held for its reasoning keeps the agent alive with SSE comments, and a request whose agent went away is recorded as canceled, not as a 200 done (#751, margbug01 on v0.1.679: Alma → magpie → Claude Code (Claude Max, claude-opus-5-5) ended with "No LLM streaming data for 240000ms", while the routing record said 200, about 240000 ms, TTFT about 4.3 s, 8 tokens out, done with no error) — for a Claude model, refusesAfterThinking, a stream that holds nothing but reasoning is held for up to holdThinking (4 minutes) so that a refusal after it can still go to another account (#248). Everything written meanwhile was held with it: message_start, the thinking deltas and the protocol keepalives relay sends every 15s (#436). The agent got no byte at all, and Alma's idle timeout for a reasoning model (60s ×4 = 240s, reset by any SSE line, comments included) ran out first. The hold is on for nearly every first try (!last || again < retries || …), so one Claude account alone was enough. The TTFT on the record is the held stream's first event, not a byte delivered. Now, once a stream has been held for its thinking or safety buffering past keepHeldAfter (holdLongest, 15s), holdWriter.keepAlive sends the agent the stream's 200 and headers once, then a ": keepalive" comment every keepaliveEvery while the stream stays held. The comment is not an event in any protocol and says nothing of the reasoning, and no model text is made up. The keptAlive is the request's and is shared by its tries. A refusal after the comments still goes to the next member: its pass() skips the headers already sent, and its stream follows in the same response. Once headers are out, a failure can no longer be a status, so the gateway's writeErrors inside the try loop go through failTo and holdWriter.release goes through streamError, which tell it as the stream's own error event (Anthropic event: error, Responses response.failed, Chat's error chunk). The last try's writer is held too once headers are out. A Responses agent (Codex) doesn't count comments, but its 300s timeout outlasts the 4-minute hold.
When the agent went away, serveSubscription's AfterFunc stopped Claude Code, but relay still called enc.finish(), which wrote message_stop to the gone writer. holdWriter.see took that as the reply made whole (ended), so serve's `r.Context().Err() != nil && !hw.ended` check, which records 499 "the agent canceled the request" with Fail canceled, was skipped and the request was recorded as 200 done. see now ignores a stream end written once the request's context is done, and the bridge logs "Claude Code run on <model> stopped: the client went away <t> into the reply".
TestHeldThinkingKeepsTheAgentAlive sends claude-opus-5-5 thinking that goes on (pings every 10ms until the client hears a keepalive, else 3s) through a group over a real HTTP gateway. It covers three cases: a refusal after it, where the client gets ": keepalive" before b's answer in the same stream, with one message_start, no reasoning text and Tries[0] refused; an answer after it, which arrives whole after the comments; and a refusal with nobody left, which arrives as a 200 stream with event: error. TestClientGoneRecordedAsCanceled checks a holdWriter whose context is canceled before message_stop, and a fake Claude Code run (fakeClaudeCalling's hang) stopped mid-reply through serveClaudeSubscription writing to a holdWriter. With keepAlive's call and see's context check taken out, both fail: the client heard nothing until the upstream gave up waiting at 3s, and ended was set. go vet, builds (darwin, GOOS=linux, GOOS=windows), go test -tags nogui -count=1 ./... under a temp HOME, and -race on the gateway's refusal, thinking, keepalive and cancel tests all pass. Not tried with real Claude Code, a real Claude Max account or Alma. Not changed: --thinking-display summarized is passed only when the request names an effort, so Claude Code's own thinking display is otherwise left at the API's default; relay's keepalives stop 5 minutes after the last event (keepaliveLongest); and Gemini clients get no keepalive.
2026-10-04 14:11:24 +08:00