Files
magpie/internal/sessions/lastindex_test.go
T
yetone 05dae78544 sessions: the last key of a line is found going forward, not a byte at a time back (#2278)
tsAt(b, true), Claude Code's reply line (the last "usage":{) and strAt
found their key with bytes.LastIndex, which goes back over the line a
byte at a time (Rabin-Karp). A Claude Code line holds a tool's whole
output, and on a first start over a real 14 GB Claude Code and 3.8 GB
Codex history, LastIndex was 8.4 s of the profile's CPU, 7 s of it
tsAt's. lastIndex finds the same index: it looks at the line's last
1 KiB first, where Claude Code writes the timestamp, then goes forward
with bytes.Index, which skips ahead with the CPU's vector instructions.

Run on mote (zone worktree at this head):
- go vet ./internal/sessions for darwin, linux and windows: ok.
- go test ./internal/sessions ./internal/usage: ok.
- TestLastIndexIsLastIndex: 3,000 random lines up to 3,000 bytes, keys
  that overlap themselves and an empty one, against bytes.LastIndex;
  and a key in the tail, before it and across its edge.
- Broken by hand: stopping at the first match forward, red
  ("lastIndex(996 bytes, "aa") = 7, want 983"); a tail match placed at
  the tail's start, red ("= 535, want 673").
- First start on mote's real history (advst.sh, 75 s, cold caches),
  v0.1.2328 against this, twice each: user CPU 3:40 and 3:38 against
  3:27 and 3:22; footprint peak 324/320 MB against 319/316 MB. The
  heatmap, requests, overview and stats answers (0, 7, 30 days) are
  byte for byte the same.
2026-10-31 12:50:14 +08:00

44 lines
1.2 KiB
Go

package sessions
import (
"bytes"
"math/rand/v2"
"strings"
"testing"
)
// lastIndex answers what bytes.LastIndex does: in the tail, before it, across
// its edge, with keys that overlap themselves, and with none.
func TestLastIndexIsLastIndex(t *testing.T) {
keys := [][]byte{[]byte(`"timestamp":"`), []byte(`"usage":{`), []byte("aa"), []byte("a"), nil}
rnd := rand.New(rand.NewPCG(1, 2))
for n := range 3000 {
size := rnd.IntN(3000)
b := make([]byte, size)
for i := range b {
b[i] = "ab\"x"[rnd.IntN(4)]
}
key := keys[n%len(keys)]
for range rnd.IntN(3) {
if len(key) <= size {
copy(b[rnd.IntN(size-len(key)+1):], key)
}
}
if got, want := lastIndex(b, key), bytes.LastIndex(b, key); got != want {
t.Fatalf("lastIndex(%d bytes, %q) = %d, want %d", size, key, got, want)
}
}
key := []byte(`"timestamp":"`)
for _, at := range []int{0, 500, 2048 - 1024 - 5, 2048 - 1024, 2048 - len(key)} {
b := []byte(strings.Repeat("x", 2048))
copy(b[at:], key)
if got := lastIndex(b, key); got != at {
t.Errorf("key at %d: lastIndex = %d", at, got)
}
copy(b[10:], key)
if got := lastIndex(b, key); got != max(at, 10) {
t.Errorf("keys at 10 and %d: lastIndex = %d", at, got)
}
}
}