Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
usage: queries reading at once share one priced copy of a gateway block (#2278)
yetoneaafbe575ce8c
diff --git a/internal/usage/block_price.go b/internal/usage/block_price.goindex 0de55460a..d6c8258cb 100644--- a/internal/usage/block_price.go+++ b/internal/usage/block_price.go@@ -1,6 +1,7 @@package usageimport (+ "crypto/sha256""slices""sync"@@ -30,7 +31,13 @@ type blockPricer struct {price func(Record) *catalog.Priceby map[[4]string]pricedAsagents map[string][2]string- pooled []*[]packedRow+ // meta names what prices and names a call (requestState.meta): the+ // blocks priced of it are shared with the other queries reading now+ // (sharedPriced). A pricer of none keeps its blocks to itself.+ meta [32]byte+ shared bool+ held []pricedKey+ pooled []*[]packedRow}// pricedRows are the rows of the blocks a query priced, handed back when@@ -38,13 +45,59 @@ type blockPricer struct {// and allocating and clearing their rows again each time was a third of it.var pricedRows = sync.Pool{New: func() any { s := make([]packedRow, 0, logBlockRows); return &s }}+type pricedKey struct {+ meta [32]byte+ block *rowChunk+}++// pricedBlock is a gateway block priced, held by refs queries.+type pricedBlock struct {+ c *rowChunk+ rows *[]packedRow // pooled, nil when c's rows are not+ refs int+}++// 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:+// at a cold start with the app open, three such queries held 105 MB of+// rows between them and the app grew to 737 MB where it was 388 MB unasked+// (#2278). A block is frozen once written (freeze), and its priced copy is+// only read after: a query that changes a row's thread clones the chunk+// first (cloneCodexChunks).+var sharedPriced = struct {+ sync.Mutex+ blocks map[pricedKey]*pricedBlock+}{blocks: map[pricedKey]*pricedBlock{}}++// share has b's blocks shared with the other queries of meta.+func (b *blockPricer) share(meta string) {+ b.meta, b.shared = sha256.Sum256([]byte(meta)), true+}+// release hands the rows of the blocks it priced back, once the query no-// longer reads them (a page's rows are copies).+// longer reads them (a page's rows are copies); a shared block's, once+// the last query holding it is done.func (b *blockPricer) release() {for _, rows := range b.pooled {pricedRows.Put(rows)}b.pooled = nil+ if len(b.held) == 0 {+ return+ }+ sharedPriced.Lock()+ 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)+ }+ }+ }+ sharedPriced.Unlock()+ b.held = nil}func newBlockPricer(renames provider.Renames, wires map[string]string, price func(Record) *catalog.Price) *blockPricer {@@ -83,18 +136,56 @@ func (b *blockPricer) agent(ua string) (string, string) {return a[0], a[1]}-// block is the priced copy of a raw block, made for one query and not kept.+// block is the priced copy of a raw block, held until release: one+// another query of the same meta priced and holds still, or one made now.func (b *blockPricer) block(packed *rowChunk) *rowChunk {+ if !b.shared {+ c, rows := b.priceBlock(packed)+ if rows != nil {+ b.pooled = append(b.pooled, rows)+ }+ return c+ }+ k := pricedKey{b.meta, packed}+ sharedPriced.Lock()+ if e := sharedPriced.blocks[k]; e != nil {+ e.refs+++ sharedPriced.Unlock()+ b.held = append(b.held, k)+ return e.c+ }+ sharedPriced.Unlock()+ c, rows := b.priceBlock(packed)+ if c == nil {+ return nil+ }+ sharedPriced.Lock()+ e := sharedPriced.blocks[k]+ if e == nil { // priced by another query meanwhile: that one's is kept+ e = &pricedBlock{c: c, rows: rows}+ sharedPriced.blocks[k] = e+ } else if rows != nil {+ pricedRows.Put(rows)+ }+ e.refs+++ sharedPriced.Unlock()+ b.held = append(b.held, k)+ return e.c+}++// priceBlock is the priced copy of a raw block, and the pooled rows it is in.+func (b *blockPricer) priceBlock(packed *rowChunk) (*rowChunk, *[]packedRow) {buf := pricedRows.Get().(*[]packedRow)raw := packed.unpackInto(*buf)// unpackInto decodes into the buffer whenever it is large enough+ var pooled *[]packedRowif raw != nil && raw != packed && cap(*buf) >= len(raw.Rows) {- b.pooled = append(b.pooled, buf)+ pooled = buf} else {pricedRows.Put(buf)}if raw == nil {- return nil+ return nil, nil}c := *rawif raw == packed {@@ -186,5 +277,5 @@ func (b *blockPricer) block(packed *rowChunk) *rowChunk {p.Cost = got.price.CostSplit(int(p.Tokens[0]), int(p.Tokens[1]), int(p.Tokens[2]), int(p.Tokens[3]), int(p.Tokens[5]))}}- return &c+ return &c, pooled}diff --git a/internal/usage/block_price_test.go b/internal/usage/block_price_test.gonew file mode 100644index 000000000..ad685285c--- /dev/null+++ b/internal/usage/block_price_test.go@@ -0,0 +1,65 @@+package usage++import (+ "testing"+ "time"++ "github.com/yetone/magpie/internal/catalog"+ "github.com/yetone/magpie/internal/provider"+)++// Queries reading at once hold one priced copy of a gateway block between+// them, kept until the last is done: the GUI's requests at a cold start+// each held the whole history's, and the app doubled (#2278). A query of+// other prices or names prices its own.+func TestPricedBlocksSharedWhileHeld(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 := raw.pack()+ if packed == &raw {+ t.Fatal("the block was not packed")+ }+ pricer := func(meta string) *blockPricer {+ b := newBlockPricer(provider.Renames{}, nil, func(Record) *catalog.Price { return nil })+ b.share(meta)+ return b+ }+ held := func() int {+ sharedPriced.Lock()+ defer sharedPriced.Unlock()+ n := 0+ for k := range sharedPriced.blocks {+ if k.block == packed {+ n+++ }+ }+ return n+ }+ a, b, other := pricer("m"), pricer("m"), pricer("n")+ ca, cb, co := a.block(packed), b.block(packed), other.block(packed)+ if ca == nil || ca != cb {+ t.Fatalf("two queries of one meta priced %p and %p", ca, cb)+ }+ if co == ca {+ t.Fatal("a query of other prices read another's block")+ }+ if ca.row(7).Input != 107 || co.row(7).Input != 107 {+ t.Fatalf("rows read back %d, %d", ca.row(7).Input, co.row(7).Input)+ }+ a.release()+ if held() != 2 || b.block(packed) != cb {+ t.Fatalf("a block one query still holds was let go: %d held", held())+ }+ b.release()+ b.release() // a second release lets nothing go twice+ other.release()+ if n := held(); n != 0 {+ t.Fatalf("%d blocks held after every query was done", n)+ }+ if c := pricer("m").block(packed); c == ca {+ t.Fatal("a block let go was handed out again")+ }+}diff --git a/internal/usage/request_page.go b/internal/usage/request_page.goindex 3d3879dc8..90d1307be 100644--- a/internal/usage/request_page.go+++ b/internal/usage/request_page.go@@ -767,6 +767,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.Cidx = shared.private()shared.Unlock()b := readRequestBlocks(idx, st, p, now, readSource)+ defer b.priced.release() // on a panic too: a shared block is held until let govar names map[string]stringif someShared {names = sharedNames()@@ -819,6 +820,7 @@ func codexEffortOfIndex(st requestState, p Period, now time.Time) map[string][]sidx := shared.private()shared.Unlock()b := readRequestBlocks(idx, st, p, now, sessions.ReadCallSource)+ defer b.priced.release()sums := effortSums{}ps, next := pairRowsMemo(p, now, b.gateways, b.chunks, b.others, st.codexIdentities, memo)ps.visitActors(func(r *Row) { sums.add(r) })@@ -893,6 +895,7 @@ func readRequestBlocks(idx *requestIndex, st requestState, p Period, now time.Tivar gateways []*rowChunkrenames := provider.UsageRenames()priced := newBlockPricer(renames, cfg.ModelWires, price)+ priced.share(st.root + "|" + st.meta)for _, packed := range snapshot.blocks {if !gatewaySince.IsZero() && packed.Latest.Before(gatewaySince) {continuediff --git a/internal/usage/request_page_test.go b/internal/usage/request_page_test.goindex db7eb6553..95a5f2007 100644--- a/internal/usage/request_page_test.go+++ b/internal/usage/request_page_test.go@@ -346,6 +346,7 @@ func TestRequestBlocksKeepOneChunkASource(t *testing.T) {read := func() (*rowChunk, *requestIndex) {idx := shared.private()b := readRequestBlocks(idx, st, All, now, sessions.ReadCallSource)+ defer b.priced.release()if len(b.chunks) != 1 {t.Fatalf("%d chunks, want 1", len(b.chunks))}