From 85fd35abcb9c738535e5e6be3c5e9777275734c8 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 6 Oct 2026 13:40:52 +0800 Subject: [PATCH] =?UTF-8?q?claude:=20Claude=20Code's=20output=20is=20read?= =?UTF-8?q?=20to=20the=20end=20before=20its=20run=20ends,=20not=20cut=20by?= =?UTF-8?q?=20Wait=20closing=20the=20pipe=20(CI=20Test=20run=2037415124103?= =?UTF-8?q?=20on=20963a8d8f:=20TestClientGoneRecordedAsCanceled=20got=20`e?= =?UTF-8?q?vent:=20error=20=E2=80=A6=20"read=20|0:=20file=20already=20clos?= =?UTF-8?q?ed"`=20in=20place=20of=20message=5Fstop=20on=20ubuntu,=20race?= =?UTF-8?q?=20shard)=20=E2=80=94=20the=20run=20read=20Claude=20Code's=20st?= =?UTF-8?q?dout=20from=20cmd.StdoutPipe,=20and=20launch's=20goroutine=20ca?= =?UTF-8?q?lled=20Wait=20as=20soon=20as=20Claude=20Code=20exited,=20which?= =?UTF-8?q?=20closes=20that=20pipe.=20A=20run=20stopped=20as=20its=20clien?= =?UTF-8?q?t=20went=20away=20(letGo=20=E2=86=92=20abort=20=E2=86=92=20Kill?= =?UTF-8?q?)=20could=20have=20Wait=20close=20the=20pipe=20under=20readOutp?= =?UTF-8?q?ut=20before=20abort's=20finish=20closed=20the=20segment:=20the?= =?UTF-8?q?=20scanner=20failed=20with=20os.ErrClosed,=20readOutput=20emitt?= =?UTF-8?q?ed=20it=20as=20a=20KError,=20and=20relay=20wrote=20it=20to=20th?= =?UTF-8?q?e=20client=20as=20the=20stream's=20error.=20The=20same=20cut=20?= =?UTF-8?q?lost=20what=20Claude=20Code=20wrote=20last=20whenever=20it=20ex?= =?UTF-8?q?ited:=20whatever=20was=20still=20in=20the=20pipe=20never=20reac?= =?UTF-8?q?hed=20the=20client.=20Its=20stdout=20and=20stderr=20now=20come?= =?UTF-8?q?=20through=20os.Pipe=20pipes=20of=20the=20run's=20own,=20which?= =?UTF-8?q?=20Wait=20doesn't=20touch;=20once=20Claude=20Code=20has=20exite?= =?UTF-8?q?d=20and=20its=20group=20been=20ended,=20the=20run=20waits=20for?= =?UTF-8?q?=20both=20readers=20(up=20to=20outputDrain,=202s,=20for=20a=20p?= =?UTF-8?q?rocess=20that=20left=20the=20group=20and=20still=20holds=20them?= =?UTF-8?q?),=20closes=20the=20pipes,=20then=20finishes.=20A=20read=20cut?= =?UTF-8?q?=20by=20that=20close=20is=20taken=20as=20the=20output's=20end,?= =?UTF-8?q?=20not=20an=20error.=20TestClaudeLastWordsAreRead=20(a=20fake?= =?UTF-8?q?=20Claude=20Code=20writes=20~300KB=20and=20exits)=20fails=20on?= =?UTF-8?q?=20the=20old=20code=20on=20every=20run=20(the=20reply's=20last?= =?UTF-8?q?=20delta=20lost)=20and=20passes;=20TestClientGoneRecordedAsCanc?= =?UTF-8?q?eled|Keepalive|TestClaudeLastWordsAreRead=20pass=20-race=20-cou?= =?UTF-8?q?nt=3D50=20under=20GOMAXPROCS=3D2=20with=204=20busy=20cores;=20t?= =?UTF-8?q?he=20gateway's=20race=20suite=20through=20build/race-shards.sh?= =?UTF-8?q?=20(4=20shards,=20as=20CI)=20and=20go=20vet=20pass.=20The=20CI?= =?UTF-8?q?=20failure=20itself=20didn't=20reproduce=20on=20macOS.=20Not=20?= =?UTF-8?q?changed:=20the=20"http:=20panic=20serving=20=E2=80=A6:=20invali?= =?UTF-8?q?d=20concurrent=20Body.Read=20call"=20lines=20in=20the=20same=20?= =?UTF-8?q?log=20are=20in=20shards=20that=20pass=20and=20in=20green=20runs?= =?UTF-8?q?=20too=20(5=20in=2037416877275),=20near=20the=20Copilot=20auto?= =?UTF-8?q?=20/=20count=5Ftokens=20tests;=20their=20handler=20wasn't=20fou?= =?UTF-8?q?nd.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/claude_output_drain_test.go | 50 ++++++++++++++++++ internal/gateway/claude_subscription.go | 54 +++++++++++++++++--- 2 files changed, 98 insertions(+), 6 deletions(-) create mode 100644 internal/gateway/claude_output_drain_test.go diff --git a/internal/gateway/claude_output_drain_test.go b/internal/gateway/claude_output_drain_test.go new file mode 100644 index 000000000..0f8341186 --- /dev/null +++ b/internal/gateway/claude_output_drain_test.go @@ -0,0 +1,50 @@ +package gateway + +import ( + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// What Claude Code writes as it exits reaches the client: its output is +// read to the end before the run ends, not cut by Wait closing the pipe +// under the reader ("read |0: file already closed", CI on 963a8d8f). +func TestClaudeLastWordsAreRead(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("a shell script stands in for Claude Code") + } + dir := t.TempDir() + // a long reply, more than a pipe holds, written all at once on exit + script := `#!/bin/sh +read -r line +d='{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"` + strings.Repeat("x", 1000) + `"}}}' +{ +echo '{"type":"stream_event","event":{"type":"message_start","message":{"id":"m","model":"claude-sonnet-5","usage":{"input_tokens":1}}}}' +echo '{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}' +i=0; while [ $i -lt 300 ]; do echo "$d"; i=$((i+1)); done +echo '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"the very end"}}}' +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"}}' +} +` + os.WriteFile(filepath.Join(dir, "claude"), []byte(script), 0o755) + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) + for i := 0; i < 5; i++ { + s := New() + p := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "u"}} + body := `{"model":"claude-sonnet-5","max_tokens":100,"stream":true,"messages":[{"role":"user","content":"say a lot"}]}` + rec := httptest.NewRecorder() + var u Usage + s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, p, "claude-sonnet-5", []byte(body), &u) + s.subscription.abortAll() + out := rec.Body.String() + if !strings.Contains(out, "the very end") || strings.Contains(out, "event: error") { + t.Fatalf("run %d: the reply's end: %q", i, out[max(0, len(out)-400):]) + } + } +} diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index 928dfd7aa..b4265b464 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -122,7 +122,10 @@ type subscriptionRun struct { model string cmd *exec.Cmd tree *proc.Tree // cmd once started, with all it starts - tmp string + // the read ends of Claude Code's output, and their readers + outputs []*os.File + reading sync.WaitGroup + tmp string // schema says the client asked for an answer fitting a JSON schema, // which Claude Code gives as its StructuredOutput call schema bool @@ -551,16 +554,22 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, con cleanup() return nil, nil, err } - stdout, err := cmd.StdoutPipe() + // Claude Code's output comes through pipes of the run's own, not + // cmd.StdoutPipe's, which Wait closes as Claude Code exits: what it + // wrote last, or the reading under way as it was stopped, failed + // "file already closed", and the client heard that for an error. + stdout, stdoutW, err := os.Pipe() if err != nil { cleanup() return nil, nil, err } - stderr, err := cmd.StderrPipe() + stderr, stderrW, err := os.Pipe() if err != nil { + _, _ = stdout.Close(), stdoutW.Close() cleanup() return nil, nil, err } + cmd.Stdout, cmd.Stderr = stdoutW, stderrW run := &subscriptionRun{bridge: b, token: token, model: model, cmd: cmd, tmp: tmp, schema: len(req.Schema) > 0, pending: map[string]chan mcpToolResult{}, stdin: stdin, owner: owner, effort: req.Effort, sessions: sessions} run.safeguardBeta = req.SafeguardBeta @@ -575,14 +584,24 @@ func (b *subscriptionBridge) start(ctx context.Context, req *Request, model, con b.runs[token] = run b.mu.Unlock() - if err := run.launch(); err != nil { + run.outputs = []*os.File{stdout, stderr} + run.reading.Add(2) + err = run.launch() + _, _ = stdoutW.Close(), stderrW.Close() // Claude Code has its own + if err != nil { + _, _ = stdout.Close(), stderr.Close() b.removeRun(run) return nil, nil, err } go func() { + defer run.reading.Done() _, _ = io.Copy(&lockedWriter{run: run}, io.LimitReader(stderr, 1<<20)) + _, _ = io.Copy(io.Discard, stderr) + }() + go func() { + defer run.reading.Done() + run.readOutput(stdout) }() - go run.readOutput(stdout) if len(req.Safeguards) > 0 { // Initialize the SDK before applying settings. Send the potentially @@ -2117,7 +2136,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) { pmu.Lock() defer pmu.Unlock() settle() - if err := s.Err(); err != nil { + if err := s.Err(); err != nil && !errors.Is(err, os.ErrClosed) { r.emit(Event{Kind: KError, Text: err.Error()}) } else if cut { failed("and Claude Code stopped") @@ -2795,11 +2814,34 @@ func (r *subscriptionRun) launch() error { r.mu.Unlock() go func() { _ = t.Wait() + r.drain() r.finish() }() return nil } +// outputDrain is how long the run's output is read once Claude Code has +// exited and its group been ended: a process that left the group may +// still hold the pipes, and is not waited for longer. +var outputDrain = 2 * time.Second + +// drain waits for what Claude Code wrote to be read, so its last lines +// reach the client before the run ends, then closes its pipes. +func (r *subscriptionRun) drain() { + read := make(chan struct{}) + go func() { + r.reading.Wait() + close(read) + }() + select { + case <-read: + case <-time.After(outputDrain): + } + for _, f := range r.outputs { + _ = f.Close() + } +} + func (r *subscriptionRun) abort() { r.mu.Lock() t := r.tree