usage: a packed row holds its time as unix ns and a zone, its tokens in 32 bits (#2278)

A packedRow was 184 bytes; it is 152 now. Its time.Time (24 bytes) is
kept as unix nanoseconds and the *time.Location it was in, read back
with Time(); its six token counts are int32s, not int64s. No call
reads or writes 2^31 tokens; one past it is kept as the most an int32
holds (tokensOf), not wrapped. The archive's encoding is varints and
is unchanged.

Run (mote, through mote-run): go build, go vet, GOOS=linux and
GOOS=windows go vet ./internal/usage, go test ./internal/usage
./internal/usageapi: ok. TestRowTokensAndZoneKept (new) packs a row in
a +05:30 zone at 123ns with 3e9 and -3e9 tokens, and checks time,
zone and the saturated counts after a pack/unpack round trip.
Broken by hand: tokensOf as a plain int32(n) makes it red ("read back
Input -1294967296 ... want 2147483647").

Real history copy on mote (cold start, magpie-ext = v0.1.2296 change):
  cold peak  this 346/342/354 MB (avg 347)  before 373/349/359 (avg 360)
  warm peak  this 273/262 MB               before 297/276
heatmap, overview 0/7/30, stats 0/30 and the request page JSON are
byte-identical to before.
This commit is contained in:
yetone
2026-10-31 10:24:23 +08:00
parent 03f3e1528b
commit 64aaf421ac
12 changed files with 94 additions and 41 deletions
+3 -3
View File
@@ -294,13 +294,13 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
id := c.Strings[raw]
to = renamedTo{timed: b.renames.Timed(id)}
if !to.timed {
shown, own := b.renames.Both(id, p.Time)
shown, own := b.renames.Both(id, p.Time())
to.to, to.own = intern(shown, raw), intern(own, raw)
}
provs[raw] = to
}
if to.timed {
shown, own := b.renames.Both(c.Strings[raw], p.Time)
shown, own := b.renames.Both(c.Strings[raw], p.Time())
to.to, to.own = intern(shown, raw), intern(own, raw)
}
sk := [3]uint32{p.Shape, to.to, to.own}
@@ -336,7 +336,7 @@ func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {
p.Cost = 0
if got.price != nil && p.Tokens[0]+p.Tokens[1] > 0 {
p.Flags |= 1
p.Cost = atWindow(got.price, got.windows, p.Time).In(p.Time).CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))
p.Cost = atWindow(got.price, got.windows, p.Time()).In(p.Time()).CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))
}
}
return &c, pooled
+1 -1
View File
@@ -136,7 +136,7 @@ func chunkFirsts(sets [3][]*rowChunk) func(*rowChunk) time.Time {
var at time.Time
open := rows.of(read)
for i := range open.Rows {
if t := open.Rows[i].Time; at.IsZero() || t.Before(at) {
if t := open.Rows[i].Time(); at.IsZero() || t.Before(at) {
at = t
}
}
+3 -3
View File
@@ -27,11 +27,11 @@ func TestHeatBeforeKeptBySerial(t *testing.T) {
var s heatSum
for _, c := range set {
for i := range c.Rows {
if p := &c.Rows[i]; p.Time.Before(cut) {
if p := &c.Rows[i]; p.Time().Before(cut) {
s.n++
s.at += p.Time.UnixNano()
s.at += p.Time().UnixNano()
for _, v := range p.Tokens {
s.tokens += v
s.tokens += int64(v)
}
}
}
+2 -2
View File
@@ -157,7 +157,7 @@ func hashRows(h hash.Hash, c *rowChunk) {
shapes := map[uint32]int{}
for i := range c.Rows {
p := &c.Rows[i]
b = binary.AppendVarint(b, p.Time.UnixNano())
b = binary.AppendVarint(b, p.Time().UnixNano())
for _, v := range p.Varied {
text(v)
}
@@ -173,7 +173,7 @@ func hashRows(h hash.Hash, c *rowChunk) {
}
}
for _, t := range p.Tokens {
b = binary.AppendVarint(b, t)
b = binary.AppendVarint(b, int64(t))
}
b = binary.AppendVarint(b, p.Order)
b = binary.AppendVarint(b, p.RouteID)
+3 -3
View File
@@ -273,11 +273,11 @@ func heatBefore(cut time.Time, recent [3][]*rowChunk) heatSum {
var part heatSum
unpacked := rows.of(c)
for i := range unpacked.Rows {
if pr := &unpacked.Rows[i]; pr.Time.Before(cut) {
if pr := &unpacked.Rows[i]; pr.Time().Before(cut) {
part.n++
part.at += pr.Time.UnixNano()
part.at += pr.Time().UnixNano()
for _, t := range pr.Tokens {
part.tokens += t
part.tokens += int64(t)
}
}
}
+1 -1
View File
@@ -302,7 +302,7 @@ func visitBlocks(blocks []*rowChunk, since time.Time, fn func(Record)) {
c := rows.of(packed)
for i := range c.Rows {
p := &c.Rows[i]
if !p.Time.Before(since) {
if !p.Time().Before(since) {
fn(c.row(i).Record)
}
}
+2 -2
View File
@@ -63,8 +63,8 @@ func hintsOf(chunks []*rowChunk, rows *chunkRows) []*chunkHints {
open := rows.of(c)
for j := range open.Rows {
p := &open.Rows[j]
if p.Time.After(h.latest) {
h.latest = p.Time
if p.Time().After(h.latest) {
h.latest = p.Time()
}
if id := open.Strings[open.text(p, 11)]; id != "" {
h.ids = append(h.ids, uint32(matchHash(id)))
+2 -2
View File
@@ -185,7 +185,7 @@ func matchedLocalLegacy(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]b
for _, c := range chunks {
for i, p := range c.Rows {
ref := rowRef{c, i}
if skip[ref] || p.Time.Before(since) {
if skip[ref] || p.Time().Before(since) {
continue
}
id := c.Strings[c.text(&p, 11)]
@@ -218,7 +218,7 @@ func matchedLocalLegacy(gateway *rowChunk, chunks []*rowChunk, skip map[rowRef]b
for _, c := range chunks {
for j, p := range c.Rows {
ref := rowRef{c, j}
if skip[ref] || matched[ref] || p.Time.Before(since) {
if skip[ref] || matched[ref] || p.Time().Before(since) {
continue
}
s := c.Strings[c.text(&p, 13)]
+45 -16
View File
@@ -67,12 +67,18 @@ type RequestPage struct {
}
type packedRow struct {
Time time.Time
// 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
// Varied are the strings of rowVaried, and Shape the chunk's Shapes
// entry that holds the row's other strings
Varied [len(rowVaried)]uint32
Shape uint32
Tokens [6]int64
Varied [len(rowVaried)]uint32
Shape uint32
// in 32 bits: no call reads or writes 2^31 tokens, and they were
// 48 of a row's bytes as int64s (#2278); one past it is kept as the
// most an int32 holds (tokensOf)
Tokens [6]int32
Order, RouteID int64
Cost, Credits float64
// the times of the call, in ms as in Record, kept in 32 bits (msOf):
@@ -90,6 +96,26 @@ type packedRow struct {
// no call takes, is kept as the longest it can be.
func msOf(ms int64) int32 { return int32(max(min(ms, math.MaxInt32), math.MinInt32)) }
// tokensOf is a token count as a packedRow keeps it.
func tokensOf(n int64) int32 { return int32(max(min(n, math.MaxInt32), math.MinInt32)) }
// Time is the row's time, in the zone it was written in.
func (p *packedRow) Time() time.Time {
if p.loc == nil {
return time.Time{}
}
return time.Unix(0, p.at).In(p.loc)
}
// 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
return
}
p.at, p.loc = t.UnixNano(), t.Location()
}
// rowHandedOn is the Flags bit of Record.HandedOn, rowReasoningHidden
// Record.ReasoningHidden's: 64 is block_price.go's swapKnown, 256
// rowOwnCost
@@ -243,7 +269,8 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
c.Bytes += int64(len(s) + 48)
return id
}
p := packedRow{Time: r.Time, Tokens: [6]int64{int64(r.Input), int64(r.Output), int64(r.CacheRead), int64(r.CacheWrite), int64(r.Reasoning), int64(r.CacheWrite1h)}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: int32(r.Tries)}
p := packedRow{Tokens: [6]int32{tokensOf(int64(r.Input)), tokensOf(int64(r.Output)), tokensOf(int64(r.CacheRead)), tokensOf(int64(r.CacheWrite)), tokensOf(int64(r.Reasoning)), tokensOf(int64(r.CacheWrite1h))}, Millis: msOf(r.Millis), TTFT: msOf(r.TTFT), FirstText: msOf(r.FirstText), FirstReasoning: msOf(r.FirstReasoning), Sent: msOf(r.Sent), Flow: msOf(r.Flow), Own: msOf(r.Own), Masking: int32(min(r.Masking, math.MaxInt32)), Retried: msOf(r.Retried), Queued: msOf(r.Queued), Order: order, RouteID: r.RouteID, Cost: r.Cost, Status: int32(r.Status), Tries: int32(r.Tries)}
p.setTime(r.Time)
var t [rowTexts]uint32
for i, s := range rowText(&r) {
t[i] = intern(*s)
@@ -308,7 +335,7 @@ func (c *rowChunk) add(r Row, msg string, order int64, failed bool) {
}
func (c *rowChunk) row(i int) Row {
p := &c.Rows[i]
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time, Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: int64(p.Millis), TTFT: int64(p.TTFT), FirstText: int64(p.FirstText), FirstReasoning: int64(p.FirstReasoning), ReasoningHidden: p.Flags&rowReasoningHidden != 0, CacheUnknown: p.Flags&rowCacheUnknown != 0, Sent: int64(p.Sent), Flow: int64(p.Flow), Own: int64(p.Own), Masking: int64(p.Masking), Retried: int64(p.Retried), Queued: int64(p.Queued), Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
r := Row{Record: Record{RouteID: p.RouteID, Time: p.Time(), Input: int(p.Tokens[0]), Output: int(p.Tokens[1]), CacheRead: int(p.Tokens[2]), CacheWrite: int(p.Tokens[3]), CacheWrite1h: int(p.Tokens[5]), Reasoning: int(p.Tokens[4]), Millis: int64(p.Millis), TTFT: int64(p.TTFT), FirstText: int64(p.FirstText), FirstReasoning: int64(p.FirstReasoning), ReasoningHidden: p.Flags&rowReasoningHidden != 0, CacheUnknown: p.Flags&rowCacheUnknown != 0, Sent: int64(p.Sent), Flow: int64(p.Flow), Own: int64(p.Own), Masking: int64(p.Masking), Retried: int64(p.Retried), Queued: int64(p.Queued), Status: int(p.Status), Tries: int(p.Tries), HandedOn: p.Flags&rowHandedOn != 0, Rejected: p.Flags&4 != 0, SessionOfficialLogin: p.Flags&8 != 0}, Cost: p.Cost, Priced: p.Flags&1 != 0, Swapped: p.Flags&2 != 0, Routed: p.Flags&32 != 0}
if p.Flags&rowCredits != 0 {
credits := p.Credits
r.Credits = &credits
@@ -381,7 +408,7 @@ type timedRef struct {
order int64
}
func timedOf(ref rowRef, p *packedRow) timedRef { return timedRef{ref, p.Time, p.Order} }
func timedOf(ref rowRef, p *packedRow) timedRef { return timedRef{ref, p.Time(), p.Order} }
func (a timedRef) newer(b timedRef) bool {
if !a.at.Equal(b.at) {
@@ -1686,7 +1713,9 @@ var matchKeySeeds = [2]maphash.Seed{maphash.MakeSeed(), maphash.MakeSeed()}
// Codex that names cache_write_input_tokens beside a gateway record that
// didn't, an older Codex that doesn't beside one that does; the sum is the
// same either way.
func matchTokens(t [6]int64) [3]int64 { return [3]int64{t[0] + t[3], t[1], t[2]} }
func matchTokens(t [6]int32) [3]int64 {
return [3]int64{int64(t[0]) + int64(t[3]), int64(t[1]), int64(t[2])}
}
type matchEnd struct {
at time.Time
@@ -1889,7 +1918,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
// minutes of polls allocated while an agent worked (#2278).
matchable := func(gateway *rowChunk, i int) bool {
p := &gateway.Rows[i]
return !(p.Flags&4 != 0 || gateway.text(p, 1) == 0 && p.Status >= 400) && !p.Time.Before(gatewaySince)
return !(p.Flags&4 != 0 || gateway.text(p, 1) == 0 && p.Status >= 400) && !p.Time().Before(gatewaySince)
}
withID := 0
for _, gateway := range gateways {
@@ -1943,7 +1972,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
for i := range open.Rows {
p := &open.Rows[i]
ref := rowRef{c, i}
if skip.has(ref) || reserved.has(ref) || p.Time.Before(since) {
if skip.has(ref) || reserved.has(ref) || p.Time().Before(since) {
continue
}
if open.text(p, 11) == 0 {
@@ -1995,7 +2024,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
return matchKey{}, false
}
p := &gateway.Rows[i]
if (p.Flags&4 != 0 || gateway.text(p, 1) == 0 && p.Status >= 400) || p.Time.Before(gatewaySince) {
if (p.Flags&4 != 0 || gateway.text(p, 1) == 0 && p.Status >= 400) || p.Time().Before(gatewaySince) {
return matchKey{}, false
}
session := gateway.Strings[gateway.text(p, 14)]
@@ -2063,7 +2092,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
g := &groups[ks[next]]
next++
p := &gateway.Rows[i]
ends[g.off+g.n] = matchEnd{p.Time.Add(time.Duration(p.Millis) * time.Millisecond), rowRef{gateway, i}}
ends[g.off+g.n] = matchEnd{p.Time().Add(time.Duration(p.Millis) * time.Millisecond), rowRef{gateway, i}}
g.n++
}
}
@@ -2086,7 +2115,7 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
for j := range c.Rows {
p := &c.Rows[j]
ref := rowRef{chunk, j}
if skip.has(ref) || reserved.has(ref) || matched.has(ref) || p.Time.Before(since) {
if skip.has(ref) || reserved.has(ref) || matched.has(ref) || p.Time().Before(since) {
continue
}
failed := p.Flags&16 != 0
@@ -2094,9 +2123,9 @@ func matchedBlocks(gateways []*rowChunk, chunks []*rowChunk, skip refSet, respon
continue
}
key := matchKey{session: c.Strings[c.text(p, 13)], tokens: matchTokens(p.Tokens), failed: failed}
from, to := p.Time.Add(-2*time.Second), p.Time.Add(2*time.Second)
from, to := p.Time().Add(-2*time.Second), p.Time().Add(2*time.Second)
if c.Strings[c.text(p, 0)] == "agy" {
key.session, to = agyMatchSession, p.Time.Add(agyStepLongest)
key.session, to = agyMatchSession, p.Time().Add(agyStepLongest)
}
count, at := 0, int32(0)
// Without a local ID either gateway partition can match. With an ID,
@@ -2297,7 +2326,7 @@ func (ps *pairedRows) visitChunk(rows *chunkRows, c *rowChunk, r *Row, fn func(t
for i := range open.Rows {
pr := &open.Rows[i] // not a copy: a row is 216 bytes
ref := rowRef{c, i}
if pr.Time.Before(ps.since) || after(ps.until, pr.Time) || ps.skip.has(ref) || ps.matched.has(ref) {
if pr.Time().Before(ps.since) || after(ps.until, pr.Time()) || ps.skip.has(ref) || ps.matched.has(ref) {
continue
}
*r = open.row(i)
+1 -1
View File
@@ -49,7 +49,7 @@ func pairSerials(sets ...[]*rowChunk) ([]uint64, bool) {
func unnamedSerial(c *rowChunk) uint64 {
h := mix(6, uint64(len(c.Rows)))
for i := range c.Rows {
h = mix(h, uint64(c.Rows[i].Order), uint64(c.Rows[i].Time.UnixNano()))
h = mix(h, uint64(c.Rows[i].Order), uint64(c.Rows[i].Time().UnixNano()))
}
return h | 1
}
+5 -5
View File
@@ -72,15 +72,15 @@ func (c *rowChunk) encode(keep func([]byte) bool) ([]byte, []*time.Location) {
locs := map[*time.Location]uint64{}
for k := range c.Rows {
p := &c.Rows[k]
loc := p.Time.Location()
loc := p.Time().Location()
id, ok := locs[loc]
if !ok {
id = uint64(len(locations))
locs[loc] = id
locations = append(locations, loc)
}
put(uint64(p.Time.Unix()))
put(uint64(p.Time.Nanosecond()))
put(uint64(p.Time().Unix()))
put(uint64(p.Time().Nanosecond()))
put(id)
put(uint64(p.Shape))
for _, n := range p.Varied {
@@ -264,7 +264,7 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string,
if loc >= uint64(len(c.Locations)) {
return nil
}
p.Time = time.Unix(sec, nano).In(c.Locations[loc])
p.setTime(time.Unix(sec, nano).In(c.Locations[loc]))
p.Shape = uint32(take())
if int(p.Shape) >= len(next.Shapes) {
return nil
@@ -277,7 +277,7 @@ func (c *rowChunk) unpackReusing(dst *rowChunk, into []packedRow, strs []string,
p.Varied[j] = uint32(n)
}
for j := range p.Tokens {
p.Tokens[j] = int64(take())
p.Tokens[j] = tokensOf(int64(take()))
}
p.Millis, p.TTFT, p.FirstText, p.Order = msOf(int64(take())), msOf(int64(take())), msOf(int64(take())), int64(take())
p.RouteID = int64(take())
+26 -2
View File
@@ -14,8 +14,8 @@ import (
// and 140 of a row's 328 bytes were string ids most rows of a chunk repeat.
// Packed and read back, every row is the row it was.
func TestRowsOfOneSessionShareAShape(t *testing.T) {
if n := unsafe.Sizeof(packedRow{}); n > 184 {
t.Fatalf("a packed row is %d bytes, want 184 at most", n)
if n := unsafe.Sizeof(packedRow{}); n > 152 {
t.Fatalf("a packed row is %d bytes, want 152 at most", n)
}
at := time.Date(2026, 10, 21, 12, 0, 0, 0, time.Local)
c := &rowChunk{}
@@ -66,3 +66,27 @@ func TestRowTimesPastWhatARowKeeps(t *testing.T) {
t.Fatalf("read back Millis %d, Queued %d, TTFT %d; want %d, %d, 1500", got.Millis, got.Queued, got.TTFT, int64(math.MaxInt32), int64(math.MinInt32))
}
}
// A row's tokens are kept in 32 bits and its time as ns beside its zone:
// a count past 2^31 is kept as the most an int32 holds, not wrapped, and
// packed and read back, the time is the instant it was in the zone it
// was, and a zero time stays zero.
func TestRowTokensAndZoneKept(t *testing.T) {
zone := time.FixedZone("IST", 5*3600+1800)
at := time.Date(2026, 10, 21, 12, 0, 0, 123, zone)
c := &rowChunk{}
c.add(Row{Record: Record{Time: at, Input: 3_000_000_000, Output: -3_000_000_000, CacheRead: 7}}, "", 0, false)
c.add(Row{Record: Record{Input: 1}}, "", 1, false)
for _, c := range []*rowChunk{c, c.pack().unpack()} {
got := c.row(0)
if got.Input != math.MaxInt32 || got.Output != math.MinInt32 || got.CacheRead != 7 {
t.Fatalf("read back Input %d, Output %d, CacheRead %d; want %d, %d, 7", got.Input, got.Output, got.CacheRead, math.MaxInt32, math.MinInt32)
}
if !got.Time.Equal(at) || got.Time.Location() != zone || got.Time.Format(time.RFC3339Nano) != at.Format(time.RFC3339Nano) {
t.Fatalf("read back time %v in %v, want %v", got.Time, got.Time.Location(), at)
}
if z := c.row(1).Time; !z.IsZero() {
t.Fatalf("a zero time read back as %v", z)
}
}
}