perf(runtime): track spilled tool-call IDs to skip re-writing spills each turn (P1)
This commit is contained in:
1 parent
671c10e89a
commit
c710ea5a94
3 files changed
+73
-14
No files matched your search
+32
-7
@@ -246,7 +246,7 @@ func TestPruneToolResults(t *testing.T) {
|
||||
}
|
||||
|
||||
// Empty spillConfig → legacy in-place truncation path.
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// User message should be unchanged
|
||||
assert.Equal(t, "hello", msgs[0].Content)
|
||||
@@ -261,7 +261,7 @@ func TestPruneToolResultsShort(t *testing.T) {
|
||||
{Role: "user", Content: "short output", ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
assert.Equal(t, "short output", msgs[0].Content)
|
||||
}
|
||||
@@ -279,7 +279,7 @@ func TestPruneToolResultsNewlineBoundary(t *testing.T) {
|
||||
{Role: "user", Content: content, ToolCallID: "tc_1"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{})
|
||||
pruneToolResults(msgs, 10000, spillConfig{}, nil)
|
||||
|
||||
// Should be truncated and contain the truncation marker
|
||||
truncated := msgs[0].Content
|
||||
@@ -298,7 +298,7 @@ func TestPruneToolResultsSpillsToDisk(t *testing.T) {
|
||||
{Role: "user", Content: original, ToolCallID: "tc_42"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_abc"}, nil)
|
||||
|
||||
// Message rewritten to head + spill marker pointing at the file.
|
||||
got := msgs[0].Content
|
||||
@@ -324,14 +324,14 @@ func TestPruneToolResultsIdempotentAfterSpill(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("b", 20000), ToolCallID: "tc_99"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
afterFirst := msgs[0].Content
|
||||
require.Contains(t, afterFirst, spillMarker)
|
||||
|
||||
// Second call: marker is present, so the message must be untouched.
|
||||
// Mutating it (e.g. spilling again or appending another marker)
|
||||
// would silently grow the prefill across turns and burn cache.
|
||||
pruneToolResults(msgs, 10000, cfg)
|
||||
pruneToolResults(msgs, 10000, cfg, nil)
|
||||
assert.Equal(t, afterFirst, msgs[0].Content)
|
||||
}
|
||||
|
||||
@@ -349,7 +349,7 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
{Role: "user", Content: strings.Repeat("c", 20000), ToolCallID: "tc_fail"},
|
||||
}
|
||||
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"})
|
||||
pruneToolResults(msgs, 10000, spillConfig{Workspace: workspace, SessionKey: "sess_fail"}, nil)
|
||||
|
||||
got := msgs[0].Content
|
||||
assert.Less(t, len(got), 20000, "fallback must still bound the message")
|
||||
@@ -357,6 +357,31 @@ func TestPruneToolResultsFallsBackToTruncationWhenSpillFails(t *testing.T) {
|
||||
assert.NotContains(t, got, spillMarker, "spilled marker must not appear when write failed")
|
||||
}
|
||||
|
||||
func TestPruneToolResultsSpillsOncePerID(t *testing.T) {
|
||||
workspace := t.TempDir()
|
||||
cfg := spillConfig{Workspace: workspace, SessionKey: "sess_once"}
|
||||
spilled := map[string]bool{}
|
||||
|
||||
big := strings.Repeat("x", 50000)
|
||||
mk := func() []llm.Message {
|
||||
return []llm.Message{{ToolCallID: "call_big", Content: big}}
|
||||
}
|
||||
|
||||
m1 := mk()
|
||||
pruneToolResults(m1, 10000, cfg, spilled)
|
||||
require.Contains(t, m1[0].Content, spillMarker)
|
||||
spillPath := filepath.Join(workspace, ".harness", "spill", "sess_once", "call_big.txt")
|
||||
require.FileExists(t, spillPath)
|
||||
require.True(t, spilled["call_big"], "ID recorded as spilled")
|
||||
|
||||
require.NoError(t, os.Remove(spillPath))
|
||||
|
||||
m2 := mk()
|
||||
pruneToolResults(m2, 10000, cfg, spilled)
|
||||
require.Contains(t, m2[0].Content, spillMarker, "message still rewritten to the marker")
|
||||
require.NoFileExists(t, spillPath, "turn 2 must NOT re-write the spill file (idempotent via spilled set)")
|
||||
}
|
||||
|
||||
// --- Runtime tests ---
|
||||
|
||||
func TestRuntimeRun(t *testing.T) {
|
||||
|
||||
+16
-2
@@ -447,7 +447,7 @@ func spillToolResult(cfg spillConfig, toolCallID, content string) (string, error
|
||||
// nearest newline boundary — most tool outputs (file reads, command
|
||||
// output) are front-loaded with the most relevant info, so the head
|
||||
// preview is usually enough on its own.
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig, spilled map[string]bool) {
|
||||
for i := range msgs {
|
||||
if msgs[i].ToolCallID == "" || len(msgs[i].Content) <= maxLen {
|
||||
continue
|
||||
@@ -467,11 +467,25 @@ func pruneToolResults(msgs []llm.Message, maxLen int, cfg spillConfig) {
|
||||
// Try spill first if configured. On any failure, fall through to
|
||||
// legacy truncation so the prefill stays bounded either way.
|
||||
if cfg.Workspace != "" && cfg.SessionKey != "" {
|
||||
if path, err := spillToolResult(cfg, msgs[i].ToolCallID, msgs[i].Content); err == nil {
|
||||
id := msgs[i].ToolCallID
|
||||
// Spill content is immutable per ToolCallID and lands at a
|
||||
// deterministic path. If this Run already spilled this ID,
|
||||
// skip the (multi-MB) disk re-write and just rebuild the
|
||||
// in-memory marker pointing at the same path.
|
||||
if spilled != nil && spilled[id] {
|
||||
path := filepath.Join(cfg.Workspace, ".harness", "spill", cfg.SessionKey, id+".txt")
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, path)
|
||||
continue
|
||||
}
|
||||
if writtenPath, err := spillToolResult(cfg, id, msgs[i].Content); err == nil {
|
||||
if spilled != nil {
|
||||
spilled[id] = true
|
||||
}
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars saved to %s; use read_file to access the full output]",
|
||||
head, spillMarker, len(head), originalLen, writtenPath)
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
msgs[i].Content = fmt.Sprintf("%s\n\n%s%d of %d chars; re-run the tool with offset/limit to see more]",
|
||||
|
||||
+25
-5
@@ -105,6 +105,14 @@ type Runtime struct {
|
||||
touchedMu sync.Mutex
|
||||
touchedFiles []string
|
||||
|
||||
// spilledIDs records ToolCallIDs whose oversized results have already
|
||||
// been written to the deterministic spill path during this Runtime's
|
||||
// lifetime. Content is immutable per ToolCallID, so once spilled we
|
||||
// skip the (multi-MB) disk re-write on subsequent turns and only
|
||||
// rebuild the in-memory marker.
|
||||
spilledMu sync.Mutex
|
||||
spilledIDs map[string]bool
|
||||
|
||||
// IngestSource controls whether this run's thread is ingested into the KG.
|
||||
// "chat" (or empty) ingests; any other value skips ingest.
|
||||
IngestSource string
|
||||
@@ -241,6 +249,18 @@ func (r *Runtime) snapshotTouchedFiles() []string {
|
||||
return out
|
||||
}
|
||||
|
||||
// prune shortens oversized tool results in msgs, spilling to disk where
|
||||
// configured. It carries the Runtime's per-Run spilled-ID set so a result
|
||||
// already spilled this Run is not re-written to disk on subsequent turns.
|
||||
func (r *Runtime) prune(msgs []llm.Message, spillCfg spillConfig) {
|
||||
r.spilledMu.Lock()
|
||||
if r.spilledIDs == nil {
|
||||
r.spilledIDs = map[string]bool{}
|
||||
}
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg, r.spilledIDs)
|
||||
r.spilledMu.Unlock()
|
||||
}
|
||||
|
||||
// isFileTool reports whether a tool name's input contains a "path" field.
|
||||
func isFileTool(name string) bool {
|
||||
switch name {
|
||||
@@ -412,7 +432,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
msgs := assembleMessages(history)
|
||||
|
||||
spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key}
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
|
||||
tr.Mark("context.assemble", "turn", turn, "msgs", len(msgs), "tools", len(toolDefs), "sysprompt_chars", len(staticText)+len(dynamicSuffix), "dur_ms_local", time.Since(phaseStart).Milliseconds())
|
||||
|
||||
@@ -423,7 +443,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
}
|
||||
}
|
||||
@@ -457,7 +477,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
} else {
|
||||
r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res})
|
||||
@@ -490,7 +510,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history = r.Session.View()
|
||||
msgs = assembleMessages(history)
|
||||
pruneToolResults(msgs, r.maxToolResultLen(), spillCfg)
|
||||
r.prune(msgs, spillCfg)
|
||||
msgs = prependPostCompactRestore(msgs, r.snapshotTouchedFiles())
|
||||
req.Messages = msgs
|
||||
stream, err = r.LLM.ChatStream(ctx, req)
|
||||
@@ -800,7 +820,7 @@ func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *
|
||||
r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res})
|
||||
history := r.Session.View()
|
||||
newMsgs := assembleMessages(history)
|
||||
pruneToolResults(newMsgs, r.maxToolResultLen(), spillCfg)
|
||||
r.prune(newMsgs, spillCfg)
|
||||
newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles())
|
||||
*msgs = newMsgs
|
||||
req.Messages = newMsgs
|
||||
|
||||
Reference in new issue
Block a user