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).
This commit is contained in:
yetone
2026-11-06 19:08:15 +08:00
parent 37c1bc043b
commit 303a31dd6b
4 changed files with 267 additions and 13 deletions
+13 -4
View File
@@ -759,23 +759,32 @@ func ccReplyHead(b []byte) bool {
// read of a 21 GB history made 82 MB of those lines and 27 MB of copies
// of their content, which nothing kept (#2278).
func ccDecode(b []byte, l *ccCall) error {
_, err := ccDecodeLess(b, l)
return err
}
// ccDecodeLess is ccDecode into any v: json.Unmarshal(b, v) with the
// message's content null, the content given as the bytes of b that hold
// it (nil when b has none, and v was decoded from b whole). v keeps no
// byte of the line decoded: its strings are copies.
func ccDecodeLess(b []byte, v any) ([]byte, error) {
if len(b) == 0 {
return json.Unmarshal(b, l)
return nil, json.Unmarshal(b, v)
}
c := gjson.Get(unsafe.String(&b[0], len(b)), "message.content")
if !c.Exists() || c.Index <= 0 || c.Index+len(c.Raw) > len(b) {
return json.Unmarshal(b, l)
return nil, json.Unmarshal(b, v)
}
p := ccLines.Get().(*[]byte)
out := append((*p)[:0], b[:c.Index]...)
out = append(out, "null"...)
out = append(out, b[c.Index+len(c.Raw):]...)
err := json.Unmarshal(out, l) // l keeps no byte of out: its strings are copies
err := json.Unmarshal(out, v)
if cap(out) <= ccLineKept {
*p = out
ccLines.Put(p)
}
return err
return b[c.Index : c.Index+len(c.Raw) : c.Index+len(c.Raw)], err
}
// ccLines holds the buffers ccDecode makes its lines in; one grown past
+133
View File
@@ -0,0 +1,133 @@
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
}
+112
View File
@@ -0,0 +1,112 @@
package sessions
import (
"encoding/json"
"fmt"
"math/rand"
"runtime"
"runtime/debug"
"strings"
"testing"
)
// TestCCUsageDecodedAsJSONUnmarshal holds the in-place usage decoder to
// json.Unmarshal: the same fields, or the same refusal, for each shape a
// usage object can take, and for objects made at random from them.
func TestCCUsageDecodedAsJSONUnmarshal(t *testing.T) {
cases := []string{
`{"input_tokens":3,"cache_creation_input_tokens":1200,"cache_read_input_tokens":45000,"cache_creation":{"ephemeral_5m_input_tokens":200,"ephemeral_1h_input_tokens":1000},"output_tokens":512,"service_tier":"standard","server_tool_use":{"web_search_requests":0}}`,
`{}`, `{"input_tokens":null}`, `{"cache_creation":null}`, `{"cache_creation":{}}`,
`{"Input_Tokens":5}`, `{"INPUT_TOKENS":5,"input_tokens":6}`, `{"cache_creation":{"Ephemeral_1h_input_tokens":4}}`,
`{"input_tokens":1.5}`, `{"input_tokens":1e3}`, `{"input_tokens":"5"}`, `{"input_tokens":true}`,
`{"input_tokens":-7}`, `{"input_tokens":99999999999999999999}`, `{"input_tokens":1,"input_tokens":2}`,
`{"cache_creation":{"ephemeral_5m_input_tokens":1},"cache_creation":{"ephemeral_1h_input_tokens":2}}`,
`{"cache_creation":{"ephemeral_5m_input_tokens":1},"cache_creation":null}`,
`{"cache_creation":[1]}`, `{"cache_creation":5}`, `{"cache_creation":{"ephemeral_5m_input_tokens":"x"}}`,
`{"input\u005ftokens":9}`, `{"x":{"input_tokens":4},"output_tokens":2}`, `{"input_tokens":3,}`, `{"input_tokens":3`,
`{"input_tokens":0, "output_tokens" : 4 }`, `{"ſerver":1,"output_toKens":3}`, `[]`, `null`, ``,
}
r := rand.New(rand.NewSource(1))
keys := []string{"input_tokens", "output_tokens", "cache_read_input_tokens", "cache_creation_input_tokens", "cache_creation", "Output_tokens", "service_tier", "x"}
vals := []string{"0", "1", "123456", "-1", "null", "1.0", `"s"`, "true", `{"ephemeral_5m_input_tokens":7}`, `{"ephemeral_1h_input_tokens":8,"z":1}`, "[]"}
for range 3000 {
var parts []string
for range r.Intn(6) {
parts = append(parts, fmt.Sprintf("%q:%s", keys[r.Intn(len(keys))], vals[r.Intn(len(vals))]))
}
cases = append(cases, "{"+strings.Join(parts, ",")+"}")
}
for _, c := range cases {
var want, got ccUsageFields
werr := json.Unmarshal([]byte(c), &want)
gerr := ccDecodeUsage([]byte(c), &got)
if (werr == nil) != (gerr == nil) {
t.Fatalf("%s: json.Unmarshal %v, own %v", c, werr, gerr)
}
if werr != nil {
continue
}
w, _ := json.Marshal(want)
g, _ := json.Marshal(got)
if string(w) != string(g) {
t.Fatalf("%s:\n got %s\nwant %s", c, g, w)
}
}
}
// TestCCUsageReadInPlace: a reply's usage, as Claude Code writes it, is
// read without an allocation.
func TestCCUsageReadInPlace(t *testing.T) {
b := []byte(`{"input_tokens":3,"cache_creation_input_tokens":1200,"cache_read_input_tokens":45000,"cache_creation":{"ephemeral_5m_input_tokens":200,"ephemeral_1h_input_tokens":1000},"output_tokens":512,"service_tier":"standard"}`)
var u ccUsageFields
if _, ok := ccUsageInPlace(b); !ok {
t.Fatal("Claude Code's usage was left to json.Unmarshal")
}
n := testing.AllocsPerRun(100, func() { ccDecodeUsage(b, &u) })
// the cache_creation it points at
if n > 1 {
t.Fatalf("a usage read made %v allocations, want at most 1", n)
}
if u.Input != 3 || u.Output != 512 || u.CacheRead != 45000 || u.CacheWrite != 1200 || u.Creation == nil || u.Creation.Ephemeral1h != 1000 {
t.Fatalf("%+v %+v", u, u.Creation)
}
}
// TestClaudePromptContentNotCopied: a prompt read whole reads its content
// where the line holds it; a pasted megabyte was copied for each line.
func TestClaudePromptContentNotCopied(t *testing.T) {
big := strings.Repeat("pasted words ", 80000)
line := fmt.Sprintf(`{"parentUuid":null,"isSidechain":false,"type":"user","message":{"role":"user","content":%q},"uuid":"u1","timestamp":"2026-09-20T12:00:00Z","cwd":"/w","sessionId":"s1"}`, "fix this: "+big)
b := []byte(line)
s := &state{}
claudeLine(s, b, true)
if !strings.HasPrefix(s.Title, "fix this: pasted words") || s.Cwd != "/w" || s.ID != "s1" {
t.Fatalf("title %q cwd %q id %q", s.Title, s.Cwd, s.ID)
}
prompts := 0
for _, e := range s.Days {
prompts += e.v.Prompts
}
if prompts != 1 {
t.Fatalf("%d prompts", prompts)
}
var l ccLine
content, err := ccDecodeLess(b, &l)
at := strings.Index(line, `"fix this`)
if err != nil || l.Type != "user" || l.UUID != "u1" || len(content) != len(big)+len("fix this: ")+2 || &content[0] != &b[at] {
t.Fatalf("err %v type %q: the content given is not the line's own bytes (%d)", err, l.Type, len(content))
}
runtime.GC()
defer debug.SetGCPercent(debug.SetGCPercent(-1))
var ms runtime.MemStats
runtime.ReadMemStats(&ms)
before := ms.TotalAlloc
claudeFull(&state{}, b, true)
runtime.ReadMemStats(&ms)
// the prompt's text once, not the line again
made := ms.TotalAlloc - before
t.Logf("a prompt line of %d bytes made %d bytes", len(b), made)
if made > uint64(len(b))*3/2 {
t.Fatalf("a prompt line of %d bytes made %d bytes", len(b), made)
}
}
+9 -9
View File
@@ -345,15 +345,9 @@ func ccReply(s *state, at time.Time, msg, b []byte, main bool) {
if i == len(b) || model == "<synthetic>" {
return
}
var u 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"`
}
var u ccUsageFields
usage := b[i+len(ccUsage)-1:]
if end := objectEnd(usage); end < 0 || json.Unmarshal(usage[:end], &u) != nil {
if end := objectEnd(usage); end < 0 || ccDecodeUsage(usage[:end], &u) != nil {
return
}
ccCount(s, m, at, model, ccTokens(u.Input, u.Output, u.CacheRead, u.CacheWrite, u.Creation), main)
@@ -370,10 +364,16 @@ func claudeFull(s *state, b []byte, main bool) {
if !want {
return
}
// its content, a prompt's pasted text and images, is read where the
// line holds it, not copied for each line (#2278)
var l ccLine
if json.Unmarshal(b, &l) != nil {
content, err := ccDecodeLess(b, &l)
if err != nil {
return
}
if content != nil {
l.Message.Content = content
}
if s.Cwd == "" && l.Cwd != "" {
s.Cwd, s.Entry = l.Cwd, l.Entrypoint
}