usage: a priced gateway block is kept 30s past its last query, so the next poll reads it (#2278)

The queries reading at once already shared each gateway block's priced
copy (sharedPriced), but let it go when the last of them was done. Its
rows' sync.Pool was emptied by the collections between polls, so every
Usage poll decoded and priced the whole history again: priceBlock was
~960 MB, the pool's New ~720 MB, of 6.1 GB allocated in 80s of polls.

A block no query holds now stays pricedLinger (30s, past the 10s and 15s
polls) and is then let go by a timer; ReleaseScratch, which the window
calls once its reads rest, lets them all go at once. The key is the same
as for the sharing (requestState root|meta, the frozen block), so what a
block is priced as is no less current than when two queries share it.

Measured on mote (~/r2278 run2278d, 10 endpoints every 5s, gateway feed
from 60s), against 936bdccfa:
  allocated 120s-200s  6151 -> 5071 MB, priceBlock and the pool gone
  60s CPU profile: madvise 1.40 -> 0.85s, GC mark 4.68 -> 4.29s
  avg CPU after feed   32.9 -> 30.3%
  footprint peak 765.6 -> 769.8M, avg RSS after 60s 967 -> 966 MiB
  ps RSS peak 1010 -> 1192 MiB (footprint, what Activity Monitor
  shows, the same)
Latency is not comparable: mote's load was ~43, and the Sessions
endpoints this doesn't touch were as much slower (1.16 -> 2.01s) as
the Usage ones in the same run.
Same output: eq2.sh asked each binary heatmap, requests and usage
30d/7d/all twice; every reply byte for byte the same across binaries
and between the first and the second (kept) ask.

Rebased onto 0e2739743 (redact, codex resets); run again after it.
Run at the pushed head on mote: GOOS=linux/windows/darwin go vet -tags
nogui ./internal/usage/ ./internal/gui/ ok; go test ./internal/usage/
./internal/usageapi/ ok; ./internal/gui/ red only in
TestMainWindowCorners/macOS_26_SDK, the open #3949.
Broken by hand: release letting go at once again (the old code) turns
TestPricedBlocksSharedWhileHeld red ("0 blocks kept after every query
was done, want 2").
This commit is contained in:
yetone
2026-10-29 08:19:54 +08:00
parent 0e2739743b
commit 926ef769ff
3 changed files with 112 additions and 8 deletions
+56 -6
View File
@@ -3,6 +3,7 @@ package usage
import (
"slices"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
@@ -54,8 +55,17 @@ type pricedBlock struct {
c *rowChunk
rows *[]packedRow // pooled, nil when c's rows are not
refs int
idle time.Time // when the last query holding it was done
}
// pricedLinger is how long a priced block is kept after the last query
// holding it is done. It outlasts the GUI's polls (Usage every 10 s,
// Sessions every 15 s): each poll priced the whole history again, its
// rows' pool emptied by the collections between, ~920 MB of 5.7 GB
// allocated in 80 s of polls (#2278). The window's rest lets them go at
// once (ReleaseScratch).
const pricedLinger = 30 * time.Second
// sharedPriced are the gateway's blocks the queries reading now priced, by
// block. A query over the whole history holds every block decoded until it
// is done, and the GUI's requests arriving together each held their own:
@@ -67,8 +77,47 @@ type pricedBlock struct {
var sharedPriced = struct {
sync.Mutex
blocks map[pricedKey]*pricedBlock
sweep *time.Timer // the idle blocks' going, or nil
}{blocks: map[pricedKey]*pricedBlock{}}
// sweepPriced lets the blocks no query has held for pricedLinger go, all
// idle ones when every is true, and is armed again while idle ones are
// left. Called under sharedPriced's lock.
func sweepPriced(now time.Time, every bool) {
left := time.Duration(0)
for k, e := range sharedPriced.blocks {
if e.refs != 0 {
continue
}
if wait := pricedLinger - now.Sub(e.idle); !every && wait > 0 {
left = max(left, wait)
continue
}
delete(sharedPriced.blocks, k)
if e.rows != nil {
pricedRows.Put(e.rows)
}
}
if sharedPriced.sweep != nil {
sharedPriced.sweep.Stop()
sharedPriced.sweep = nil
}
if left > 0 {
sharedPriced.sweep = time.AfterFunc(left, func() {
sharedPriced.Lock()
defer sharedPriced.Unlock()
sweepPriced(time.Now(), false)
})
}
}
// releasePriced lets every block no query holds now go.
func releasePriced() {
sharedPriced.Lock()
defer sharedPriced.Unlock()
sweepPriced(time.Now(), true)
}
// share has b's blocks shared with the other queries of meta, a hash of
// requestState's root and meta.
func (b *blockPricer) share(meta [32]byte) {
@@ -76,8 +125,8 @@ func (b *blockPricer) share(meta [32]byte) {
}
// release hands the rows of the blocks it priced back, once the query no
// longer reads them (a page's rows are copies); a shared block's, once
// the last query holding it is done.
// longer reads them (a page's rows are copies); a shared block's,
// pricedLinger after the last query holding it is done.
func (b *blockPricer) release() {
for _, rows := range b.pooled {
pricedRows.Put(rows)
@@ -87,15 +136,16 @@ func (b *blockPricer) release() {
return
}
sharedPriced.Lock()
now := time.Now()
for _, k := range b.held {
e := sharedPriced.blocks[k]
if e.refs--; e.refs == 0 {
delete(sharedPriced.blocks, k)
if e.rows != nil {
pricedRows.Put(e.rows)
}
e.idle = now
}
}
if sharedPriced.sweep == nil {
sweepPriced(now, false)
}
sharedPriced.Unlock()
b.held = nil
}
+53 -1
View File
@@ -57,10 +57,62 @@ func TestPricedBlocksSharedWhileHeld(t *testing.T) {
b.release()
b.release() // a second release lets nothing go twice
other.release()
// the next poll's query reads the same priced block
if n := held(); n != 2 {
t.Fatalf("%d blocks kept after every query was done, want 2", n)
}
next := pricer("m")
if c := next.block(packed); c != ca {
t.Fatal("the next query of one meta priced the block again")
}
next.release()
// kept until pricedLinger passes with no query holding them
sharedPriced.Lock()
sweepPriced(time.Now().Add(pricedLinger/2), false)
sharedPriced.Unlock()
if n := held(); n != 2 {
t.Fatalf("%d blocks kept before pricedLinger passed, want 2", n)
}
sharedPriced.Lock()
sweepPriced(time.Now().Add(pricedLinger+time.Second), false)
sharedPriced.Unlock()
if n := held(); n != 0 {
t.Fatalf("%d blocks held after every query was done", n)
t.Fatalf("%d blocks kept pricedLinger after every query was done", n)
}
if c := pricer("m").block(packed); c == ca {
t.Fatal("a block let go was handed out again")
}
}
// The window's rest lets every priced block no query holds go at once,
// and one a query still holds stays.
func TestPricedBlocksGoWithTheScratch(t *testing.T) {
var raw rowChunk
at := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC)
for i := 0; i < logBlockRows; i++ {
raw.add(Row{Record: Record{Time: at, Provider: "openai", Model: "gpt-5", Input: 100 + i, Output: 10}}, "", int64(i), false)
}
packed, other := raw.pack(), (&raw).pack()
pricer := func() *blockPricer {
b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })
b.share(sha256.Sum256([]byte("scratch")))
return b
}
idle, holding := pricer(), pricer()
idle.block(packed)
idle.release()
held := holding.block(other)
ReleaseScratch()
sharedPriced.Lock()
_, kept := sharedPriced.blocks[pricedKey{sha256.Sum256([]byte("scratch")), packed}]
_, still := sharedPriced.blocks[pricedKey{sha256.Sum256([]byte("scratch")), other}]
sharedPriced.Unlock()
if kept {
t.Fatal("ReleaseScratch kept a priced block no query held")
}
if !still || held.row(3).Input != 103 {
t.Fatal("ReleaseScratch let go a block a query still held")
}
holding.release()
ReleaseScratch()
}
+3 -1
View File
@@ -1396,10 +1396,12 @@ func mapFor[K comparable, V any](m map[K]V, n int) map[K]V {
return m
}
// ReleaseScratch lets go of what the request matching keeps between calls.
// ReleaseScratch lets go of what the request matching keeps between calls,
// and the priced blocks no query holds.
func ReleaseScratch() {
keptMatch.Store(nil)
keptPicks.Store(nil)
releasePriced()
}
// sized is s[:n], zeroed, in s's array when it holds n