sessions: a file's head and prefix hashes are kept as 16 bytes, not hex (#2278)

Each kept file's state held its head hash as 64 hex characters and its
sampled prefix hash as "sample-v1:" and 64 more, two allocations of 64
and 80 bytes beside the state. They are only compared, so they are now
a digest: the first 16 bytes of the same SHA-256, inline in the state's
own 16 bytes where each string header was. The state's size class is
unchanged (416), and the 144 bytes a file are gone.

A cache written before reads as the same files: digest reads the old
hex (with or without "sample-v1:") as its first 32 characters, which
are what headDigest and prefixHash give now, so the first start after
the update reads nothing again. The call shards' gob keeps its string
fields, written and read through the digest, so a shard written before
restores the same too. File names still use hashHead's full hex.

Run, on a sandbox HOME holding the owner's real account history (18,346
session files), the same sessions.json before each run, web mode, at
120 s:
- w14 (main): live heap 88.8 MB, footprint 129 MB, 127 MB after GC,
  CPU 2.35 s
- w15 (this): live heap 86.1 MB, footprint 124 MB, 121 MB after GC,
  CPU 2.48 s; at 30 s 2.31 s of CPU against 2.15 s, so no file was read
  again from the old cache
Broken by hand: digest no longer stripping "sample-v1:" turns
TestDigestReadsTheHashesWrittenBefore and
TestPrefixHashUnchangedAndUnbuffered red.
At the pushed head (rebased on 848269fcf): gofmt clean, go vet for darwin,
windows and linux (nogui) ok, go test ./internal/sessions/ ./internal/usage/
ok on mica. The full suite runs after the push (both test boxes were
loaded).
This commit is contained in:
yetone
2026-11-12 09:41:52 +08:00
parent 9197804144
commit 88d2962e0c
9 changed files with 160 additions and 32 deletions
+3 -3
View File
@@ -596,7 +596,7 @@ type callDiskState struct {
}
func diskCallState(s *callFile) callDiskState {
d := callDiskState{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head, HeadSize: s.HeadSize,
d := callDiskState{ContentHash: s.ContentHash.String(), Size: s.Size, Mod: s.Mod, Off: s.Off, Head: s.Head.String(), HeadSize: s.HeadSize,
Path: s.Path, Agent: s.Agent, Parser: callParseVersions[s.Agent], At: s.At, End: s.End, AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested,
LastUser: s.LastUser, LastAsst: s.LastAsst}
if s.Dsh != nil {
@@ -611,8 +611,8 @@ func diskCallState(s *callFile) callDiskState {
return d
}
func (s callDiskState) restore() *callFile {
st := &callFile{ContentHash: s.ContentHash, Size: s.Size, Mod: s.Mod, Off: s.Off,
Head: s.Head, HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End,
st := &callFile{ContentHash: parseDigest(s.ContentHash), Size: s.Size, Mod: s.Mod, Off: s.Off,
Head: parseDigest(s.Head), HeadSize: s.HeadSize, Path: s.Path, Agent: s.Agent, At: s.At, End: s.End,
AsstEnd: s.AsstEnd, Session: s.Session, Requested: s.Requested, LastUser: s.LastUser, LastAsst: s.LastAsst}
if len(s.Dsh) > 0 {
var c dshCarry
+3 -3
View File
@@ -35,7 +35,7 @@ func writeCallRevisions(st *callFile) {
_ = os.Remove(path)
return
}
r := callRevisions{Off: st.Off, ContentHash: st.ContentHash, CompactMs: st.CompactMs, Window: st.Claude.window()}
r := callRevisions{Off: st.Off, ContentHash: st.ContentHash.String(), CompactMs: st.CompactMs, Window: st.Claude.window()}
var data bytes.Buffer
if gob.NewEncoder(&data).Encode(r) != nil {
return
@@ -57,7 +57,7 @@ func writeCallRevisions(st *callFile) {
// withCallRevisions is old with the window kept for it, when old is a
// Claude file's read without one and the window kept is of that same read.
func withCallRevisions(old *callFile) *callFile {
if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == "" {
if old == nil || old.Claude != nil || (old.Agent != "claude" && old.Agent != "claude-desktop") || old.ContentHash == (digest{}) {
return old
}
data, err := os.ReadFile(callRevisionsPath(old.Path))
@@ -65,7 +65,7 @@ func withCallRevisions(old *callFile) *callFile {
return old
}
var r callRevisions
if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || r.ContentHash != old.ContentHash {
if gob.NewDecoder(bytes.NewReader(data)).Decode(&r) != nil || r.Off != old.Off || parseDigest(r.ContentHash) != old.ContentHash {
return old
}
c := *old
+12 -12
View File
@@ -70,7 +70,7 @@ type Call struct {
// what it takes to read on from off.
type callFile struct {
Claude *claudeUsageState
ContentHash string
ContentHash digest
dirty map[int]bool
// readSize is the size of the file being read (prepareCalls), for
// growCalls
@@ -80,7 +80,7 @@ type callFile struct {
Size int64
Mod int64 // unix nanoseconds
Off int64 // after the last whole line read
Head string // hash of the prefix, to tell one replaced from one grown
Head digest // of the prefix, to tell one replaced from one grown
HeadSize int
Path string
Calls []Call
@@ -392,7 +392,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile {
head := headOf(f.path)
var st *callFile
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != "" && prefixHash(f.path, old.Off) == old.ContentHash {
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(head, old.Head, old.HeadSize) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Off) == old.ContentHash {
if owned {
st = old.cloneState()
} else {
@@ -411,7 +411,7 @@ func prepareCalls(f file, old *callFile, owned bool) *callFile {
}
}
st.dirty = map[int]bool{}
st.Head, st.HeadSize, st.Path = hashHead(head), len(head), f.path
st.Head, st.HeadSize, st.Path = headDigest(head), len(head), f.path
st.readSize = f.size
return st
}
@@ -1292,18 +1292,18 @@ func (st *callFile) codexCompact(i int) {
}
func hashHead(head string) string { return fmt.Sprintf("%x", sha256.Sum256([]byte(head))) }
func sameHead(head, hash string, size int) bool {
return size >= 0 && len(head) >= size && hashHead(head[:size]) == hash
func sameHead(head string, hash digest, size int) bool {
return size >= 0 && len(head) >= size && headDigest(head[:size]) == hash
}
// prefixHash checks distributed windows of the indexed prefix. Small files
// are checked in full. The version tag invalidates earlier full-file hashes.
// are checked in full.
// Rewrites outside the sampled windows can go undetected; appends cost at most
// 64 KiB of reads per fingerprint regardless of the session's length.
func prefixHash(path string, n int64) string {
func prefixHash(path string, n int64) digest {
f, err := os.Open(path)
if err != nil {
return ""
return digest{}
}
defer f.Close()
h := sha256.New()
@@ -1314,7 +1314,7 @@ func prefixHash(path string, n int64) string {
defer hashBufs.Put(buf)
if n <= window*samples {
if _, err = io.ReadFull(f, buf[:n]); err != nil {
return ""
return digest{}
}
h.Write(buf[:n])
} else {
@@ -1322,12 +1322,12 @@ func prefixHash(path string, n int64) string {
off := (n - window) * i / (samples - 1)
// A full window may come back with io.EOF at the file's end.
if k, _ := f.ReadAt(buf[:window], off); int64(k) < window {
return ""
return digest{}
}
h.Write(buf[:window])
}
}
return fmt.Sprintf("sample-v1:%x", h.Sum(nil))
return digest(h.Sum(nil)[:16])
}
var hashBufs = sync.Pool{New: func() any { return new([64 << 10]byte) }}
+59
View File
@@ -0,0 +1,59 @@
package sessions
import (
"crypto/sha256"
"encoding/hex"
"strings"
)
// digest is a file's head or sampled prefix as kept to know it again
// (headDigest, prefixHash): the first 16 bytes of its SHA-256, in the
// state itself. As hex strings, 64 and 74 bytes of their own, they were
// 144 bytes a file beside its state; 18k files' states held 2.6 MB of
// them (#2278). The zero digest is none: the file couldn't be read.
type digest [16]byte
// MarshalText is d in hex, "" for none.
func (d digest) MarshalText() ([]byte, error) {
if d == (digest{}) {
return nil, nil
}
return []byte(hex.EncodeToString(d[:])), nil
}
// UnmarshalText reads a digest as written, or as a magpie before it wrote
// the whole hash: the 64 hex of hashHead's, or prefixHash's "sample-v1:"
// before them, whose first 32 are this digest. A cache from before reads
// as the same files, so nothing is read again for it. Anything else is
// none, which matches no file.
func (d *digest) UnmarshalText(b []byte) error {
*d = parseDigest(string(b))
return nil
}
// parseDigest is the digest s spells (UnmarshalText), none when it spells
// none.
func parseDigest(s string) digest {
var d digest
s = strings.TrimPrefix(s, "sample-v1:")
if (len(s) != 32 && len(s) != 64) || s == "" {
return d
}
if _, err := hex.Decode(d[:], []byte(s[:32])); err != nil {
return digest{}
}
return d
}
// String is d as MarshalText writes it, for the shards' gob, whose
// field stays a string so a shard written before reads the same.
func (d digest) String() string {
b, _ := d.MarshalText()
return string(b)
}
// headDigest is the digest of a file's first bytes, head.
func headDigest(head string) digest {
sum := sha256.Sum256([]byte(head))
return digest(sum[:16])
}
+68
View File
@@ -0,0 +1,68 @@
package sessions
import (
"crypto/sha256"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
// A cache a magpie before digest wrote holds the whole hashes in hex. Read
// now, its files must be the same files, or every one is read again on the
// first start after the update.
func TestDigestReadsTheHashesWrittenBefore(t *testing.T) {
path := filepath.Join(t.TempDir(), "rollout.jsonl")
head := strings.Repeat(`{"type":"session_meta"}`+"\n", 3)
if err := os.WriteFile(path, []byte(head+strings.Repeat("x", 200<<10)), 0o600); err != nil {
t.Fatal(err)
}
size := int64(len(head) + 200<<10)
oldHead := fmt.Sprintf("%x", sha256.Sum256([]byte(head)))
oldHash := oldPrefixHash(path, size)
if !strings.HasPrefix(oldHash, "sample-v1:") || len(oldHead) != 64 {
t.Fatalf("old forms %q %q", oldHead, oldHash)
}
var st state
old := fmt.Sprintf(`{"head":%q,"head_size":%d,"content_hash":%q,"size":%d}`, oldHead, len(head), oldHash, size)
if err := json.Unmarshal([]byte(old), &st); err != nil {
t.Fatal(err)
}
if !sameHead(head, st.Head, int(st.HeadSize)) || st.ContentHash != prefixHash(path, size) || st.ContentHash == (digest{}) {
t.Fatalf("an old state reads as another file: %x %x", st.Head, st.ContentHash)
}
// A shard keeps its hashes as strings: one written before restores the same.
c := callDiskState{Head: oldHead, ContentHash: oldHash}.restore()
if c.Head != st.Head || c.ContentHash != st.ContentHash {
t.Fatalf("an old shard reads as another file: %x %x", c.Head, c.ContentHash)
}
if back := diskCallState(c).restore(); back.Head != c.Head || back.ContentHash != c.ContentHash {
t.Fatal("a shard written now reads back as another file")
}
b, err := json.Marshal(&st)
if err != nil {
t.Fatal(err)
}
var again state
if err := json.Unmarshal(b, &again); err != nil || again.Head != st.Head || again.ContentHash != st.ContentHash {
t.Fatalf("written now, read again: %s", b)
}
if strings.Contains(string(b), oldHead) || !strings.Contains(string(b), oldHead[:32]) {
t.Fatalf("not written as the digest: %s", b)
}
// None stays none, and isn't written.
b, _ = json.Marshal(&state{})
if strings.Contains(string(b), "head") || strings.Contains(string(b), "content_hash") {
t.Fatalf("no hash written as one: %s", b)
}
for _, s := range []string{"", "sample-v1:", "zz" + oldHead[2:], oldHead[:40]} {
if parseDigest(s) != (digest{}) {
t.Fatalf("%q read as a digest", s)
}
}
}
+2 -2
View File
@@ -51,7 +51,7 @@ func TestSampledPrefixFingerprint(t *testing.T) {
}
os.WriteFile(path, data, 0600)
}
if prefixHash(path, n+1) != "" {
if prefixHash(path, n+1) != (digest{}) {
t.Fatal("short read accepted")
}
}
@@ -64,7 +64,7 @@ func BenchmarkPrefixFingerprint(b *testing.B) {
for _, impl := range []struct {
name string
f func(string, int64) string
}{{"sampled", prefixHash}, {"without_sampling", fullPrefixHash}} {
}{{"sampled", func(p string, n int64) string { return prefixHash(p, n).String() }}, {"without_sampling", fullPrefixHash}} {
b.Run(impl.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
+5 -4
View File
@@ -10,8 +10,9 @@ import (
"testing"
)
// oldPrefixHash is prefixHash as it was, through io.CopyN: a stored hash
// must still match after the change, or every cache is read again.
// oldPrefixHash is prefixHash as it was, through io.CopyN and written in
// full: a stored hash must still match after the change, or every cache
// is read again.
func oldPrefixHash(path string, n int64) string {
f, err := os.Open(path)
if err != nil {
@@ -45,13 +46,13 @@ func TestPrefixHashUnchangedAndUnbuffered(t *testing.T) {
t.Fatal(err)
}
for _, n := range []int64{0, 1, 4095, 4096, 65535, 65536, 65537, 1 << 20, 3 << 20} {
if got, want := prefixHash(path, n), oldPrefixHash(path, n); got != want || got == "" {
if got, want := prefixHash(path, n), parseDigest(oldPrefixHash(path, n)); got != want || got == (digest{}) {
t.Fatalf("n=%d: %q, was %q", n, got, want)
}
}
// Past the file's end is unknown, as it was.
for _, n := range []int64{3<<20 + 1, 4 << 20} {
if got := prefixHash(path, n); got != "" {
if got := prefixHash(path, n); got != (digest{}) {
t.Fatalf("n=%d past the end: %q", n, got)
}
if old := oldPrefixHash(path, n); old != "" {
+4 -4
View File
@@ -218,14 +218,14 @@ type state struct {
Codex *codexUsageState `json:"-"`
codexPath string // the rollout read, for its fork's parent
Claude *claudeUsageState `json:"claude,omitempty"`
Head string `json:"head,omitempty"`
Head digest `json:"head,omitzero"`
// int32 beside CdRead: the head is headLen bytes at most, and the 8 bytes
// it saves take a state from the 448-byte size class to 416 (#2278)
HeadSize int32 `json:"head_size,omitempty"`
// Claude Code: parsed by a magpie that reads /cd's relocated lines
// (ccRelocated), so Cwd is the folder the session was last moved to
CdRead bool `json:"cd_read,omitempty"`
ContentHash string `json:"content_hash,omitempty"`
ContentHash digest `json:"content_hash,omitzero"`
Size int64 `json:"size"`
Mod int64 `json:"mod"` // unix nanoseconds
Off int64 `json:"off"` // after the last whole line read
@@ -2346,13 +2346,13 @@ func parseRead(f file, old *state, calls *callsRide) *state {
headBytes := headOf(f.path)
var s *state
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != "" && prefixHash(f.path, old.Size) == old.ContentHash {
if old != nil && !packed(f.path) && f.size >= old.Size && old.Off <= f.size && sameHead(headBytes, old.Head, int(old.HeadSize)) && old.ContentHash != (digest{}) && prefixHash(f.path, old.Size) == old.ContentHash {
s = old.clone()
} else {
s = &state{}
}
s.Size, s.Mod = f.size, f.mod.UnixNano()
s.Head, s.HeadSize = hashHead(headBytes), int32(len(headBytes))
s.Head, s.HeadSize = headDigest(headBytes), int32(len(headBytes))
s.CdRead = parser.claude
s.ContentHash = prefixHash(f.path, f.size)
var head func([]byte) bool
+4 -4
View File
@@ -17,9 +17,9 @@ type tail struct {
Off int64 `json:"off"`
Skip int64 `json:"skip,omitempty"`
Size int64 `json:"size"`
Head string `json:"head"`
Head digest `json:"head"`
HeadSize int `json:"head_size"`
Hash string `json:"hash"`
Hash digest `json:"hash"`
}
// markTail is the tail of a file read up to off, its first size bytes the
@@ -30,10 +30,10 @@ func markTail(path string, off, skip, size int64) *tail {
head = head[:size]
}
h := prefixHash(path, size)
if h == "" && size > 0 {
if h == (digest{}) && size > 0 {
return nil
}
return &tail{Off: off, Skip: skip, Size: size, Head: hashHead(head), HeadSize: len(head), Hash: h}
return &tail{Off: off, Skip: skip, Size: size, Head: headDigest(head), HeadSize: len(head), Hash: h}
}
// holds says whether the file at path is still the one t was read from,