Files
magpie/internal/sessions/cc_usage.go
T
yetone 303a31dd6b sessions: a Claude prompt's content and a reply's usage are read in place
The Sessions read of a Claude history decoded a prompt line whole, so
its content (pasted text, images) was copied into a json.RawMessage
for each line, then copied again as the prompt's text; and each reply's
usage object, a few numbers, went through a json.Unmarshal of its own.

- claudeFull decodes its line as the calls' read does (ccDecode, now
  ccDecodeLess for any line): content nulled, given as the bytes of the
  line that hold it. Nothing keeps those bytes: the prompt's text and
  title are copies, as before.
- ccReply reads its usage with ccDecodeUsage, in place through gjson.
  What it can't be sure of reading as json.Unmarshal does (a known key
  in another case, a number that isn't a plain integer, a value of
  another type, cache_creation twice, invalid JSON) goes to
  json.Unmarshal.

Measured on mote, cold start over a copy of real Claude and Codex
histories (acold.sh, 120s), against v0.1.3155's build at the same base:
  ccReply 540MB -> 395MB, claudeFull 450MB -> 412MB,
  encoding/json.(*RawMessage).UnmarshalJSON 209MB -> gone.
mote's load was 74 to 126 from other sessions' runs, so the 120s
totals and peaks moved between runs of one binary (footprint peak
193-228MB, heap peak 164-194MB for this build; 180-181MB and
163-176MB for the base); neither is claimed as a change.

Tests:
- TestCCUsageDecodedAsJSONUnmarshal: the same fields or the same
  refusal as json.Unmarshal for 30 hand-made shapes and 3000 random
  objects. Red by hand with the case-folded key check taken out.
- TestCCUsageReadInPlace: Claude Code's usage read with at most 1
  allocation (its cache_creation); 7 by hand with json.Unmarshal.
- TestClaudePromptContentNotCopied: a 1 MB prompt line read whole
  makes 1.05 MB (its text once), bar 1.5x the line; 2.09 MB by hand
  with the old decode. The content given is the line's own bytes, and
  the title, prompt count, cwd and session id are read as before.

Run on mote at the pushed tree: go vet and go test ./internal/sessions.
Not run: the full suite (last at v0.1.3152's change: 85 packages ok,
reds only #3949 and #5481).
2026-11-06 19:08:15 +08:00

134 lines
3.3 KiB
Go

package sessions
import (
"encoding/json"
"strconv"
"strings"
"unsafe"
"github.com/tidwall/gjson"
)
// ccUsageFields is a Claude Code message's usage object, as json.Unmarshal
// reads it.
type ccUsageFields struct {
Input int `json:"input_tokens"`
Output int `json:"output_tokens"`
CacheRead int `json:"cache_read_input_tokens"`
CacheWrite int `json:"cache_creation_input_tokens"`
Creation *ccCacheCreation `json:"cache_creation"`
}
// ccDecodeUsage is json.Unmarshal(b, u) for a reply's usage object, read
// in place: json.Unmarshal made a decoder of its own for each reply's
// few numbers (160 MB of a first start's read of a real history). What
// it can't be sure of reading as json.Unmarshal does (a key spelt in
// another case, a number that isn't a plain integer, a value of another
// type, a repeated cache_creation) is left to json.Unmarshal.
func ccDecodeUsage(b []byte, u *ccUsageFields) error {
if v, ok := ccUsageInPlace(b); ok {
*u = v
return nil
}
return json.Unmarshal(b, u)
}
func ccUsageInPlace(b []byte) (ccUsageFields, bool) {
var u ccUsageFields
if len(b) == 0 || b[0] != '{' || !gjson.ValidBytes(b) {
return u, false
}
ok, creations := true, 0
var creation ccCacheCreation
gjson.Parse(unsafe.String(&b[0], len(b))).ForEach(func(k, v gjson.Result) bool {
key := k.Raw
if len(key) < 2 || strings.IndexByte(key, '\\') >= 0 {
ok = false
return false
}
key = key[1 : len(key)-1]
var dst *int
switch key {
case "input_tokens":
dst = &u.Input
case "output_tokens":
dst = &u.Output
case "cache_read_input_tokens":
dst = &u.CacheRead
case "cache_creation_input_tokens":
dst = &u.CacheWrite
case "cache_creation":
if creations++; creations > 1 {
ok = false
return false
}
switch v.Type {
case gjson.Null:
return true
case gjson.JSON:
if !v.IsObject() {
ok = false
return false
}
default:
ok = false
return false
}
v.ForEach(func(k, v gjson.Result) bool {
key := k.Raw
if len(key) < 2 || strings.IndexByte(key, '\\') >= 0 {
ok = false
return false
}
key = key[1 : len(key)-1]
var dst *int
switch key {
case "ephemeral_5m_input_tokens":
dst = &creation.Ephemeral5m
case "ephemeral_1h_input_tokens":
dst = &creation.Ephemeral1h
default:
if strings.EqualFold(key, "ephemeral_5m_input_tokens") || strings.EqualFold(key, "ephemeral_1h_input_tokens") {
ok = false
}
return ok
}
ok = ccUsageInt(v, dst)
return ok
})
if ok {
u.Creation = &creation
}
return ok
default:
for _, known := range [...]string{"input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "cache_creation"} {
if strings.EqualFold(key, known) {
ok = false
return false
}
}
return true
}
ok = ccUsageInt(v, dst)
return ok
})
return u, ok
}
// ccUsageInt sets *dst to v when v is a plain integer, leaves it for null,
// and is false for anything else.
func ccUsageInt(v gjson.Result, dst *int) bool {
switch v.Type {
case gjson.Null:
return true
case gjson.Number:
n, err := strconv.Atoi(v.Raw)
if err != nil {
return false
}
*dst = n
return true
}
return false
}