diff --git a/internal/usage/request_index_review_test.go b/internal/usage/request_index_review_test.go index fda15da76..0513cbc11 100644 --- a/internal/usage/request_index_review_test.go +++ b/internal/usage/request_index_review_test.go @@ -92,7 +92,7 @@ func TestQueryPageIOOutsideCacheLock(t *testing.T) { func TestPackedGatewayRetainsOversizedSnapshot(t *testing.T) { c := &rowChunk{} now := time.Now().Round(0) - for i := 0; i < 170000; i++ { + for i := 0; i < 180000; i++ { c.add(Row{Record: Record{Time: now.Add(time.Duration(i) * time.Second), Agent: "codex", Provider: "relay", Model: "m", Input: 10, RequestID: fmt.Sprint(i)}}, "", int64(i), false) } if c.Bytes <= 32<<20 { diff --git a/internal/usage/request_page.go b/internal/usage/request_page.go index 8d230a08f..6bf14a440 100644 --- a/internal/usage/request_page.go +++ b/internal/usage/request_page.go @@ -67,10 +67,9 @@ type RequestPage struct { } type packedRow struct { - // at is the row's time in unix ns, and loc its zone (Time): a - // time.Time was 24 of a row's bytes (#2278) - at int64 - loc *time.Location + // at is the row's time in unix ns, and zone its zone in rowZones + // (Time): a time.Time was 24 of a row's bytes (#2278) + at int64 // Varied are the strings of rowVaried, and Shape the chunk's Shapes // entry that holds the row's other strings Varied [len(rowVaried)]uint32 @@ -90,6 +89,69 @@ type packedRow struct { Masking int32 // ms (Record.Masking) Status, Tries int32 Flags uint16 + zone uint16 +} + +// rowZones are the zones rows' times are in, by a row's zone; 0 is the +// zero time. A row held its *time.Location, and that one pointer made +// every []packedRow a slice the collector scans: the pages' and the kept +// buffers' hundreds of thousands of rows, on every cycle, while calls +// came in (#4737). A zone is known by its name and offset, not its +// pointer: a time parsed with an offset, or a chunk read from disk, has +// a new FixedZone each. +var rowZones struct { + sync.Mutex + list atomic.Pointer[[]*time.Location] + ids map[rowZoneKey]uint16 + seen map[*time.Location]uint16 +} + +type rowZoneKey struct { + name string + offset int +} + +// zoneUTC is UTC's id. time.Local is a zone as any other: a test sets +// it, and a row keeps the zone it was written in. +const zoneUTC = 1 + +func init() { + list := []*time.Location{nil, time.UTC} + rowZones.list.Store(&list) + rowZones.ids = map[rowZoneKey]uint16{} + rowZones.seen = map[*time.Location]uint16{} +} + +// zoneOf is loc's id in rowZones, added when it is new. Past the most a +// row's zone holds, a new zone's times are kept in UTC: the same +// instants, read in another zone. +func zoneOf(loc *time.Location) uint16 { + if loc == time.UTC || loc == nil { + return zoneUTC + } + rowZones.Lock() + defer rowZones.Unlock() + if id, ok := rowZones.seen[loc]; ok { + return id + } + _, offset := time.Unix(0, 0).In(loc).Zone() + key := rowZoneKey{loc.String(), offset} + id, ok := rowZones.ids[key] + if !ok { + list := *rowZones.list.Load() + if len(list) > math.MaxUint16 { + return zoneUTC + } + id = uint16(len(list)) + next := append(list[:len(list):len(list)], loc) + rowZones.list.Store(&next) + rowZones.ids[key] = id + } + if len(rowZones.seen) >= 1024 { // a pointer each parse: kept bounded + clear(rowZones.seen) + } + rowZones.seen[loc] = id + return id } // msOf is a time in ms as a packedRow keeps it: one past 24 days, which @@ -101,19 +163,28 @@ func tokensOf(n int64) int32 { return int32(max(min(n, math.MaxInt32), math.MinI // Time is the row's time, in the zone it was written in. func (p *packedRow) Time() time.Time { - if p.loc == nil { + if p.zone == 0 { return time.Time{} } - return time.Unix(0, p.at).In(p.loc) + return time.Unix(0, p.at).In((*rowZones.list.Load())[p.zone]) } // setTime keeps t as the row's time. The zero time stays zero. func (p *packedRow) setTime(t time.Time) { if t.IsZero() { - p.at, p.loc = 0, nil + p.at, p.zone = 0, 0 return } - p.at, p.loc = t.UnixNano(), t.Location() + p.setTimeIn(t, zoneOf(t.Location())) +} + +// setTimeIn is setTime of a time in zone, which zoneOf gave. +func (p *packedRow) setTimeIn(t time.Time, zone uint16) { + if t.IsZero() { + p.at, p.zone = 0, 0 + return + } + p.at, p.zone = t.UnixNano(), zone } // rowHandedOn is the Flags bit of Record.HandedOn, rowReasoningHidden diff --git a/internal/usage/request_snapshot.go b/internal/usage/request_snapshot.go index fa3dda449..aae817550 100644 --- a/internal/usage/request_snapshot.go +++ b/internal/usage/request_snapshot.go @@ -258,13 +258,18 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string, } } next.Bytes += int64(len(next.Shapes)) * int64(unsafe.Sizeof([rowTexts]uint32{})) + var few [4]uint16 + zones := few[:0] + for _, loc := range c.Locations { + zones = append(zones, zoneOf(loc)) + } for i := range next.Rows { p := &next.Rows[i] sec, nano, loc := int64(take()), int64(take()), take() - if loc >= uint64(len(c.Locations)) { + if loc >= uint64(len(zones)) { return nil } - p.setTime(time.Unix(sec, nano).In(c.Locations[loc])) + p.setTimeIn(time.Unix(sec, nano), zones[loc]) p.Shape = uint32(take()) if int(p.Shape) >= len(next.Shapes) { return nil diff --git a/internal/usage/row_zone_test.go b/internal/usage/row_zone_test.go new file mode 100644 index 000000000..3bf8c1b27 --- /dev/null +++ b/internal/usage/row_zone_test.go @@ -0,0 +1,94 @@ +package usage + +import ( + "fmt" + "reflect" + "runtime" + "testing" + "time" +) + +// A row holds no pointer, so a slice of rows is one the collector never +// scans: its *time.Location made the pages' and kept buffers' rows a scan +// on every cycle (#4737). +func TestPackedRowsAreNotScanned(t *testing.T) { + var walk func(reflect.Type, string) + walk = func(ty reflect.Type, path string) { + switch ty.Kind() { + case reflect.Pointer, reflect.String, reflect.Slice, reflect.Map, reflect.Chan, reflect.Func, reflect.Interface, reflect.UnsafePointer: + t.Errorf("packedRow%s is a %s: every []packedRow is scanned", path, ty.Kind()) + case reflect.Array: + walk(ty.Elem(), path+"[]") + case reflect.Struct: + for i := range ty.NumField() { + f := ty.Field(i) + walk(f.Type, path+"."+f.Name) + } + } + } + walk(reflect.TypeOf(packedRow{}), "") +} + +// A row's time keeps its zone through pack and unpack, and the times of +// a zone parsed again and again, a new FixedZone each, are one zone. +func TestRowZoneKeptThroughPack(t *testing.T) { + before := len(*rowZones.list.Load()) + c := &rowChunk{} + var want []time.Time + base := time.Date(2026, 11, 1, 9, 0, 0, 123, time.UTC) + for i := range 90 { + var at time.Time + switch i % 3 { + case 0: + s := base.Add(time.Duration(i) * time.Minute).In(time.FixedZone("", 5*3600+1800)).Format(time.RFC3339Nano) + parsed, err := time.Parse(time.RFC3339Nano, s) + if err != nil { + t.Fatal(err) + } + at = parsed + case 1: + at = base.Add(time.Duration(i) * time.Minute) + default: + at = base.Add(time.Duration(i) * time.Minute).Local() + } + want = append(want, at) + c.add(Row{Record: Record{Time: at, Agent: "codex", Model: "m", Input: i}}, fmt.Sprint("msg", i), int64(i), false) + } + c.add(Row{Record: Record{Agent: "codex", Model: "m"}}, "zero", 90, false) + want = append(want, time.Time{}) + packed := c.pack() + if len(packed.Archive) == 0 { + t.Fatal("the chunk wasn't packed") + } + for _, chunk := range []*rowChunk{c, packed.unpack()} { + for i, w := range want { + got := chunk.Rows[i].Time() + if !got.Equal(w) || got.IsZero() != w.IsZero() { + t.Fatalf("row %d: %v, want %v", i, got, w) + } + gn, go_ := got.Zone() + wn, wo := w.Zone() + if gn != wn || go_ != wo || got.Location().String() != w.Location().String() { + t.Fatalf("row %d is in %q %d (%s), want %q %d (%s)", i, gn, go_, got.Location(), wn, wo, w.Location()) + } + } + } + if grew := len(*rowZones.list.Load()) - before; grew > 1 { + t.Fatalf("30 parses of +05:30 added %d zones, want 1 at most", grew) + } +} + +// BenchmarkCollectWithRowsHeld is a collection while a million rows are +// held, as a year's page holds them. +func BenchmarkCollectWithRowsHeld(b *testing.B) { + rows := make([]packedRow, 1_000_000) + for i := range rows { + rows[i].setTime(time.Unix(int64(i), 0)) + } + b.ResetTimer() + for range b.N { + runtime.GC() + } + b.StopTimer() + runtime.KeepAlive(rows) +}