ac4af582301a4e8a29245dbba767eba31334ddf9
22
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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. |
||
|
|
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). |
||
|
|
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.
|
||
|
|
8f0d21a009 |
usage: a start reads the gateway log's full blocks from log-v1.bin, not the whole log again (#2278)
Every start parsed the whole of usage.jsonl with json.Unmarshal a line at a time. On the owner's real history (109 MB) that was 622 MB of the first 18s's 1765 MB allocated, and most of the GC work of a cold start. The full blocks the log index freezes are now kept in log-v1.bin beside the sessions cache, with where they end in the log (offset, line count), the SHA-256 of the log up to there and the hasher's state, first/firstOwn, the provider keys and hosts seen, and the probe rows before that offset. A start reads them and parses only the lines after. They stand only while the log's bytes up to the offset hash the same and the code that reads them is the same (requestDiskBinary); otherwise the whole log is parsed as before. The file is written through a temp file and a rename, at most every 10 minutes and only when it gains blocks. Run on mote at this tree, rebased on origin/main: - go test ./internal/usage ./internal/usageapi: ok - GOOS=linux|windows|darwin go vet -tags nogui ./internal/usage: ok - TestStartReadsKeptLogBlocks: a second start loads the kept blocks, and rows, probes, keys, hosts and hash equal a whole parse; a log edited before the offset is parsed whole. - Broken by hand: accepting the kept blocks without resumeLogHash turns TestStartReadsKeptLogBlocks red (hash differs); restored, green. - Bench on a copy of the real history (~/r2278, 109 MB log), cold start polled 120s, second start of each binary (caches hit): v0.1.2184: peaklive 217MB fp_peak 307MB, 156 GCs this: peaklive 210MB fp_peak 315MB, 98 GCs readLogSnapshot alloc_space 622MB -> 8.6MB; total 1765MB -> 1095MB. The first start writes log-v1.bin (7.4 MB). Not tried: the GUI suite (no GUI file changed); Windows and Linux runs of the package (vet only). |
||
|
|
1bbaded622 |
usage: an agent's call to magpie's own MCP tools is a row of Requests
ferock (Discord) asked to see calls to magpie's MCP tools, such as magpie-image's generate_image, generate_video and generation_result, in Routing > Requests. Each tools/call to magpie's own MCP servers (image, vision, web search, tools and the Library hub) is now a row of the request log. The row has Source and Kind "mcp", the tool as its model, the server as its host, how long the call took, and its error if it failed. The provider and model it shows are those of the model requests the call made, collected through the request's context in appendUsage. generation_result names the model of the job it answers. The stdio Magpie Image server reports each call it answered to the gateway as "magpie/toolCalled". That report carries the tool, ms, model and error, never the prompt. The arguments are never stored at all, so there is nothing to mask. The rows go down the probe lane: they are listed, but no total, host list, budget or key limit counts them. The model requests a call made are rows of their own. In the GUI the row reuses the Requests list. It gets a muted "MCP" badge with a tooltip, the server beside the provider, and a Succeeded/Failed status. The Purpose filter gains "MCP tool" in every language. There is no new page, no <select> and no left border. The core scripts went over their budget with the new purpose. genpurposes now writes purposes.js as compact JSON, which makes the core 448 bytes smaller than main in all, and coreScriptBudget is lowered to the new total, 1,538,975. No room is added. Run on mote, at the rebased head: - gofmt -l: clean. go vet -tags nogui ./... with GOOS darwin, linux and windows: ok. - go test -tags nogui -timeout 45m: ./internal/usage, ./internal/imagemcp, ./internal/usageapi and ./internal/gui ok. internal/budget has no test files. ./internal/gateway (805s): every test ok except five Antigravity and Codex/Grok tests. They fail the same on a clean origin/main |
||
|
|
28c89afcef |
usage: a period's summary counts only the log's blocks since the last
Each call the gateway logged changed the log's version, and every
/api/usage ask for Week or Month counted the whole period again: on
the #2278 bench (a busy gateway, 4 calls a second, the GUI's polls every
5 s) topSummary was 11% of CPU, beside GC at ~30%.
A period's summary now keeps what it counted over the log's full blocks
(512 rows each, never written again once full) and counts only the
blocks since, then the last block. It counts afresh when anything a
count depends on changed: a block it counted was replaced, a rewrite,
prices or names (meta), cleared calls, the period's bounds or series, or
the keying (hosts, accounts, keyed providers) changed. In the last case
an account that newly answers for a provider splits that provider's
earlier calls too. Rows are counted in the same order as before, so
every float comes out bit-identical. The group maps are copy-on-write
over the kept prefix, and only what was touched is copied.
Run at this tree, 213a31b4d before this message (the parent is origin/main
|
||
|
|
dc6f6d9022 |
usage: a read of the gateway log decodes its blocks into one buffer (#2278)
logSnapshot.visit unpacked each block of usage.jsonl's snapshot into rows of its own. Every Sessions, Usage and Routing poll reads the log through it (buildGatewaySessions, topSummary, buildVias), so while calls came in it allocated ~800 MB of rows a minute: 1.3 GB of the 5.3 GB a 24s heap profile of a fed sandbox allocated was unpackReusing's rows, strings and text under visit. It now decodes every block into one chunkRows buffer, each over the one before, as the page's other readers do. A record's strings are the block's own text, not the buffer's, so fn may keep them. Run at this head ( |
||
|
|
f39fc3ac8b |
usage: a model list that was answered is no row of Requests (ferock on Discord)
ferock (Discord #general): Usage > Requests is full of rows like "magpie · magpie's own · Remote magpie · API · Model list · 0 0 · 757 ms · 200, GET /v1/models", which no tool of theirs sent. Cause: |
||
|
|
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").
|
||
|
|
a6399dd494 |
usage: a Requests page sums each chunk once and reuses it while the chunk is the same
Turning a page, or the 15s refresh of the open page, built every sum, chart and share from every row of history again. On the owner's real history that was 1.15-1.36s a page (load 170) after the chunks were already cached. Each chunk's rows are now folded into cells: one per provider, agent, model, kind, caller, account, computer, source, filter bits and chart bucket, with its totals. A page merges the cells. The cells of a chunk are kept per (period, filter, since, until, zone), up to 4 such sets, keyed by the chunk's serial (a new one every time a chunk is read or frozen) and a signature of what pairing gave it: rows skipped or matched, Codex actors and their identities (with the parent's role), and compactions. A changed file, a gateway tail block or an identity change from another file sums that chunk again. The newest rows are taken from chunks in Latest order, stopping once the heap holds rows newer than the next chunk. Cell strings are unique handles, so the cache holds no chunk's string block. Totals and Part sums are linear, so merged cells equal the row-by-row sums; date-mode buckets store the day number and are placed against the chart's first day at merge time. What was run (macOS, arm64): - Real history (sbmem sandbox HOME, read-only links to the owner's data), zzbench dump of 9 cases x 2 pages (offset 0/50 after a warm 7/50 call, and 120/30) with the base |
||
|
|
ffe493773c |
usage: magpie's own Test, Detect APIs and model list requests are rows of the request log, counted nowhere
neiko and gys619 on Discord: a provider's Test or Detect APIs left no
trace in Usage > Requests, so a failing test couldn't be read back.
The provider package marks the context of the editor's Test, Detect APIs
(and per-model detection) and a model list's refresh with a kind
(internal/probelog). Each request sent under the mark is written once:
by the provider's Do, or by probelog.Transport under http.DefaultClient
(netproxy.Install), whichever sends it first; the Claude Code run and
the gateway's translated test write theirs from their result. A row
keeps time, provider, account, model, host, path (no query, no
user:password), method, status, ms and the first 500 bytes of the error.
The row is usage.SourceProbe, agent "magpie", Kind provider_test /
api_detect / model_list ("Test", "Detect APIs", "Model list" in Called
for; purposes.js regenerated). The log index keeps probes apart
(logSnapshot.probes), so Visit, Load, Summarize, budgets, Vias, heatmap,
shared days, LastSeen and observers never meet one. The request page
lists them (probeChunk) and counts none: Row.IsProbe, since a packed row
keeps the row's Source and not its record's. The page shows a muted
badge "magpie's own · not counted in any total" (en, zh, zh-TW, ja, de);
no new control, no layout change.
Tests, each red on the old code:
- usage TestProbeRowsListedNotCounted: listed, clipped, and absent from
Sum, Through, every By group, Summarize, Load, LastSeen, OwnDays and
the observer; a provider filter lists it and sums 0.
- provider TestTestWritesItsRequestsDown / TestDetectWritesItsRequestsDown:
every request the fake server saw is exactly one row, with the right
kind, model and 401 text; an unmarked Do writes nothing.
- probelog TestNoteKeepsNoSecret, TestTransportOnce.
- GUI usage-ledger-probe: badge per language, both engines, 1180/420,
light and dark, no left border, no sideways scroll.
- gui TestProviderDetectDraft now expects the log line (source probe,
kind api_detect, no key) and leaves usage.jsonl out of the unchanged
config comparison.
Broken by hand, each went red: request_page's uncounted check,
log_index's probe skip, Append's observer skip, Do's Taken (6 rows for
4 requests), Test's and Detect's marks, probelog's query strip,
page.js's badge (11 GUI fails).
Run at this head (on origin/main
|
||
|
|
f6a96b2f0b |
usage: a change time with a fraction settles in 100ms, so a read after an append hashes no log (#3394)
readLogSnapshot checks its snapshot against a SHA-256 of the log's whole prefix whenever the log's change time is under a second old. Under steady traffic every read came within a second of the gateway's last append, so each one hashed the whole usage.jsonl again: 1.8 times the log for each append and read. A stamp with a nonzero fraction of a second comes from a clock that ticks in milliseconds (APFS in ns, Linux's coarse clock 1-10 ms, NTFS ~15.6 ms), so it settles in logFineSettle = 100ms. A stamp in whole seconds (HFS+, FAT, a share) keeps the one-second settle. Run: - go test -count=1 -timeout 45m ./internal/usage/ ./internal/budget/: ok. - TestUsageReadAfterAppendHashesNothingOnAFineClock (20000-row log, 5 appends, each followed by two reads): fine stamp 0 bytes hashed; whole-second stamp 50.7 MB. Broken by hand (logFineSettle = time.Second): 54 MB hashed, red. - Real account, sandbox HOME, a deepseek-only providers.json and a 98 MB usage.jsonl (the owner's own log, repeated 50 times). magpie serve took 30 real /v1/responses calls with a Codex user agent to deepseek/deepseek-flash, all answered, while /v1/magpie/usage?period=today (the Usage page's read) was polled every second. Process CPU time, two runs each: before 3.11 s and 3.05 s, after 1.95 s and 2.25 s. The same calls with /v1/magpie/quotas polled cost 0.2 s on both binaries, since that path never reads the log. - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/ clean. Not tried: an HFS+ or FAT volume (the test skips when the file system gives whole-second stamps, and covers that case by truncating the stamp); the full suite at this head runs after the push. |
||
|
|
4042aa4d1d |
usage: a row keeps the strings its chunk shares once, in Shapes
The usage page holds every row of the period at once, and a packed row was 328 bytes, 140 of them 35 string ids. On the owner's real history (364,013 calls in 6,445 chunks) only five of those vary call by call: the error, the request id, the archive, the response id and the message id. The other 30 (agent, provider, model, session, endpoint, client...) repeat for most rows of a chunk: 364k rows have 7,300 distinct sets. So a row keeps those five ids and a Shape, an index into its chunk's Shapes table, which holds every other set once. packedRow is 216 bytes. A snapshot (process-private, nothing on disk) writes the table once after the strings and per row the shape and the five ids, so archives shrink too. block() renames and re-prices per shape, not per row. Same output: |
||
|
|
60f896031e |
usage: a client the user counts as an agent is counted as it on Usage and Sessions (#1958, NorethSea)
NorethSea's bridge (hermes-codex-thread-bridge) starts Codex's
app-server under a User-Agent of its own, so its calls were a row
apart from Codex on Usage, and its threads weren't Codex's in Sessions.
Rather than learn one bridge's name, the user says which agent a client
counts as.
- settings: clientAgents, client name (lowercased) -> agent id.
ClientAgentsNow reads just that field through filememo, so a pass over
the ledger costs a stat.
- usage: ReportedAs(ua) is AgentOf, then the user's mapping. It is used
for what is reported only: the summary, the agents list and filters,
request rows and pages, priced blocks, direct, Vias and gateway
sessions. The gateway's routing, keys and caps still go by AgentOf,
the client's own name. The mapping is read once per ledger pass
(readLogSnapshot) and is part of the keys of the summary price cache,
the vias cache and the request page cache, so a change redraws the
history already counted. A request row keeps the client's own name in
a new "client" field, shown as "Client" in its details.
- gui: POST /api/usage/arrange takes {count:{client,as}}. It refuses a
client magpie already knows as an agent, "other" or magpie's own, and
an "as" that isn't a known agent or is magpie. as "" counts it on its
own again. /api/settings keeps the mapping it doesn't send. On the
Usage page an unknown client's "…" offers "Count as an agent…" (a
picker of the known agents), the agent's row says "with <client>",
and the agent's "…" offers "Count <client> on its own". Strings are
in all 5 languages.
Run:
- go test -count=1 ./internal/usage ./internal/settings ./internal/gui: ok.
- TestClientCountedAsAgent goes red with reportedAs broken, and with the
mapping left out of the vias key or the request page key. With the
summary key alone left out it stays green, because the settings stat
already moves it.
- TestUsageArrangeCountClient and TestSettingsSaveKeepsWhatItDoesNotSend
(ClientAgents added) pass.
- Playwright usage-count-client.test.cjs (new) and usage-agents-hide
(its menu now has two items for an unknown client) pass in Chromium
and WebKit, in all 5 languages, at 1100 and 420: 54/54. With
countable() forced false, the new test goes red.
- gofmt -l is clean. go vet is clean for darwin, linux -tags nogui and
windows.
Not tried: a real hermes bridge (the records' UA is from the issue), and
the Client line in a request's details has no GUI test.
|
||
|
|
d4c2512d2d |
usage: apps report their own calls with POST /v1/magpie/usage/requests, backfill included (#1874)
What changed
- POST /v1/magpie/usage/requests (internal/gateway/usage_ingest.go) takes
one record or an array, in usage.jsonl's shape:
- the post may carry up to 5000 records and 32 MiB;
- t, agent, provider, model and rid are required.
Each field is checked: unknown fields, quoted numbers, negative or absurd
counts, a status outside 100-599, a cost over 10000 USD, and a t more
than an hour ahead or before 2000-01-01T00:00:00Z. Any fault refuses the
whole post with a 400 that names error.index and error.param, and nothing
is written. A past t is otherwise taken as given, so history can be
backfilled. The reply gives accepted and skipped counts and each
record's index, rid and status.
- Access: lanGuard's rule (this machine, or another with a key while
shared, behind the Host check). A browser page also needs a key, since
corsGuard lets localhost pages and Origin null through. A held key is
refused.
- usage.IngestReported writes under usage.mu to the same file as
usage.Append. Rows carry source "reported" and no caller key. A rid
already reported is skipped, as is one repeated in the post. The set of
reported rids is read back from the log: one scan after a restart (lines
without the reported mark aren't parsed), then only what was appended.
- Pricing: a record with cost keeps it (Record.OwnCost, the rowOwnCost
flag; packed flags widened to uint16). Otherwise it is priced at
magpie's prices.
- Display:
- SourceReported is a source of its own: RequestPage.Reported,
?via=reported, and Ledger now honours via.
- The Requests tab gains a fourth cell "reported by apps", shown once
there are some, and a "Reported" badge (en, zh, zh-TW, ja, de).
- Nothing live: Record.IsReported keeps reported rows out of:
- a key's budget/spend limit (budget.counts);
- window holds, and the log start that decides whether a window can be
reckoned (logSnapshot.firstOwn);
- gateway sessions and Vias;
- Codex's sealed answers and remembered model.
There is no OTel span, rate limit, rest or alert for them.
- Docs: gateway-sessions.md, reference.md (with a curl), integrating.md,
site integrate.html (en, zh).
Why: the reporter's apps call vendors directly, and their usage (and
history) should show on the Usage page without becoming live traffic.
Run, in a worktree with sandbox HOME and a private GOCACHE
- gofmt -l: clean.
- go vet ./...: darwin, GOOS=linux -tags nogui, and GOOS=windows.
- go test internal/usage, usageapi, budget, gateway, gui: ok.
- -race -count=3 of the new usage/gateway tests: ok.
- GUI with playwright 1.62.0:
- usage-ledger-reported.test.cjs, 26/26 in chromium and webkit (5
languages, 1180 and 420 wide, light and dark);
- usage-ledger*.test.cjs, ledger-*.test.cjs, usage-sum-whole,
usage-unpriced-sum and i18n-keys: all pass.
- Timings with 200k reported rows (47 MB log, darwin):
- 40 posts of 5000 took 0.40 s (worst batch 18 ms);
- the first post after a restart took 0.45 s (rid rescan), a later one
1.6 ms;
- the cold index build took 2.1 s (as for gateway rows);
- page all took 27 ms warm, page 30d 39 ms, all via=reported 0.53 s;
- summary all took 215 ms, 30d 20 ms.
Broken by hand, each went red, then restored
- Go: dedupe against stored rids; the restart scan; CostAt ignoring own
cost; the block pricer overwriting own cost; the Reported split;
fromBrowser's key rule; skipping bad records instead of refusing; the
max-records and body limits; the ingest lock (race); both locks;
firstOwn -> first; the IsReported guards in windowHolds,
buildGatewaySessions, buildVias, budget.counts and loggedAnswers.
- GUI: the fourth cell, the --vias column count and the badge class.
Not shown red on its own: the remote-no-key and evil.example refusals come
from lanGuard and corsGuard before the handler, so breaking only the
handler's own check stays green. The codex_memory guard is not tested
alone: a reported row has no Requested there anyway. Not tried: a real
client against a live gateway, Windows/Linux runs of the tests, the full
GUI suite.
|
||
|
|
47269f448f |
usage, gateway, gui: the Requests card counts requests once, a try handed on to the next isn't a failure, and says how many were answered on a retry (小一 on Discord)
小一's Codex-on-credits ledger read "5,482 · 1,094 failed" while many rows said "2 tries/3 tries" and had been answered. "Failed" counted usage rows, not requests: besides each request's final row, the gateway writes a row for every try a vendor refused or turned away (hw.refused/hw.turnedAway), and each of those was counted as a call and a failure even when a later member answered. (Ordinary failovers write no row; 499 cancels and the agent's own client-side retries are separate requests.) In the owner's own usage.jsonl, 24 of the 71 "failed" rows were such refusals a later member answered. Now a request counts once, by how it ended: - usage.Record gains `tries` (final row, when the route took more than one) and `handed_on` (the row of a try that failed and handed the request on). Totals.count skips handed-on rows; a failure is a request whose agent got an error (LostRequest); one answered after a failed try is Totals.Retried (RetriedRequest), with a `retried=1` filter. - Logs written before this are read the same way: the log index marks a failed, non-rejected row followed by another of the same route id as handed on and raises the later row's tries (routeRows); the packed row and its snapshot carry both. - Panel card, Usage overview tile, ledger card, rankings and group rows, `magpie usage` and the TUI say "N answered on a retry"; the CSV adds `tries` and `handed_on` at the end. A row says "· handed on" (with why in its title) or "· N tries". - On the ledger's Requests card "N failed" and "N answered on a retry" are buttons that switch the list to the Failed / new Retried filter, and back when pressed again. The lines wrap rather than cut a button off (German). zh, zh-TW, ja, de strings added. - Docs: reference.md (counting, filter, CSV columns), gateway-routing.md. Run: - go test -tags nogui ./internal/usage ./internal/usageapi ./internal/tui ./internal/gateway . : ok. New TestRequestsCountedOnceWithTheirRetries (JSONL fixture: legacy refused row + 200, handed_on + 200 tries 3, 502 tries 2, plain 200, routeless 429 → 5 calls, 2 failed, 2 retried, across Ledger, QueryPage, Summarize, heatmap, filters, CSV) and TestRetriedRequestCountsOnce (group a refuses, b 500s, c answers → 1 call, 0 errors, 1 retried; a lone 400 → 1 error). - Broke each by hand (count without the HandedOn skip, gateway without HandedOn, log index without routeRows): each test went red; restored. - go test -tags nogui -timeout 40m ./... under the gotest lock, rebased on origin/main |
||
|
|
99fcddeeba |
usage: the Requests tab, its filters and refresh, the charts, the TUI and magpie usage answer at once over a long history (Vantiboo1ean)
Vantiboo1ean (Discord, macOS M2, v0.1.1157) has ~750,000 requests in usage.jsonl. On Usage > Requests every filter, model pick and refresh spun forever and the page never updated. Reproduced in a sandbox HOME with 750k generated records in the real format (400 MB usage.jsonl, ~84k sessions), on magpie web and in process. The cause: the #563 budget dropped the index's blocks once they passed 24 MB (60 MB here), so every read, of any period, parsed the whole file again (6 s CPU) and priced every call again; All took 12 s of CPU, the heatmap 13 s, and the page read both at once. What changed: - log_index: the gateway's blocks are always kept (about 80 bytes a call, S2-compressed instead of flate); the file is parsed once, then only what was appended. - block_price: the gateway's blocks are priced per query, once per set of provider/model/served/effort names rather than per call, into pooled buffers; range loops go by pointer (a packed row is 264 bytes). - request_page: pages are always cached (16 at most), session-file chunks stay in the budget, and a page asked again while it is worked out (the refresh button, the timer) waits for that one instead of starting a second scan. - Siblings that read the same history: - The heatmap names each day once. - A day filter no longer allocates per call. - The ledger behind the TUI, magpie usage, the CSV export and sync (LedgerOf, OwnDays) reads the gateway's calls from the index instead of Load parsing the whole file. - Direct/Summaries matches the session files' calls against the index's blocks without pricing all 750k gateway calls. - A summary of more than 1024 sessions is now cached with its top 1024 (it was not cached at all). The Usage page's /api/usage gets the top 100 (it was sent all 84k, 19 MB, which it never draws) plus a new sessionCount. /v1/magpie/usage still lists every session, and magpie usage says "top 10 of <sessionCount>". Timings, CPU (the box was at load 130-190 on 14 cores, so wall is inflated; min of repeated runs), before -> after: Requests today 6.0 s -> 20 ms Requests 7d 5.8 s -> 93 ms Requests 30d ~6 s -> 362 ms Requests all 12.4 s -> 2.4 s first, ~8 ms again all, model filter 12.3 s -> 1.5 s all, agent filter 11.3 s -> 1.8 s 30d, search "opus" 6.7 s -> 353 ms day filter 6.0 s -> ~0.1 s heatmap 13.7 s -> ~2.3 s first summary today / all 6.0 / 9.2 s -> 25 ms / 1.6 s first, <1 ms again /api/usage?period=all 1.6 s + 19 MB JSON each time -> <1 ms, 53 KB TUI Summaries(all) ~8.5 s (Load + ledger) -> 1.1 s first, <1 ms again TUI Summaries(today) ~6 s -> 29 ms Visit 7d (budget, codex) 5.9 s -> 10 ms The first read of the file after start costs ~5 s of CPU, once. Tests (each seen red with its guarantee broken by hand): - TestUsageOverBudgetHistoryIsReadOnce - TestUsageSessionChunksStayInBudget - TestUsageOverBudgetPageIsCached - TestUsagePageAskedTwiceIsWorkedOutOnce - TestUsageLedgerReadsTheIndexNotTheFile - TestUsageLargeSummaryIsCompleteAndKeptTrimmed (was ...ButNotCached) - TestDirectCountsOnlySessionFileCalls, now with a request-id match, checks that Direct/Summaries equal the ledger's. Run: go test -tags nogui ./... (temp HOME), gofmt -l, GOOS=linux and GOOS=windows go vet on the touched packages. |
||
|
|
439cfc4ac4 |
usage: the parse is the log fingerprint, dropping the build's full re-read before it (#1357)
What changed. A usage-log snapshot's fingerprint is now produced by the parse itself: each complete line read is fed into a SHA-256. When a build continues the old snapshot's blocks, it continues the old snapshot's digest too (crypto/sha256's state, kept on the snapshot as `digest`); otherwise the digest starts fresh from byte 0 with the parse. The build's before-read logRecordHash over the whole file is gone. The fingerprint covers the bytes actually parsed (`off`), not info.Size(), so a half line another writer is in the middle of appending is no longer counted as read; the unchanged check, the prefix check and the after-read check all hash `off` bytes. What stays, as #1328's tests require (ggbdpq's analysis on #1357): the unsettled unchanged check, the prefix re-verification on a non-trusted continuation, and the after-read check, which now compares the parse's own digest against the file as it is after the read. A same-tick rewrite is still caught at the build, not at a later read. On the trusted, settled path nothing is re-read, as before; that snapshot now also carries a fingerprint (the continued digest), so a later non-trusted append can verify its prefix instead of rebuilding from byte 0. Test changed: TestUsageRewriteBeforeFingerprintIsNotCached counted logRecordHash calls and rewrote the file at call 1 (after the before-read hash, before the parse) or call 2 (after the read). With the parse being the fingerprint there is no call 1 any more, so the hash=2 case could no longer fire. Its guarantee still holds and is still tested at both boundaries: "before-read" rewrites at the build's first change-time look, after its stat and before it opens and parses; "after-read" rewrites at the after-read fingerprint check. Removing the after-read check makes after-read fail. No other test changed. New tests: - TestUsageAppendReadHashesNoPreReadScan: 20,000-row settled log (2,760,615 bytes), 5 x Append + Summarize(Today), counts the bytes logRecordHash re-reads. origin/main: 7,728,984 bytes per cycle (2.80x the log), FAIL; this commit: 4,968,615 (1.80x), PASS. Wall time per cycle on an M-series Mac, 3 runs each: 3.43-3.52 ms before, 2.28-2.52 ms after (~32% less). The remaining two passes are the prefix check and the after-read check, which the same-tick guarantee needs. - TestUsagePartialLineThenCompletion (settled and unsettled): another writer's half line, a read, then the line completed; the fingerprint covers the parsed bytes only and the completed record is counted. On origin/main it fails on the fingerprint check (it covered the half line). Break checks: no after-read check -> RewriteBeforeFingerprint/after-read fails; no prefix verification on a continuation -> SameSizeAndMtimeRewrite append=true, SameTickRewrite append=true and LogGrowingRewriteThenAppend fail; lines not fed into the digest -> SameTickRewrite fails. Run: go test -tags nogui ./internal/usage/... ./internal/gateway/... (ok, temp HOME, pinned caches, removed after); go test -race ./internal/usage/... (ok); -race -count=10 on the rewrite/append tests (ok); gofmt -l (empty); go vet, GOOS=linux and GOOS=windows go vet -tags nogui ./internal/usage/ (ok). Not tried on Windows or Linux hardware; the change is platform-independent hashing over the same read. |
||
|
|
3c629133c2 |
usage: refresh caches after same-tick log rewrites (#1328)
* usage: same-tick rewrites refresh cached totals and request pages Trust change stamps only when they were settled at the snapshot read's start. Fingerprint recent snapshots and append prefixes, and discard fingerprint trust when the content changes during a read. Fixes https://github.com/yetone/magpie/issues/1305 Verified: deterministic old-predicate FAIL/new PASS; usage tests with race; nogui vet; Linux nogui and Windows builds; usage test cross-compilation for Windows, Darwin and the unsupported-stamp fallback on FreeBSD. Full nogui suite exposed the independent sessions TestList empty-session limit failure. Native Linux GUI vet/build lack pkg-config and GTK/WebKit; native Windows/NTFS execution was not run. * usage: keep FILETIME stamp ages valid beyond UnixNano range Convert whole seconds and the 100ns fraction separately. Checked the epoch, current dates with fractional ticks and year 2500; Windows build and usage test cross-compilation pass. Native Windows execution was not run. * usage: keep history cached after an append settles An unchanged log now validates a recent snapshot's nonempty fingerprint before publishing a settled clone. Preserve its version and sealed blocks so the summary and page caches stay warm without mutating readers' snapshots. Follow-up to the review on https://github.com/yetone/magpie/pull/1328, for https://github.com/yetone/magpie/issues/1305. On e28e686, the real-clock append/read/settle/read tests fail with a version bump and 32,428 additional allocations over 4,000 versus 10 rows. With this change the targeted race run passes, with 165 extra allocations. The existing performance test now measures this path on the real clock. Verification uses Go 1.26.8, a temporary HOME and pinned Go caches. Native Linux GUI checks require missing pkg-config/GTK/WebKit libraries; native Windows/NTFS execution is not available. No GUI assets change. Implementation and verification used AI assistance. Final checks: usage race PASS (421 test results); nogui suite PASS (7,273 test results, 44 packages; 21 skipped tests, 3 packages without tests). Nogui vet, Linux nogui build, Windows build, and usage test cross-compilation for Windows amd64, Darwin arm64 and FreeBSD amd64 PASS. Native Linux GUI vet/build were attempted and failed at the missing pkg-config executable. |
||
|
|
3d8c6f24c5 |
usage: capture Windows change time for cached logs (#594)
* usage: capture Windows change time for cached logs * ci: show native Windows usage test outcomes |
||
|
|
7464ee5075 | usage: bound retained chunks and invalidate same-stat rewrites (#563) | ||
|
|
9657d3e9d8 | usage: reuse incremental log blocks and index CSV matches (#550) |