diff --git a/internal/sessions/claude_reuse_test.go b/internal/sessions/claude_reuse_test.go index 0567d8a06..c633c9f0d 100644 --- a/internal/sessions/claude_reuse_test.go +++ b/internal/sessions/claude_reuse_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" "time" + "unsafe" ) // reuseLine is reply i of a history: its own message, block and two tools. @@ -116,3 +117,29 @@ func TestClaudeHistoryReadAllocations(t *testing.T) { t.Fatalf("a reply's two reads made %d bytes, want at most 4200", per) } } + +// TestClaudeMessageLookupAllocations: the later lines of a message find +// it without making its key again, and a new branch of it takes the key +// its first one made. +func TestClaudeMessageLookupAllocations(t *testing.T) { + r := &claudeUsageState{} + id := "msg_01ABCDEFGHIJKLMNOPQRSTUVWX" + m := r.message(id, "req_1") + r.finish(m) + if n := testing.AllocsPerRun(100, func() { r.message(id, "req_1") }); n != 0 { + t.Fatalf("a message's later line made %v allocations, want 0", n) + } + if got := r.message(id, "req_1"); got != m || m.key != "message:"+id { + t.Fatalf("found %p (%q), want %p", got, got.key, m) + } + other := r.message(id, "req_2") + if other == m || other.key != m.key || unsafe.StringData(other.key) != unsafe.StringData(m.key) { + t.Fatalf("a second branch: %q, its own key made again", other.key) + } + if len(r.Messages["message:"+id]) != 2 { + t.Fatalf("branches %v", r.Messages) + } + if q := r.message("", "req_9"); q.key != "request:req_9" || r.Messages["request:req_9"]["req_9"] != q { + t.Fatalf("a message with only its request: %q", q.key) + } +} diff --git a/internal/sessions/claude_usage.go b/internal/sessions/claude_usage.go index eadeb607e..c0fa85e1a 100644 --- a/internal/sessions/claude_usage.go +++ b/internal/sessions/claude_usage.go @@ -139,15 +139,21 @@ func (r *claudeUsageState) message(id, request string) *claudeContribution { if id == "" && request == "" { return &claudeContribution{Call: -1} } - key := "message:" + id + // the key is looked up from a buffer and made a string only to be + // kept: every line of a message looks it up, one keeps it + var buf [96]byte + kb := append(buf[:0], "message:"...) + kb = append(kb, id...) if id == "" { - key = "request:" + request + kb = append(append(buf[:0], "request:"...), request...) } if r.Messages == nil { r.Messages = make(map[string]map[string]*claudeContribution) } - branches := r.Messages[key] + key := "" + branches := r.Messages[string(kb)] if branches == nil { + key = string(kb) if n := len(r.freeBranches); n > 0 { branches = r.freeBranches[n-1] r.freeBranches[n-1] = nil @@ -172,6 +178,15 @@ func (r *claudeUsageState) message(id, request string) *claudeContribution { return m } } + if key == "" { + for _, m := range branches { + key = m.key // the same string, made once + break + } + if key == "" { + key = string(kb) + } + } var m *claudeContribution if n := len(r.free); n > 0 { m = r.free[n-1]