From 7151562d9986172f4eb24f6d246bc4a2008e9240 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 09:55:58 +0800 Subject: [PATCH 1/7] perf(runtime): drop dead resultIDs map and mid-loop tool-result injection (P2) --- runtime/context.go | 14 -------------- runtime/context_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/runtime/context.go b/runtime/context.go index b2acad5..d357613 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, 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") +} From 1da058453004ce54c8cf6ac1069480a30efda943 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 09:57:39 +0800 Subject: [PATCH 2/7] perf(runtime): hoist tool-def filter/sort/normalize out of the turn loop (P3) --- runtime/runtime.go | 33 ++++++++++++++++++--------------- 1 file changed, 18 insertions(+), 15 deletions(-) diff --git a/runtime/runtime.go b/runtime/runtime.go index d7645e1..1beb96a 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -338,6 +338,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" @@ -378,21 +396,6 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon spillCfg := spillConfig{Workspace: r.Workspace, SessionKey: r.Session.Key} pruneToolResults(msgs, r.maxToolResultLen(), 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 From 671c10e89a388ab7a825ad7f29c77cd8afcad87a Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 10:00:52 +0800 Subject: [PATCH 3/7] perf(runtime): persist calibrator once per Run; reuse per-turn estimate (P8) --- runtime/calibrator_persist_test.go | 58 ++++++++++++++++++++++++++++++ runtime/runtime.go | 37 ++++++++++++++++--- 2 files changed, 90 insertions(+), 5 deletions(-) create mode 100644 runtime/calibrator_persist_test.go 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/runtime.go b/runtime/runtime.go index 1beb96a..0cb7cdd 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -114,6 +114,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. @@ -254,6 +260,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 @@ -410,12 +428,20 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon } } + // turnEstimate is the raw (uncalibrated) token estimate for this + // turn's context. Computed here for preventive compaction and + // reused by the EventDone calibrator Update so we don't re-scan + // the whole context a second time per round. -1 = not computed + // this turn (e.g. compaction disabled); EventDone falls back to + // computing it itself in that case. + turnEstimate := -1 compactionAllowed := turn == 0 || r.providerSupportsMidLoopCompaction() if compactionAllowed && r.Compaction != nil && r.Model != "" { if r.calibrator == nil { r.calibrator = tokens.NewCalibrator() } - estimate := r.calibrator.Adjust(tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs)) + turnEstimate = tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs) + estimate := r.calibrator.Adjust(turnEstimate) window := tokens.ContextWindowFor(r.Model, r.ContextWindow) threshold := 0.6 if r.Compaction != nil && r.Compaction.Threshold > 0 { @@ -552,11 +578,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon lastUsage = event.Usage } if event.Usage != nil && r.calibrator != nil { - 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) + est := turnEstimate + if est < 0 { + est = tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs) } + r.calibrator.Update(event.Usage.InputTokens, est) + r.calibratorDirty = true } case llm.EventError: From c710ea5a949e618d5d4f6da7bcc7069e283388cc Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 10:04:46 +0800 Subject: [PATCH 4/7] perf(runtime): track spilled tool-call IDs to skip re-writing spills each turn (P1) --- runtime/agent_test.go | 39 ++++++++++++++++++++++++++++++++------- runtime/context.go | 18 ++++++++++++++++-- runtime/runtime.go | 30 +++++++++++++++++++++++++----- 3 files changed, 73 insertions(+), 14 deletions(-) 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/context.go b/runtime/context.go index d357613..14ac14e 100644 --- a/runtime/context.go +++ b/runtime/context.go @@ -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]", diff --git a/runtime/runtime.go b/runtime/runtime.go index 0cb7cdd..5a2c3b4 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 @@ -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 From 25b2e9163f3c5d3191ed127991d4673d7b0aef47 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 10:06:43 +0800 Subject: [PATCH 5/7] perf(session): persist entry after releasing the session lock (P5) --- session/session.go | 13 +++++++++---- session/session_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 4 deletions(-) diff --git a/session/session.go b/session/session.go index 01e1fb9..45e46a4 100644 --- a/session/session.go +++ b/session/session.go @@ -100,7 +100,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 +114,15 @@ 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 + s.mu.Unlock() + + // Persist after releasing s.mu so disk latency doesn't block concurrent + // View()/append callers. Store.mu still serializes the file write and + // preserves append ordering (callers reach this point in lock order). (P5) + if store != nil { + store.AppendEntry(s, finalized) } } diff --git a/session/session_test.go b/session/session_test.go index 4817669..42f17fb 100644 --- a/session/session_test.go +++ b/session/session_test.go @@ -350,3 +350,30 @@ 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) +} From e1fd4dc689e1103a3422981d24cc1f0750411436 Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 10:27:53 +0800 Subject: [PATCH 6/7] fix(runtime): recompute calibrator estimate at EventDone (P8 stale-estimate bug) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The earlier P8 change reused the pre-compaction turnEstimate at EventDone, but mid-turn compaction reassembles msgs without recomputing it — so the persisted calibration ratio diverged from main whenever compaction fired, changing future compaction timing. Recompute fresh at EventDone exactly as the pre-debounce code did; keep only the disk-write debounce (the real win). --- runtime/runtime.go | 22 ++++++++-------------- 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/runtime/runtime.go b/runtime/runtime.go index 5a2c3b4..25b7379 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -448,20 +448,12 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon } } - // turnEstimate is the raw (uncalibrated) token estimate for this - // turn's context. Computed here for preventive compaction and - // reused by the EventDone calibrator Update so we don't re-scan - // the whole context a second time per round. -1 = not computed - // this turn (e.g. compaction disabled); EventDone falls back to - // computing it itself in that case. - turnEstimate := -1 compactionAllowed := turn == 0 || r.providerSupportsMidLoopCompaction() if compactionAllowed && r.Compaction != nil && r.Model != "" { if r.calibrator == nil { r.calibrator = tokens.NewCalibrator() } - turnEstimate = tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs) - estimate := r.calibrator.Adjust(turnEstimate) + estimate := r.calibrator.Adjust(tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs)) window := tokens.ContextWindowFor(r.Model, r.ContextWindow) threshold := 0.6 if r.Compaction != nil && r.Compaction.Threshold > 0 { @@ -598,11 +590,13 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon lastUsage = event.Usage } if event.Usage != nil && r.calibrator != nil { - est := turnEstimate - if est < 0 { - est = tokens.Estimate(msgs, llm.JoinSystemPromptParts(parts), toolDefs) - } - r.calibrator.Update(event.Usage.InputTokens, est) + // 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)) r.calibratorDirty = true } From 34ebfc5e9502d3d466053bccb8b5ad560cb23ead Mon Sep 17 00:00:00 2001 From: sausheong Date: Sat, 13 Jun 2026 10:29:07 +0800 Subject: [PATCH 7/7] fix(session): lock-couple writeMu to preserve disk order under concurrent Append (P5) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The earlier P5 change released s.mu before the store write, which let concurrent appends on one Session reach the disk writer out of in-memory order. Acquire a dedicated writeMu while still holding s.mu, then release s.mu before the disk write — disk latency stays off s.mu while on-disk order still matches append order. Adds a disk-order regression test. --- session/session.go | 18 ++++++++++++++---- session/session_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/session/session.go b/session/session.go index 45e46a4..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. @@ -116,13 +122,17 @@ func (s *Session) Append(entry SessionEntry) { finalized := entry // value copy with all fields set store := s.store - s.mu.Unlock() - // Persist after releasing s.mu so disk latency doesn't block concurrent - // View()/append callers. Store.mu still serializes the file write and - // preserves append ordering (callers reach this point in lock order). (P5) + // 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 42f17fb..feea48d 100644 --- a/session/session_test.go +++ b/session/session_test.go @@ -377,3 +377,33 @@ func TestConcurrentAppendAndViewNoRace(t *testing.T) { 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) + } +}