usage: Codex threads' model/effort consumption is read again only when a call, price or identity changed (#1591)

e3d3f75fd added model_effort to /api/sessions, /one, /manage and
/overview. Each answer read the whole ledger (LedgerOf(All) for the list),
and the Sessions page asks for the list and the overview every 15s while it
is open, so a long history was worked out again on every refresh.

CodexModelEffort now keeps its last answer per period under the key the
request index already keys its pages on (gateway log version, the agents'
call files, other computers' days, Codex identities, prices, the day).
That key is read by readRequestState, taken out of queryPage unchanged. An
answer from a log read part way is not kept, as cachedVias does. Callers
get their own copy.

Run at this commit on d692b2548 (Go 1.26.8 darwin/arm64, sandbox HOME):
- go test -tags nogui -run Codex ./internal/usage: pass
- TestCodexModelEffortReadsLedgerOnlyWhenCallsChange, broken by hand three
  ways, each red: the key not compared (a changed rollout still read 20,
  not 2000), the cache never hit (ledger read 2 times), the cached slice
  handed out (a caller's write showed in the next answer).
The full suite, vet and builds are in the commit that lands with it.
Not measured against a real 750k-call history.
This commit is contained in:
yetone
2026-10-14 22:45:40 +08:00
committed by yetone
parent 644f4316f9
commit 019199e0f7
3 changed files with 127 additions and 20 deletions
+47 -1
View File
@@ -3,6 +3,7 @@ package usage
import (
"slices"
"strings"
"sync"
"unsafe"
"github.com/yetone/magpie/internal/sessions"
@@ -240,15 +241,60 @@ func codexActorBytes(actors []string) int64 {
return bytes
}
// codexEffortCache keeps CodexModelEffort's last answer for each period: the
// Sessions page asks for all history every 15s, and the ledger under it is
// read again only when a call, a price or an identity changed.
var codexEffortCache struct {
sync.Mutex
key string
values map[Period]map[string][]sessions.ModelEffort
}
// effortBuilt, in tests, is told each time CodexModelEffort reads the ledger.
var effortBuilt func()
// CodexModelEffort reports each Codex thread's own priced ledger consumption.
func CodexModelEffort(p Period) map[string][]sessions.ModelEffort {
if LogCalls != nil { // synthetic logs carry no state to key on
return codexModelEffort(LedgerOf(p, Filter{}).Rows)
}
now := Clock()
st := readRequestState(now)
codexEffortCache.Lock()
cached, ok := codexEffortCache.values[p]
if codexEffortCache.key != st.key {
ok = false
}
codexEffortCache.Unlock()
if !ok {
if effortBuilt != nil {
effortBuilt()
}
cached = codexModelEffort(LedgerOfAt(p, Filter{}, now).Rows)
if st.snapshot.info != nil && st.snapshot.off == st.snapshot.info.Size() {
codexEffortCache.Lock()
if codexEffortCache.key != st.key {
codexEffortCache.key, codexEffortCache.values = st.key, map[Period]map[string][]sessions.ModelEffort{}
}
codexEffortCache.values[p] = cached
codexEffortCache.Unlock()
}
}
out := make(map[string][]sessions.ModelEffort, len(cached))
for actor, values := range cached {
out[actor] = slices.Clone(values)
}
return out
}
func codexModelEffort(rows []Row) map[string][]sessions.ModelEffort {
type modelEffortKey struct{ model, effort string }
type total struct {
value sessions.ModelEffort
priced bool
}
groups := map[string]map[modelEffortKey]*total{}
for _, row := range LedgerOf(p, Filter{}).Rows {
for _, row := range rows {
if row.codexActor == "" || row.IsRejected() ||
row.Input+row.Output+row.CacheRead+row.CacheWrite == 0 {
continue
+42
View File
@@ -452,3 +452,45 @@ func TestCodexActorSurvivesPackedRequestChunk(t *testing.T) {
t.Fatal("query identity changed the source chunk")
}
}
// The Sessions page asks for every Codex thread's consumption over all
// history each time it refreshes: the ledger is read again only when a call
// changed, and a changed rollout shows at once.
func TestCodexModelEffortReadsLedgerOnlyWhenCallsChange(t *testing.T) {
pageHome(t)
now := holdClock(t, time.Date(2026, 9, 30, 12, 0, 0, 0, time.UTC))
Append(Record{Time: now.Add(-2 * time.Hour), Agent: "claude-code", Provider: "openai", Model: "m", Input: 1, Output: 1, Status: 200})
path := filepath.Join(sessions.CodexDir(), "sessions", "2026", "09", "30", "rollout-2026-09-30T10-00-00-main-a.jsonl")
writeCodexCall(t, path, "main-a", "main-a", `"vscode"`, "resp-1", "m", "low", now.Add(-time.Hour), 20, 3)
built := 0
effortBuilt = func() { built++ }
t.Cleanup(func() { effortBuilt = nil })
first := CodexModelEffort(All)
if got, ok := findModelEffort(first["main-a"], "m", "low"); !ok || got.Input != 20 {
t.Fatalf("first read = %+v", first)
}
first["main-a"][0].Input = 999 // a caller's copy is its own
again := CodexModelEffort(All)
if built != 1 {
t.Fatalf("ledger read %d times for an unchanged history, want 1", built)
}
if got, _ := findModelEffort(again["main-a"], "m", "low"); got.Input != 20 {
t.Fatalf("cached answer was changed through a caller's copy: %+v", again)
}
writeCodexCall(t, path, "main-a", "main-a", `"vscode"`, "resp-1", "m", "low", now.Add(-time.Hour), 2000, 30)
later := now.Add(time.Minute)
if err := os.Chtimes(path, later, later); err != nil {
t.Fatal(err)
}
changed := CodexModelEffort(All)
if got, _ := findModelEffort(changed["main-a"], "m", "low"); built != 2 || got.Input != 2000 {
t.Fatalf("after the rollout changed: built %d, %+v", built, changed)
}
Append(Record{Time: now.Add(-time.Minute), Agent: "codex", Provider: "openai", Model: "m", Input: 5, Output: 1, Status: 200, ResponseID: "resp-2"})
CodexModelEffort(All)
if built != 3 {
t.Fatalf("a new gateway call did not read the ledger again: built %d", built)
}
}
+38 -19
View File
@@ -293,22 +293,21 @@ func recordHash(path string, n int64) string {
return fmt.Sprintf("%x", h.Sum(nil))
}
func QueryPage(p Period, f Filter, offset, limit int) RequestPage {
return queryPage(p, f, offset, limit, sessions.ReadCallSource)
// requestState is what the calls read at now depend on: the gateway log's
// snapshot, the agents' call files, other computers' days, Codex's thread
// identities and what prices and names a call. A change to meta drops the
// request index's chunks; a change to key, its pages.
type requestState struct {
sources []sessions.CallSource
codexIdentities map[string]sessions.CodexIdentity
cfg settings.Settings
snapshot *logSnapshot
days []sharedSource
someShared bool
root, meta, key string
}
func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.CallSource) []sessions.Call) (page RequestPage) {
if limit <= 0 {
limit = 100
}
limit = min(limit, 500)
offset = max(0, offset)
// The time is read once, so that the rows, the chart and the day the page
// is kept for are of one day when midnight falls while it is worked out.
now := Clock()
// A replacement reader remains useful to callers supplying synthetic logs.
if LogCalls != nil {
return pageFromLedgerAt(p, f, offset, limit, LedgerOfAt(p, Filter{}, now), now)
}
func readRequestState(now time.Time) requestState {
sources := sessions.CallSources()
codexIdentities := sessions.CodexIdentities()
slices.SortFunc(sources, func(a, b sessions.CallSource) int {
@@ -340,8 +339,7 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
meta += fmt.Sprintf("|%x|%s", h.Sum(nil), statKey(catalog.LivePath("antigravity")))
h.Reset()
snapshot := readLogSnapshot()
version := snapshot.version
fmt.Fprint(h, meta, version, now.Format("2006-01-02 MST"))
fmt.Fprint(h, meta, snapshot.version, now.Format("2006-01-02 MST"))
for _, s := range sources {
fmt.Fprintf(h, "%s:%d:%d;", s.Path, s.Size, s.Modified.UnixNano())
}
@@ -349,8 +347,29 @@ func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.C
for _, s := range days {
fmt.Fprintf(h, "%s:%d:%d;", s.path, s.size, s.mod.UnixNano())
}
key := fmt.Sprintf("%x", h.Sum(nil))
root := Path() + "|" + catalog.CachePath()
return requestState{sources: sources, codexIdentities: codexIdentities, cfg: cfg, snapshot: snapshot, days: days, someShared: someShared,
root: Path() + "|" + catalog.CachePath(), meta: meta, key: fmt.Sprintf("%x", h.Sum(nil))}
}
func QueryPage(p Period, f Filter, offset, limit int) RequestPage {
return queryPage(p, f, offset, limit, sessions.ReadCallSource)
}
func queryPage(p Period, f Filter, offset, limit int, readSource func(sessions.CallSource) []sessions.Call) (page RequestPage) {
if limit <= 0 {
limit = 100
}
limit = min(limit, 500)
offset = max(0, offset)
// The time is read once, so that the rows, the chart and the day the page
// is kept for are of one day when midnight falls while it is worked out.
now := Clock()
// A replacement reader remains useful to callers supplying synthetic logs.
if LogCalls != nil {
return pageFromLedgerAt(p, f, offset, limit, LedgerOfAt(p, Filter{}, now), now)
}
st := readRequestState(now)
sources, codexIdentities, cfg, snapshot, days, someShared := st.sources, st.codexIdentities, st.cfg, st.snapshot, st.days, st.someShared
version, meta, key, root := snapshot.version, st.meta, st.key, st.root
idx := &requestCache
idx.Lock()