diff --git a/runtime/agent_test.go b/runtime/agent_test.go index cdccbd9..61d4d64 100644 --- a/runtime/agent_test.go +++ b/runtime/agent_test.go @@ -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) { diff --git a/runtime/calibrator_persist_test.go b/runtime/calibrator_persist_test.go new file mode 100644 index 0000000..5fd2c46 --- /dev/null +++ b/runtime/calibrator_persist_test.go @@ -0,0 +1,58 @@ +package runtime + +import ( + "context" + "testing" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/llm/llmtest" + "github.com/sausheong/harness/session" + "github.com/sausheong/harness/tokens" + "github.com/sausheong/harness/tool" + "github.com/stretchr/testify/require" +) + +// usageDoneProvider emits a usage-bearing EventDone so the agent loop can +// populate (and persist) the per-session token calibrator. +type usageDoneProvider struct { + llmtest.Base +} + +func (p *usageDoneProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) { + ch := make(chan llm.ChatEvent, 4) + ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "answer"} + ch <- llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 1000, OutputTokens: 10}} + close(ch) + return ch, nil +} + +// TestCalibratorPersistsByEndOfRun guards that the per-session calibrator is +// persisted to the CalibratorStore by the time Run completes. After the P8 +// debounce change the Save moves from per-round to a single deferred flush at +// Run end; this test asserts the observable end state (persisted) is unchanged. +func TestCalibratorPersistsByEndOfRun(t *testing.T) { + dir := t.TempDir() + store := tokens.NewCalibratorStore(dir) + rt := &Runtime{ + LLM: &usageDoneProvider{}, + Tools: tool.NewRegistry(), + Session: session.NewSession("a", "k"), + AgentID: "a", + Model: "claude-sonnet-4-5", + // Compaction must be non-nil for the runtime to lazily create the + // per-session calibrator (the calibrator-creation path is gated on + // it). MessageCap/threshold left at defaults so no compaction fires + // during this short run. + Compaction: newCompactionMgr(), + Provider: "anthropic", + MaxTurns: 2, + Workspace: t.TempDir(), + CalibratorStore: store, + } + _, err := rt.RunSync(context.Background(), "go", nil) + require.NoError(t, err) + + ratio, count := tokens.NewCalibratorStore(dir).Load("a", "k") + require.Greater(t, count, 0, "calibrator must be persisted by end of Run") + require.Greater(t, ratio, 0.0) +} diff --git a/runtime/context.go b/runtime/context.go index b2acad5..14ac14e 100644 --- a/runtime/context.go +++ b/runtime/context.go @@ -168,17 +168,6 @@ func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string { // corresponding tool_result in the next user message. Orphaned tool calls // (e.g. from interrupted sessions) get synthetic error results injected. func assembleMessages(history []session.SessionEntry) []llm.Message { - // First pass: collect tool result IDs so we can detect orphaned tool calls. - resultIDs := make(map[string]bool) - for _, entry := range history { - if entry.Type == session.EntryTypeToolResult { - var tr session.ToolResultData - if err := json.Unmarshal(entry.Data, &tr); err == nil { - resultIDs[tr.ToolCallID] = true - } - } - } - var msgs []llm.Message for _, entry := range history { @@ -219,9 +208,6 @@ func assembleMessages(history []session.SessionEntry) []llm.Message { if err := json.Unmarshal(entry.Data, &md); err != nil { continue } - // Before appending a new message, check if the last assistant - // message has orphaned tool calls that need synthetic results. - msgs = injectMissingToolResults(msgs) msg := llm.Message{ Role: entry.Role, Content: md.Text, @@ -461,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 @@ -481,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]", diff --git a/runtime/context_test.go b/runtime/context_test.go index 84ad8ab..8adba21 100644 --- a/runtime/context_test.go +++ b/runtime/context_test.go @@ -1,12 +1,14 @@ package runtime import ( + jsonpkg "encoding/json" "os" "path/filepath" "strings" "testing" "time" + "github.com/sausheong/harness/session" "github.com/stretchr/testify/require" ) @@ -123,3 +125,28 @@ func TestFormatDateLine(t *testing.T) { }) } } + +func mustJSON(t *testing.T, v any) jsonpkg.RawMessage { + t.Helper() + b, err := jsonpkg.Marshal(v) + require.NoError(t, err) + return b +} + +func TestAssembleMessagesInjectsOrphanedToolResult(t *testing.T) { + history := []session.SessionEntry{ + {Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "hi"})}, + {Type: session.EntryTypeToolCall, Role: "assistant", Data: mustJSON(t, session.ToolCallData{ + ID: "call_1", Tool: "bash", Input: jsonpkg.RawMessage(`{}`), + })}, + {Type: session.EntryTypeMessage, Role: "user", Data: mustJSON(t, session.MessageData{Text: "still there?"})}, + } + msgs := assembleMessages(history) + var found bool + for _, m := range msgs { + if m.ToolCallID == "call_1" { + found = true + } + } + require.True(t, found, "orphaned tool call must get a synthetic tool result from the terminal pass") +} diff --git a/runtime/runtime.go b/runtime/runtime.go index d7645e1..25b7379 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -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 @@ -114,6 +122,12 @@ type Runtime struct { calibrator *tokens.Calibrator + // calibratorDirty records that the calibrator was updated during this + // Run and must be flushed to CalibratorStore once at Run end. Accessed + // only on the Run goroutine (EventDone handling + deferred flush), so no + // lock is needed. + calibratorDirty bool + // mcpClients holds the MCP client sessions resolved from // AgentSpec.MCPServers. Released by Close. Untouched when MCP is // not used. @@ -235,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 { @@ -254,6 +280,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon defer close(r.events) defer tr.Summary() + // Flush the per-session calibrator once at Run end (all exit paths: + // normal, error, abort) instead of writing to disk on every LLM + // round. EventDone sets calibratorDirty when it folds in a usage + // sample; this defer persists the final state. Registered here so it + // runs regardless of which return below fires. + defer func() { + if r.calibratorDirty && r.CalibratorStore != nil && r.Session != nil && r.calibrator != nil { + ratio, count := r.calibrator.Snapshot() + r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count) + } + }() + // stopReason is read by the OnStop deferred hook below. Each early // return path reassigns it before returning. Default is "max_turns" // so the natural fall-through (loop exhausted MaxTurns) records the @@ -338,6 +376,24 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon // Computed once per Run so the date stays stable across turns. dateLine := FormatDateLine(time.Now()) + // Tool defs are invariant for the whole Run (tools and permission don't + // change mid-Run), so normalize once instead of per turn (P3). + toolDefs := r.Tools.ToolDefs() + if r.Permission != nil { + toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID) + } + sort.SliceStable(toolDefs, func(i, j int) bool { + return toolDefs[i].Name < toolDefs[j].Name + }) + toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs) + for _, d := range diags { + slog.Info("tool schema normalized", + "tool", d.ToolName, + "field", d.Field, + "action", d.Action, + "reason", d.Reason) + } + for turn := 0; turn < maxTurns; turn++ { if ctx.Err() != nil { stopReason = "aborted" @@ -376,23 +432,8 @@ 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) - toolDefs := r.Tools.ToolDefs() - if r.Permission != nil { - toolDefs = r.Permission.FilterToolDefs(toolDefs, r.AgentID) - } - sort.SliceStable(toolDefs, func(i, j int) bool { - return toolDefs[i].Name < toolDefs[j].Name - }) - toolDefs, diags := r.LLM.NormalizeToolSchema(toolDefs) - for _, d := range diags { - slog.Info("tool schema normalized", - "tool", d.ToolName, - "field", d.Field, - "action", d.Action, - "reason", d.Reason) - } 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()) // Wait briefly on any in-flight async compaction kicked off by @@ -402,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()) } } @@ -428,7 +469,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}) @@ -461,7 +502,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) @@ -549,11 +590,14 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon lastUsage = event.Usage } if event.Usage != nil && r.calibrator != nil { + // Recompute the estimate on the CURRENT msgs (which may + // have been reassembled by mid-turn compaction) so the + // calibration ratio matches event.Usage.InputTokens, as + // the pre-debounce code did. The P8 change only debounces + // the disk write (calibratorDirty + deferred flush), not + // the estimate computation. r.calibrator.Update(event.Usage.InputTokens, tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs)) - if r.CalibratorStore != nil && r.Session != nil { - ratio, count := r.calibrator.Snapshot() - r.CalibratorStore.Save(r.AgentID, r.Session.Key, ratio, count) - } + r.calibratorDirty = true } case llm.EventError: @@ -770,7 +814,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 diff --git a/session/session.go b/session/session.go index 01e1fb9..db2737c 100644 --- a/session/session.go +++ b/session/session.go @@ -85,6 +85,12 @@ type Session struct { entryMap map[string]*SessionEntry leafID string // current leaf for history traversal store *Store + + // writeMu serializes store writes and preserves their order. Acquired in + // Append while s.mu is still held (lock-coupling), then s.mu is released + // before the disk write — so disk latency stays off s.mu while on-disk + // order still matches in-memory append order under concurrent callers. (P5) + writeMu sync.Mutex } // NewSession creates a new empty session. @@ -100,7 +106,6 @@ func NewSession(agentID, key string) *Session { // Append adds an entry to the session. func (s *Session) Append(entry SessionEntry) { s.mu.Lock() - defer s.mu.Unlock() if entry.ID == "" { entry.ID = generateID("e") } @@ -115,9 +120,19 @@ func (s *Session) Append(entry SessionEntry) { s.entryMap[entry.ID] = &s.entries[len(s.entries)-1] s.leafID = entry.ID - // Persist if store is set - if s.store != nil { - s.store.AppendEntry(s, entry) + finalized := entry // value copy with all fields set + store := s.store + + // Lock-coupling: take writeMu BEFORE releasing s.mu so the disk-write + // order matches the in-memory append order even under concurrent callers, + // then release s.mu so disk latency doesn't block concurrent View()/append. + if store != nil { + s.writeMu.Lock() + s.mu.Unlock() + store.AppendEntry(s, finalized) + s.writeMu.Unlock() + } else { + s.mu.Unlock() } } diff --git a/session/session_test.go b/session/session_test.go index 4817669..feea48d 100644 --- a/session/session_test.go +++ b/session/session_test.go @@ -350,3 +350,60 @@ func TestSession_ViewReturnsCopy(t *testing.T) { require.Len(t, v2, 1) require.Equal(t, "e_1", v2[0].ID, "internal state must not be mutated by caller's slice modification") } + +func TestConcurrentAppendAndViewNoRace(t *testing.T) { + dir := t.TempDir() + store := NewStore(dir) + require.NoError(t, store.Create("a", "k")) + sess := NewSession("a", "k") + sess.SetStore(store) + + var wg sync.WaitGroup + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 500; i++ { + sess.Append(SessionEntry{Type: EntryTypeMessage, Role: "user", Data: []byte(`{"text":"x"}`)}) + } + }() + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < 500; i++ { + _ = sess.View() + } + }() + wg.Wait() + + require.Len(t, sess.Entries(), 500) +} + +// TestAppendPreservesDiskOrder verifies that the P5 lock-coupling keeps the +// on-disk JSONL order identical to the in-memory append order: sequential +// appends must persist in order, and reloading from disk must round-trip them +// in the same sequence. +func TestAppendPreservesDiskOrder(t *testing.T) { + dir := t.TempDir() + store := NewStore(dir) + require.NoError(t, store.Create("a", "k")) + sess := NewSession("a", "k") + sess.SetStore(store) + + const n = 200 + for i := 0; i < n; i++ { + sess.Append(SessionEntry{ + Type: EntryTypeMessage, + Role: "user", + Data: json.RawMessage(fmt.Sprintf(`{"text":"%d"}`, i)), + }) + } + + reloaded, err := store.Load("a", "k") + require.NoError(t, err) + got := reloaded.Entries() + require.Len(t, got, n) + for i := 0; i < n; i++ { + require.JSONEq(t, fmt.Sprintf(`{"text":"%d"}`, i), string(got[i].Data), + "on-disk entry %d out of order", i) + } +}