diff --git a/docs/subsystems/claude-subscription-bridge.md b/docs/subsystems/claude-subscription-bridge.md index dbdc4ae81..8bbe71a0f 100644 --- a/docs/subsystems/claude-subscription-bridge.md +++ b/docs/subsystems/claude-subscription-bridge.md @@ -747,6 +747,13 @@ came before any failure is a failure too, as a translated reply cut short is (`errEndedShort`). `TestClaudeSubscriptionRunExitedMidReplyFails` holds it on all three protocols, streamed and not, `-p` and interactive. +A streamed reply whose run is quiet past `bridgeHeardAfter` begins +without it and is sent the protocol's pings until the run speaks +(`keepBridgeHeard`, #5043): the replay of a long conversation can take +minutes before its first word, and Claude Code hung up at 599s and +started again from the replay, writing it to the cache once more (#3808). +See [gateway routing](gateway-routing.md) for the keepalive rules. + magpie ends a run (`abort`) by asking Claude Code to end with SIGTERM (`proc.Tree.Stop`) and kills its tree only once it has exited or `stopGrace` (5s) has passed; Windows kills the job at once. Claude Code diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a375aa962..dca22179f 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -1141,6 +1141,27 @@ A provider that says nothing at all, not even a keepalive, is handed on a `KAlive` every `keepaliveEvery` by the same ticker `streamTranslated` uses (`keepThroughSilence`), for up to `translatedQuietLongest` of its silence. +A Claude subscription run is heard from the same way (`keepBridgeHeard`, +in `claude_subscription.go`). Its run says nothing before its reply: in +the interactive mode a message is told whole from the transcript, and a +long conversation replayed to a new Claude Code is prefilled uncached +first. The held stream's comments stop at `keepaliveLongest`, and Claude +Code 2.1.316's byte watchdog hung up 300s later, at 599s (#5043). Comments +forever would not do: its event watchdog counts no comment and hangs up +600s after the headers. So after `bridgeHeardAfter` (1 minute) of a quiet +run, the run's events gain an empty `KStart`, which begins the reply +(`message_start`), and a `KAlive` every `keepaliveEvery` while it stays +quiet, for up to `translatedQuietLongest`. The client gets the protocol's +own pings, held like any frames-only stream (`holdLead`). The run's own +start, later, adds its usage. A failure in the first minute is still a +status. The gain is bounded: Claude Code 2.1.316 turns every 10s with +bytes into a ping of its own and counts 30 pings in a row, so a stream of +pings and comments alone ends 600s after its last other event. The +reply's start goes out when the hold lets it go, about 4 minutes in, and +the run has until about 14 minutes where it had 599s. A run quiet for +longer still ends: only a real event of the reply would keep it. Covered by `TestClaudeBridgeQuietRunKeepsClientAlive` in +[`claude_bridge_keepalive_test.go`](../../internal/gateway/claude_bridge_keepalive_test.go). + ## Which providers search for another model `Searchers()` (Settings › Web search's picker) and `autoSearcher` (magpie's diff --git a/internal/gateway/claude_bridge_keepalive_test.go b/internal/gateway/claude_bridge_keepalive_test.go new file mode 100644 index 000000000..87a3625f8 --- /dev/null +++ b/internal/gateway/claude_bridge_keepalive_test.go @@ -0,0 +1,83 @@ +package gateway + +import ( + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/testenv" +) + +// #5043: a Claude Code run that says nothing for minutes before its +// reply (a long conversation replayed whole, prefilled uncached on a +// high effort) left a streaming client with the held stream's comments +// only, and those stop at keepaliveLongest: Claude Code 2.1.316's byte +// watchdog then hung up 300s later, at 599s, and its event watchdog +// counts no comment at all. Past bridgeHeardAfter the reply begins +// (message_start) and the client is sent its protocol's pings while the +// run is quiet, and the run's own start, when it comes, adds its usage. +func TestClaudeBridgeQuietRunKeepsClientAlive(t *testing.T) { + claudeMadeFirst(t, false) + keepFast(t, 10*time.Millisecond, 50*time.Millisecond, keepaliveLongest) + heard, ping := bridgeHeardAfter, pingEvery + bridgeHeardAfter, pingEvery = 200*time.Millisecond, 100*time.Millisecond + t.Cleanup(func() { bridgeHeardAfter, pingEvery = heard, ping }) + + // a Claude Code quiet for 1.5s before its reply: ~13 pings' room at + // 100ms from 200ms, of which 3 are asked for + bin := t.TempDir() + testenv.Program(t, filepath.Join(bin, "claude"), `#!/bin/sh +case "$1" in auth) exit 1;; esac +if [ "$2" = "/usage" ]; then + echo '{"type":"result","is_error":false,"result":"Current session: 10% used"}' + exit 0 +fi +while read -r line; do + case $line in *'"type":"control_request"'*) + id=$(printf '%s' "$line" | sed 's/.*"request_id":"\([^"]*\)".*/\1/') + echo '{"type":"control_response","response":{"subtype":"success","request_id":"'$id'"}}' + continue ;; + esac + sleep 1.5 + echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":4242}}}}' + echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"after the quiet"}}}' + echo '{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}}' + echo '{"type":"stream_event","event":{"type":"message_stop"}}' + echo '{"type":"result","subtype":"success","is_error":false,"result":""}' +done +`) + t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH")) + + s := New() + t.Cleanup(s.subscription.abortAll) + body := `{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + rec := httptest.NewRecorder() + var u Usage + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "a@example.com"}} + if code, msg := s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u); code != 200 { + t.Fatalf("%d %s", code, msg) + } + out := rec.Body.String() + said := strings.Index(out, "after the quiet") + if said < 0 { + t.Fatalf("no answer:\n%s", out) + } + before := out[:said] + if n := strings.Count(before, "event: message_start"); n != 1 { + t.Fatalf("%d message_start before the reply, want 1 (the client heard nothing it counts while the run was quiet):\n%s", n, out) + } + if n := strings.Count(before, `data: {"type":"ping"}`); n < 3 { + t.Fatalf("%d pings while the run was quiet, want 3 or more:\n%s", n, out) + } + if n := strings.Count(out, "event: message_start"); n != 1 { + t.Fatalf("%d message_start in the reply, want 1:\n%s", n, out) + } + // the run's own start, after the one sent for it, still counts + if u.Input != 4242 || !strings.Contains(out, `"input_tokens":4242`) { + t.Fatalf("the run's start lost its usage: %+v\n%s", u, out) + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 724d7c29b..84bdef8a7 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -6161,6 +6161,11 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from run.mu.Lock() req.interactive = run.tui run.mu.Unlock() + if req.Stream { + quit := make(chan struct{}) + defer close(quit) + events = keepBridgeHeard(events, quit) + } return relay(w, r, from, name, req, events, usage, abort, begin, func(said, stop string, ok bool) { if !gone() { return // the client went first: letGo has the run @@ -6233,6 +6238,89 @@ func thirdPartyRefused(name string, req *Request, code int, msg string) string { "or in this provider's editor; the plan counts a -p request at about twice the interactive mode's.)" } +// bridgeHeardAfter is how long a Claude Code run may work on its turn +// with nothing of the reply before its client is told the reply goes on +// (keepBridgeHeard). Before it, a failure is still a status for the next +// account; after it, the client's stream begins, held for another account +// all the same (holdLead), so that its first event reaches the client +// well within the 600s Claude Code waits for one. +var bridgeHeardAfter = time.Minute + +// keepBridgeHeard hands on a run's events, and a KAlive whenever the run +// has said nothing for keepaliveEvery, from bridgeHeardAfter on, for up +// to translatedQuietLongest of silence: a run whose Claude Code is still +// working is heard from, as a translated provider's keepalives are. The +// interactive mode tells a message only once it is written whole, and a +// long conversation's first reply, at effort high on claude-opus-5-5, +// took 385 to 527s (#5043). Its client heard the held stream's comments +// for keepaliveLongest (keepQuiet), then nothing, and Claude Code 2.1.316 +// ended the request at 599s ("Streaming idle timeout (byte-level): no +// bytes for 300000ms"); comments for as long as it waited would not do +// either, since it ends a stream with no event for 600s from its headers +// ("no chunks received for 300s"). Every new try then started a Claude +// Code that wrote the whole conversation to the cache again (#3808). +// What this buys is bounded: Claude Code 2.1.316 makes a ping of its own +// of every 10s with bytes and counts 30 pings in a row, so a stream that +// sends only pings and comments is ended 600s after its last other +// event. The reply's start goes out when the hold lets it (holdLead, +// ~4 minutes in), and the run then has until ~14 minutes, where it had +// 599s. +// The run's end closes events, and with them what this hands on; quit +// ends it when relay is done with them. +func keepBridgeHeard(events <-chan Event, quit <-chan struct{}) <-chan Event { + out := make(chan Event) + go func() { + defer close(out) + tick := time.NewTicker(keepaliveEvery) + defer tick.Stop() + began := time.Now() + last := began + started := false // the reply has its start, the run's or this one's + send := func(ev Event) bool { + select { + case <-quit: + return false + case out <- ev: + return true + } + } + for { + select { + case <-quit: + return + case ev, ok := <-events: + if !ok { + return + } + last = time.Now() + started = started || ev.Kind == KStart + if !send(ev) { + return + } + case <-tick.C: + quiet := time.Since(last) + if time.Since(began) < bridgeHeardAfter || quiet < keepaliveEvery || quiet >= translatedQuietLongest { + continue + } + // the reply begins, with none of it, for the client's + // keepalive to be its protocol's own event: an Anthropic + // ping before message_start breaks the SDKs (keepalive); + // the run's own start that comes later adds its usage + if !started { + started = true + if !send(Event{Kind: KStart}) { + return + } + } + if !send(Event{Kind: KAlive}) { + return + } + } + } + }() + return out +} + // relay answers the client with a reply's events: abort is called when // there is no answer to give, ended when one was given, before its last // event goes out.