fix(pi): distinguish protocol read errors from EOF

This commit is contained in:
Sycun committed 2026-11-24 09:27:43 +08:00
1 parent 3cb81999fc
commit 6c0cd29dcf
2 files changed
+58 -8

No files matched your search

+18 -6
View File
@@ -2,6 +2,7 @@ package agentruntime
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
@@ -156,10 +157,15 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
go func() {
scanner := bufio.NewScanner(stdout)
scanner.Buffer(make([]byte, 64*1024), maxRecordBytes+1)
for scanner.Scan() {
for line := 1; scanner.Scan(); line++ {
data := scanner.Bytes()
var r record
if err := json.Unmarshal(scanner.Bytes(), &r); err != nil {
readDone <- fmt.Errorf("invalid Pi protocol JSON: %w", err)
if err := json.Unmarshal(data, &r); err != nil {
if len(bytes.TrimSpace(data)) == 0 {
readDone <- fmt.Errorf("blank Pi protocol line %d", line)
} else {
readDone <- fmt.Errorf("invalid Pi protocol JSON on line %d: %w", line, err)
}
return
}
select {
@@ -187,7 +193,10 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
return nil, errors.New("Pi runtime protocol mismatch")
}
case err := <-readDone:
return nil, fmt.Errorf("Pi worker exited before handshake: %v", err)
if err != nil {
return nil, fmt.Errorf("read Pi worker handshake: %w", err)
}
return nil, errors.New("Pi worker closed stdout before handshake")
case <-readyTimeout.C:
return nil, errors.New("Pi worker startup timeout")
case <-ctx.Done():
@@ -295,12 +304,15 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
return nil, fmt.Errorf("unexpected Pi record: %s", r.Type)
}
case err := <-readDone:
// All queued protocol records precede EOF; process them before interpreting exit.
// Drain records queued before the reader reported EOF or an error.
if len(incoming) > 0 {
readDone <- err
continue
}
return nil, fmt.Errorf("Pi worker exited without a result: %v", err)
if err != nil {
return nil, fmt.Errorf("read Pi worker output: %w", err)
}
return nil, errors.New("Pi worker closed stdout without a result")
case <-ctxDone:
ctxDone = nil
_ = write(map[string]any{"type": "cancel"})
+40 -2
View File
@@ -2,6 +2,7 @@ package agentruntime
import (
"context"
"encoding/json"
"errors"
"os"
"os/exec"
@@ -98,12 +99,49 @@ if(r.type==='cancel')send({type:'result',result:{status:'canceled',response:'par
}
}
func TestPiReportsProtocolFailures(t *testing.T) {
for _, tt := range []struct {
name string
write string
want string
wantSyntax bool
}{
{
name: "blank line",
write: "process.stdout.write(' \\t\\n');",
want: "read Pi worker output: blank Pi protocol line 2",
},
{
name: "partial JSON at EOF",
write: "process.stdout.write('{\"type\":', () => process.exit(0));",
want: "read Pi worker output: invalid Pi protocol JSON on line 2: unexpected end of JSON input",
wantSyntax: true,
},
} {
t.Run(tt.name, func(t *testing.T) {
p := fixtureWorker(t, "input.once('line', () => {"+tt.write+"});")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
result, err := p.Run(ctx, Request{}, nil, nil, nil)
if result != nil || err == nil || err.Error() != tt.want {
t.Fatalf("got result=%+v, err=%v, want %q", result, err, tt.want)
}
var syntaxErr *json.SyntaxError
if errors.As(err, &syntaxErr) != tt.wantSyntax {
t.Fatalf("got syntax error %v, want syntax error: %t", syntaxErr, tt.wantSyntax)
}
})
}
}
func TestPiUnexpectedExitIsNotSuccess(t *testing.T) {
p := fixtureWorker(t, `input.on('line',()=>process.exit(0));`)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if _, err := p.Run(ctx, Request{}, nil, nil, nil); err == nil {
t.Fatal("worker exit without final result was accepted")
result, err := p.Run(ctx, Request{}, nil, nil, nil)
if result != nil || err == nil || err.Error() != "Pi worker closed stdout without a result" {
t.Fatalf("got result=%+v, err=%v, want EOF without a result", result, err)
}
}