sessions: tsAt looks for the first timestamp only when that one is asked (#2278)
tsAt(b, true) found the first "timestamp" with bytes.Index over the whole line, then threw it away for lastIndex's. On a first start's CPU profile (mote, the 13 GB + 52 GB fixture history, 120 s) that Index was 2.11 s of tsAt's 5.68 s. Run on mote at the head: - go vet ./internal/sessions; go test ./internal/sessions ./internal/usage: ok. - Broken by hand (the last case taking bytes.Index): nothing went red, so TestTsAtLastIsTheLines is new: a tool result's own timestamp before the line's, with the line's in and past lastIndex's 1 KB tail. Red under that break (last = 2020-01-01), green on the fix.
This commit is contained in:
@@ -2317,9 +2317,13 @@ func forwardLast(b, key []byte) int {
|
||||
// without decoding the rest of it.
|
||||
func tsAt(b []byte, last bool) time.Time {
|
||||
key := []byte(`"timestamp":"`)
|
||||
i := bytes.Index(b, key)
|
||||
// the first is looked for only when it is the one asked: found before
|
||||
// each last one too, it was ~2 s of a first start's CPU (#2278)
|
||||
var i int
|
||||
if last {
|
||||
i = lastIndex(b, key)
|
||||
} else {
|
||||
i = bytes.Index(b, key)
|
||||
}
|
||||
if i < 0 {
|
||||
return time.Time{}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package sessions
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A line's time is its own "timestamp", the last: a tool's result
|
||||
// before it may hold another, as Claude Code writes its own after the
|
||||
// message.
|
||||
func TestTsAtLastIsTheLines(t *testing.T) {
|
||||
inner := `{"type":"user","message":{"role":"user","content":[{"type":"tool_result","content":"{\"x\":1,\"y\":{\"timestamp\":\"x\"}} {"}]},"toolUseResult":{"timestamp":"2020-01-01T00:00:00Z"},`
|
||||
for _, pad := range []int{0, 2000} {
|
||||
b := []byte(inner + `"pad":"` + strings.Repeat("a", pad) + `","timestamp":"2026-10-31T08:00:00.123Z"}`)
|
||||
want := time.Date(2026, 10, 31, 8, 0, 0, 123e6, time.UTC)
|
||||
if got := tsAt(b, true); !got.Equal(want) {
|
||||
t.Fatalf("pad %d: last = %v, want %v", pad, got, want)
|
||||
}
|
||||
if got := tsAt(b, false); !got.Equal(time.Date(2020, 1, 1, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Fatalf("pad %d: first = %v", pad, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user