fix(pi): isolate pooled worker tail calls, record image read receipts, and fallback polyglots

This commit is contained in:
Sycun 2026-11-29 23:44:22 +08:00
parent 5212870e9c
commit e7669f445d
6 changed files with 121 additions and 28 deletions

View File

@ -114,7 +114,7 @@ func (p Pi) Run(ctx context.Context, req Request, execute ToolExecutor, emit fun
}
res, runErr := w.run(ctx, req, execute, emit, bind)
w.runs++
if runErr == nil && ctx.Err() == nil && !w.writeFailed.Load() && w.runs < poolMaxRunsPerWorker {
if runErr == nil && ctx.Err() == nil && !w.writeFailed.Load() && len(w.incoming) == 0 && w.runs < poolMaxRunsPerWorker {
pool.release(node, workerPath, w)
} else {
w.destroy()

View File

@ -224,7 +224,12 @@ func CloseIdleWorkers() {
// worker returns to the pool; any cancel, timeout or protocol error destroys it.
func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, emit func(Event), bind func(Control) func()) (*Result, error) {
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
var toolWG sync.WaitGroup
var inFlightTools atomic.Int32
defer func() {
cancel()
toolWG.Wait()
}()
run := runRequest{Request: req, LegacyProfile: json.RawMessage(`{"enabled":false}`)}
if err := w.write(record{Type: "run", Version: ProtocolVersion, KeepAlive: true, Request: &run}); err != nil {
return nil, err
@ -272,7 +277,11 @@ func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, e
default:
return nil, errors.New("Pi tool concurrency limit exceeded")
}
toolWG.Add(1)
inFlightTools.Add(1)
go func() {
defer toolWG.Done()
defer inFlightTools.Add(-1)
defer func() { <-toolSlots }()
body, _ := json.Marshal(call)
toolMu.Lock()
@ -300,6 +309,9 @@ func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, e
case <-runCtx.Done():
return
}
if runCtx.Err() != nil {
return
}
res := cached.result
if cached.call != string(body) {
res = ToolResult{IsError: true, Content: "Tool call ID reused with different arguments"}
@ -319,6 +331,11 @@ func (w *piWorker) run(ctx context.Context, req Request, execute ToolExecutor, e
if r.Result.Status == "canceled" {
return r.Result, context.Canceled
}
if inFlightTools.Load() > 0 {
// A run that settled while sibling tool calls were still in flight cannot
// safely share its stdio stream with a subsequent run; mark it non-reusable.
w.writeFailed.Store(true)
}
return r.Result, nil
case "fatal":
return nil, fmt.Errorf("Pi protocol failure: %s", r.Error)

View File

@ -101,4 +101,40 @@ func TestPoolConcurrentRunsRaceFreeAndCloseReapsIdle(t *testing.T) {
if n := idleCount(); n != 0 {
t.Fatalf("CloseIdleWorkers left %d idle workers", n)
}
}
func TestPoolDiscardsWorkerWhenResultArrivesWithInFlightSiblingTool(t *testing.T) {
p := fixtureWorker(t, `let runCount=0;input.on('line',line=>{const r=JSON.parse(line);
if(r.type==='run'){
if(++runCount===1){
send({type:'tool_call',call:{id:'fast',name:'fast',arguments:{}}});
send({type:'tool_call',call:{id:'slow',name:'slow',arguments:{}}});
} else {
send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
}
}
if(r.type==='tool_result'&&r.id==='fast'){
send({type:'result',result:{status:'completed',response:String(process.pid),history:[]}});
}});`)
slowStarted := make(chan struct{})
first, err := p.Run(context.Background(), Request{RunID: "early-settle"}, func(c context.Context, call ToolCall) (ToolResult, error) {
if call.Name == "fast" {
<-slowStarted
return ToolResult{Content: "done"}, nil
}
close(slowStarted)
<-c.Done()
return ToolResult{}, c.Err()
}, nil, nil)
if err != nil {
t.Fatal(err)
}
second, err := p.Run(context.Background(), Request{RunID: "clean-followup"}, nil, nil, nil)
if err != nil {
t.Fatal(err)
}
if first.Response == "" || second.Response == "" || first.Response == second.Response {
t.Fatalf("expected tainted worker to be replaced, first=%q second=%q", first.Response, second.Response)
}
}

View File

@ -896,6 +896,7 @@ func (a *App) shutdown() {
if a.externalMCPMgr != nil {
a.externalMCPMgr.StopAll()
}
agentruntime.CloseIdleWorkers()
// 关闭知识库数据库连接(如果使用独立数据库)
if a.knowledgeDB != nil {

View File

@ -262,7 +262,11 @@ func (r *piRun) executePiLocal(ctx context.Context, call agentruntime.ToolCall)
return result, fmt.Errorf("not a regular file")
}
if img, ok, err := readPiLocalImage(path, f, st.Size()); ok {
return img, err
if err != nil {
return result, err
}
result = img
break
}
offset, limit := 1, 1000
if n, ok := call.Arguments["offset"].(float64); ok && n >= 1 {
@ -462,22 +466,29 @@ func lockPiFilePath(path string) func() {
func readPiCappedLine(r *bufio.Reader, cap int) (string, bool, error) {
var parts []byte
trunc := false
sawData := false
for {
frag, isPrefix, err := r.ReadLine()
if err != nil {
return "", false, err
}
if !trunc {
room := cap - len(parts)
if len(frag) <= room {
parts = append(parts, frag...)
} else {
if room > 0 {
parts = append(parts, frag[:room]...)
if len(frag) > 0 {
sawData = true
if !trunc {
room := cap - len(parts)
if len(frag) <= room {
parts = append(parts, frag...)
} else {
if room > 0 {
parts = append(parts, frag[:room]...)
}
trunc = true
}
trunc = true
}
}
if err != nil {
if err == io.EOF && sawData {
return string(parts), trunc, nil
}
return "", false, err
}
if !isPrefix {
return string(parts), trunc, nil
}
@ -499,20 +510,26 @@ func readPiLocalImage(path string, f *os.File, size int64) (agentruntime.ToolRes
if size > 10*1024*1024 {
return agentruntime.ToolResult{}, true, fmt.Errorf("image exceeds 10 MiB")
}
cfg, _, err := image.DecodeConfig(f)
if err != nil {
return agentruntime.ToolResult{}, true, fmt.Errorf("decode image: %w", err)
}
if _, err := f.Seek(0, io.SeekStart); err != nil {
return agentruntime.ToolResult{}, true, err
}
raw, err := io.ReadAll(io.LimitReader(f, 10*1024*1024+1))
if err != nil {
return agentruntime.ToolResult{}, true, err
}
// Polyglot payloads (e.g. GIF89a followed by PHP/text) sniff as image/*;
// verify full image decoding and fall back to text when there are no NUL bytes.
decoded, _, decErr := image.Decode(bytes.NewReader(raw))
if decErr != nil {
if bytes.IndexByte(raw, 0) < 0 {
if _, seekErr := f.Seek(0, io.SeekStart); seekErr != nil {
return agentruntime.ToolResult{}, true, seekErr
}
return agentruntime.ToolResult{}, false, nil
}
return agentruntime.ToolResult{}, true, fmt.Errorf("decode image: %w", decErr)
}
bounds := decoded.Bounds()
out, outMIME := raw, mime
if len(raw) > 4*1024*1024 || cfg.Width > 4096 || cfg.Height > 4096 {
compressed, err := compressPiImage(raw)
if len(raw) > 4*1024*1024 || bounds.Dx() > 4096 || bounds.Dy() > 4096 {
compressed, err := compressPiDecodedImage(decoded)
if err != nil {
return agentruntime.ToolResult{}, true, err
}
@ -524,11 +541,7 @@ func readPiLocalImage(path string, f *os.File, size int64) (agentruntime.ToolRes
}, true, nil
}
func compressPiImage(raw []byte) ([]byte, error) {
src, err := imaging.Decode(bytes.NewReader(raw))
if err != nil {
return nil, err
}
func compressPiDecodedImage(src image.Image) ([]byte, error) {
dim := 2048
dst := imaging.Fit(src, dim, dim, imaging.Lanczos)
for attempt := 0; attempt < 6; attempt++ {

View File

@ -56,6 +56,9 @@ func TestPiReadFileReturnsImageForVisionModels(t *testing.T) {
if !strings.Contains(res.Content, "[Image ") || !strings.Contains(res.Content, "image/png") {
t.Fatalf("content summary missing: %q", res.Content)
}
if strings.TrimSpace(res.ExecutionID) == "" {
t.Fatalf("image read_file skipped local execution receipt: %+v", res)
}
fake := filepath.Join(dir, "fake.png")
if err := os.WriteFile(fake, []byte("just text, not an image"), 0o600); err != nil {
@ -65,6 +68,19 @@ func TestPiReadFileReturnsImageForVisionModels(t *testing.T) {
if len(textRes.Images) != 0 || textRes.Content != "just text, not an image" {
t.Fatalf("disguised text must read as text: %+v", textRes)
}
// GIF89a polyglot payloads sniff as image/gif via magic bytes and must fall back to text.
polyglotBody := "GIF89a; <?php echo 'polyglot-check'; ?>"
for _, ext := range []string{".php", ".gif"} {
poly := filepath.Join(dir, "sample"+ext)
if err := os.WriteFile(poly, []byte(polyglotBody), 0o600); err != nil {
t.Fatal(err)
}
polyRes := callLocal(t, r, "read_file", map[string]any{"path": poly})
if len(polyRes.Images) != 0 || polyRes.Content != polyglotBody {
t.Fatalf("GIF89a polyglot (%s) did not fall back to text: %+v", ext, polyRes)
}
}
}
func TestPiReadFileStreamsLargeLogWithOffsetAndTruncatesLongLine(t *testing.T) {
@ -98,6 +114,16 @@ func TestPiReadFileStreamsLargeLogWithOffsetAndTruncatesLongLine(t *testing.T) {
if strings.Contains(res.Content, strings.Repeat("x", 5000)) {
t.Fatal("full long line leaked into output")
}
// Over-buffer (>64 KiB) final line without a trailing newline must not be dropped at EOF.
noNL := filepath.Join(dir, "no-trailing-newline.txt")
if err := os.WriteFile(noNL, []byte(strings.Repeat("Q", 64*1024)), 0o600); err != nil {
t.Fatal(err)
}
eofRes := callLocal(t, r, "read_file", map[string]any{"path": noNL})
if !strings.HasPrefix(eofRes.Content, strings.Repeat("Q", 4096)+" [line truncated]") {
t.Fatalf("64 KiB line without newline lost at EOF: len=%d", len(eofRes.Content))
}
}
func TestPiWriteFileCreatesParentsAndEditFilePreservesCRLFAndBatches(t *testing.T) {