usage: a row keeps its zone as an id, so the collector never scans rows (#4737)
A packedRow held its *time.Location, and that one pointer made every
[]packedRow a slice the GC scans word by word: the pages' rows of a
period, the kept decode buffers and every unpacked chunk, hundreds of
thousands of rows on each cycle. #4737's profile has gcDrain at 12% of
the CPU, scanObject 7.65% of it.
A row now keeps its zone as a uint16 into rowZones, a copy-on-write
list read with one atomic load. A zone is known by its String() and
offset, not its pointer: a time parsed with an offset, and a chunk read
from disk, has a new FixedZone each, and 30 parses of +05:30 are one
zone. time.Local is a zone as any other (a test sets it to UTC), so a
row keeps the zone it was written in, as before. Past 65535 zones a new
one's times are kept in UTC: the same instants. unpack looks a chunk's
Locations up once, not once a row. packedRow is 8 bytes smaller, so
TestPackedGatewayRetainsOversizedSnapshot's fixture has 180000 rows to
stay over its 32 MB.
Run on mote (M5 Pro):
- BenchmarkCollectWithRowsHeld, a runtime.GC() with 1M rows held:
4.1-7.9 ms at origin/main 1fac66c06, 1.1-1.5 ms here (3 runs of 20).
- TestPackedRowsAreNotScanned: red with a *time.Location field put
back ("packedRow.broke is a ptr"). TestRowZoneKeptThroughPack: times
and zones (name, offset, String) the same through pack and unpack;
red with the name-and-offset lookup taken out ("30 parses of +05:30
added 31 zones").
- go test ./internal/usage: ok. go vet; GOOS=windows and GOOS=linux
go vet ./internal/usage: ok. gofmt -l: clean.
Not tried: the GC share in a running magpie with a real history; the
benchmark is the scan this takes away, not the reporter's 12%.
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
Reference in New Issue
Block a user