ac4af582301a4e8a29245dbba767eba31334ddf9
19
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
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 |
||
|
|
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 ( |
||
|
|
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
|
||
|
|
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 ( |
||
|
|
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
|
||
|
|
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 |
||
|
|
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 |
||
|
|
d03779cc10 |
usage: the Requests page's seen message ids are hashes, not copies
visibleLocal leaves out a Claude message written again in another file
(a resumed or forked session's copy). It kept every id it had seen as a
strings.Clone of the decoded chunk's string, so a long history's ~400k
ids were copied on each page build: ~7MB held at the start's peak and
27MB more allocated per run. It now keeps two maphash values of each id
(seeds made per process); two ids alike in both are ~1e-28 likely.
Measured with the real ~/.codex and ~/.claude histories (sandbox HOME,
fp3 harness), base
|
||
|
|
9916a94608 |
gateway, usage, plugins: OTel export is the first plugin on the gateway's observer point (P3)
P3 of docs/subsystems/plugin-runtime.md opens the gateway to plugins. The
observer point is first: it only reads, so it carries the least risk.
With plugins/otel off, the gateway exports nothing and does no observing
work. It keeps no reply whole and adds no request context.
- usage.Observer:
- Methods: Serve, Bodies, Begin(Request) Watch and Ledger(Record). Watch
has Attempt and End.
- Observe(o) registers an observer until its remove is called.
- ServeObservers is counted, and only Server.ListenAndServe calls it.
- ObservedBodies takes the most any observer wants.
- Record.SkipOTel becomes Watched, set by appendUsage for a request an
observer watched.
- The gateway's otel.go becomes observe.go:
- observeRequest asks each observer through Begin.
- attempt and end call each Watch. Bodies are added only when an
observer asks for them, and the whole reply only for WholeBodies.
- internal/otlp: the exporter (otel*.go) moves out of internal/usage, and
the gateway's per-request span state moves into request.go. otlp.New()
is an Exporter, a usage.Observer. What it sends is unchanged.
- plugins/otel:
- Apply registers otlp.New() and disposes of it when turned off.
- InUse is 1 while settings.OTelExport says to send. A user who exports
only through MAGPIE_OTEL_* keeps the plugin on under Essentials.
- pluginrt.KeepFresh: the process serving the gateway refreshes every 2s
when plugins.yml or settings.json changes. A switch made in the window or
the CLI reaches a running gateway, or a headless serve, without a restart.
- docs: plugin-runtime.md gets a P3 section, a gateway runtime path and an
updated failure section; reference.md says the export is the otel plugin.
Run at this tree on origin/main
|
||
|
|
e95852e301 |
usage, gui: 用量页补上各 agent 会话文件里的用量,请求页按「经过 / 不经过 magpie」拆开 (#948)
* sessions: dsh、ZCode、WorkBuddy 的会话文件里有各自花掉的 token,用量台账从来不读
Sessions 页面一直都在读这些 agent 自己的会话文件,用量台账没有:用量页只显示网关本
身应答过的调用——也就是装上 magpie 之前的什么都没有,而一个直接指向厂商的 dsh 更
是什么都没有。本机上装 magpie 之前就已经在用这些 agent(用它们自带的模型),那段
用量一直对不上账。
* 新增三类"整文件读取"的调用来源,走 wholeCallReaders(它们的调用不是一行一条,
或者文件不能从中间接着读):dsh 的会话是 zstd 分帧追加的;ZCode 用的是 OpenCode
那几张表;WorkBuddy 的同一句回复会在多行里重复同一个 messageId。三者的 token
语义各自换算成 Call 的 Input/Output/CacheRead/CacheWrite,调用缓存跟着记一份(v9)。
* 每个来源都跳过经由 magpie 网关发出的调用:网关自己记过那一本账,还带着真正应答
的供应商和账号;dsh 发往网关的请求不带会话头,两边事后对不上(token 数每次不同、
又没有可配对的 id),硬读就是同一通调用记两次。dsh 认它被配置去的那个 provider
(dshGatewayProvider:magpie / dial),ZCode 和 OpenCode 认路由里写的 provider
(ocGatewayProvider)。WorkBuddy 那部分见下一个提交。
* WorkBuddy 的调用里,同一句回复的多行只记最后一次(它带这个回复的总量);而它从
旧历史搬过来的回复一条 messageId 都没有,每一条都是独立的一通调用——会话汇总的
读法(workbuddyLine)就是这么数的,这里照它来,否则台账会比 Sessions 页面少算,
正是本次要消灭的那类"两页对不上",只是方向相反。
* dsh 的一通调用保留它文件里记的两样东西:被配置去的供应商(Upstream,作为历史,
从来不当成路由的证据),以及厂商真正应答的模型——回复的 replayState 里那个和
请求模型不一致时,Model 记应答的、Requested 记被请求的,和 Claude Code 的文件
一样的读法,好让请求表的若干列有东西可填。
* 会话的 fork:dsh 的会话从另一个会话续起来时会带上对方已写入的事件(isSeeded /
seedLength,session/end-seed 标记之后的不算),parser 跳过的这里同样跳过,否则
同一通调用会在每个 fork 上再花一次。
* WorkBuddy 的 subagents/ 子目录是父会话自己的调用来源(它带自己的消息 id,会话
归到父会话名下);调用这条路不读 file.main,那个标记是 Sessions 页面给"会话自己的
文件、不是子代理的"用的。
夹具:dsh 的三个会话(普通、带供应商与应答模型、以及一通经网关的),ZCode 的两条
(其中 ses_zcA 那条的 providerID 是 magpie,应被跳过),WorkBuddy 的既有会话(m1 的
usage 同时落在 assistant message 和它最后一个 function_call 上,只能记一次;旧历史
三条无 messageId 的回复各记一次)和一通经网关、一通走用户自建端点的会话。
调用缓存升到 v9:v8 里既没有 dsh 的供应商和应答模型,也没有"跳过网关调用"这件事,
旧缓存会继续把旧账 Serve 出来。
TestDshCalls、TestZCodeCalls、TestWorkBuddyCalls 是新的;把跳过网关调用那几行、以及
WorkBuddy 旧历史那条判据去掉,它们必挂、加上必过(都实际跑过反向验证)。
验证:go vet;go test ./internal/sessions(只余 TestCursor,Windows 路径前缀问题,
改动前同样失败);go build(windows)。
* usage: 请求页把"magpie 转的"和"它只读到的"分成两个数,GUI 跟着拆成两栏
用量页一直只显示网关自己应答过的调用,而现在它还要读 agent 自己会话文件里的调用:
两本账混在一行里,读者分不清哪一段是 magpie 转的、哪一段只是它从文件里读到的,
而总数事实上几乎全部来自后者(本机 30 天 847M token 里,网关只转了 2.4%)。Summary
里的两个来源卡片也加不出这个数来:它们只算 input 和 output,上面的 KPI 把缓存的
token 也算在内,于是"全部请求"读作 13.6M,而"Tokens"是 847M。
* usage.RequestPage 和 usage.Filter 各多一样东西:前者在 Sum 之外带上 Through 和
Direct(网关应答的,和从会话文件读到的),后者多一个 Through 维度。两种建页路径
(流式的 queryPage 和治疗桌用的 pageFromLedger)都做同一个拆分,两边一致——
TestCompactPageMatchesLedger 现在也覆盖两个来源筛选。
* 每一行本来就是按 Source 区分这两类的("log" 是会话文件里的调用,其余走的网关),
拆分就落在它上面;网关自己拒掉的调用两边都不算(页面在总数下面也这么说),所以
SourceOf 对它返回 "",点哪一栏都同样把它排除,两栏自己的计数本来也不含它。
* 两栏自己的数字是在"来源"这个挑选被清空的情况下数的,和各维度分组一样:三栏是读者
来回切换的地方,各自得一直报着自己的数,否则点了其中一栏另一栏读作 0,且没有回
到全部的路。
* /api/usage/requests 支持 via=through|direct;GUI 那一侧的三个格子、计数单位、
方块样式在下一个提交里。
* Filter.Via 这个名字和 Record.Via(转发调用的那台电脑,#542)重了,改叫 Filter.Through。
Sessions 页列表长度那件事(sessionListLimit)拆到单独的 PR 里,不在这里。
验证:go vet;go test ./internal/usage(只余 TestOTelRetryAfterBound,计时的 ±30ms,
origin/main 同样失败);go build(windows)。
* gui: 请求页把来源拆成三栏,汇总那一排也改成方块
用途页的请求栏一直只有一本账(Sum),而现在它既显示网关应答的调用,也显示从各 agent
自己会话文件里读到的调用。三个格子画在上方汇总那一排方块里,样式一致:三张各自带
边框、彼此留缝的卡片,窄屏(≤620px)下竖排。
* 每栏是一个 button:点一下就只列这一来源的请求,再点一下、或点"全部请求"回到
全部;被选中的那一栏底下有一道本主题色的线。aria-pressed 标出当前选中的是哪一栏。
* 计数后面跟单位("147 请求"),免得一个光秃秃的数字被读成下面的 token;token 是
四项合计,和上面 KPI 的算法一致。
* 三个格子在重绘之间是同一批元素、原地改(class / aria / 文本 / onclick),不是每次
replaceChildren 重建——同一份 app.js 里 5810 行的规定就是这么写的("The switch is
the same element across redraws, changed in place, so one being pressed or focused is
never swapped out"),正在点的那个不该被换掉。
* 汇总那一排本身(五张 KPI 卡)改成同样的方块:各自一张卡、有缝,边框写成
var(--line) 而不是 --card-edge(那是面板用的变量,这些卡在独立窗口里也有)。
≤860px 两列排布时卡片之间的那几条线照旧:奇数位去掉左边框、第三张起加上边框,
是 e0eaf5b4 带 #799 的老规则,这里只是跟着搬了位置,没有删。三张来源格是 button,
不参与这套分隔线。
* 供应商·账号 一栏:来自会话文件的行显示它文件里记的那个供应商 id(Codex 一向
如此),有账号时仍是账号优先,什么都没有才说"本地会话"。"本地会话"角标的条件
跟着放宽到账号或供应商任一存在,提示分两种说法:文件记了供应商的,说明这是它
被配置去调用的那个记录、不是 magpie 看到的路由(不等于官方供应商);只认得出
账号的,沿用原来那句"仅当本地元数据能明确识别时显示账号"。
* 窗口参数支持 via,用后从地址栏清掉,和 tab/provider/agent 等一致。
* 新增的串子在 en/zh/ja/de 四种语言里都有("{n} tokens" 上游已有,不重复加,
i18n-keys 绿)。
验证:node --check(app.js、i18n.js);go vet;go build(windows)。
界面效果在本机用改动后的源码构建的二进制上过目:三栏的切换与计数、方块样式、
窄屏竖排、请求表新增的会话文件行(含供应商 id)。
浏览器套件(chromium 与 webkit、en/zh):session-identity、usage-ledger、
ledger-protocol、number-units、usage-ledger-chart、usage-ttft-rounding、
usage-chart-axis、usage-fold、web-page、usage-accounts、i18n-keys 全绿;
ledger-hscroll、usage-speed、click-scroll 全绿;gui-ja、gui-de 各一条失败、
usage-ledger-detail 六条失败,均在本机 origin/main 上同样失败,与本次改动无关。
usage-ledger-chart 新钉了 ≤620px 下 KPI 卡与来源格的分隔线(把 app.css 换回上游版本
它必挂,实测过)。
---------
Co-authored-by: wizzy-yang <wizzy-yang@users.noreply.github.com>
|
||
|
|
e961836fb0 |
usage, gateway, gui, provider, cli: the tests pass when a run crosses midnight, and a usage answer reads the clock once (#1046)
* usage: the usage tests pass at any time of day, midnight included The usage tests stamped their calls with the machine's time and then asked for today, 7 or 30 days, or a cached answer, which the code worked out from its own time.Now a moment later. A minute after midnight a call made "a minute ago" was yesterday's, and when midnight fell between the test's read and the code's, the call and the period were of two days. magpie usage, the TUI's Usage page, the two Codex cache-write tests and the computers' shared days failed in the first minutes after midnight (the TUI's after midnight UTC, the zone its package's tests run in since |
||
|
|
e277f5c5ef |
usage: four tests pass when run alone and in any order — one saves no account copy mid-test, three price with the catalogue they write (#1045)
* usage: TestQueryPageSourceAndIdentityInvalidation passes when run alone
Run alone, the test failed at any time of day:
request_page_test.go:224: unchanged source rebuilt
In a package run it passed only because an earlier test had looked at
the accounts less than 30 seconds before it. QueryPage calls
provider.All, whose rememberLogins saves a copy of the account Codex is
signed in to into logins.json, at most once every 30s (loginsSeenAt, a
package variable in provider). Alone, the test's first QueryPage made
that save. SessionIdentities then listed "one" twice (auth.json and the
saved copy), the request cache's key changed and every chunk was
rebuilt, so the pointer check failed. The test also expects only
auth.json's identity later on: with a saved "one" sharing a/u with
"two", the "two" step resolves to "" (two members of one workspace).
With the first check let through, it failed at request_page_test.go:237
"identity {... SessionAccount: ...}". The same failure hits a package
run whenever more than 30s pass between the last earlier look and this
test.
The test now calls provider.ForgetAccounts and provider.Accounts before
it signs Codex in, as an earlier test in a package run does, so no copy
is saved while it runs and the result no longer depends on test order.
This holds while the test runs within rememberLogins' 30s of that look;
it takes well under a second, -race and at.sh included. No other usage
test fails run alone: each test in the package was run alone, each
under a fresh HOME, and only this one failed.
Verified (go test -tags nogui under a temp HOME, Go caches pinned):
- before: -count=1 -run '^TestQueryPageSourceAndIdentityInvalidation$'
./internal/usage: --- FAIL ... request_page_test.go:224: unchanged
source rebuilt; -race -count=20: 1 of 20 failed (the first; the
later ones ran inside the 30s window); the same at local 12:00:00.
With its neighbours (-run '^(TestQueryPage|TestRequestPage)') it
passed, and failed again at :224 with a scratch 31s sleep at the
test's start.
- after: alone -count=1 ok, -count=20 ok, -race -count=20 ok; at local
12:00:00 and 00:00:30 PASS; with neighbours plus the scratch 31s
sleep ok; go test ./internal/usage ok; go vet ok; gofmt clean.
Without the change the run-alone command fails with the FAIL line above.
* usage: tests that write their own catalogue price with it, in any order
TestDirectCountsOnlySessionFileCalls and TestLedgerWithSessionLogCalls
write a catalogue to catalog.CachePath() and expect calls priced from
it, but never called catalog.Reset. The catalog package reads the cache
once and keeps what it read until Reset, so each test priced with
whatever catalogue an earlier test had left loaded. In file order they
passed only because no earlier test had. In another order the calls
came out unpriced. Run as
go test -run '^(TestDirectCountsOnlySessionFileCalls|TestLedgerUsesTheStatedPrice|TestLedgerWithSessionLogCalls)$' ./internal/usage
TestDirectCountsOnlySessionFileCalls ran first and left its gpt-6
catalogue loaded, and TestLedgerWithSessionLogCalls failed:
ledger_test.go:228: logged call {... Provider:session-unknown ...
Cost:0 Priced:false ... Source:log}
With -shuffle=1, TestLedgerWithSessionLogCalls ran first and left its
claude-sonnet-5 catalogue loaded, and the other one failed:
direct_test.go:55: not priced: {Calls:2 ... Cost:0 Unpriced:2 ...}
Each passes alone, so running every test alone doesn't find this. It
was found in review with go test -shuffle=on ./internal/usage, which
failed 5 runs of 6.
Both tests now call catalog.Reset after writing the cache, and again
on cleanup, as TestLedger and TestSummaryByAccount do. So does
TestLedgerUsesTheStatedPrice, the only other test that writes the
cache with no Reset there. It passes in any order, since its stated
prices win, but it checks that no tier is counted at the catalogue's
price, which needs its own catalogue. Every other test in the
repository that writes catalog.CachePath() already resets the
catalogue there.
Verified (go test -tags nogui under a temp HOME, Go caches pinned):
- before, on main: the run above fails as shown. All six orders of the
three tests (-shuffle=1, 2, 5, 7, 13 and 16) fail: at
ledger_test.go:228 when TestDirectCountsOnlySessionFileCalls runs
before TestLedgerWithSessionLogCalls, at direct_test.go:55 when it
runs after. go test -shuffle=N ./internal/usage fails for the
review's seeds 1791276105858112000, 1791276117280881000,
1791276129005822000, 1791276140549291000 and 1791276151835143000,
and for 101, 202, 505, 808 and 1010 of the seeds 101, 202, ... 1010;
each failure is in one or both of these two tests.
- after: the run above ok; all six orders ok; -race -count=20 on the
three tests ok; at local 12:00:00 PASS; go test ./internal/usage ok,
and ok with each of those 15 seeds; each test in the package
passes run alone; go vet ./internal/usage ok; gofmt clean.
Without the change the run above fails with the ledger_test.go:228
line, and with -shuffle=1 it fails with the direct_test.go:55 line.
|
||
|
|
f506d08d28 | usage, gui: the Requests tab ranks one model at each provider it went to (inaction on Discord) — the trend's ranking already gave each model its speed, first token and requests, but "Model" put a model's requests at every provider together, so glm-5.3 at Zhipu and at ZCode couldn't be told apart. The split has "Model · provider" now: a "modelAt" dimension (provider/model) whose rows are named by both with the provider's icon, each with its own tokens/s, first token and requests, ranked by any metric (Speed: the fastest first). A click lists that provider's requests of that model, again all of them; the others stay ranked. The trend's bar wraps at the narrowest window, "Split by" with its choices. The key of each provider and model is built once per page (TestRequestPageAppendDoesNotRepriceHistory's allocations). TestRequestPageRanksModelAtEachProvider, TestLedgerNamesModelAtProvider and usage-model-at-provider (WebKit, en and zh) fail without the change. go vet, go build (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass (TestProvidersAnswerWhileListsComeIn and TestUserPath failed under load and pass alone). | ||
|
|
48d524d65a | feat: select a day in usage charts (#683) | ||
|
|
c0f3fa012a |
usage: combine gateway and local session requests with model charts and account labels (#239)
* usage: Requests lists the agents' own session-file calls, put to the vendor and account their files prove, charts them by provider, agent or model, shows what was said, and the tray panel gets a Usage tab The Usage page's Requests tab now covers requests an agent sends with its own sign-in (Claude Desktop's Code tab and Cowork, Claude Code, Codex), which never pass the gateway, and shows more of every request: why it failed, what was said in it, who it was of. Requests tab: a strip of four totals (tokens, requests, cost, cache hit rate); the trend of one metric — tokens, cost or requests — as columns by the hour, day or week, told apart by provider, agent or model (both remembered), beside a ranking of the same that is its legend and a way in (a click lists only that provider's or agent's requests; a provider picker sits beside the agent's). The ranking is as tall as the chart and scrolls in itself, with no scrollbar: a slim rail in the card's margin shows how much there is and where it is (its thumb dragged, the rail clicked), and the edge with more beyond it fades; under the chart (860px and narrower) it shows whole. A row opens to its details: the vendor's error type and words, request id, endpoint, and what was said in it (input and output, read from the agent's session file when opened, the call that ended nearest the request — nothing stored). A refresh period (off / 5 s / 10 s / 30 s / 1 min) and refresh-now. The Overview says it counts gateway calls only; Requests and the panel say they count both. The tray panel gets a Usage tab (today / 7 / 30 days, provider picker, four totals, a small chart, top five, "Open Usage"), and is as tall as its tallest tab (#124). Provider and account of a session-file call: never magpie's "claude" or "codex" subscription. Anthropic's when Claude Desktop's session metadata (not Claude-3p) names the account and organization, with that account's email; OpenAI's when Codex's rollout names a provider that is OpenAI's in config.toml — the built-in "openai", or a named one at OpenAI's address or signed in with the ChatGPT account and no base_url (requires_openai_auth) — with the creator account's email when the file records it. Anything else is "Local session", its recorded provider id and session account kept (CSV: session_provider, session_account). The config read is today's: a file names the provider id only. Gateway: a failed call keeps the vendor's error text and type, request id and endpoint; a Claude subscription's failure uses the status Claude Code reports (api_error_status). A request turned away before any vendor was asked is logged, marked rejected, listed in Requests and left out of every total. The client's own session header is kept as native_session beside X-Magpie-Session, and a session-file call is matched to a gateway record by request id, then by that session, equal tokens and an end within 2 s, only when unique both ways. Reading: session-file calls live in the session index main keeps on disk, parsed incrementally and outside its lock (Claude Code, Cowork in both Claude folders, Codex); the usage log is read on from where it was; a page builds the ledger once. Days are counted on calendar dates (DST). CSV gains request_id, endpoint, error_message, error_type, source, session_provider, session_account. i18n: one "Endpoint" (终结点), which a second key had turned for Azure's field. Tested: go vet ./..., go build (also GOOS=linux/windows, -tags nogui) and go test -tags nogui ./... pass. The whole GUI suite in Chromium and WebKit, en and zh (Playwright 1.62.1): all 393 tests pass. On this computer's files (7 days): 3,330 Claude Desktop calls resolve to Anthropic with the account, 1,991 Codex calls on a named ChatGPT-signed-in provider to OpenAI (620 with the account; older rollouts don't record it), 9 Claude Code CLI calls stay Local session. Co-authored-by: yetone <yetoneful@gmail.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * usage: a session-file call of one of magpie's own Codex or Claude accounts is told as that provider, beside the gateway's calls on it — "OpenAI" and "Codex" (or "Anthropic" and "Claude Code") read as two vendors when they were one subscription Codex: an official route (above) whose creator account and user are one of magpie's Codex sign-ins (the CLI's own or a saved one) is magpie's "codex", with that account's email as the gateway's rows have it. Claude Desktop (not Claude-3p): an account and organization that are one of magpie's Claude sign-ins is magpie's "claude". Only while magpie has that provider signed in; another account, a rollout with no account recorded, or an ambiguous workspace stays OpenAI or Anthropic, and a relay stays Local session. Tested: TestSessionCallsOfMagpiesAccountsAreItsProviders (the account matched, another account, none recorded, magpie's account through a relay, Desktop in magpie's and another organization, Claude-3p, magpie signed out) and TestLedgerTellsCodexSessionCallsAsMagpiesCodex (a gateway Codex call and a session call of its account one provider of two calls, another account's OpenAI). On this computer (7 days): 3,439 Claude Desktop calls are magpie's Claude, 626 Codex calls its Codex, 1,322 older Codex rollouts with no account stay OpenAI. go test -tags nogui ./... and the usage GUI tests pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: 修复请求统计缓存膨胀与会话账号误归属 #239 调用明细改为按会话文件分片保存并限制内存缓存,汇总索引仅保留统计数据;网关日志按需读取。 严格匹配订阅账号与用户 ID,排除自定义渠道、非官方端点覆盖、外部 CODEX_HOME 及关闭的供应商。补齐零 token 失败去重、Codex 原始会话 ID、拒绝标记导出和面板显示修复。 通过全量 Go 测试、静态检查、受影响模块的并发检查、52 项浏览器测试及 macOS/Linux/Windows 构建;使用 35 万条合成调用验证索引体积与内存改善。 * fix: 降低请求统计刷新与写入开销并明确本地账号展示 #239 请求分片改为追加帧和字符串去重,分页复用未变化的紧凑快照,采用 LRU 并移出全局锁内的磁盘读取。缓存 Cowork 目录,补齐同前缀改写检测及崩溃临时文件清理。 本地记录仅显示匹配账号或本地会话,明确官方登录标记与请求路由的区别。默认今日与模型维度,Auto Review 复用共享目录定价并单独标注估价参考。 完整 Go 测试、vet、相关 race 和 52 项浏览器回归通过;提供 2000 文件及四个大会话连续追加的可复现性能对照。 * fix: 优化用量徽标与耗时分级并保护分页边界 #239 官方登录、API、订阅和本地会话采用独立颜色与柔和底色,兼容明暗主题。耗时按 10 秒及 30 秒阈值着色,保留估算标识与原始毫秒提示;无有效耗时显示短横线。 限制分页选取范围,避免超大偏移整数溢出及越界空页的无效堆构造。补充阈值、徽标对比度和极端分页参数回归。 * fix: 将账号与来源徽标分为两行展示 #239 * fix: 提高用量表格模型文字对比度 #239 发送模型和已知实际模型使用主题正文次级色,表头与时间同步加深。保留缺失值弱化、转发提示和本地日志来源说明。Chromium 与 WebKit 的中英文、浅深色主题 10 项界面检查通过。 --------- Co-authored-by: yetone <yetoneful@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> |