ac4af582301a4e8a29245dbba767eba31334ddf9
119
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |
||
|
|
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 (
|
||
|
|
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 |
||
|
|
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.
|
||
|
|
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
|
||
|
|
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 |
||
|
|
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
|
||
|
|
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
|
||
|
|
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.
|
||
|
|
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 |
||
|
|
5bb252c8f3 |
usage: a poll's small pairing lets a whole history's scratch go (#2278)
The matcher, the response picks and visibleLocal's set of ids seen are kept for the next pairing, and each pairing that puts one back holds it scratchLinger more. A poll's pairing of its last few days put back the scratch the cold start's pairing of the whole history made, sized for every call, so ~140 MB of maps and slabs stayed while the window polled: the heap profiles at 44, 50, 56, 62 and 68 s were alike to the MB, all of it under codexEffortOfIndex, with no pairing of the history running. Each scratch now records the rows of the largest call it served, and a call over a quarter of that or less (and over 4096 rows' floor) makes its own; the large one goes with the collection. A call alike in size takes what is kept, as before, so the polls while an agent works still reuse it. holdBigBuild counts its rows through the same rowsOfAll. Run on mote at this head (parent |
||
|
|
18b63fe5f8 |
usage: a cold start's builds find the pairing the build before them made (#2278)
On a cold start the page of the month, the page of All, Codex's effort and the heatmap read the history side by side and pair it in turn (holdBigBuild). Each one missed the pairing the one before had kept (pairMemo), and paired the whole history again beside it. On the real history (469 gateway blocks, 16619 session chunks) every big build missed; the warm All page's miss had a memo whose session serials all differed (16619 of 16619). Three things kept them apart: - A session file's chunk got a serial from a counter each time a read built it. The builds read the same files together and share one build of each (sharedBuild), but each named its copy apart. A chunk's serial is now made from what it is made of: the file's path, size and mtime under the index's root and meta (sourceSerial), the same in a build and in a chunk read back from requests-v1.bin. The top bit keeps it apart from a counted serial (gateway blocks, other computers' days). The caches keyed by serial (cells, fold ids, match hints, message keys) hold what a chunk's rows give, so a chunk of the same file and meta reads the same from them. - A build took the last pairing when it began, before waiting its turn. It now takes it once it has the turn (lastPairs). - A build kept its pairing after it let the turn go, so the build that waited took its turn first and found none. It now keeps it while still holding the turn (keepPairsFor). The memo is kept though the build's index isn't: it stands only for chunks of its serials. TestBigBuildsBegunTogetherPairOnce starts the page of All and the heatmap together over a gateway log and eight session files, both having read their rows before either pairs: two pairings, every row once and the heatmap's recent days. Broken by hand, the test is red (3 pairings) with any one of the three undone: the counted serial back, the memo taken before the turn, the memo not kept. Run at this head, rebased on |
||
|
|
a6e7d40421 |
usage: the heatmap pairs its year through All's pairing, not a third time (#2278)
A cold start paired the whole history three times in turn: the page of All, Codex's effort through All's memo, and the heatmap's 53 weeks on their own. The year covers the same chunks as All for most histories, and its pairing was the last and highest of the footprint's peaks (fp 503 -> 565 -> 574 -> 582 -> 592 MB as each pairing ran, e18 on the real history). heatSplit's cold path now pairs through pairEvery: All's window and All's memo (cache.pairs), visited from the heatmap's since on. Whichever of the page of All, the effort and the heatmap comes first pairs every row; the others take the memo. A call is paired to its session row as the whole history pairs it, so a call early in the year can match a session row from before it, as the page of All already counts it. Only the heatmap's recent days are paired again for it. On a cold start this alone moved no peak (597/619/595/611 MB against e18's 592-628): every build missed the memo, for the reasons the next commit fixes. With it, the effort, the page of All and the heatmap take one pairing. TestHeatmapPairsAsAllDoes counts the pairings with the page first and with the heatmap first; both orders are red on the old code. Run at this head, rebased on |
||
|
|
0606e03702 |
usage: a settled chunk's message keys are read for a pairing, not kept (#2278)
msgKeysOf kept every chunk's message keys by serial, for the next
pairing of the same chunks. A cold start pairs the whole history (the
warm-up's page of All, then the heatmap's year and Codex's effort when
page-v1, heat-v1 and effort-v1 miss), so it kept every session file's:
67 MB of the 460 MB live heap 30s after the footprint passed 400 MB
(heap profile of a cold start of the real history on mote), while
polls pair only the days since the split's cut.
A chunk whose rows end before settledBefore(now) is now left nil by
msgKeysOf, and visibleLocal reads its keys into one buffer as it
reaches it. Such a chunk is paired only when a split page's, the
heatmap's or the effort's kept cells are missed. What is left out is
the same: TestVisibleLocalSettledNotKept pairs a settled and a recent
chunk three times and checks the copy left out each time and that only
the recent chunk's keys are kept.
Cold start of the real history (fullcold.sh on mote, caches deleted):
phys_footprint_peak 613 and 603 MB with this change, against 638, 648,
654, 660, 663 and 682 MB before it.
Run at the rebased tree (on origin/main
|
||
|
|
3bce283df4 |
usage: visibleLocal keeps its set of ids seen for the next pairing, not made again each time (#2278)
visibleLocal made a map of every Claude message id (~400k on the bench HOME) to size for every pairing: 212 MB of the ~2 GB 90 s of polls allocated, the largest single site left after the decode buffers were kept ( |
||
|
|
70d9996c57 |
usage: a pass's decode buffer is kept past a collection, not grown again after every GC (#2278)
chunkRows decoded each chunk into a rowBuffer from a sync.Pool. A poll
while an agent works collects several times a second, and each
collection emptied the pool, so the next pass grew a buffer to the
largest session chunk again. In 90 s of polls on the 65 GB bench HOME,
unpackReusing allocated 779 MB (486 MB flat), 553 MB of it under
matchedBlocks.
The buffers are now kept as the matcher's scratch is: up to four in
keptRows (atomic pointers), taken by chunkRows.of and put back by
release, and let go with the scratch, on ReleaseScratch or scratchLinger
after the last pass.
Run on mote at this tree, rebased on origin/main:
- go test -count=1 ./internal/usage/ ./internal/usageapi/: ok, at ae906d4df on
|
||
|
|
4023a2e999 |
usage: a page's newest rows are kept on each chunk's part, not decoded again for every page (#2278)
A Usage page read again after a call picked its newest rows by decoding the few newest chunks again, then decoded them once more for the rows themselves (rowsOf). Under an agent at work that is the long session's own file among them (57k calls): in the writer bench (a call every 3s, the GUI's 10 endpoints polled) pairedRows.newest was 392 MB of 90s. newest now keeps what a chunk gave on the chunk's part: its newest rows the filter keeps, up to take, each with its row (strings copied, as the chunk is decoded lent), and whether that was all of them. The part is the cell cache's: its chunk serial and pairing sig, under the page's period and filter, dropped with the rest when the clears, names or prices change (meta). A page that wants more rows than the chunk gave reads it again. The page's rows come from newest, and rowsOf is not called for them. Run at the pushed head, on mote: - TestNewestKeptOnPart: pages of take 2, 2, 1, 4, 4, 6 decode 1, 0, 0, 2, 0, 0 chunks with the same refs and rows; new parts decode again; rows read stay as they were after the chunks are decoded again over the lent block. Broken by hand, red each way: the kept rows never used; the take check dropped; the lent strings not copied. - go test ./internal/usage/ ./internal/usageapi/: ok - go vet -tags nogui, GOOS linux, windows, darwin: ok - Writer bench, second start of each binary, 90s, load ~25: newest 392 MB and rowsOf 88 MB (v0.1.2190) -> 6 MB and none. Everything allocated: 3698 MB with only the refs kept -> 2742 MB. fp_peak 312 -> 333 MB, late GCs 46 -> 26. Not changed: the decode buffers are a sync.Pool, emptied at each GC, so the big chunk's buffer is now grown by matchedBlocks (18 -> 553 MB) where newest and rowsOf grew it before. That is the next change. |
||
|
|
819aad1bc1 |
usage: a chunk's Claude message ids are read once per serial, not on every pairing (#2278)
visibleLocal leaves out a Claude message written again in another file. To do it, every pairing decoded every local chunk of the period and hashed each row's message id. While an agent worked (a call appended every 3s, the GUI's endpoints polled every 5s), that was 1.1 GB of the 4.5 GB allocated in 90s; 840 MB of it was decoding. Each chunk's message keys (the two hashes and the row) are now kept by the chunk's serial, as matchedBlocks' hints are, with the same pruning (hintsKept turns). Only a chunk with no serial, or none kept, is decoded. The keys are read in the order the chunks are passed, so what is left out is the same as before. Run at this head, on mote: - go vet ./internal/usage/; GOOS=linux, windows, darwin go vet -tags nogui ./internal/usage/ ./internal/usageapi/: ok - go test -count=1 ./internal/usage/ ./internal/usageapi/: ok - TestVisibleLocalKeptBySerial: three chunks, two with serials. The calls decode 3, then 1, then 1 chunk, with the same rows left out each time, and in reverse order too. - Broken by hand: ignoring the kept keys made it red (call 1 decoded 3 chunks); shifting each kept row index made it and TestVisibleLocalLeavesOutRepeatedMessages red. - Writer bench (hmw.sh: the real 109 MB usage.jsonl history, calls appended every 3s, 10 endpoints polled), at the second start, heap profile at 90s, against v0.1.2188's code: - visibleLocal: 1111 MB -> 259 MB (msgKeysOf 53 MB); - pairRowsIn: 1394 MB -> 331 MB; - total allocated: 4537 MB -> 3908 MB; - fp_peak: 544 MB -> 315 MB. mote was at load ~26 from other work, so the times are noisy. Not changed: the seen map is still built on every pairing (206 MB of the 259 MB left). |
||
|
|
f8088cb2d1 |
usage: a page whose settled days are kept leaves the gateway's older blocks unpriced (#2278)
Every query of All priced and unpacked every gateway block of the history
before it looked at what it needed. With the page's cells, the heatmap's
days and Codex's effort kept from earlier days (page-v1, heat-v1,
effort-v1), a cache hit reads only the last days' rows. Pricing the rest
was still 53 MB of the 219 MB heap at 18s on the real history
(blockPricer.priceBlock: 38 MB of pooled rows, 14 MB of unpacking).
readRequestBlocks now leaves a packed, named block whose newest call is
before settledBefore(now) (the splits' edge) as a stub: its serial, count
and latest time, the raw block and the pricer. priceStubs prices stubs in
place, and every pairing calls it first (pairRowsIn, pairRowsMemo,
heatBefore). So a miss, a page of older rows, or a period the splits don't
cover prices them as before. rowsIn counts a stub by its raw block.
heatSettledKey names a gateway block by its raw rows, which requestState's
meta prices, so a priced block and a stub get one key. That changes the
keys once; this binary's own keys already change.
Run at
|
||
|
|
4650e1e3c4 |
usage: this computer's zone is one page key, so the warm-up builds the page the Usage page reads (#2278)
The warm-up and the tray ask QueryPage with Filter{} (no zone); the
Usage page asks with Zone: time.Local (usageapi.FilterIn, usage.Zone("")
is time.Local). Both read their days in time.Local, but the pages cache,
the parts cache, pageOld and the page-v1.json/heat-v1.json keys took
them as two filters. So the warm-up's pairing of the whole history
warmed nothing the page read: the page built its own beside it, and
page-v1.json held two All pages. Found by logging the page key of every
start on the real history: the warm-up's key had zone "" and the page's
"Local", with everything else the same. queryPageOf now treats Zone ==
time.Local as no zone, before any key is made.
Real history on mote (~/r2278), 120s each, the build with this and the
next commit:
new-binary miss fp_peak 518 MB, peaklive 378 MB (v0.1.2180: 587/408)
hit fp_peak 374 MB / 356 MB, peaklive 271/266 MB
The hit after the five pg.sh pages (all, 7d, 30d, all with offset,
codex) started with the page cached on disk.
Test: TestLocalZoneIsTheWarmUpsPage (the page in time.Local after the
warm-up's pairs nothing more and is equal). Broken by hand (the
normalisation off): red, "the page in time.Local paired [6 6]".
TestPageSettledFromDisk's setup moved into pageHistory, which the new
test shares.
Run at this head, on mote:
go test -count=1 ./internal/usage ./internal/usageapi: ok, ok
GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage: ok
go test ./internal/gui: 8 AppKit window tests time out at 30s
(TestDockJoinLeadsCommandTab, TestPanelCloseHidesIt, TestMainWindowCorners
and others): mote's AppKit hang, #4125. This change is internal/usage only.
Not run: the full suite.
|
||
|
|
c7171a2561 |
usage: a page's cells before its last days are kept in page-v1.json, so a start pairs only the recent chunks for All (#2278)
A start's first page of All (the warm-up's, and the Usage page's own)
paired the whole history for the page's cells, every gateway call with
its session row: ~85 MB of a ~316 MB heap at 18s after the heatmap's days
and Codex's effort were kept (v0.1.2172). The cells of the rows before
cut (local midnight two days back) are now kept as heatSplit keeps its
days, in memory and in page-v1.json beside the sessions cache, under a
key from heatSettledKey plus the page's until, names and hours. A start
pairs only the chunks since the edge. A page whose rows are older than
cut (an offset past the recent rows) falls back to the full pairing.
Real history on mote (~/r2278, a copy of the owner's), 120s each,
three starts in a row:
v0.1.2165 fp_peak 451-471 MB, peaklive 326-364 MB
this, miss fp_peak 587 MB, peaklive 408 MB (a new binary's first start)
this, hit fp_peak 361/366 MB, peaklive 265 MB, gcs 150 (was ~150)
page-v1.json is ~240 KB.
The output is the same: /api/usage/requests for period all, 7d, 30d,
all with offset/limit and all filtered to codex, from a start that hit
page-v1.json and from a cold one (file moved away): 0 differences, each
float within 1e-6, on two hit runs.
Test: TestPageSettledFromDisk (first page pairs once and writes the file;
after a restart fewer chunks are paired and the page is equal; an older
offset falls back and equals the cold page; a changed settled file pairs
everything, then hits again). Broken by hand (pageSplit always false):
it goes red at "first page: pairings []".
Run at this head (rebased on
|
||
|
|
cd5df81ecd |
usage: Codex's effort before the last days is kept on disk, so a start pairs only the recent chunks (#2278)
After the heatmap's settled days were kept (heat-v1.json, fixed in the
commit before), the cold start's largest part was codexEffortOfIndex:
a pairing of the whole history, every gateway call with its session
row, for the effort column, ~90 MB of a ~310 MB heap at 18 s on the
real history bench.
effortSplit does for it what heatSplit does for the heatmap: the effort
of rows before cut (local midnight two days back) comes from memory
while the settled chunks' serials match (10 min), else from
effort-v1.json under a key built by heatSettledKey (the settled chunks,
the recent chunks' rows before cut, the identities, the code, root and
meta); only the chunks since edge are paired again. When neither
stands, the full pairing is used as before and the part before cut is
kept. Old data: no file yet means one full pairing, as today, then the
file. A write that fails only means the next start pairs again.
Real history (mote ~/r2278/full, heap at 18 s, three starts of this
build): CodexModelEffort 14 MB, effortSplit 3.6 MB on the third start
(v0.1.2156: 91 MB); /api/usage/heatmap at 40 s byte-identical to
v0.1.2156's (md5 7e458920...) on all three. The first two starts of a
new binary write the files (the settled chunks differ once between a
fresh build and requests-v1.bin's read), the third reads them.
TestCodexEffortSettledFromDisk: a restart pairs fewer chunks with the
same sums; a changed settled file pairs all with the changed input; a
cold run without the file equals it. Red with effortDiskRead disabled
by hand ("started again, paired 6 of 6").
Run at this tree, on
|
||
|
|
8d4c07ffed |
usage: the heatmap's settled days are kept on disk, so a start pairs only the last days (#2278)
The heatmap's days before the cut (two days ago) came from heatOld, a full pairing of the whole history kept in memory. A started magpie made it again on its first heatmap, and again every heatOldFresh (10 min): on the 52G Codex + 13G Claude bench history that was heatSplit's 88 MB of the cold start's ~325 MB in-use heap at 18 s. The days are now kept in heat-v1.json beside the sessions cache, under a key (heatSettledKey) naming what they were counted of: the request code and the index's root and meta (prices, names), the cut, since, zone, filter, the recent chunks' rows before the cut, the Codex thread identities, and each settled chunk (a session file's by path, size and mtime, like requests-v1.bin; any other chunk by its rows). The file is written through a temp file renamed over the last. A key that can't be named (a chunk with no serial) pairs as before; after heatOldFresh a same-named key keeps the days without pairing again. Measured on mote, ~/r2278/full, cold start + the page's 10 endpoints polled every 5 s: - heap at 18 s: v0.1.2149 324.6 MB in use, heatSplit 88.3 MB, HeatmapOf 135.8 MB; this 310.1 MB, no heatSplit, HeatmapOf 44.1 MB. - /api/usage/heatmap at 40 s: byte-for-byte the same as v0.1.2149's. - gcpeak 120 s, 3 rounds each, alternated (mote under other load): live 360/393/414 vs 378/404/387 MB, gcs 148/174/168 vs 201/209/160. The peak moves to CodexModelEffort's own full pairing (91 MB), next. - First start, no file yet: pairs as before and writes 7.9 KB. Tests: TestHeatmapAfterACallPairsOnlyTheLastDays now removes the file for its cold oracle, and past heatOldFresh with nothing changed pairs less than all, then a new settled file pairs all and equals cold. TestHeatmapSettledDaysFromDisk: restarted with memory cleared pairs less than all and gives the same heatmap; another filter, a rewritten settled file, and no file each pair all. Run at this tree (mote): go test ./internal/usage ok (71s); go test -tags nogui ./internal/gui -run 'Heat|Usage' ok, usageapi ok; go vet -tags nogui ./internal/usage/... ./internal/gui/... on linux, windows, darwin ok; gofmt -l clean. Rebased onto |
||
|
|
fddd7ff08f |
usage: pairing keeps its rows as bits and its groups by sums, and lets its pairs go (#2278)
A cold start pairs the whole history, and pairing held its row sets as map[rowRef]bool, ~40 bytes a row, several sets of most rows at once. They are now refSet: a bitset a chunk, a bit a row. matchScratch's groupOf was keyed by the whole matchKey (a session string and its tokens); it is keyed by a 128-bit maphash sum of them now, and the sessions map is filled when a group is made. pairedRows' pairs and compactions maps were filled and never read; they are gone. Measured on mote, a copy of the real full history (52G Codex, 13G Claude), GODEBUG=gctrace=1, 120s of /api polls, 3 rounds each, alternating, v0.1.2143 ( |
||
|
|
807048470e |
usage: a row keeps its times in ms in 32 bits, 184 bytes where it was 216 (#2278)
A page holds every row of its period at once, and at a cold start over
the full history the rows held were most of what the footprint's peak
held: on mote's copy of the real history (52G Codex, 13G Claude Code),
the inuse heap 20s into a polled start had 48.5 MB of decoded session
rows (unpackReusing) and 42.9 MB of priced gateway rows (pricedRows),
both packedRow.
Millis, TTFT, FirstText, FirstReasoning, Sent, Flow, Own, Retried and
Queued are ms (Record's *_ms) and go in an int32, as Masking already
did. One past 24 days, which no call takes, is kept as the longest an
int32 holds (msOf), not wrapped. The snapshot's encoding is unchanged:
each is written as the int64 it was and read back through msOf.
unsafe.Sizeof(packedRow{}) goes from 216 to 184, 15% of every row held:
~14 MB of the 91 MB above.
Run at this head (rebased on
|
||
|
|
99c2567cfa |
usage: the matcher's scratch goes 30s after the last pairing used it (#2278)
With nothing new to pair, every poll of the window is answered from the pairings kept (pairMemo) and pairs nothing, so the scratch of one pairing of the whole history (keptMatch's groupOf/calls/ends/byID maps, keptPicks' picks and slab) sat unused while the window polled, until pageRest's ReleaseScratch 30s after polling stopped. On the real 65 GB history (52 GB Codex, 13 GB Claude) that was ~120 MB of the ~270 MB live heap over 60s of polls. Now each release of either scratch (re)arms one timer, and scratchLinger (30s) after the last pairing put it back both are let go. While an agent works, every poll pairs again inside 30s and finds it kept, as before. Run at this head (origin/main |
||
|
|
c8095d1101 |
usage: pages of 131k rows or more pair one at a time (#2278)
On a cold start the Usage page's requests (All) and heatmap (a year),
and the warm-up's Codex effort, each paired the whole history side by
side, and the live heap reached 624–630 MB at ~10–12 s: the peak. Now
a page's build, or Codex effort's pairing, of bigBuildRows (1<<17) rows
or more holds bigBuilds; a smaller page, Today's, goes beside them, and
its IO never waits (TestQueryPageIOOutsideCacheLock passes). Nothing
under the gate takes requestCache's lock or waits on a flight.
Measured on mote (M5 Pro), cold start with no caches, 390k calls,
a growing Codex rollout, 10 endpoints polled every 5 s, 60 s each:
- before (v0.1.2113): phys_footprint_peak 794 / 783 MB, CPU
2:01.55 / 2:01.12
- after: 610 / 646 MB, CPU 2:01.08 / 2:03.22
- the first round's slowest usage answers, before 7.9 / 10.3 s and
7.9 / 10.3 s, after 7.9 / 11.5 s and 6.4 / 8.7 s
On v0.1.2111 plus the warm-up fix alone, the gate cut the max live heap
from 624/630 to 473/480 MB but not the peak, which the request file's
write then set (
|
||
|
|
839e606575 |
usage: a read marks a published chunk used without copying it (#2278)
requestIndex.use copied every chunk another read had published, only to
set its Used tick for trim, and readRequestBlocks, trim and visibleLocal
grew their maps and slices by appending. Under 80s of polls while a
session was written (ab17) the copies were 255 MB of 5.4 GB allocated,
visibleLocal's seen map 246 MB, readRequestBlocks' on map 96 MB and
trim's kept 107 MB, all garbage the GC then marked through.
A chunk's use is now a counter of its own (*atomic.Uint64, raised to the
read's tick by CAS, never lowered), shared by the map and every page
that holds the chunk, so use returns the chunk itself. A chunk from
elsewhere with no counter yet is copied once to get one. keep and trim
read lastUse. The maps and slices are made at their size.
TestRequestBlocksKeepOneChunkASource asserted the copy; it now asserts
the same chunk comes back with the later read's tick.
Run at this head (mote, Go 1.26.8):
- GOOS=linux/windows/darwin go vet -tags nogui ./internal/usage/: clean.
- go test -timeout 45m ./internal/usage/: ok.
- go test -race -count=3 -run 'RequestBlocks|RequestIndex|Ledger|Heatmap'
./internal/usage/: ok.
Rebased onto origin/main
|
||
|
|
926ef769ff |
usage: a priced gateway block is kept 30s past its last query, so the next poll reads it (#2278)
The queries reading at once already shared each gateway block's priced copy (sharedPriced), but let it go when the last of them was done. Its rows' sync.Pool was emptied by the collections between polls, so every Usage poll decoded and priced the whole history again: priceBlock was ~960 MB, the pool's New ~720 MB, of 6.1 GB allocated in 80s of polls. A block no query holds now stays pricedLinger (30s, past the 10s and 15s polls) and is then let go by a timer; ReleaseScratch, which the window calls once its reads rest, lets them all go at once. The key is the same as for the sharing (requestState root|meta, the frozen block), so what a block is priced as is no less current than when two queries share it. Measured on mote (~/r2278 run2278d, 10 endpoints every 5s, gateway feed from 60s), against |
||
|
|
d7e9c37454 |
usage: a call pairs again only the heatmap's last days, not its year (#2278)
Each call through magpie changes the gateway's newest block, so the heatmap's 30 s reuse missed and HeatmapOf paired a year of gateway rows against every session file again: 15% of magpie's CPU on real history (HeatmapOf -> pairRows 5.2 s of 32.7 s sampled), ~2.3 s a refresh, and a large share of the allocation the GC marks. heatSplit keeps the days before cut (00:00 two days ago) from the last full pairing, with the serials of the chunks that can't reach past cut (newest row more than heatReach = 48 h before it). A call then pairs only the recent chunks, from cut on (pairRowsIn), and adds their days to the kept ones. Every chunk is paired again when: - a settled chunk changed or went (its serials differ), or - the recent chunks' rows before cut changed: a session file copied in or a rollout forked from an old one holds calls of then (heatBefore, a count, time and token sum of those rows), or - cut moved (a new day), or the kept pairing is heatOldFresh (10 min) old. heatReach covers a call paired across cut: a full gateway block whose newest call is before cut is still paired with the session row after it. TestHeatmapAfterACallAddsUpOnlyWhatChanged's gateway now has a call of the last days before its first build, as a gateway in use does: with only a call of 40 days ago its block went from settled to recent at the call, which is a full pairing by design. Run on mote, heat2278 at this head (based on |
||
|
|
49d4d0f7ab |
usage: the request matcher keeps its maps for the next call, and gives them back once the window rests (#2278)
Every poll while an agent works matches a year's history again: matchedBlocks and codexChunkResponsePairs grew their maps (byID, reserved, used, groupOf, picks, picked, ...) and slices from nothing on each call. They were ~3.0 GB of the ~40 GB a poll-heavy 80 s allocated on the real-history harness (d1951 heap diff, 120 s to 200 s). A sync.Pool was tried first and kept nothing in real use: under tightenGC a poll collects 4-5 times a second (1029 GCs in 230 s), each collection empties the pool, and the matcher's flat allocation went only from 2241 to 1840 MB. So one scratch of each is kept in an atomic.Pointer, emptied after a call (clear() keeps the maps' buckets, and drops every chunk the call saw), and let go by usage.ReleaseScratch, which releaseIfPagesRest calls before FreeOSMemory: once the window's reads have rested 3 s, what the matching kept goes back with the rest. A call that finds the scratch taken makes its own, sized as before. matchedBlocks' result map is now made once the id matches are known, not grown from the response pairs alone. Measured on mote (Apple M5 Pro), at |
||
|
|
06469694b7 |
usage: pairing a poll's calls allocates 40% less, in a few slabs (#2278)
Under polls, with calls coming in, GC was ~35% of magpie's CPU and
madvise another 16%, both driven by how much a poll allocates. The
pairing that the heatmap and every page run did most of it: in an 80 s
heap diff on a year's history, matchedBlocks allocated 3.2 GB and
codexChunkResponsePairs 2.6 GB.
- matchedBlocks: a match key holds a call or two, so each key's ends
and range counts were two slices of their own. They are now one ends
slab and one counts slab, a group an offset into them, and groupOf is
made the size of the calls it keeps. The candidates and unique maps
are a slice and a []bool over slab positions.
- codexChunkResponsePairs: picks and their slab are made the size of
the gateway's response ids, and a gateway call is judged from its
packed strings (codexGatewayCall) instead of being made a whole Row.
What a call pairs with is unchanged.
BenchmarkPairRows (new; 2,000 session files of 100 calls, half Codex by
response id, half Claude Code by session and tokens), on mote:
|
||
|
|
655f8dbd1c |
usage: matching by request id keeps no slice an id (#2278)
matchedBlocks kept each request id's gateway calls in a map of slices, the local calls that named it in a second map of slices with the id cloned, and each match group behind a pointer. Over a year's calls the alloc profile of v0.1.1928 on mote (34k session files, 240k gateway rows, two minutes of polls while an agent worked) had matchedBlocks at 2.5 GB: groups 598 MB, byID 547 MB, byRequest 504 MB, matched/used 463 MB. Now: - an id is a place in one slice of calls, its first call held in place and only repeats in a slice; the map of ids is sized by a count pass; - the local calls that name an id are one slice, each linked to the one found before it, read back in the order they were found, so the order (and newestIDs' sort) is what it was; - the id is looked up, not cloned, and a call with no id is skipped before the lookup; - groups are a slice the map points into. TestMatchByIDAllocatesNoSliceAnID: 4000 gateway calls with ids, a third of the locals naming an earlier id again, match as matchedLocalLegacy does, and the second match makes at most n/10 allocations. Red on the old code (11,334 allocations), green on the new (168). Run on mote at the pushed head (rebased onto origin/main |
||
|
|
b5d2858f41 |
usage: matching gateway calls decodes only the session files they can match (#2278)
matchedBlocks paired the gateway's calls with the session files' by request id, then by session, tokens and time, and decoded every session file of the period for each pass: twice per poll, for the few sessions the gateway had calls of. In a 24s heap profile of a fed sandbox it was 0.77 GB of the 5.3 GB allocated, and 5.4s of a minute's 42s of CPU. Each local chunk's hints are now kept by its serial (match_chunks.go, as chunkIDs keeps Codex's response ids): a 32-bit hash of each request id it names, a hash of each session a call of it can be matched in (agy's as agyMatchSession, rows of no tokens and no failure left out, as the pass does), and its last call's time. A pass decodes a chunk only when one of its ids or sessions is the gateway's and its last call is in the period. A hash that matches only decodes the chunk, so the matches are exact. Hints live 8 matchings past their last use. Run at this head ( |
||
|
|
b69f8e96af |
usage: a call through magpie adds up the heatmap only for the chunks it changed (#2278)
A call through magpie changes the gateway's log, so the heatmap's kept
page (heatFresh) is no use and the Requests tab's refresh read every
row of the year again: unpacked each session file's chunk and summed its
days. While an agent worked through magpie that was every refresh.
The heatmap now keeps each chunk's day sums (chunkPart.days, in
requestIndex.heatParts, apart from the pages' cells so neither pushes
the other's out), under the same pairing signature the cells use, and
adds up again only a chunk whose rows or pairing changed. A call is
still counted at once. pairedRows.visit had no other caller and is gone.
Measured on mote at #2278's scale (synthetic HOME: 15 GB of Codex
rollouts, 1.9 GB of Claude sessions, 240k-row usage.jsonl), the GUI's
polls every 5s and 4 gateway records appended a second, against
v0.1.1920:
- CPU of a 60s profile while appending: 57.9s -> 42.1s;
HeatmapOf 11.5s -> 6.7s, of it the visit 4.8s -> ~0
- /api/usage/heatmap mean 2.79s -> 1.69s; process CPU average
107% -> 83%
- peak footprint unchanged (579 MB, 607 MB this run: noise; what is
left is pairRows' pairing of the year, next)
Test: TestHeatmapAfterACallAddsUpOnlyWhatChanged (8 session files and
a gateway call: after one more call, at most 1 chunk is added up again,
the call is counted, and the sums equal a cold build). Broken by hand
(old sums never taken): red, "a call added up 9 chunks again".
Run at the pushed head (rebased on
|
||
|
|
6104e88aa9 |
usage: a session file two queries read at once is made once (#2278)
At a cold start with the app open, the warm-up's request page and the GUI's heatmap each read every session file at the same time. Each one decoded and priced its own chunk of each file. That is twice the CPU, and the GUI's requests queued behind it. sharedBuild keys a build by the request state (root and meta, hashed) and by the file's path, size and time. A query that finds the same file already being made waits for that build, then takes its own shallow copy, because a query writes its chunk's serial, use and archive place. The rows and the archive are shared and only read. If the build panics, the waiter builds its own. Only QueryPage and the effort index share builds; queryPage's other callers build as before. blockPricer.share now takes the hashed state directly. Measured on mote with synthetic history at #2278's scale (25k Codex rollouts, 9k Claude sessions, a 115 MB usage.jsonl), with a cold `magpie web` and 10 GUI endpoints polled every 5 s for 150 s. Built on v0.1.1903 before the rebase: - slowest GUI response: 61 s on v0.1.1903, 15.3 s with this change - footprint peak: 591 MB on v0.1.1903, 609 MB with this change, so no memory gain; the peak is a transient spread over the page, heatmap, effort index and session stats (heap profile at 15 s: QueryPage 145 MB, HeatmapOf 87 MB, buildEffort 51 MB, StatsAndNative 43 MB) TestSharedBuildMakesAFileOnce checks several things: - a second query waits for the first one's build - each query gets its own copy, and the copies share one archive - a change to one copy doesn't show in the other - the map is empty afterwards - after a panicked build, the waiter builds its own With the join broken by hand (the lookup disabled), it failed with "a file made again while another query was making it". Run at the pushed tree (rebased onto |
||
|
|
aafbe575ce |
usage: queries reading at once share one priced copy of a gateway block (#2278)
A query over the gateway's history decodes and prices every block it reads and holds them until it is done. At a cold start with the GUI open, the warm-up's page, the heatmap and Codex's model/effort each ran such a query at the same time, and each held its own copy: 105 MB of pooled rows between them at the peak, and the app's footprint went to 737-760 MB where it is 388 MB with nothing asking. A priced block is now kept in sharedPriced, by the frozen block and a hash of what prices and names a call (requestState.meta and root), while any query holds it; the last release hands its rows back to the pool. A block is never changed once frozen, and a priced copy is only read: pairing clones a chunk before it writes a row's thread. A pricer that was not given a meta (the tests' own) keeps its blocks to itself, as before. Both callers release on a panic too (defer), so a block is never held for good. Run on mote (M5 Pro), rebased onto |
||
|
|
012c584cc1 |
usage: clear a model's usage, or all of it, from the Usage page
CrazyMouse_TT on X asked for a way to clear usage, all of it or one model's, to measure a local model fresh after deploying it. The Usage page's Models list has a "…" on each row (and a right-click menu) with "Clear usage…", and "Clear all usage…" sits under the lists below the "Counted from…" note. Each asks first, in a confirmation that says what is deleted, that it can't be undone, and that key spending limits and allowances still count the calls. A clear is a mark in settings (usageCleared: provider, model, unix ms), read at read time; usage.jsonl is never rewritten. The Overview hides calls up to the mark in summarizeFrom; the Requests page, heatmap and ledger/CSV hide them in Filter.keepsRow, their one choke point, and the request index's meta carries the marks so its cache is dropped. Key budgets, window holds and Codex reads go through usage.Visit and the raw log, so a clear never resets a key's spending limit or a quota. A later clear of the same model or of everything takes the place of an earlier one. The marks ride the settings part of a sync (sync-backup.md) and a save of the Settings page keeps them (api.go's keep list; the guard test TestSettingsSaveKeepsWhatItDoesNotSend caught it missing). gateway-sessions.md and sync-backup.md say so. Run on mote (mote-run) at this tree, rebased on origin/main |
||
|
|
b7b8171165 |
usage: a source's chunk is kept once, the index's and the page's both (#2278)
readRequestBlocks copied every source's chunk twice, one for the index and one for the page, on every read: 13.5 MB of the 176 MB live heap after 34k sessions' cold start (synthetic history at #2278's scale on mote, 240k gateway records in usage.jsonl). Nothing writes a published chunk in place (pairRows and pairMemo.apply clone, keep copies, the spill gives an archive back before the read returns), so both now take one chunk. A chunk this read built or read from disk is its own and is not copied at all; one an earlier read published is copied once, for its Used, since that read's page may still hold it. The other computers' days are kept the same way. TestRequestBlocksKeepOneChunkASource: a built chunk is the map's and the page's one pointer, with this read's tick; read again after keep, it is one new copy and the published one is unchanged. Broken by hand (the index given its own copy again) it failed with "a built chunk is copied". Run at this change on |
||
|
|
0dc4cec85d |
usage: a row's Codex thread is kept as a 4-byte place, not a string (#2278)
Every row of a chunk had a 16-byte string header for its Codex
thread. A day's rows are a few hundred threads, one after another. At
the scale of #2278 (34k session files, 1M Codex rows), these headers
were the largest single holder in the heap, 24.5 MB of 184 MB live.
codexActors now keeps a []uint32 into the chunk's thread names. The
row before's thread is checked first, then the names. A clone shares
the names clipped, so adding a name to one never writes into the
other. The disk format is unchanged: each row's thread is still
written as a string.
Measured on mote, at 7e58591dc's parent with this change. The history
is synthetic: 25,000 Codex rollouts and 9,000 Claude Code sessions, 40
turns each (13 GB), plus a 115 MB usage.jsonl of 240k gateway calls on
the newest 3,000 of each. Cold `magpie web --no-open` in a sandbox
HOME, with `magpie heap` taken at 130 s:
- main: live heap 195.2 MB (both runs), physical footprint peak 389 to
417 MB.
- this change: live heap 175.6 MB, physical footprint peak 366 MB.
The reporter's 0.1.1318 peaked at 2.85 GB RSS on such a history.
Run at the pushed head (rebased onto
|
||
|
|
396e0e4638 |
usage: a deleted provider's requests merged into another, or named, from the Requests filter
CyberCaius on Discord: a deleted provider's requests sat under its old id
("<date> 已删除"), and the only way to put them under a provider they
have was renaming that provider onto the old id. Now, with a deleted
provider picked in Usage › Requests' Provider filter, a "…" beside it
offers Merge into… (an app menu of the providers there are now) and
Rename… (the filter's button turns into a name field; Enter or leaving
it saves, Escape keeps it). With the merged-into provider picked, the
same "…" lists Separate <name> for each, the undo.
Nothing in the log is rewritten. Both live on the deletion's own record
in providers.json (Deleted.Into/MergedAt, Deleted.Label), so a provider
added later under the old id inherits neither: it is a different
provider, and its record of its own is what it has. Renaming the target
carries the merge (Rename rewrites Into); deleting the target ends it.
Renames.Both(id, time) gives the id a call is shown under and the one it
was made to (Own). Listing, filtering, the summary and vias go by the
shown id; pricing (Record.priceID, block_price's as), window holds and
the gateway's loggedAnswers go by the own one, so a merge moves no cost
or token, only whose name they sit under. The target's face lists what
was merged into it (Named.Merged). Routes: GET /api/usage/deleted/into,
POST /api/usage/deleted {id, into?, name?}; a field not sent stays.
Run (mote, at this tree on
|
||
|
|
841bcf8da7 |
usage: a reply under the name its provider's list gives the model is not a swap
jzing.draw (Discord #general, 10-27) had a Usage row for Qoder's free
Qwen model, sent as qfmodel, tagged "actual Qwen3.8-Flash". Since
plugins#412/#413 (qoder 0.2.38) the plugin answers under the model list's
display name, and Qoder's list names qfmodel Qwen3.8-Flash, so it is the
model asked for. Swapped compares names alone and can't know that.
usage.ListedAs(provider, model, served) reads the provider's own list
(Provider.Available, once a minute per provider, only once a reply already
reads as swapped) and holds when served is the name it gives the model,
spelled however (SameSpelled). Every place a swap is set or read again
asks it: the gateway's try, the ledger and request-page rows, block
pricing, a kept row read back (request_page unpack) and a kept route
(history routedAgain), so old rows lose the false tag too.
Run at this tree (base
|
||
|
|
94c2aaecba |
usage: a deleted provider's tests stay listed under it, not its host (cybercaius)
cybercaius on Discord: one custom provider (example, on api.example.me)
was listed in the Requests page's provider filter under its id and its
host, and the host stayed after the provider was deleted.
The Add sheet's Detect, model-list and Test requests are sent before the
provider has an id, so probelog records them under the host asked
("a provider being added has no id yet").
|
||
|
|
f3c4d7b7a7 |
usage: Codex effort reads only the session chunks that have Codex threads
CodexModelEffort (the Usage page's model and effort per Codex thread, read again each minute) unpacked every chunk of the ledger, Claude Code's and every other agent's too, to sum the few rows a Codex actor owns. codexEffortOfIndex now visits only chunks with a Codex actor (pairedRows.visitActors), and effortSums.add clones the model and effort it keeps, since lentRows lends its strings. Run at this head ( |
||
|
|
8fba65d0bc |
gateway: what masking took a request is kept, and shown as Masking in its time
fremontdango on Discord asked, after the request that sat as "routing…" while it was masked, how long masking took. Now each request keeps it. noteRedacting adds up the time from the first masking at once to the last's end (redaction.spent); maskingMs gives it in ms, at least 1 when there was any, never more than Own, magpie's own time before the request went out (splitSent), since masking happens inside it. It goes on the route (Route.Masking, /api/gateway/trace) and in the usage record (Record.Masking, masking_ms; packedRow's int32 fits in its padding, so TestRowsOfOneSessionShareAShape's 216 bytes are unchanged, and the process-private snapshot carries it). It is a duration, no text. The Routing page shows it as magpie's "Masking" part, first in where the first try's time went (timeParts, renderSteps); the Usage page's detail splits it out of "In magpie" (page.js). Both use the core "Masking" string every language already has (脱敏, 脫敏, マスク, Maskierung). Why masking can be slow, measured on this machine (go1.27, M-series): the rules are linear, ~0.25 ms/KB. redact.MaskJSON over a Claude Code shaped body: 283 KB 35 ms (secrets) / 63 ms (+ personal data); 511 KB 70 / 122 ms; a dense 402 KB with 7,821 hits 173 ms with personal data, 144 ms with the user's words too. Through the gateway (redactedHits, secrets + personal, 402 KB dense) 145 ms the first time, 123 ms again; noteMasked ~2.6 ms. Doubling the body doubles the time; nothing quadratic or repeated per hit. So a request held "routing…" for 15 s or more (unroutedShow) while masked is the local model (Settings → Privacy → Find with a local model, internal/pii): it reads each text it hasn't seen (a new turn's tool results are the misses), one model turn at a time, so requests queue behind each other (#3682: 480 KB took 90 s on an RX 470/580). No change to masking's speed here; the phase and the time now say which it was. Run at this head, on origin/main |
||
|
|
c2c08850f6 |
usage: a request state hashes Codex's thread identities without encoding them
readRequestState json.Marshal()ed every Codex thread's identity (~20k over a real history) into a new buffer only to write it into the key's hash, on every requests page and effort ask: every 15 s poll. They are now written into the hash directly, each field length-prefixed, in the order of their keys. The key lives in memory only (the disk index is keyed by meta), so the changed form costs nothing on upgrade. Benchmark, 20k identities (a throwaway benchmark, not committed): json.Marshal + hash 7.06 ms, 6.49 MB, 40012 allocs an ask; now 3.36 ms, 0.36 MB, 3 allocs. In a 12-poll real-history run json.Marshal under readRequestState was 116 MB. Test: TestCodexIdentitiesHashed (same identities in another order hash the same; a thread turning subagent changes it; ab|c is not a|bc; none is not one). It fails with the length prefixes taken out by hand. The rest of the package's tests passed with this hash removed altogether: an identity changes only with a rollout, whose size and time are in the key too. Run at this tree: go test ./internal/usage/ ok (8 runs; one earlier run of this change printed a bare FAIL whose test I lost to a tail, not seen again in 8 package runs and 30 of the effort tests); gofmt -l clean; go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage ok. |
||
|
|
61d656c696 |
usage: a Codex thread's consumption is built again at most once a minute
The Sessions page asks CodexModelEffort(All) on every 15 s poll. It
built the ledger of all history again whenever any session file or the
gateway log had changed, and with Codex and Claude Code at work they
change between nearly every two polls. In a 3.5-minute real run that was
2.49 GB allocated, the largest single cost of a poll. An answer now
stands for effortFresh (a minute) before a change is built into it, and
an ask inside the minute is answered before the sources' state is read
(that listing and hashing is most of an unchanged ask's cost). Another
home's answer is never held (requestRoot). The page's own rows, totals
and the requests page are read as they change; only this per-thread
model/effort breakdown can be up to a minute behind.
Tests: TestCodexModelEffortHeldForAMinute holds the answer inside the
minute (no build, the old value), builds the change after it, and
builds for a new home at once. It fails with the check turned off by
hand ("inside the minute: builds 2 ... want 1"). The package's TestMain
sets effortFresh to 0, so every other test still sees a change at once.
Measured on a copy of the owner's real history, 12 poll cycles 15 s
apart after a warm start, origin/main
|