fix(builtin): bound read/edit filesystem work by DefaultToolTimeout

WIRE: read and edit each declared a DefaultToolTimeout deadline and then
discarded it, so the documented contract (Tools that exceed this are
cancelled) was a no-op on the live tool-executor path. Wire the deadline
through runWithContext, the same helper write already uses, so a hung
filesystem cannot block the tool executor.
This commit is contained in:
sam committed 2026-09-15 13:12:21 +10:00
1 parent d0395cebd5
commit bf7eb16bc4
4 files changed
+156 -67

No files matched your search

+72 -53
View File
@@ -131,9 +131,6 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor {
return Result{Content: "at least one edit is required", IsError: true}, nil
}
_, cancel := context.WithTimeout(ctx, DefaultToolTimeout)
defer cancel()
path := resolvePath(cwd, p.Path)
if !isConfined(cwd, path) {
@@ -147,63 +144,85 @@ func makeEditExecutor(cwd string, mq *MutationQueue, rt *ReadTracker) Executor {
}
}
// Check file size before reading to avoid OOM on large files.
info, err := os.Stat(path)
editCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout)
defer cancel()
var result Result
err = runWithContext(editCtx, func() error {
result = performEdit(path, p, mq)
return nil
})
if err != nil {
return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true}, nil
}
if info.Size() > maxReadBytes {
return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}, nil
}
release := mq.Acquire(path)
defer release()
data, err := os.ReadFile(path)
if err != nil {
return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}, nil
}
// Strip a UTF-8 BOM and normalise CRLF to LF before matching - the
// model never includes an invisible BOM or carriage returns in
// old_text. Both are restored on write.
raw := string(data)
bom := ""
if strings.HasPrefix(raw, utf8BOM) {
bom = utf8BOM
raw = strings.TrimPrefix(raw, utf8BOM)
}
hadCRLF := strings.Contains(raw, "\r\n")
content := strings.ReplaceAll(raw, "\r\n", "\n")
newContent, err := applyEdits(content, p.Edits)
if err != nil {
errorKind := "invalid_arguments"
if strings.Contains(err.Error(), "old_text not found") {
errorKind = "stale_edit"
if errors.Is(err, context.DeadlineExceeded) {
return Result{Content: fmt.Sprintf("edit timed out after %v", DefaultToolTimeout), IsError: true}, nil
}
return Result{
Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying",
IsError: true,
ErrorKind: errorKind,
}, nil
}
if newContent == content {
return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true}, nil
return Result{Content: fmt.Sprintf("edit failed: %v", err), IsError: true}, nil
}
if hadCRLF {
newContent = strings.ReplaceAll(newContent, "\n", "\r\n")
}
return result, nil
}
}
if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil {
return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true}, nil
}
// performEdit loads, mutates, and writes path according to the edits in p.
// Every failure is returned as a Result with IsError set, never a non-nil
// error, so the executor keeps a single error envelope.
func performEdit(path string, p EditParams, mq *MutationQueue) Result {
// Check file size before reading to avoid OOM on large files.
info, err := os.Stat(path)
if err != nil {
return Result{Content: fmt.Sprintf("error stating file: %v", err), IsError: true}
}
if info.Size() > maxReadBytes {
return Result{Content: fmt.Sprintf("file too large to edit (%s > %s)", FormatSize(int(info.Size())), FormatSize(maxReadBytes)), IsError: true}
}
release := mq.Acquire(path)
defer release()
data, err := os.ReadFile(path)
if err != nil {
return Result{Content: fmt.Sprintf("error reading file: %v", err), IsError: true}
}
// Strip a UTF-8 BOM and normalise CRLF to LF before matching - the
// model never includes an invisible BOM or carriage returns in
// old_text. Both are restored on write.
raw := string(data)
bom := ""
if strings.HasPrefix(raw, utf8BOM) {
bom = utf8BOM
raw = strings.TrimPrefix(raw, utf8BOM)
}
hadCRLF := strings.Contains(raw, "\r\n")
content := strings.ReplaceAll(raw, "\r\n", "\n")
newContent, err := applyEdits(content, p.Edits)
if err != nil {
errorKind := "invalid_arguments"
if strings.Contains(err.Error(), "old_text not found") {
errorKind = "stale_edit"
}
return Result{
Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path),
Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent},
}, nil
Content: err.Error() + "; no edits were written; reread the smallest affected range before retrying",
IsError: true,
ErrorKind: errorKind,
}
}
if newContent == content {
return Result{Content: fmt.Sprintf("no changes made to %s: the edits produced identical content", path), IsError: true}
}
if hadCRLF {
newContent = strings.ReplaceAll(newContent, "\n", "\r\n")
}
if err := writeFileAtomic(path, []byte(bom+newContent), 0o644); err != nil {
return Result{Content: fmt.Sprintf("error writing file: %v", err), IsError: true}
}
return Result{
Content: fmt.Sprintf("applied %d edit(s) to %s", len(p.Edits), path),
Details: DiffDetails{Path: path, OldContent: content, NewContent: newContent},
}
}
+34
View File
@@ -7,6 +7,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
func TestApplyEdits(t *testing.T) {
@@ -329,3 +330,36 @@ func TestEdit_NotFoundWithNoPlausibleMatchStaysGeneric(t *testing.T) {
t.Fatalf("expected the generic error, got:\n%s", res.Content)
}
}
// TestEditToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout
// contract: when the caller's context is already expired, edit must not
// ignore that deadline and mutate the file anyway.
func TestEditToolHonoursDeadlineOnExpiredContext(t *testing.T) {
tmp := t.TempDir()
path := filepath.Join(tmp, "f.txt")
if err := os.WriteFile(path, []byte("hello\n"), 0o644); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
tool := NewEditTool(tmp, NewMutationQueue(), nil)
res, err := tool.Execute(ctx, json.RawMessage(
`{"path":"f.txt","edits":[{"old_text":"hello","new_text":"hi"}]}`,
), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !res.IsError {
t.Fatalf("edit on an expired context must not succeed; got content %q", res.Content)
}
after, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
if string(after) != "hello\n" {
t.Fatalf("file was mutated despite the expired context: %q", after)
}
}
+29 -14
View File
@@ -15,6 +15,7 @@ package builtin
import (
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
@@ -222,28 +223,42 @@ func makeReadExecutor(cwd string, rt *ReadTracker) Executor {
return *terminal, nil
}
_, cancel := context.WithTimeout(ctx, DefaultToolTimeout)
defer cancel()
path := resolvePath(cwd, p.Path)
if !isReadConfined(cwd, path) {
return Result{Content: "path escapes working directory", IsError: true, ErrorKind: "sandbox_escape"}, nil
}
info, err := os.Stat(path)
if err != nil {
msg := fmt.Sprintf("error stating file: %v", err)
if hint := suggestPaths(cwd, path); hint != "" {
msg += "\n" + hint
readCtx, cancel := context.WithTimeout(ctx, DefaultToolTimeout)
defer cancel()
var result Result
err = runWithContext(readCtx, func() error {
info, statErr := os.Stat(path)
if statErr != nil {
msg := fmt.Sprintf("error stating file: %v", statErr)
if hint := suggestPaths(cwd, path); hint != "" {
msg += "\n" + hint
}
result = Result{Content: msg, IsError: true, ErrorKind: "not_found"}
return nil
}
return Result{Content: msg, IsError: true, ErrorKind: "not_found"}, nil
state, terminal := readFileContent(cwd, path, p, info, rt)
if terminal != nil {
result = *terminal
return nil
}
result = serveReadContent(cwd, path, p, info, state, rt)
return nil
})
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
return Result{Content: fmt.Sprintf("read timed out after %v", DefaultToolTimeout), IsError: true}, nil
}
return Result{Content: fmt.Sprintf("read failed: %v", err), IsError: true}, nil
}
state, terminal := readFileContent(cwd, path, p, info, rt)
if terminal != nil {
return *terminal, nil
}
return serveReadContent(cwd, path, p, info, state, rt), nil
return result, nil
}
}
+21
View File
@@ -8,6 +8,7 @@ import (
"path/filepath"
"strings"
"testing"
"time"
)
func execRead(t *testing.T, cwd, params string) Result {
@@ -210,3 +211,23 @@ func TestReadTool_NotFoundListsExistingParentDir(t *testing.T) {
t.Fatalf("expected the existing directory to be listed, got:\n%s", res.Content)
}
}
// TestReadToolHonoursDeadlineOnExpiredContext pins the DefaultToolTimeout
// contract: when the caller's context is already expired, read must not
// ignore that deadline and read the file anyway.
func TestReadToolHonoursDeadlineOnExpiredContext(t *testing.T) {
tmp := t.TempDir()
writeReadTestFile(t, tmp, "f.txt", "alpha\nbeta\n")
ctx, cancel := context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
defer cancel()
tool := NewReadTool(tmp, nil)
res, err := tool.Execute(ctx, json.RawMessage(`{"path":"f.txt"}`), nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !res.IsError {
t.Fatalf("read on an expired context must not succeed; got content %q", res.Content)
}
}