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: