d3fc6f2bfada18e6ae7887b79ed1e4c650ca37e1
309
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
7c1dc198d1 |
usage: a turn over the Responses WebSocket counts what the socket was sent, and says so
A Codex turn kept on a Responses WebSocket sends only the new items as a
delta, but the row's ↑ was the whole HTTP body magpie built before the
transport ran, so a long conversation read as ~13MB up per turn
(matrix0487 on Discord). overSocket now records what each socket write
carried (wroteSocket) and, when the turn went out on the socket alone,
replaces the HTTP figure with those bytes (sentOnSocket); a turn that fell
back to HTTP keeps the HTTP body and adds any socket write made before the
fallback. errCodexSocketAgain's retry on a new socket counts both writes.
The row remembers that it went over the socket: Record.Socket (json "ws"),
packed as Flags bit 16384 (rowSocket, added to TestRowFlagsApart). The
Requests table's protocol badge says "Responses · WS" and the details'
Protocol line "Responses · WebSocket".
Run on mote at this commit (rebased on origin/main
|
||
|
|
a8aeb2cad2 |
usage: picked days can start and end at a minute
blrbrzkj on Discord asked to see usage from one time to another, not only whole days. The range menu has a start and an end time under its month (empty is the whole day; 9:30, 0930 and 09:30 all read 09:30). Picked with the days, the period is "2026-10-01T09:30..2026-10-01T18:00"; Enter applies new times to the days already picked. A time that isn't one, or an end not after the start on one day, is marked and asks for nothing. The opt says "Oct 1 09:30 – 18:00". The backend reads either end as a date or a date with its minute (usage.RangeOf, bounds); an untimed end is its next midnight. A timed range of 48 hours or less is drawn by the hour from the first's hour. CSV names drop the colons. Run (mote): node --test usage-range-times (new, chromium + webkit, en + zh), usage-range, i18n-keys, credit-days: 26/26 ok. go test ./internal/usage ./internal/gui ok (TestCoreScriptBudget fits, the periodDays comment cut to pay for its regex); gofmt clean; go vet native, GOOS=windows (usage, gui), GOOS=linux (usage) ok. Broken by hand: a timed end read as its day's midnight turns TestPickedMinutesArePeriod red. The page's own typedTime first clashed with app.js's hhmm and stopped the Usage page mounting; the GUI run caught it. Not tried: the real app with a real ledger; ja/de/zh-TW screens. Reported-by: blrbrzkj (Discord) |
||
|
|
7e5cebb86c |
usage: a model list fetched again unchanged keeps the usage index
Each account's model list is fetched again on every start and every 45 minutes, and saveLive writes it again with only its "fetched" time moved. Usage keyed the request index (and its file on disk, requests-v1.bin) and the priced summaries on that file's mtime (statKey(catalog.LivePath)), so each such save dropped every chunk: every start, and every refresh while running, read the whole session history again, decoded every call shard and rebuilt every row. catalog.LiveKey names a saved list by a hash of its bytes without the fetch time, made once per parse of the file (readLive's memo). A list saved before Since was kept is dated by its fetch (LiveSince), so its fetch time stays in its key. usage's liveListKey uses it for every provider and Antigravity in readRequestState's meta and in usagePriceCacheKey (the same mtime key, the sibling), and falls back to the stat when the list can't be read. Found by dumping both disk headers on mote: same binary, same sources, and only the providers' hash differed, run to run. Measured on mote, a copy of the owner's real accounts, GUI open, network blocked, the Claude list rewritten as a start's fetch does. Restart of the same build, t10 (main) against t11 (this): CPU in the first ~3 minutes 11.6s -> 2.5s allocated 2.74GB -> 0.81GB sessions.loadCalls 771MB -> gone from the top footprint 174MB -> 175MB The first start after an upgrade that changes usage's code still builds everything once (requestDiskBinary), as before. Tests: TestRequestStateKeptAcrossAListFetchedAgain saves the same list again an hour later and needs readRequestState's meta and usagePriceCacheKey unchanged, and both changed for another list; on the old usage code it is red on both. TestLiveKeyOnlyMovesWithTheList and TestLiveKeyOfAnOldListKeepsItsFetch cover the key itself. Run on mote at this tree: go test ./internal/catalog ./internal/usage ./internal/provider -count=1 ok; go vet ./... ok; GOOS darwin/linux/ windows go vet ./internal/catalog ./internal/usage ok (./... cross-OS stops at wails' cgo files, as on main); gofmt clean. Not run: the full ./... suite before the push (running after), GUI. |
||
|
|
fc9ce34d86 |
usage: hashRows reuses its scratch, within sizes its rows exactly
Startup on a copy of the owner's real accounts (mote, GUI, network
blocked, acgui.sh) allocated ~3.5GB, and two usage functions were near
the top of it:
- hashRows built a fresh 32KB byte buffer and shape map for every chunk
it hashed: 510MB of the startup's allocations. It now takes them from
a sync.Pool and clears the map before use. The digest is the same
byte for byte (checked against the old code on the same chunks).
- rowChunk.within appended into a nil slice, growing it step by step
(292MB flat). It now counts the rows in range first, returns nil when
there are none, and makes the slice at that size.
Measured, same real-account copy, t9 (main) against t10 (this):
startup CPU 13.81s -> 9.77s
allocated (3m) 3483MB -> 2768MB (hashRows 510MB -> gone,
within 427MB -> 244MB cumulative)
footprint 179MB -> 175MB
Tests: TestHashRowsReusesItsScratch hashes a chunk again after a bigger
one and must get the same digest, and must allocate under 16KB a call
(min of 5 batches, so other goroutines' allocations don't count). Old
heat_disk.go: red at 32768 bytes a chunk; dropping clear(shapes): red.
TestWithinSizesItsRows needs len = cap = 600 (old code: cap 646).
Run on mote at this tree: go test ./internal/usage -count=1 ok, -race
ok, gofmt clean, go vet darwin/linux/windows ok, gui tests ok earlier.
An earlier usage run went red on a test whose name was lost (the log was
cut by tail); four full runs since are green, and the likely cause, the
first byte check counting other goroutines, is what the min-of-5 fixes.
|
||
|
|
3a5e4b62d0 |
usage: TestRowTokensAndZoneKept compares the zone by name and offset
The test compared got.Time.Location() with its own *time.Location by pointer. rowZones keeps the first zone it sees for a name and offset, so under -count=3 the second run got the first run's location back and the test went red on unchanged code. It now checks the zone's name and offset (IST, +5:30), which is what rowZones promises. Run on mote: go test ./internal/usage -count=1 ok; -run TestRowTokensAndZoneKept -count=3 ok (red on the old test). Broken by hand: writing the row with an "XST" zone turns it red. |
||
|
|
e3f1efdaac |
usage: a message id's pairing key is 16 bytes, not 24
msgKeysOf keeps each chunk's message ids as hashes, with the row, for every chunk a pairing reads. The key was two 64-bit hashes and an int32, padded to 24 bytes. It is now a 64-bit and a 32-bit hash with the row, 16 bytes: two of a long history's ~300k ids alike in all 96 bits is ~1e-18 likely. Run on mote at this head: - go test ./internal/usage: ok (28.8s) - GOOS=darwin/linux/windows go vet ./internal/usage: ok - gofmt -l: clean - Broken by hand: with the second hash back at 64 bits, TestMsgKeySize is red (24 bytes). - Real-account copy (~/r2278/acct), idle heap at 180s, v0.1.3404's tree vs this: appendMsgKeys 6.49 MB -> 3.69 MB, inuse 103.0 MB -> 97.8 MB, Footprint 154 MB. |
||
|
|
a06872dec8 |
caps: a wallet window's spend is counted, so a cap holds it (#5770)
A window that tells only what is left (QuotaWindow.Balance: AStudio 0.2.0's 通用积分 and 星火积分, SuperMagic's points) read 0% used until it was empty, so an account cap never tripped on it. 9won capped an AStudio account at 4 and it spent over 1,000 credits past it. magpie now counts what such a wallet spends (wallet_spend.go). Each plugin reading's balance is set against the one before: a fall is spent, a rise (top-up, daily grant) is not. The count runs over the window's own period when it tells a reset, else the local day: a wallet never renews, and a cap reached for good would switch the account off with no time it comes back; the ask was "N a day". Spend before a period's first reading, or across a gap between periods, is unknown and not counted; spentSince says when counting began. The counts are kept in wallet-spend.json beside providers.json, so a restart doesn't lose them. Every wallet window carries spent and spentSince. On an account with a usage cap (WindowCaps.Holds) it also reads as amount spent of limit (spent plus what is left), and used that share. A cap by share then holds it in routing (allowanceOf takes the fields as they are) and on the GUI row (capHeldOf reads used). So does 40cbdaa7e's amount cap, which skipped a window with no total: 9won's "at most 300 a day" on a wallet now holds (magpie provider account-cap ... --window 通用积分 --amount 300). An uncapped wallet is unchanged: balance alone, routed by Allowance.Left. A cap just set is judged from the next reading. holdsBounds leaves wallets out: there is no whole to reckon "holds" from. Tests, each red on the old code (broken by hand where they compile): - TestPluginWalletCapHolds: real plugin host, fake plugin, wallet 10,000 -> 9,500 on an account capped at 4. Used 5, CapHeld set, the uncapped account untouched. Red with the plugin_usage.go hook removed (Used 0, Spent nil). - TestWalletSpendCounted: falls counted, top-ups not, a restart reads the count back, the next local day and a told reset start over (UTC+8 fixed zone), failed and share readings left alone. - TestWalletCapHolds: account cap 4, the window's own cap 4, and an amount cap of 700 (not held at 650 spent, held at 750). - TestWindowHoldsLeavesAWalletOut: red without the holdsBounds change (a wallet reckoned a 500-token whole). Run on mote at this tree on |
||
|
|
f8525323dd |
providers: a key with no balance URL takes a balance typed by hand, counted down by magpie's own usage
Some API-key providers tell no balance magpie can read (no Balance URL, no relay query found), so their keys showed none. Now the user types what the vendor's page says is left, on the key's row in the provider editor (Set balance) or with `magpie provider key-balance <id> [key [usd|off]]`. The key's card shows that less what magpie's usage priced the calls it sent on the key since it was typed (usage.KeySpent, the spend caps' count), marked as an estimate: "≈$12.50", the pill "≈$12.50 left", its title saying what was typed, when, and what was counted since. Typing it again counts from then; No balance takes it off. A balance the vendor tells always wins: a provider with a Balance URL, a plan source, Cline's or OpenCode Zen's card takes none typed, and a relay whose query is found shows its own; when the probe finds none (errNoBalance) the typed one is shown. A typed balance stays saved as the user left it: the editor's save keeps it, a key's replaced value carries it. An estimate is never kept in the balance history and tells routing nothing (the routing allowances cache is left alone). keybalance.js is loaded by keyspend.js (itself loaded when the editor draws a key) for a provider that takes one, so app.js and the core's script budget are unchanged. Words in zh, zh-TW, ja and de. Run at this tree (mote): - go vet ./... (darwin), GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./... at base 46b10af87; at this tree go vet of gui, provider, cli and usage; - go test -tags nogui -count=1 ./internal/gui ./internal/provider ./internal/cli ./internal/usage: provider and usage ok; gui and cli red only on #5644 below; TestCoreScriptBudget ok (1,533,747, as main) - the provider tests under -race -count=3; - GUI: key-own-balance (new: Chromium and WebKit, en zh zh-TW ja de, 900 and 400px, 20/20), key-spend-cap, old-webkit, i18n-keys, gui-de, gui-ja, gui-zh-tw, balance-found, key-balance-card, i18n-en-no-cjk: 104 pass, 1 fail, i18n-keys "a plugin's words are its own", red the same on origin/main |
||
|
|
d4712e1312 |
usage: a probe's chunk among the settled days no longer drops the heatmap's disk cache
heatSettledKey gave up whenever a settled chunk had no serial. A probe's
chunk (MCP and search calls) is made again for each query, so it never
has one. When a user had no tool call in the last two days, that chunk
fell among the settled days, the settled count was never kept on disk,
and every Usage refresh paired and counted every day again.
The loop below already names such a chunk by its rows (hashRows), the
same rows give the same key, and pairSerials already allows one unnamed
chunk. So the early return goes; the doc comment says what false means
now.
Ran (mote, at this head):
- TestHeatSettledKeyNamesAProbeChunk: green; red with the early return
put back ("a probe's chunk left the settled days unnamed").
- go test -count=1 ./internal/usage ok; go vet for darwin, linux and
windows ok; gofmt clean.
Not tried: timing a real Usage page with no recent tool calls.
Reported-by: gua2100 (Discord #feedback)
|
||
|
|
8373aaf14a |
usage: a settled session file touched keeps its settled days
The Requests page and the heatmap keep the days before the last two
counted (page-v1/heat-v1), under a key of the settled chunks. A session
file's chunk was keyed by its size and mtime, so a file touched without
a new call made a new key, and every poll of every period and filter
paired the whole history again (pageCold/heatCold). Agents do touch old
files: on this Mac a 15 min stat watch of ~/.claude/projects saw
settled files (last call 11-03/11-04) get their mtime moved exactly
+3600 s with the same size, and others get queue-operation, hook and
file-history lines that are no call. The key also hashed the chunks in
mtime order, so a touched file moved in it.
A session chunk is now keyed by its path and a digest of its rows
(hashRows, memoized per chunk serial, which names the file as read),
and each set is hashed in path order; a pairing breaks its ties by path
(timedRef.newer). A real change of rows still makes a new key
(TestPageSettledFromDisk). The key format changed, so the first start
after the upgrade counts the settled days once.
Measured on mote (M5 Pro), a sandbox HOME of 3000 Claude Code and 2000
Codex sessions (1.1 GB) and 300k gateway rows, the harness polling
requests+heatmap for today/7d/30d/all three times each, a line that is
no call appended to an old Claude Code file before each poll:
before: heatmap 0.86-1.62 s every poll, requests all 1.34-1.43 s,
30d 0.33-0.44 s
after: heatmap 0.13-0.42 s, requests all 0.15-0.44 s, 30d 0.07-0.69 s
(the first poll of a period counts its recent days)
first process, no caches: 17.4 s -> 10.8 s for the 14 calls; warm
274 -> 278 ms. Sessions polls were 0.07-0.2 s in both.
Run on mote: go test ./internal/usage ./internal/sessions
./internal/usageapi ./internal/gui (ok); gofmt -l; go vet, GOOS=linux
-tags nogui and GOOS=windows go vet of ./internal/usage.
Broken by hand: TestSettledFileTouchedPairsRecentOnly is red on the old
heat_disk.go (paired 6 of 6); with the digest but not the path order it
is red too.
Not tried: GrayRabbit's own history (no sizes from them yet, #5618);
Windows or Linux timing; the GUI, which is unchanged.
Reported-by: GrayRabbit (Discord)
|
||
|
|
8de63c8b5a |
gateway, usage, gui, otlp: a request its agent canceled is no failure (#2398)
An agent that cancels its request before it is answered is logged 499 "the agent canceled the request": a person stops the reply, or sends the next message while it is coming and Claude Desktop cancels it and asks again, or Codex takes a subagent's report (#2398). The gateway already says nobody failed (no rest, no reroute: TestCanceledRequestRestsNobody), but Record.Failed is a status >= 400 or an error, so every page counted it as a failure: the Requests card's "N failed" and success share, its Failed filter, the CSV's error column, the Routing page's "errors your agent saw", the Context page's error rate, the failed colour in the Requests list, Routing and Recent calls, and the OTLP export's error status. A Claude Desktop session on 2026-10-27 had four, each a message sent mid-reply; #2398 had 91 of a day's 92 failures. usage.CanceledBy tells the agent's cancel (499 with AgentCanceled) from magpie's own limit on a request it asked of itself, logged 499 too and still a failure (#2318). The cancel is logged with an error type of its own, agent_canceled (usage.CanceledErrType, set in failedWith), so the record says what it was and nothing guesses it from a 499, as #2398 asked. Record.Canceled reads the type, and a record logged before it by its status and message, so the old log reads the same with nothing migrated. A middleware's usage rows carry the type, so a module can tell the cancel from magpie's own limit, which its rows (no error text) couldn't. Record.Failed leaves the cancel out; Totals counts it apart (Canceled, in count and plus); RetriedRequest and the first-token and speed sums ask Answered, so a canceled request is timed nowhere, as before; Codex's memory of the last model still skips it. Routes and Recent calls say canceled (set as a route is done and as a day's history is read, so old days read the same); the Routing totals and the Context page's errors leave it out. Ledger rows say canceled, and the pages show it muted, in neither the failed nor the answered colour: the Requests list and its detail ("499 · canceled"), the Requests card ("N canceled", the success share of the requests not canceled), the overview tile, the Routing page (a "gone" outcome, no speed) and Recent calls (muted). New strings are in zh, zh-TW, ja and de. The OTLP export: the records the gateway gives its observers for a request and its try carry the type too (canceledAs), and a root span's error.type follows Record.Failed, so a canceled request's span and its try's go with status code 499, no error and no error.type. TestOTelWaterfallFailureAndCancellation's canceled case held two failed spans (the try the vendor refused as the agent left is recorded canceled, as the request is); it now holds neither failed, both 499 and no error.type. That change to the test is the point of this one. mdwsk88's patch (aea0027fd) ran its tests at |
||
|
|
2f660ca86b |
sessions, usage: Antigravity's gemini-4-argon-d is gemini-4-argon, not a second unpriced model
oioio's Antigravity database names gemini-4-argon's generator
"gemini-4-argon-d". agAppModel took only "-n" off a gemini-* id (Google's
gemini-3.8-flash-n,
|
||
|
|
640825b09a |
usage: the Requests card's traffic line reads whole, and a row says how many images went by file
matrix0487 on Discord:
- The Requests card's line "↑ 13 GB · ↓ 13 MB · 图片文件省下 44…" was cut
with an ellipsis. It was one nowrap span.
- A row's details say "图片文件省下 10 MB" and should say "10 MB(3 张)".
The card line is now made of whole parts (usageParts, the pattern the
token line has since #2378). A card too narrow for all three puts the
saving on a line of its own. A part that is wider than the card by
itself (German at 420 wide) wraps inside itself; it is never cut.
The count:
- withDeepSeekFiles counts the image blocks it puts a file id in place
of, on each try, and upBytes keeps the most of any one try (a retry
sends the same images again, as the saved bytes are counted).
- It goes into usage.Record as `image_files` (omitempty) beside
image_files_saved.
- packedRow keeps Tries and ImageFiles in int16 each (clamped to
MaxInt16), so the row stays 152 bytes. request_snapshot carries the
new field, and heat_disk hashes Tries as before.
- The detail row says "{size} ({n} image|images)": zh "10 MB(3 张)",
zh-TW 張, ja 枚, de "Bild/Bilder", en "image/images".
- A row from before the count was kept has no image_files and shows
the size alone, with no parentheses. The card's period total gets no
count.
Run on mote, at this tree:
- gofmt -l (clean), go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./..., go build ./...: ok.
- go test -run 'TestRowImageFilesKept|TestRowBytesKept|TestRowsOfOneSession|
TestDeepSeek|Snapshot|Heat' ./internal/usage ./internal/gateway: ok.
- TestRowImageFilesKept: the count survives pack/unpack beside Tries,
100000 clamps to 32767, an old row reads 0, the JSON has
"image_files":3 and leaves out 0, and packedRow is 152 bytes.
- TestDeepSeekImageFilesCountedInRow: two images in one message and
one again in a later message make 3 in the stored row, twice, and a
request with no image makes 0.
- GUI, BROWSER=chromium and webkit: usage-ledger-bytes runs every
language at 1180 and 420. The 3-image and 1-image rows read in each
language's unit, singular in en and de, and the old row stays bare.
The reporter's period (13 GB, 13 MB, 44 MB) at 1180, 760 and 420 has
every part whole and inside its card.
- The 79 usage-*/led* GUI files (concurrency 2): 641 of 659 pass in
chromium and 637 of 654 in webkit. Every red is filed and red on
origin/main
|
||
|
|
783537e810 |
sessions: the Antigravity app's own conversations count on Usage and Sessions (#2190)
xxooioo (Discord) asked for the Antigravity desktop app's calls made
without magpie's gateway on Usage and Sessions. The app keeps each
conversation as a SQLite database, ~/.gemini/antigravity/conversations/
<id>.db (WAL). Messages are encrypted, but steps.metadata is plain
protobuf: 1 the step's start, 9 the call's usage (2 input, 3 output,
4 cache write, 5 cache read, 11 response id), 20.3 the gen_metadata idx
of its generator, whose message names the model (field 19, else 21/22).
The reader opens the database read only, in one read transaction; a
response id seen twice is one call at its last step. Each conversation is
a read-only session under agent "antigravity", gated by Reads like every
other agent and added to Found. A call the app sent through magpie is
matched to the gateway's record by tokens and time the way agy's steps
are (agyLocal now covers "antigravity"), so it is counted once.
"gemini-3.8-flash-n", the model the rows name, is counted as
gemini-3.8-flash (
|
||
|
|
baf70992f6 |
usage: a call the vendor answered with another model is priced as the model that served it (#5340)
The ledger priced a call at the model asked for and fell back to the
model the reply named (Served) only when the asked-for one had no price
(#1498). That order is right for a relay that sells kimi-k3 as
moonshot-kimi-k3 and bills by the name it sold, but it also priced a
real substitution: claude-opus-5-5 asked, claude-opus-5 served. The
vendor bills for the model that ran. kaimo455's ledger had 836 such
rows, every one at the asked-for rate: $374.06 reported against
$493.28 at the served model's rate. gateway-key cost limits (KeySpent,
NewCoster) and budgets read the same pricer.
Pricer now prices a call the ledger marks swapped at the served model's
price. That covers a price the user set for the served model and every
other layer of BasePriceIn. A price the user set for the model asked for
still wins, 0 included (new provider.UserBasePriceIn is BasePriceIn's
user layer alone). When the served model has no price, the asked-for
one's stands. Renames, vendor aliases, serving names and region
deployments price as before, and rate windows still read each record's
own time. apiPricer, the API price behind a subscription window's whole,
follows the same rule: the served model's API price first, then the
asked-for one's.
Review changes on top of ggbdpq's patch:
- The swap is judged the way the ledger's Swapped column judges it: on
the model id and on the name that went out (SentNameIn over the
user's ModelWires). A model the user sends under the served one's name
was answered as asked, so it keeps its own price. The patch judged the
model id alone, so such a row was priced as swapped while the Requests
page said it wasn't. The pricers' memo keys now include the effort,
because the sent name depends on it.
- apiPricer (window holds) got the same rule. The patch left it on the
old order.
Tests:
- TestLedgerPricesASwappedCallAsTheModelThatServed (patch, plus a
ModelWires case) checks the ledger and the Requests page.
- TestLedgerPricesARenamedModelAsTheOneServed: the sol row (sol asked,
kimi-k3 served, both priced) is a genuine swap, so it now prices at 3,
not 2.
- TestHoldsPriceTheModelTheReplyNamed: claude-opus-4-7 answered by
gpt-5.5 is priced at gpt-5.5's API price. Answered by an unpriced name,
it keeps opus's.
Run on mote at this tree, on origin/main
|
||
|
|
8b70b7d976 |
usage: a request's bytes up and down, and what DeepSeek's image files saved, in Requests
Suggested by @faithleysath (matrix0487 on Discord): the usage ledger now keeps what each request received back (down_bytes) beside what it sent up (up_bytes, #4456), and what DeepSeek's image files (#5407) kept out of the upload (image_files_saved). Shown in Usage → Requests: - a row's details: "Sent upstream", "Received" and "Saved by image files", each only when it is above 0. A row from before has none of them, not 0; - under the Requests card, the period's "↑ up · ↓ down", with "{n} saved by image files" when there is a saving. Its title gives the exact bytes. A period with no counted bytes shows no line. What is counted: - Down bytes are counted as the reply body is read, after Go's transport has undone gzip, so a gzipped reply counts its plain size, not wire bytes. A plugin's row counts the local hop to the plugin host. A 101 body is not wrapped. Every try counts, so a refused try plus the answering one add up (TestLedgerKeepsDownBytes). - Image files saved, per try: the body before the swap minus the body sent, minus the upload bytes this request itself paid (len(b64)/4*3). It can be negative on the turn that uploads; the GUI shows only a saving above 0. Gaps: an upload that finishes after the wait timeout or ctx-done is not subtracted (as with up_bytes); a joined upload flight is paid by the request that started it; multipart overhead is approximate. - packedRow grows by three int32 (152 bytes, still within the test's bound), clamped to the int32 range. Totals sum all three. - settledCountVersion goes 1 → 2, because Totals now count bytes. The settled page, heat and effort caches recount once, on the first start after the update. The heat key hash includes the new fields. Run on mote at |
||
|
|
2df5d40ee3 |
usage: a ChatGPT API account's calls count in the same ChatGPT account's Codex window estimate (jctaoo on Discord)
A ChatGPT account signed in through Sign in with ChatGPT (chatgpt-api) and to Codex draws on one plan's five hours and week. Only the Codex card reads those windows, and its whole-window estimate (usage.windowHolds) keyed the ledger's calls by provider + account, so the chatgpt-api calls were never counted and the estimate came out low. provider.SamePlanAccounts maps each chatgpt-api account to the Codex account that is the same ChatGPT account, matched on the tokens' chatgpt_account_id and chatgpt_user_id, both known and both equal, never on a name: two Team seats of one email share the name and the user id, not the account id. A token that names neither matches nothing, as before. windowHolds (current and HistoricalWindowHolds) counts a matched account's calls as the Codex account's, dry runs included. chatgpt-api alone (no Codex account) is unchanged: its card reads no windows, so there is nothing to estimate. Routing's caps and pace go by the vendor's own reading of the windows and don't sum the ledger, so they are unchanged; the per-provider account breakdown in the summary stays per provider on purpose. Run (mote, at this tree): - go test ./internal/usage/ ./internal/provider/: ok. ./internal/gui/: TestMainWindowCorners/macOS_26_SDK red, the AppKit test filed as #3949 (macOS 27 on mote), untouched by this change; the rest ok. - go vet, GOOS=linux go vet -tags nogui, GOOS=windows go vet of internal/usage and internal/provider: ok. gofmt -l: nothing. - quota-holds.test.cjs in Chromium and WebKit: 2/2 each (the GUI only renders the server's holds; no asset changed). Broken by hand: - remap removed in windowHolds: TestWindowHoldsCountsTheSameChatGPTAccount- ThroughTheAPI red, "whole 5 hours 2500 tokens, want 10000" and "the personal account holds 2500 tokens, want 10000". - account id ignored (user id only) in SamePlanAccounts: red, "the Team seat holds 12500 tokens, want 5000" and "whole 5 hours 10000 tokens, want 2500" (token naming no account). Not tried: a real chatgpt-api sign-in. No such account on this machine, so whether OpenAI's Sign in with ChatGPT tokens carry chatgpt_account_id and chatgpt_user_id (Codex's do, checked on the real Codex logins here) is not verified; if they don't, nothing is matched and the estimate stays as before. GUI suite in other languages not run (no strings changed). |
||
|
|
7b5e773873 |
provider: a model at a window (claude-opus-5-5@300k) is priced as its model, so Cursor's sized ids have a cost
RyuJeXu on X (tweet 2117971061103100279), building an iOS board on magpie's
usage data: "cursor的用量好像不计费呀". Cursor calls showed no cost.
Cause: the Cursor plugin lists each model once per context size
(claude-opus-5-5@300k, @1m, gpt-5.5@272k, ...), lists them all at cost 0
(no price, pluginPrice), and its reply echoes the asked id, so usage rows
carry the sized id. pricedNames only took a window off grok- ids, so every
other sized id fell through the maker catalogs with no price. The plain ids
(claude-opus-5-5) were priced at the maker's list price all along.
Fix: pricedNames also tries the id with an "@<digits>k|m" window taken off
(modelWindow), for every provider. The window names the context size, not
a different model; long-context tiers still follow the call's own prompt
tokens through Price.At. Dated ids (claude-opus-4-5@20251101) and ids with
anything else after the @ are left alone. The regexp runs only for an id
with an @, since every listed model is priced on each Providers poll.
Tests:
- internal/provider/cursor_price_test.go: a moved Cursor provider prices
@300k, @1m, upper case, a maker-prefixed id and gpt-5.5@272k/@1m as the
plain model, through ListPrice, MakerPrice, PricedName(For), and its
tier at 300K prompt tokens; a dated id, "@272", "@", "@272kb", an
unknown model and auto stay as they were.
- internal/usage/cursor_window_cost_test.go: a Cursor row for
claude-opus-5-5@300k costs what the plain id does ($6 each), auto stays
unpriced, the page total is $12.
- grok_price_test.go: gpt-6-astra@500k under grok is now priced ($10/$50);
grok-4.7-build@500k still isn't.
Run (all through mote-run, go1.26.8, base
|
||
|
|
69167bc299 |
usage: a reply let go under a second after a wait four times longer tells no speed
pluviophile714 on Discord: a gpt-6.1-sol row on Routing read 1,539 tok/s (input 21,617, output 392, first token 8.2 s, total 8.3 s), where another monitor measures ~70. The reply came whole about 255 ms after an 8.2 s wait. Its content was spread over that short window (flow 230 ms), so the HeldShare flow check passed, and so did the 100 ms floor, and 392/0.255 s read as 1,539 tok/s. New rule, usage.HeldWindowMs: a window under 1,000 ms whose start (first token, first text or first reasoning) is more than HeldShare (4) times the window tells no speed. One rule in every place that computes one: - usage.DecodeOf: the Usage page's speed and totals, the CLI, the GUI's model speeds, and the gateway's Speed first pacing (noteTrySpeed); - routing/client.js decodeOf: the Routing row's speed and its story line; - usage/page.js ledDecode, plus a ledNoSpeed_ reason for the dash's tooltip, in en, zh, zh-TW, ja and de. docs/reference.md and docs/subsystems/gateway-sessions.md say so. On the owner's usage.jsonl (read only), 103 of the 106 rows over 600 tok/s were such windows (e.g. 448 tokens in 107 ms after 8.1 s) and are dropped. The 3 that stay have windows of 2 to 5 s. The overall speed goes from 103.8 to 97.9 tok/s. What it costs: a short reply that really streamed after a long wait tells no speed either. The live visible-reasoning fixture (76 tokens over 731 ms after 6.8 s, ~104 tok/s) and #2637's grok record (307 tokens 403 ms after a 4.6 s first token, 531 tok/s) now read "—". Their tests keep their guarantees with the same timings after a short wait, and also check the long-wait case. Tests: - New: internal/usage TestShortWindowAfterLongWaitTellsNoSpeed (the reporter's numbers, a reasoned row from the ledger, the boundary, a second after a long wait, Totals) and internal/gateway TestShortWindowAfterLongWaitNotesNoPace. - GUI: usage-speed-every-row has the reporter's row (dash, and the tooltip in all five languages); routing-burst-speed has it (first token 8.2 s, no tok/s). - Updated to the new rule: TestVisibleReasoningSpeed's decode-minimum and max-speed cases (short wait now), TestCodexTurnMeasured...'s gateway/Claude rows, TestLiveVisibleReasoningFixture and TestUsageIngestTellsSpeed. Run on mote at this tree (rebased on |
||
|
|
e41ef6288c |
providers: a spend cap on an API key, per day, month or in all (sparkling_lemur_62868)
sparkling_lemur_62868 on Discord: a team's OpenAI key holds granted credits that other docker services spend from too, and they want magpie to stop at a share of it. Their workaround was two magpies behind a gateway-key limit. What changed - provider: KeySpendCaps on a provider, keyed by the key's fingerprint (key_spend.go): USD over a local calendar day, a local calendar month, or in all since it was set. Since is kept while the cap stays one in all. SetKeySpendCap and ParseSpendCap refuse an amount outside 0 < usd <= 1,000,000 and an unknown period, and leave the saved cap as it was. Subscriptions are refused, since an account has its own usage-window cap. - usage: KeySpent(keyID, start) is what magpie's own calls on the key cost at the Usage page's prices. Turned-away calls and app-reported ones are left out. It reads usage.jsonl once per key and start, keeps the sum for 5 minutes, and Append counts each new call into it (spentNew). A read that a write races is read again. - gateway: perKeyEvery bars a key at its cap (spendHeld) as a usage cap holds an account. The next key serves, then the fallbacks. With none, the reply is 429 "spend cap reached: ..." naming each key, what it spent of which cap, and how to go on. Retry-After is when the soonest period renews; a cap in all gives none. A spend hold is not a usage cap: Stop at the caps and strictKeep don't end at it (capHeldOnly). The trace's barred row carries the cap, the spend and the period. - GUI: a pill on each key's row in the provider editor, for example "$7.50 of $20.00 today". It opens the app's menu (No spend cap, Per day..., Per month..., In all...) and then takes the amount in place, as the lane-limit pill does. A key at its cap gets a line under its row: "At its spend cap · back in ...". Every string is in all five languages. The pill and the line are in keyspend.js, which app.js imports when it draws a key's row, so the core's script budget is not raised. /api/providers' keyList carries spend, and POST provider/keyspendcap sets it. - CLI: magpie provider spend-cap <id> [key [usd [day|month|total]|off]] lists each key's spend and sets or removes a cap. - docs: providers-accounts.md and gateway-routing.md. Caveats, also in the tooltips: - What counts is magpie's priced usage, not OpenAI's bill. - A model with no known price counts $0. - Requests already under way when the cap is reached still finish, so a key can go a little past it. Run on mote at the pre-rebase head ( |
||
|
|
dcc84dbc04 |
usage: the Overview says each account's credits, and the period's (lcyksp)
lcyksp (Discord #feedback) asked to see the WorkBuddy credits (积分) the
calls spent, per account too, not only tokens. The summary already summed
each reply's usage.credit into every group's Totals, and the Requests
page's ranking showed it, but the Overview's Accounts, Models and Agents
rows and its tiles never said it. Each row's line now says "{n} credits"
when a reply said any, and the calls tile says the period's sum. No tile
is added, so the four-tile grid is as it was; the text was translated
already.
Run on mote:
- go test ./internal/usage ./internal/usageapi: ok. TestPlanCreditsByAccount
(new) checks each account's sum in the summary and the Requests page;
with Totals.count not adding credits it is red (summary a@x: 0 of 0).
- GUI, every usage*, i18n*, ledger and credits file (both engines):
1322 pass, 31 fail. plan-credits' new Overview test (5 languages, 420px)
is red with page.js as before ("WorkBuddy · 70 calls"). The reds are
usage-agents-hide (#2276, #3414), usage-fold "most on one screen"
(#4790) and usage-ledger's return-to-live (#3104, #4078, #4626). Run
alone at
|
||
|
|
4bac5eed26 |
usage: a request's row says what went up to the vendor, tries summed (#4456)
RunMintOn asked how much a long session sends upstream: a proxy counted ~900 MB up in 45 minutes, and no ledger row said what a request sent. A row now has up_bytes, the bytes that went on the wire, every try and every second ask summed (zstd's size for a ChatGPT turn), and plain_bytes, the last try's body before compression. They are summed in the request's context on its own goroutine, set in serve and, for Codex's own turns that come from the mux and not through serve, in codexUpstreamOn. Handed-on rows carry neither; rows from before carry neither. From ggbdpq's patch (via gua2100), two changes: - the patch counted in codexUpstreamOn but set the context only in serve, so a Codex turn on its ChatGPT sign-in, the zstd case the issue is about, wrote 0 and 0 (TestCodexOwnTurnKeepsUpBytes); - a second request inside one try (RetryOneAuth, RetryZhipuCoding, RetryOpenCodeFreeOnZen) went up uncounted; it counts now (TestLedgerCountsATrysSecondAsk). Request bodies to other vendors stay as their client sent them; zstd stays Codex's (the owner's call, on the issue). Run at this tree on mote: go test ./internal/gateway -run 'UpBytes|TrysSecondAsk|OneAuth|Codex|Draw|Relay' -count=1: ok; go test ./internal/usage ./internal/redact -count=1: ok. gofmt clean. Broken by hand: no context in serve: TestLedgerKeepsUpBytes and TestLedgerCountsATrysSecondAsk red; none in codexUpstreamOn: TestCodexOwnTurnKeepsUpBytes red (row 0/0, backend got 79 of 8444); the second ask not counted: TestLedgerCountsATrysSecondAsk red. Not tried: a real session's numbers against a proxy's; the GUI shows neither field yet. Co-authored-by: ggbdpq <ggbdpq@gmail.com> |
||
|
|
e156fdd032 |
usage: a model's region deployment answered under its own name is not a swap (plugins#628)
WorkBuddy AI lists DeepSeek V4.1 Flash as deepseek-v4.1-flash-sg, its paid id for the Singapore deployment. The plugin's product config names it paidId to the free deepseek-v4.1-flash, with one window for both. WorkBuddy answers under the model's own name, so the Routing page tagged each request "请求 deepseek-v4.1-flash-sg · 实际 deepseek-v4.1-flash". Old routes and kept usage rows kept the mark, so removing the model and setting the provider up again didn't clear it (chansee97, plugins#628). - RegionTail (internal/usage/served.go) covers a name that is the other with -sg, -us, -eu, -cn, -intl or -global after it. Such a pair is the same model, and Swapped excludes it. - A region in both names, or a name that differs besides the region, is still a swap. - Kept rows (request_page.go) and kept routes (gateway history.go's routedAgain) are judged again with it, so old marks go too. Run on mote, at |
||
|
|
07dc0b4ec1 |
usage: an agy following the Antigravity app's gateway is counted once (Chamberlain_zyz on X)
An agy not connected on its own row follows the Antigravity app's
gateway, with the app's key (internal/agent/antigravity.go), so the
gateway records its calls as the app's ("antigravity"). Its transcript's
steps were matched only to records of agent "agy", so each one was
counted twice: Chamberlain_zyz's 17:00 hour showed Antigravity
39,104,506 and Antigravity CLI 38,562,861 tokens for the same calls.
agyGateway takes the app's session-less records too, at all three places
that matched agy's alone: the gateway side of the match key, the chunk
hints that pick which transcripts to open, and matchingRecords. The
match is still by exact tokens and time, so an app call of its own is
paired with an agy step only if both counted the same tokens within the
step's window. It is worked out when usage is read, so hours already
recorded are counted once too, for every user, with nothing to redo.
Run (mote, this tree):
- go test -count=1 -run Agy ./internal/usage: ok.
- Broken by hand (agyGateway back to "agy" alone):
TestAgyStepThroughTheAppsGatewayCountedOnce and
TestMatchOpensAgyChunksForTheApp fail; restored, ok.
- go test -count=1 ./internal/usage ./internal/sessions: both ok.
- go vet ./internal/usage, and with GOOS=linux and GOOS=windows: ok.
- The whole suite was not run: only these two packages are touched.
Not tried: a real agy through a real Antigravity app's gateway; the
reporter's case is taken from their screenshots and the app's wiring.
|
||
|
|
1829cd52ff |
sessions: a poll while a session grows makes only the rows it shows
VeryBTC on X (tweet 2117104179454091396) reported RSS that rises and
stays up while the window is open and a long-context session is active.
In that case every Sessions poll sees a changed file and rebuilds the
list. That rebuild copied every gateway-only session three times
(GatewaySessions, listedGateway, gatewayListed) and made each one a
Session row before EachMerged stopped at its 5000-row limit. It also
made every Claude Code file's path and key again.
- usage.EachGatewaySession walks the projection without copying it.
gui's listedExternal stops at the list's limit and skips hidden
sessions and sessions without an agent or id, as listedGateway did.
- sessions.EachMerged sorts indexes and makes a row only when the merge
reaches it. The order is unchanged: newest first, stable on ties.
- listCCFiles reuses the last listing's path and key strings while a
folder lists the same names. One file new or gone is stepped over.
This holds ~32 B per file (~480 KB at 15k files), and the strings are
shared with the listing it already held.
- page_memory.go's ~330 MB comment now has current numbers.
gateway-sessions.md describes the lazy rows.
Per poll, on mote (go test probe through the real /api/sessions
handler, TotalAlloc):
15k sessions x 10 turns, 400k ledger rows
after a session file grows 150.6 MB, 201 ms -> 109.9 MB, 170 ms
unchanged (warm) 17.2 MB -> 12.0 MB
3k sessions x 40 turns, 150k rows (no gateway-only rows past the cap)
after a session file grows 31.3 MB -> 29.6 MB
unchanged (warm) 4.5 MB -> 3.4 MB
/api/usage is unchanged at 0.4 MB.
Tests:
- TestSessionsListMakesOnlyTheGatewayRowsItShows (gui) uses 3 natives,
6000 gateway sessions in tied pairs, one hidden and one carrying a
native's id. At limits 5, 40 and 6010, and with no limit, the rows
equal the old pipeline's (listedGateway + gatewayListed +
MergeExternal) after the JSON round trip. A grown native comes first
with its new Last. The poll's allocation stays under 6000 rows' size.
- TestEachMergedMakesOnlyTheRowsItReaches (sessions): 15000 externals
and 20 rows give MergeExternal's first 20, with allocation under a
tenth of the rows.
- TestCCListingKeepsItsNames (sessions): a second listing of 3000 files
is equal to the first, in at most 3n mallocs. A file added, files
removed, and a folder gone with another new each list as a fresh
listing does. Another agent's keys keep their own prefix.
Broken by hand, each red:
- EachMerged building every row first: 8.8 MB, the sessions test fails.
- The GUI handler back on the listedGateway(GatewaySessions) loop, with
the lazy merge kept: 13.7 MB, the gui test fails.
- The gui test on origin/main's code: 23 MB, fails.
- The ccNames reuse turned off: 12197 mallocs, the listing test fails.
Run on mote (mote-run) at 73a1b8769, rebased on origin/main
|
||
|
|
276c806db2 |
plugins: a plugin's own requests are counted; a provider plugin's options get the editor (plugins#592)
zelong77 asked for two things once Devin 0.1.30's cache keep-alive
worked: its pings were invisible in magpie, and the interval and ping
count could only be edited in plugins.json. The owner decided pings are
shown as counted usage and the two numbers are edited in the GUI.
- host.js gives plugins input.magpie.usage(provider, call) and
input.magpie.account(provider). usage validates the call (kind
[a-z0-9_-]{1,40}, a model id, whole-number tokens from 0, status at
most 999, error clipped to 500) and sends an unasked "usage" event;
host.go hands it to plugin.OnUsage in the background.
- internal/usage/plugin_calls.go writes each one as a row of agent
magpie on the plugin's provider (provider.PluginID) and account
(provider.PluginAccountUser), with its kind. It is counted, priced
and in every total, not a probe. Kind cache_keepalive is in the
purpose catalog as "Cache keep-alive" (five languages), so the
request log names and filters it. The ping itself still goes straight
to Devin, never through the gateway, which would break the cache.
- /api/plugins reads every plugin's package options example, not only a
middleware's or request hook's, and the Installed row offers the same
Options JSON editor for a provider or agent plugin that suggests or
has options (not while it is off). Clear's confirm no longer calls
them a middleware's options.
- The Devin mover's min is 0.1.31, which reports each ping and gives
its two settings' defaults (285 s, 6) to the editor. npm has 0.1.31
(published 10:03Z); the plugins publish run is red only for
think-tags' known E404 (plugins#180).
- docs: provider-plugins.md (the API, the options editor),
gateway-sessions.md (the counted row beside probes).
Run at this tree (rebased on origin/main
|
||
|
|
cbfbcb383b |
usage: a lead's answers are looked up in the blocks that name its conversation (#4370)
loggedAnswers, which leadFirst falls back to when affinity has lost a Codex subagent's lead, read thirty days of the log into a Record a row and kept the rows of one conversation. usage.VisitSessions reads only those rows: a block whose Session and NativeSession strings don't name the conversation is skipped, a row of another session is passed over by its shape's string ids without becoming a Record, and a matched row's strings are cloned out of the lent decode buffer. Each packed block's sessions are kept once it is decoded (blockSessions, by weak pointer, so no block the log let go is held), so a lookup decodes only the blocks the conversation is in and the open tail. A page's copy with Codex identities (which rewrite Session as a row is read) is read whole and filtered on its records. Run on mote (macOS 27.2), at load ~70: - BenchmarkLeadLookup (40 blocks of 3000 rows, one conversation of 300): visit+filter 39-56ms and 2.9MB an op; VisitSessions 0.38-0.52ms and 12KB. - A copy of the owner's real usage.jsonl (8,853 rows, 1,270 sessions, 18 blocks): every session looked up both ways gives the same records; 6.9ms a lookup before, 3.4ms for the first and 0.39ms after, 14us for a conversation that isn't there. - TestVisitSessionsIsVisitOfThoseSessions, red with the shape filter's session ids taken out; TestVisitSessionsRecordsKeepTheirStrings, red with the clone taken out; TestVisitSessionsSkipsBlocksOfOtherSessions, red with the known-sessions skip taken out. - GOOS=windows go vet; GOOS=linux -tags nogui go vet: ok. gofmt -l: clean. - go test -race of the new tests and the gateway tests of a lead's answers, in internal/usage and internal/gateway: ok (4.4s, 31.3s). - go test ./internal/usage ./internal/gateway (whole packages) was still running on mote at load ~190 when this was pushed; its result goes on #4370. Not tried: a real Codex subagent whose lead lost affinity; the lookup's callers and filters are as they were, and the gateway's loggedAnswers tests cover them. |
||
|
|
d7b42fcf23 |
usage: a chunk's one-byte numbers are read without Uvarint's loop, and a copying pass keeps its decode buffer (#4372)
A pass over packed chunks decodes every row's ~40 varints, and most are
under 128. binary.Uvarint was 42% of a lent pass's CPU on mote; take
now reads a one-byte number itself. A pass that copies its strings
(visitBlocks, rowsOf, within, the Codex pairs) decoded into a sync.Pool
buffer, which each collection empties, so after one it made the buffer
again and grew it to the largest block. It now decodes into its
rowBuffer's, as a lent pass does; unpackReusing takes the buffer and
whether its strings are lent apart.
Run on mote (M5 Pro), BenchmarkChunkRowsPass, 40 chunks of 3000 rows,
4 runs each, base
|
||
|
|
43d442700c |
usage: a row keeps its zone as an id, so the collector never scans rows (#4737)
A packedRow held its *time.Location, and that one pointer made every
[]packedRow a slice the GC scans word by word: the pages' rows of a
period, the kept decode buffers and every unpacked chunk, hundreds of
thousands of rows on each cycle. #4737's profile has gcDrain at 12% of
the CPU, scanObject 7.65% of it.
A row now keeps its zone as a uint16 into rowZones, a copy-on-write
list read with one atomic load. A zone is known by its String() and
offset, not its pointer: a time parsed with an offset, and a chunk read
from disk, has a new FixedZone each, and 30 parses of +05:30 are one
zone. time.Local is a zone as any other (a test sets it to UTC), so a
row keeps the zone it was written in, as before. Past 65535 zones a new
one's times are kept in UTC: the same instants. unpack looks a chunk's
Locations up once, not once a row. packedRow is 8 bytes smaller, so
TestPackedGatewayRetainsOversizedSnapshot's fixture has 180000 rows to
stay over its 32 MB.
Run on mote (M5 Pro):
- BenchmarkCollectWithRowsHeld, a runtime.GC() with 1M rows held:
4.1-7.9 ms at origin/main
|
||
|
|
1fac66c06d |
usage: a log snapshot read inside its stamp's tick is checked once, when it settles (#4368)
Each request the gateway writes wakes several readers at once: the menu bar, the pages, the Sessions list. They all read inside the change stamp's tick (100ms on a fine clock, 1s on a whole-second one). The read that built the snapshot hashed the whole log after its parse, each later reader in the tick hashed it again, and the first read once it settled hashed it once more. That was four times the log for one request with three readers, the recordHash 3.08s in KaranocaVe's profile. Now a snapshot read inside the tick is not hashed after its parse, and a reader still inside the tick takes it as it is. The first read once the tick settles hashes it and makes it settled, as before, so nothing settled is made of an unchecked read. A snapshot continued from one that never settled still hashes its prefix first, since trusted needs the old one settled. The disk copy is checked against the file when it is loaded, as before. What changes: a same-size rewrite by another program inside the tick reaches readers when the tick settles, up to 100ms or 1s later, not within it. A read a moment earlier would have had the old bytes anyway. TestUsageSameTickRewriteIsNotCached's case with no append and no settle now settles before it checks; its other seven cases are as they were. Run: - TestUsageReadersOfOneAppendHashTheLogOnce (new): an append, three readers in the tick, one after it settles. 1.00x the log hashed per append, 4.00x on the old code (red there). - TestUsageAppendReadHashesNoPreReadScan: 0.80x per append + read, 1.80x before. - go test ./internal/usage: ok on mote (macOS 27.2, 44s) and in WSL magpie-desktop (Ubuntu 24.04, 32s). - GOOS=windows and GOOS=linux go vet ./internal/usage: ok. gofmt: clean. Not tried: the reporter's log size, and a filesystem with whole-second stamps (where the tick is 1s, the same path). |
||
|
|
344a59f9db |
gui: an unchanged Sessions poll answers Same without making the rows
The Sessions tab asks for every session each 15 s. When nothing had changed, the handler still copied the kept listing, made a row of each session, merged the gateway's sessions, read Codex's effort and the vias, encoded every row and hashed them, only to answer X-Magpie-Same. Over ~17k real sessions (69 GB of Claude Code and Codex history) that was ~140 ms of CPU and ~24 MB of garbage per poll. Now the handler keeps, per ?limit, what the last list it sent was made from: the sessions listing (sessions.ListUnless's number, which changes whenever the listing is made again, and at least once a minute), the usage log's version (usage.LogVersion), the user's usage aliases, and the agents' names and icons with the folders. An ask whose X-Magpie-Had is that list's tag, while all of these stand, gets X-Magpie-Same before any row is made or the listing copied. Anything else a row shows (a Codex thread's effort, a gateway title) follows within the minute the kept listing stands. writeJSONRows returns the tag it sent. Measured on the real history (a sandbox HOME with APFS clones of ~/.claude/projects and ~/.codex/sessions, 17,140 files), 30 polls of /api/sessions + stats + overview, the same script for both builds: before ( |
||
|
|
2b067434d7 |
provider: a Kimi Code membership's k3.1-pro and k3.1-pro-highspeed are priced at the Kimi API's (#4635)
hlyx1's fix (#4635, branch hlyx1/magpie kimi-code-k31-pro-price), asked to be expedited by matrix0487 on Discord. Kimi Code's plans serve k3.1-pro and k3.1-pro-highspeed, which models.dev's kimi-code-plan-* catalogs list at the membership's $0. Neither id was in kimiCodeAPI, so a membership's call on either was unpriced on Usage. They now map to kimi-k3.1-pro and kimi-k3.1-pro-highspeed, like k3 to kimi-k3, and the Requests list names that model (PricedNameFor). Checked: Kimi Code's own /models answer (internal/catalog/testdata/ kimi-code-cn-models-2026-10-31.json) lists k3.1-pro "K3.1 Pro" and k3.1-pro-highspeed "K3.1 Pro Highspeed". Kimi's pricing page (platform.kimi.ai/docs/pricing/chat, read 2026-11-01) and models.dev's live moonshotai entry both give kimi-k3.1-pro $2 in / $10 out / $0.20 cached / $2 5m write, and kimi-k3.1-pro-highspeed $4 / $20 / $0.20 / $4. The fixture's new entries match models.dev's api.json in id, name, cost and canonical_model_id. The alias stays Kimi Code's (kimiCodePlans): the test's relay catalog now lists a k3.1-pro of its own at $0.50/$1, which keeps that price, and PricedNameFor(relay, k3.1-pro) stays k3.1-pro. Docs: docs/reference.md, docs/subsystems/providers-accounts.md. Run on mote (Go 1.26.8), at this change rebased on |
||
|
|
96a37ee5e3 |
usage: the vendor's own alias for a model isn't a swap (#4593)
A request via Top-API for deepseek-v4.1-flash answered under deepseek-flash was marked a swap. It isn't one: DeepSeek renamed its V4.1 Flash deepseek-flash (api-docs.deepseek.com/updates, 2026-09-10: "Change the model name to deepseek-flash to call the latest V4.1 Flash model"), and every exemption Swapped knows is structural - a dated or pinned tail, a Bedrock geography, a relay's word in front, a serving name - none of which an official rename reads as. VendorAlias reads a small table of rename pairs the vendor's own docs state (deepseek-flash is V4.1 Flash), both ways, over squashed bare names so case and separators don't matter; a bareModel'd name feeds it, so the dated spellings either side writes hit it too. Only pairs the docs state go in: a retired name routed elsewhere (deepseek-v4-flash) is another model, and catalog's SameModel keeps deepseek-flash an id of its own. The kept-row readers take the alias in beside the other exemptions, so rows recorded before it are read back as not swapped. Run (sandbox HOME, GOTOOLCHAIN=auto, -tags nogui): go test ./internal/usage -run 'TestSwappedVendorAlias| TestKeptRowVendorAliasNotSwapped' -> ok (base |
||
|
|
0565c0bbac |
usage: a test's comment no longer says the Requests page's word Unmarked (#4524)
i18n-keys' "a plugin's words are its own" was red on main since
|
||
|
|
d1b62f4604 |
usage: price a local session's call at the provider its file names
What changed A call read from an agent's own session file (omp's model_usage, say) has no billing provider of ours — its row reads session-unknown — so Pricer priced it only through the maker lookups, which answer nothing for models no vendor catalog lists as its own, even when the models.dev catalog lists the model under the provider the file recorded (openrouter listing typesafe/jev-1.14 at $0.042/M in, #4278). When the effective price is unknown and the record is one of those, its session provider now prices the call — but only what the catalog itself affirms: the very model id, listed under that provider, with a price. A provider models.dev doesn't know, a model it lists that provider without, and an entry with no price stay unpriced, the CSV cost empty, rather than priced at another entry's guess; the pricer's memo is keyed by the session provider too, so two files naming different routes price apart. Run - go test -tags nogui -run 'TestUnknownProviderPricedBySessionProvider' ./internal/usage — red before (the named route stayed unpriced), green after - go test -tags nogui ./internal/usage/... — ok - gofmt -l internal/usage — clean Generated-by: GLM-5.3-FlashX (ZCode) Reviewed and applied from #4278 (ggbdpq, 645e80ab2). It differs from the patch hashed on the issue only in its git-version trailer. The reporter's own call stays unpriced for now. models.dev's default api.json, which magpie fetches, does not list openrouter typesafe/jev-1.14; only api.json?type=all does. #4278 stays open for that. The Sessions page prices a session-unknown call through its own priceOf, by model only: #4591. Broken by hand: ledger.go back at main with the test kept, and TestUnknownProviderPricedBySessionProvider fails. Run (on mote, through mote-run): - Full `go test -tags nogui -count=1 -timeout 45m ./...` with this stack on |
||
|
|
e94fb18b8f |
usage: a page's cells and the heatmap's days read strings where they were decoded (#2278)
partsOf, cellsBefore and heatDaysOf read each chunk through a chunkRows that copied the chunk's whole string section first. What they keep is unique's handles (a cell), a date made by Format and numbers (a day), so the copy was thrown away chunk by chunk. They now read through lentRows(), as newest and the Codex readers already do. Run on mote: - go test ./internal/usage/ -count=1 -timeout 45m: ok (40s). - -race -count=3 on TestPartsReadStringsWhereDecoded, TestRowBufferKeptPastCollections, TestRequestCells*, *Heat*, *PageSplit*: ok. - TestPartsReadStringsWhereDecoded (new): 8 packed chunks, 1.1MB of strings. With the three sites put back to `var rows chunkRows` by sed it is red: partsOf 1,188,672 bytes, cellsBefore 1,197,568, heatDaysOf 1,187,616. Green with the change; the cells' names and the days' counts are right after the buffer was decoded over again. - Real history copy (66GB, ~12k session files), magpie web in a sandbox HOME, heap profile 40s after start, two rounds each: unpackReusing 183MB / 174MB before, 106MB / 113MB after; partsOf 76MB / 78MB before, 55MB / 56MB after. A warm poll of every page reads cached parts and is unchanged. Not tried: the Windows and Linux boxes (no OS-specific code). |
||
|
|
213d59f3b3 |
usage: a first start pairs the history once for the page and Codex's effort (#2278)
A first start, with no sums on disk, paired the whole history a few
days at a time (coldSpans) for the warm-up's page of All (pageCold),
then again for Codex's effort of the same period (effortCold), or the
other way round when the Sessions overview asked first. Both read the
same blocks and name the settled days by the same heatSettledKey, so
whichever runs first now counts both from its one pairing and writes
both files: pageCold counts the effort when its filter is empty and
effort-v1.json lacks it, effortCold counts the cells of the period's
unfiltered page when page-v1.json lacks them.
Run on mote (M5 Pro), at this tree (rebased on
|
||
|
|
9551fadcb4 |
gateway: reasoning streamed with no count in its usage is marked unknown, not read as none (#4545)
A reply whose stream carried reasoning (reasoning_content, Anthropic thinking deltas) while its usage counted no reasoning tokens was recorded Reasoning 0, ReasoningHidden false: the same record as a reply that never reasoned, and a tool-only one was timed with its reasoning counted as answer. hidesReasoning now takes the usage's reasoning count and marks such a reply ReasoningHidden, the record's existing "the stream doesn't tell how much it reasoned". Reasoning stays the vendor's 0; nothing is estimated, so no new field or Flags bit (rowReasoningHidden 512 is the one it already uses). Who does this, from real bytes and docs: Anthropic's Messages usage has no thinking count at all (output_tokens includes it), so every visible Anthropic-protocol thinking reply was this case. The fixture testdata/reasoning-uncounted-deepseek-anthropic.sse is DeepSeek's Anthropic endpoint as it came on 2026-10-31 (deepseek-v4-pro, thinking on): 33 thinking deltas, "391", usage output_tokens 35 and nothing else. The owner's usage.jsonl has 12 kiro claude-haiku-4.5 rows with paced first_reasoning_ms and reasoning 0, the same case through a plugin. DeepSeek's Chat endpoint does count (completion_tokens_details), and those rows are unchanged. No captured Chat vendor omits the count; the Chat subtests are built from the shape, not a capture. Siblings: Responses, Gemini and Code Assist were already marked hidden whenever reasoning streamed (summaries). The Codex backend's two calls pass its count too (no change for Responses; its call record now reads the count after the sniffed usage is added). The Claude subscription bridge counts thinking from the CLI and is unchanged. What changes for a reader: Decode already leaves a hidden reply with no text untimed, so a thinking + tool-call reply with no count tells no speed now; one with text is timed as before (whole output from first content). The GUI's decodeOf/ledDecode read the same flag; no GUI code changed. Run on mote at base |
||
|
|
f1d0c0bfdd |
usage: Codex's effort is kept on disk for each period, not one (#2278)
effort-v1.json held one entry. The Sessions list asks Codex's effort
for All and the overview for its own period (30d by default), and the
two wrote over each other, so every start, a warm one too, paired one
of them a few days at a time again (effortCold): ~100 MB of the warm
start's live heap at the moment and seconds of CPU. The file now holds
a list of up to four, the last written first, one per since; a file of
one entry, as earlier releases wrote it, is read as that one, so an
upgrade pairs nothing again.
Run on mote (M5 Pro), at this tree:
- go test -count=1 ./internal/usage/: ok (28.6s).
- GOOS=linux and GOOS=windows go vet ./internal/usage/: ok.
- Broken by hand: effortDiskPeriods = 1 turns
TestCodexEffortPeriodsKeptApart red ("all started again, paired 6 of
6"); 4 is green.
- Real start on the 11,925-file fixture (8.5GB .zst + 17GB jsonl),
`magpie web` warm after a cold start, two runs each:
before (
|
||
|
|
7b09d2c951 |
provider: a model can be listed by an id of the user's at its provider, asked for by its own
zeewell on X (tweet 2116404121930432888): relays serve one model under
ids of their own (deepseek-v4.1-flash-1017, grok-4.6@500k). They want to
give each one their own id at the provider layer. magpie then lists,
routes, groups and finds groups by that id, and the upstream request
still carries the vendor's id.
Choice: a new per-model map, settings' ModelIDs
("<pid>/<local>": "<own id>"), served through the wire names that
already exist. ModelSameAs was not widened. It means "same as another
vendor's model": it lends specs and joins found groups. Making it rename
models everywhere would change every existing user's ids and refs.
ModelWires was not reinterpreted either, for the same reason. ModelIDs is
ModelWires turned round: a wire keeps magpie's id and changes the one
sent, and this keeps the one sent and changes magpie's. Settings.Wires()
merges each entry in as a wire name (wrapped by a "<pid>/*" wire). Every
place that sent a ModelWires name (gateway, usage ledger, request page,
UpstreamName, UpstreamNameAs) reads Wires(), so the upstream id needs no
new path. An explicit ModelWires entry for the same id wins.
- Listed by the local id: Available, liveIDs/liveByID, Serving and
ListPrice translate through OwnModelID. /v1/models, agents' lists,
Resolve, routing groups and found groups (auto/<local>, merged with
every other provider serving that id) all see the local id.
- Only a provider of the user's own (Account == nil) takes one. An
account's or a plugin's request is built from its list's id, which no
wire reaches.
- Two variants of one provider given one id: the latest given it wins,
and the earlier one is listed by its own id again. The CLI names it.
The editor refuses two rows given one id in one save. A model of the
provider's own id that a variant is listed by (plain grok-4.6 beside
grok-4.6@500k) is not listed while the variant has it.
- The user's values are never overridden. SetModelID moves picks,
contexts, fallbacks, groups' members/rules/fast/placed/off/weights/
classifier/pick, the pickers' lists, every per-model setting
(Settings.MoveModel) and gateway keys' models (provider.ModelMoved,
set by access) to the new id, but only where nothing is under the new
id yet. Agents' own files are not rewritten: an old provider/<own id>
still resolves and is sent as it is. Group match patterns and key
patterns stay as written.
- Key limits: a key held to either id passes for both (modelAllowed:
the ref, OwnModelID, ListedModelID). Group members use the same check.
- Usage: model = the listed id, served = the vendor's id from its reply.
The price is the own id's first.
CLI: magpie model id <provider/model> [<id>|--reset], magpie model ids.
GUI: Providers > a provider's editor > Names & levels > "Listed as",
beside Same as. It is staged with the editor's Save and taken back by
Restore default, in zh, zh-TW, ja and de. Accounts have no box.
Docs: providers-accounts.md, gateway-routing.md, and site start.html in
en, zh and ja.
Run (mote-run, at this tree rebased on
|
||
|
|
19594cc1cb |
usage: a span's trimmed chunk keeps only the strings its rows name
A first start's page, heatmap and Codex effort build pair their history
in 4-day spans, and a session file that reaches past a span is trimmed
to it (within). The trimmed chunk cloned the file's whole Strings
table, whose strings all point into the one decoded block of the file:
every span it reached held the whole file's text. within now copies the
strings its kept rows name into one block of its own, renumbers them
("" stays id 0), and rebuilds Shapes through setTexts.
Run on mote, at
|
||
|
|
2eac916170 |
gateway: short-lived gateway keys, issued by POST /v1/magpie/keys or magpie gateway-key issue
xazaj on X is moving an enterprise LLM gateway onto magpie. Their
orchestrator gives each sandboxed agent a key of its own, and that key
has to stop working by itself.
A gateway key can now expire (Key.Expires) and can be issued under
another key (Key.Issuer). It lives from 1m to 30d. It can be held to a
set of models, a set of accounts, tokens or cost over its whole life
(one "hours" limit as long as its life), and read-only.
- POST /v1/magpie/keys {"ttl":"1h"|3600, name, models, accounts, tokens,
cost, readOnly} answers 201 with the secret once, no-store. GET lists
the caller's keys, masked. DELETE /v1/magpie/keys/{id} revokes one.
- magpie gateway-key issue --ttl 1h [--name] [--models] [--accounts]
[--tokens] [--cost] [--read-only] [--from <id>] [--json] prints the key
alone. gateway-key issuer <id> on|off lets a key issue keys. list shows
until/expired/issued by.
Who may issue:
- a key the user let issue (Issues), from wherever that key is let in,
so a container or CI can;
- with no key, a request that profileRefused passes: loopback, no
forwarding header, no Origin/Sec-Fetch/Mozilla marks, a loopback Host.
Such a request can already use every model with no key and run the CLI,
so it gains nothing.
Never: a page, another computer without such a key, a key not let issue,
an issued or expiring key, or a read-only key (readOnlyGuard).
An issued key never outlives or exceeds its issuer. IssueKey clamps its
expiry and refuses models and accounts the issuer can't use. On every
authentication (access.Check, under Authenticate and On), identityOf
folds the key into its issuer as the issuer is now: models, accounts,
read-only, quotas and expiry. An issuer that is off, removed or expired
refuses its keys. Spend counts against the issuer too: the new usage
field callerIssuerId, budget.read/Append counting both keys, and Reserve
reserving on both. /v1/magpie/limit answers expires and issuerLimits.
An expired or refused key gets 401 with why ("… expired at …: ask for a
new one") on every route, from loopback too. Otherwise a held sandbox
whose key ran out would be let in as no key. Expired keys are pruned
after an hour (every 10 minutes while serving, and on each issue).
rowText packs CallerIssuerID: without it, usage.Visit returned the field
empty and the issuer's limit counted none of its keys' calls.
Docs: gateway-routing.md has "Short-lived gateway keys" and the
/v1/magpie stats API table. site/public/docs remote has "Short-lived
keys" and "Stats API" in en, zh and ja. GitHub OIDC is filed as #4531.
Run at base
|
||
|
|
30f29564eb |
sessions: a change to one agent's calls reads that agent's files again, not every shard (#2278)
callCacheVersion named every shard, so raising it for a fix to one agent's calls threw away every agent's calls and re-read the whole history on the next start: on a real history of ~4,700 transcripts that is minutes of CPU and the ~310MB peak, for a change to Claude alone. Each agent now has its own number in callParseVersions. A shard frame records the number its agent had when it was written (callDiskState .Parser), and loadCalls drops a frame whose number is not the current one, so only that agent's files are read again. CallCacheVersion() adds the raised numbers, so the usage caches built on calls (requestDiskBinary, heat_disk) still start again when any agent's calls change. callCacheVersion stays for a change to every agent or to the shards' form. Existing shards are kept: the map is empty, gob leaves a zero Parser out, and CallCacheVersion() is still "calls-v15". Run on mote (zone worktree at this head): - go vet ./internal/sessions ./internal/usage for darwin, linux and windows: ok. go build ./...: ok. - go test ./internal/sessions ./internal/usage: ok. - go test -race -count=3 -run 'TestCallParseVersionRaise|Calls|Shard|Frame' ./internal/sessions: ok. - TestCallParseVersionRaiseReadsThatAgentAlone: a Claude transcript and a Codex rollout; raising claude scans the Claude file alone, with the same calls, and the next start scans nothing. - Broken by hand (the Parser check in loadCalls removed): red at call_versions_test.go:67, "scanned map[], want Claude's file alone". Not changed: internal/gui's TestCoveredWindowStaysUp is killed at 30s on mote, as in #4125. |
||
|
|
5787d758a7 |
usage: a search a provider's model runs with its own tool is a Web search row
cybercaius on Discord: with magpie's search APIs off, DeepSeek was asked to search, and Usage › Requests showed nothing of it; its purpose list had only All, Connection check and Unmarked. DeepSeek searches by itself on its Anthropic and Responses APIs (searchHosts): Claude Code's web_search_20250305 and Codex's web_search are relayed as sent, and the reply carries server_tool_use and web_search_tool_result blocks (#669), or web_search_call items. magpie read only the reply's tokens. Its Chat API has no search tool, so a Chat client's request there, with the searcher and the APIs off, gets no search at all. searchTally (search_native.go) counts what the reply shows: Anthropic's server_tool_use blocks named web_search and usage.server_tool_use.web_search_requests, the Responses API's web_search_call items. What a stream named as it went (a block's start, an item done, by id), what a whole reply or the stream's end listed, and what the usage said are counted apart and the most is taken, so an item named added, done and again in response.completed is one search. The relay's usage sniffer and both translated readers feed it into an unexported Usage.searches; after the request's own row, logNativeSearches writes one row per search (at most 20): Source search, Kind web_search, the request's agent, provider, host and model, status 200. No query is kept and nothing goes to telemetry: the rows ride the probes' lane as the search API rows do (listed, counted nowhere, not exported). An event is parsed for it only when it holds server_tool_use or web_search_call. The purpose filter needed no change: a search row's kind already gives it Web search (TestSearchRowsListTheirPurpose guards that, and passes on the old code too). The Requests tab shows the row with its model and provider as it shows a plan's own search. Run (mote, at this tree): - go test -count=1 -timeout 45m ./internal/usage ./internal/gateway: ok - go vet ./internal/gateway ./internal/usage, GOOS=windows and GOOS=linux go vet ./internal/gateway: ok; gofmt -l clean Broken by hand: - without this change TestOwnProviderSearchesAreLogged fails: "anthropic whole: 0 search rows, want 1" - counting every streamed web_search_call event instead of the done ones by id: "responses stream: 4 search rows, want 2" Not tried: a real DeepSeek account (the fixtures are #669's DeepSeek reply and Anthropic's documented stream shape); the translated readers' counting has no test of its own; no GUI file changed, so no GUI run. |
||
|
|
ef8dfaa463 |
usage: a span pairs a long session's rows within its reach alone (#2278)
A first build pairs four days at a time, but a chunk was taken whole into each span it reached. A session file or ledger block written over weeks was paired in every span: on the owner's history the late spans paired ~257k rows each, near all of it, ~230k of them from ~180 such chunks. coldSpans now takes a chunk reaching past a span's [from-heatReach, to+heatReach) as its rows within that window, and its rows of no time, as a chunk of its own (rowChunk.within). Rows past the reach pair with nothing counted in the span. Lazy gateway blocks and chunks with raw rows are taken as before. Run (mote, at this head): - go vet ./internal/usage; GOOS=linux and GOOS=windows go vet ./internal/usage: ok. - go test -count=1 ./internal/usage ./internal/usageapi: ok. - TestFirstBuildPairsSpans gains a Codex thread written over 20 days, each call with its gateway record; spans of 1, 4 and 14 days must match pairing at once (total 11). - Broken by hand: within keeping no rows -> TestFirstBuildPairsSpans red (the long thread's effort 71 vs 141 at once). Not caught: a window narrowed by heatReach on each side stays green, since the fixture's call and its record are a second apart. - Real history (owner's, sandbox HOME copy, cold start, 3 runs each, against v0.1.2310's change): phys_footprint_peak 313/318/317 MB vs 324/318/325 MB (avg 316 vs 322). CPU 4:15/4:07/4:04 vs 4:10/3:58/3:59 at load ~23 (within noise, maybe +2%). The span log shows the late spans' rows 256,871 -> 144,691. heatmap, sessions overview (0/7/30) and stats (0/30) JSON byte-identical in all three runs; requests equal to 1e-9 (summation order). Not changed: the peak now sits on the requests page's first build (~73MB) beside the sessions stats cache (~85MB retained) and Codex effort (~28MB); those come next. |
||
|
|
a377ffde9e |
usage: a first build pairs four days of history at a time, not two weeks (#2278)
coldSpan was 14: each span of a first start's pairing held ~1000 to
4700 chunks' matched blocks, priced stubs and Codex pairs at once,
the largest part of the cold-start peak. Four days holds less of it
at the same CPU. The comments that said "a few weeks" say days, and
TestFirstBuildPairsSpans checks 1, 4 and 14 days a span against a
pairing of every chunk.
Run (mote, through mote-run): go build, go vet ./internal/usage,
go test ./internal/usage ./internal/usageapi: ok.
Real history copy on mote, cold starts:
coldSpan 4 peak 319/322/328 MB (avg 323) cpu 3:55/4:23/4:05
coldSpan 14 peak 354/356/342 MB (avg 351) cpu 4:20/4:08/4:05
(an earlier pass: 14 → 353/372, 4 → 332/326, 2 → 325/323 with
cpu 4:26/4:32; 2 days bought little more, so 4.)
heatmap, overview 0/7/30 and stats 0/30 JSON are byte-identical; the
request page differs in 10 floats by summation order only (<1e-9
relative), counts and every other value the same.
Rebased onto
|
||
|
|
c420559fdf |
usage: a search API's asks, and a plan's own searches, are rows of the request log (#3528)
cybercaius on Discord: "能记录代搜 API 的用量信息吗,在使用过程中看不到它用了哪些代搜 API". Nothing recorded which search API answered a search, how often, or whether it failed. Each ask of a search API (askSearchAPIKeys) and each search sent to Kimi Code's or WorkBuddy's own search service (ownSearch) is now a row of Usage › Requests, source "search" (usage.SourceSearch, kind web_search): the vendor or plan, the host asked, ok / found nothing / refused / the error, and the time. The row is a probe: it is listed, never counted in a total or a chart, and never exported. Telemetry reads no usage rows, so nothing is added to it. The query is not written: an error's text is scrubbed of it (url.Error reduced to op and host, and the plain, QueryEscape and PathEscape forms replaced). The Usage page badges the row "Search API", or "Web search" under a plan's provider, muted. Run (rebased on |
||
|
|
64aaf421ac |
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.
|
||
|
|
a808c31a75 |
usage: a plan key's window is reckoned from the calls routed on that key (#3747)
A plan bought with an API key (Kimi Code, a GLM Coding Plan, MiniMax's
and the rest of planquota) tells its windows to the key, and when a
provider holds several keys each card names its key: the card's user is
the key's name (PlanQuotas). The ledger names a key's call by the key
alone, ProviderKeyName with no account, since accountOf answers "" for a
key (#557). windowHolds looked a window's calls up by provider and
account, so a key card looked for calls answering as "new" or "old",
found none, and said "not enough data" at 87% used (davisjiahao).
A call now answers as the account it went out as or, when it names no
account, as its key. The key was in the ledger all along, so calls
logged before this fall in too and nothing is rewritten. The same key
also places the call in that card's dry runs, which were keyed by the
card's user already. Every planquota provider's named-key cards go
through this one predicate; the ledger's other Account() readers (the
accounts view, filters, CSV, requests page) keep their meaning.
Not covered, as before: a lone key's card names no user and is never
reckoned (holdsBounds), an unnamed key beside others gets a masked-key
card the ledger can't name, and calls made before a key was renamed
stay under the old name. The lone key is filed as #4507.
Ported from gua2100's branch hunt91-l3-3747-key-card (deb1c0ba0) as
written, reviewed line by line.
Run at this head (rebased on
|
||
|
|
86e19b9b74 |
gui: a cold start's turn lets the matcher's scratch go when it ends (#2278)
Each turn of the warm-up and of a page's first ask (coldTurns) now ends with usage.ReleaseMatchScratch: the request matcher's kept maps, picks and row buffers, which sat for scratchLinger (30 s) under the next turn's read of the history. The priced blocks stay, so the next turn's queries don't price the history again. On mote, a sandbox HOME with the real history (13k sessions, ~720k gateway calls), 75 s with ten answers asked every 5 s, phys_footprint peak: - start with its caches: 260 and 263 MB, against 274 and 285 MB at v0.1.2284. - first start, run alternately with v0.1.2284: 359, 359 and 361 MB against 360, 360 and 364. CPU 3:41-3:47 against 3:35-3:41. The slowest first answer was 31.5-32.4 s against 30.9-31.8 s. - the heatmap and the requests answers are byte for byte the same. Dropped: releasing the priced blocks too (ReleaseScratch). That gave 253-255 MB with caches, but 362-369 MB on a first start, which priced the history again in each turn. Run on mote at |