Commit Graph
4 Commits
Author SHA1 Message Date
yetone 9cd4ef6a19 sessions: an aliased range is named once per change, not on every 10 s read
While the Sessions page is open, the GUI reads the 7, 30 and all-days
ranges again every 10 s. Those ranges are kept (keptStats), so a read
with nothing changed costs almost nothing, except when a model is
counted under another name (a usage alias, or a shared group's spelled
name). Then aliasStats copied every day's usage and every session's
summary of each range on each read: ~5 MB a read for the owner's real
history, which was then thrown away because nothing had changed.

aliasKept keeps each range's aliased Stats with the kept Stats it came
from and the names (provider.UsageNamesKey). When the kept Stats are the
same slices and the names haven't changed, it returns the same answer.
Kept Stats are never written, and MergeExternalStats copies before it
writes, so the answer can be shared. The memo is dropped with the kept
ranges (forgetKeptStats), so it never outlives them. UsageAliasKeyed
reads settings once for both the alias and its key.

Run: TestAliasedRangeMadeOncePerNames (new) passes. With the memo
skipped it fails at "named again with nothing changed". With the key
and source check removed it fails at "the old names' range given after
the names changed". go test ./internal/sessions ./internal/provider
./internal/gui and GOOS=windows / GOOS=linux -tags nogui vet: ok at
328dc97e2 plus this change.
Real account (mote, ~/r2278/acct, /api/sessions/stats polled every 10 s
for days 0, 7 and 30, 4 minutes of
alloc_space diffed): aliasStats 75.1 MB before (v0.1.3664 build), not
in the profile after; everything allocated 519.7 -> 467.3 MB. Not
tried: Windows and Linux runs (nothing here is per OS).
2026-11-11 09:30:53 +08:00
yetone d401c25951 usage: the found-group names hold the catalog, so a usage ask no longer builds it again (#5978)
4921bf5a9 (#5892) put provider.UsageNamesKey into usagePriceCacheKey,
the check every GatewaySessions ask, summary and Codex model/effort read
makes before using its kept view. UsageNamesKey reads usageGroupNames,
which asked sharedGroups outside a catalog hold, so each ask built every
provider's entries and the found groups again. In the test sandbox that
was ~130 KB more per ask, enough to take TestGatewaySessionsHandOutTheKeptProjection
over its bar on macOS CI and Windows (547208 / 671560 > 552000). With
real providers it is a whole catalog build on every Sessions poll.

usageGroupNames now holds the catalog (provider.Hold), and so does
usagePriceCacheKey, so provider.All and the group names it reads share
one build. A held catalog is checked against the providers' and
settings' files at the first hold and dropped on any write, as for every
GUI request.

Found by bisect on mote over TotalAlloc per ask: 44732325e 407218,
4921bf5a9 537040.

Run at 9522288b1 plus this change:
- mote (macOS): go vet -tags nogui and go test -count=1 -tags nogui
  ./internal/provider ./internal/usage: ok. Before the rebase, the same
  plus ./internal/sessions ./internal/usageapi ./internal/gui: ok.
  An ask allocates 381834 bytes (was 547208); the Codex effort build
  271472 against 456152.
- xiaomi-gpu (Windows): both allocation tests pass, 399501 and 371480
  (were 699558 and 488640 at origin/main 87dfc0d0b, both red).
  The package run of ./internal/usage ./internal/provider is red on
  18 tests there; each one that also ran at origin/main 87dfc0d0b is red
  the same there (Codex keychain, TestDesktopSessionAccountMetadata,
  TestGitOnDisk*, TestResolveKeptAcrossRequests, TestSavedButSignedOut,
  TestPricerAllocatesNothingPerModel, TestLANNeighbours), and
  TestUsageReadAndReadAgain is #4796 (equal clock readings). Filed the
  two with no issue: #6024, #6025.
- gofmt -l: clean.

Broken by hand:
- both holds out (origin/main): 547208 on mote, red.
- only usagePriceCacheKey's hold out: 414295, green; it is the
  provider-side hold that fixes the class (UsageAlias and PublicRefs
  read usageGroupNames too).

Not tried: a real config with many providers (the saving there is a
catalog build per ask, not measured), and Linux.
2026-11-11 05:54:17 +08:00
yetoneandNorethSea 4921bf5a97 usage, sessions: one model option for a found routing group's two ids (#5892, Norethcy on X)
A found routing group is called by its public id (auto/<model>) and is
kept as group/auto-<slug>; calls recorded under either were counted as two
models, so Usage › Sessions' model filter listed the same group twice and
the ledger, summaries and session lists split its calls.

Ported from NorethSea's 30d6261cd on their fork: UsageAlias names a found
group by its public id before the user's alias (both spellings, old
session files too), sessions' lists, the ledger keyer, the summary cache's
key and Codex's model/effort read through it, and a cache keyed on the
group names (UsageNamesKey) is read again when a group is renamed. A user's
own provider named "auto" keeps auto/<model> (autoRefsOn).

Changed in review: the patch's ledger filter compared every record with
provider.SameRef, which reads the providers (customIDs, a stat of
providers.json) for each record a filter passes over. FilterOf, the one
place a Filter is made from a query, now canonicalizes the model once, and
keepsRecord asks the providers only for an auto/ record under a group/
filter (sameGroupModel).

Run (mote's sshd reset every connection all afternoon, so on the Linux box
through wsl-run; the package run at base 720200092, and the -run tests,
quota-holds and i18n-keys again at this head on 208b89422; rebased since onto 44732325e,
a gateway test only):
- go test -count=1 -tags nogui ./internal/gui ./internal/provider
  ./internal/sessions ./internal/usage ./internal/usageapi: ok
- go vet -tags nogui (linux), GOOS=darwin CGO_ENABLED=0 go vet (provider,
  usage, usageapi, sessions), and go vet on Windows (win-run, those and
  internal/gui): clean. gofmt -l: clean.
- GUI: usage-ledger-model-pick, usage-ledger, quota-fit-batched,
  i18n-keys in chromium and webkit. usage-ledger's "newest live route
  needs no return-to-live button" (and zh "request routing links") is red
  the same on origin/main 987eac0aa on that box: #3104, #4078.

Broken by hand:
- keepsRecord back to r.Model != f.Model: TestUsageFoundGroupNames and
  TestLedgerFoundGroupNames red.
- usageGroupNames returning nothing: TestUsageFoundGroupNames (provider,
  usage), TestSessionsFoundGroupNames, TestCodexEffortFoundGroupNames,
  TestLedgerFoundGroupNames red.

Not tried: a macOS run (mote unreachable), the darwin gui package's vet,
and the reporter's own usage log.

Co-authored-by: NorethSea <963979204@qq.com>
2026-11-10 18:01:13 +08:00
yetone ea9454d2d8 usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:

  magpie model alias deepseek-v4.1-flash deepseek-flash
  magpie model alias deepseek-v4.1-flash            (what it is counted as)
  magpie model alias deepseek-v4.1-flash --reset
  magpie model aliases

kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.

Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.

Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.

Run (worktree at f4640c0ae, rebased onto 2b4c0664e with no overlap):
- gofmt -l: clean. go vet ./... darwin, GOOS=linux -tags nogui, GOOS=windows: ok.
- go test -count=1 -timeout 45m (sandbox HOME) internal/usage,
  sessions, provider, cli, settings, gui, tui: all ok.
- Real binary in a sandbox HOME: two usage.jsonl calls priced $2 and
  $100 per M: `magpie usage` showed two model rows ($2.00, $100), and
  after `magpie model alias` one row, 2.0M, 2 calls, $102; the session
  row too. alias/aliases/--reset/loop/self output checked by hand.

Broken by hand, each red then restored:
- no alias in summarizeFrom: TestUsageAlias* red
- nil alias into the gateway projection: TestUsageAlias* red
- statsIn without aliasStats / List without aliasSession:
  TestSessionsCountAliasedModelsAsOne red
- merged usage row keeps Priced true: TestAliasStatsLeavesItsInputAlone red
- loop check off / self check by == / last-good read off / flag check off:
  TestUsageAliasRefusesSelfAndLoops, TestUsageAliasUnreadSettings,
  TestModelAliasCmd red
- GUI save drops UsageAliases: TestSettingsSaveKeepsWhatItDoesNotSend red

Not tried: the GUI pages in a browser (no app.js change; the Usage and
Sessions pages read the same rows), the full go test ./... before push,
Windows box.
2026-10-24 02:48:50 +08:00