a77ecbf8a1dbf2fc8a0dd7484ddaf58a9e37177d
3991
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
a77ecbf8a1 |
gui: models of one provider named alike say what tells them apart (sunset on Discord)
sunset (#feedback, 10-19): with the Our Free Model plugin the provider editor's chips read "DeepSeek-V4.1-Flash · x0.1" three times over; the ids (buddy/…, cline/…, kilo/…) told them apart only in the tooltip. modelTells(items, label, id, key) finds, among the models of one list (and one group, for a picker), those that would show the same label, and gives each the part of its id that tells it from the others: the segments left after the ones all of them share at the front and back are taken off, the whole id when that isn't enough or is empty. A label no other model has gets nothing, so every list that was fine is drawn exactly as before. The tell is quiet secondary text after the name (.mtell, muted, never the accent of a pick); where only plain text fits it is " · tell". No new control. Where: the provider editor's model chips, the detect sheet's chips, an account's model chips, the fallback list and its suggestions, every openPicker list (agents' model menus, Settings' model pickers, Routing's member and classifier pickers; worked out per group, so one name under two providers says nothing), and the Routing page's member names and labels (routing/client.js). Routing keys its groups by the model's provider, or its provider's name where a list carries only that, so one name under two providers says nothing there either. Run (tree at 818007045 on |
||
|
|
f73378365f |
gui: a filter a click set on Usage's Requests goes when they are left (TJHHHH on Discord)
TJHHHH: after a jump to Codex's requests on the Usage page, every later
visit listed only Codex's. The Requests' filters are module state in
plugins/usage/page.js and nothing ever reset them, so a click on Codex in
the ranking split by agent stuck for the app's lifetime.
Now a filter a click lent the Requests (a ranking click on an agent,
provider, model or gateway key, a chart day, the address's ?agent= and
the like, a route from Routing) is remembered in ledLent and given back
by ledLeave when the reader leaves the Requests: for another Usage tab
(renderUsageTab), or another page through a new page hook, `leave`, that
show() calls on the page it leaves. A filter picked in its own menu or
typed in the search stays, as a menu choice does in a Mac app. A route's
saved filters keep their lent marks, and leaving with a route on gives
back the route too. Docs: plugin-runtime.md's Usage hooks.
Siblings judged and left: the tray panel's Usage tab ranking (its own
view, not the page's Requests), the Sessions reveal (per agent, no "all"), the KPI
failed/retried jumps (shown in the status segment, read as own picks).
Test: tests/usage-ledger-leave.test.cjs, chromium and webkit, en zh
zh-TW ja de: ranking click leaves for a page and for a tab, menu pick
stays, ?agent= goes, a route goes. On the old app.js/page.js/client.js
it is red, 20 of 25 in chromium ("back from another page: last asked
period=today&agent=codex"); only the menu-pick case passes there.
Green with the fix, in both engines.
Run at
|
||
|
|
be6a74f13e |
provider: a routing group told its largest member's window runs to it when the user typed it (Osal on Discord)
Osal set the codex provider's windows to each model's most (gpt-6-astra=872k and the rest) and ran Codex on "6 Astra · routing group Ultra". Codex said "已用 114k 标记,共 258k": 95% of magpie's default working window, 272K. A group that names no size of its own is told its largest member's window (#712), but buildGroupEntries never carried whether the user typed that window (Entry.WindowSet), as it does for a group set to a size (#1809) or one following its smallest member (#2224). CompactFor then returned 0 and codexcat wrote context_window 272000, max_context_window 872000. Now the largest member's WindowSet comes along (a tie counts as typed), unless a rule of length lifted the window past it; WindowTyped says the same for Claude Code and Claude Desktop (largestWindow). A group whose largest member's window nobody typed keeps the default, and a size typed in Settings (Compact at) still comes first. TestLargestMemberTypedWindow (internal/agent): on the old code the gateway's list compacts group/ultra at 0, magpie-models.json tells it 272000 (max 872000), Claude Code gets CLAUDE_CODE_AUTO_COMPACT_WINDOW 272000 and Claude Desktop no per-model window; all four pass now, and a group whose 1M member is untyped keeps 272K. Run: gofmt -l (clean); go vet ./... on darwin, GOOS=linux -tags nogui, GOOS=windows (clean); go test -run 'TestLargestMemberTypedWindow| TestSmallestMemberTypedWindow|TestTypedWindowReaches' ./internal/agent; go test -timeout 45m ./... at |
||
|
|
197849ad4d |
gateway: image generation's timeout is a setting, 1 to 60 minutes
neighbads on X: a slow image endpoint needed more than the fixed 5 minutes. Settings > Images > Image generation timeout (imageTimeout in settings.json, 5 when unset, 1 to 60 accepted, anything else a 400) now gives every drawing that long, on each route it takes: - drawTimeout() reads the setting; drawWithin marks the context as a drawing and sets its deadline. Error texts say the time it was given (givenTo), ModelScope's task polling too. - A marked drawing goes through a vendor transport with no ResponseHeaderTimeout (drawsApart), since an images API sends its headers only once it has drawn; everything else keeps the 10-minute upstreamHeaderWait, so a 30-minute setting isn't cut at 10. - An image answered as a link is downloaded within the same time (imageLongest, never under ImageLongest). - Videos keep 5 minutes per call (videoTimeout): a video is made between its calls, so the setting isn't theirs. - magpie mcp image waits on a call up to callLongest (2h1m, past the 60-minute bound twice over), since it may not read the settings (WSL); ToolTimeout, which agent configs carry, is unchanged. - The plugin path: Bun 1.4.2's fetch has no 5-minute cap (tried against a server answering after 330s), so nothing changes there. - api.go keeps the saved value when a page doesn't send imageTimeout; prefsKeep carries it on every other Settings save. GUI: a segmented row under Image generation (5, 10, 15, 30, 60 min; a value set by hand gets its own segment), in en, zh, zh-TW, ja and de. Three GUI tests clicked controls the new row pushed under the window's foot or past the viewport; they now wheel to them with reader.cjs's reach (disabled-models, search-api, refusal-retries-setting). searcher-pick checks the help has no title before reach's pointer passes over it (the app's mouseover sets one on cut-short text). Run, at |
||
|
|
b10788745a |
agent: Claude Desktop on magpie keeps the language picked signed in with Anthropic (memory, Osal on Discord)
Desktop's 3p mode runs in a userData of its own, Claude-3p, whose
config.json (Desktop's settings, not claude_desktop_config.json) starts
with no "locale", so after magpie turned 3p on Desktop came up in the
system's language. magpie never wrote Claude-3p/config.json before this
commit: it writes only claude_desktop_config.json (deploymentMode, merged
key by key) and configLibrary's _meta.json and its own profile. So the
hand-set locale that reporters saw lost on restart was not written over by
magpie; Desktop 2.7032's own main process sets "locale" back to en-US when
its UI asks for one with no bundled catalog (pit in its index chunk), and
resets an unparsable config.json to {}. Which of those hit them is not
known.
Turning Desktop onto magpie now copies the one key "locale" from the
signed-in userData's config.json (Claude, %APPDATA%\Claude on Windows,
the first set's before the others for an MSIX install) into
Claude-3p/config.json, only when that file is missing or a JSON object
with no locale, and only a name Desktop takes for a catalog
(^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$, as Desktop's lit). A locale already in
Claude-3p is never written over, no other key there is written, and an
unreadable or non-object file is left alone without stopping the
takeover. Off removes the file only when magpie made it and it still
holds nothing but the carried language. The key name "locale" was read
from /Applications/Claude.app 2.7032's bundle (Fo.get("locale") on its
config.json store).
Tests: TestClaudeDesktopCarriesTheLanguage, TestClaudeDesktopKeepsThe3pLanguage,
TestClaudeDesktopUserEditsThenReapply, TestClaudeDesktopLanguageOddValues.
Broken by hand, each went red: no carry (Carries red), overwrite an
existing 3p locale (Keeps3p and UserEdits red), no removal on off
(Carries red), no name check (OddValues red). UserEdits passes on the
old code too: it guards that magpie never writes the user's file.
Run at
|
||
|
|
8febe3a50c |
provider: a pick a plugin's list leaves for a while comes back when it is listed again (多喝热水 on Discord)
多喝热水 picked models of the Our Free Model plugin
(mu-zi-lee/magpie-our-free-model) and had to pick them again after every
magpie update. A minute after magpie starts, and hourly, KeepPluginsListed
reads every plugin's models again and dropGonePicks deleted for good each
pick the list didn't have. OFM, started again with magpie, lists its free
pools at once and its account channels' models ("qoder/...", "kiro/...")
only once it has read them, so the first list was short and the channel
picks were lost. A relay's Fetch models or RefreshEvery list that left a
model out once did the same.
Now a pick the list leaves out moves to Delisted (providers.json
"delisted"): not served while it isn't listed, put back in Models when a
list has it again (relistPicks), for plugins and fetched lists alike.
After a list left picks out, the loop asks again in 5 minutes
(relistSoon), not an hour. A provider whose every pick is set aside serves
none of its models (waitsForPicks), not the whole list. Editor saves keep
Delisted (delistedWith, withPicks, the account whitelist); Select none or
the vendor's list picked clears it. While picks are set aside, new picks
saved keep the earlier PickedFrom too, so a model seen and left unpicked
isn't served as new when the list has it again; a list short of no pick is
taken as it is, as TestClaudePicksOfEveryModelTakeOnesListedSince wants.
New tests: TestPluginPicksComeBackWithTheirList (through the real
KeepPluginsListed loop), TestEveryPickDelistedServesNone,
TestRelayPicksComeBackWithTheirList (through Refetch on an httptest
/v1/models). Broken by hand, each red: relistPicks returning false (the
old behaviour: picks not restored), relistSoon as relistEvery ("wasn't
asked for again soon"), waitsForPicks removed (pool-a served with every
pick set aside), the PickedFrom union off (kiro/claude-z served).
The plugin side, for its author: OFM's managed runner answers `models`
before its channels and first model refresh are read; awaiting them (with
a timeout) or answering fallback(previous) with the magpie.fellBack marker
would keep magpie's last good list. OFM itself was not run here (its
install scripts weren't run, by instruction).
Run at base
|
||
|
|
dd70c5e6ae |
provider: ClinePass's Upstream tick pins GLM models to Z.ai too (sdytman on Discord)
sdytman (#feedback, 10-19) asked for GLM to have what DeepSeek has: with
Upstream ticked, a cline-pass/glm-* request goes only to Z.ai. ClinePin
now reads a maker table (deepseek -> deepseek, glm -> zai) and appends
providerOptions.gateway.only = ["zai"] for a GLM model, at the body's end
as before so the cached prefix is unchanged. cline-free/ models are never
pinned, other makers are unchanged, and a client's own providerOptions is
kept as sent. The tick stays one control; its label and hint now name
DeepSeek and GLM in en, zh, zh-TW, ja and de.
The slug: Cline routes through Vercel AI Gateway. Vercel's provider table
lists Z.ai as slug "zai" (name "Z.AI", website z.ai), and
ai-gateway.vercel.sh/v1/models/zai/glm-*/endpoints gives provider "zai".
sdytman called the upstream "z.ai", Z.ai's site and shown name; the
routing slug Vercel takes is "zai". Not tried with a real request: there is no
Cline account here, and both gateways answer 401 without a key.
The Cline plugin got the same change in
@magpie-community/opencode-cline-auth 0.1.9 (plugins ff13aac). There is
no cline mover, so no min to raise.
Run at
|
||
|
|
d44d81d9ad |
provider: qoder's mover min is 0.2.19, so a model list it can't read falls back (plugins #249)
qoder 0.2.19 answers a model list it can't read with a 502, which the
gateway's passing() treats as the member's failure, so a routing group
moves to its next member instead of ending the request. Raising the
mover's min updates every moved user's plugin through keepMovedCurrent.
npm view @magpie-community/opencode-qoder-auth shows 0.2.19.
Run: gofmt clean; go vet ./internal/provider/ on darwin, linux and
windows ok; go test -tags nogui ./internal/provider/ ok (1152s). The
full suite was not run: only the min string changed (as
|
||
|
|
b641868eb3 |
gateway: TestHeldClock passes each zone in instead of writing time.Local (#2949)
CI run 39242954115 (
|
||
|
|
b749cffbb1 |
gateway: a reply asked past what the window leaves is asked again for what it leaves, not failed as too long (molvqingtai, da34, Jeremy.Zhou on Discord)
DeepSeek counts the reply asked for (max_tokens) in its 1M window with the prompt: "maximum context length is 1000000 tokens. However, you requested N tokens (P in the messages, C in the completion)". Since |
||
|
|
c3b2e6109b |
provider: signing in to a plugin again takes the lapsed mark off when the providers' list is empty too (#2748)
clearPluginLapse cleared an account's "sign in again" mark only through
plugin.Cached(): it looked for the plugin's provider in the list and
cleared nothing when it wasn't there. The list is empty while
checkList reads another magpie's change to plugins.json again
(provCache = nil, before the providers file is written), so a sign-in
finished then left the account lapsed until a request or usage read
went through. TestPluginLoginTakesTheLapseOff (internal/cli) went red
that way on ubuntu CI twice (runs 39216129687 and 39234604936: "signed
in again, but still lapsed").
The mark now goes by the account's agent and key alone
(notePluginLapseOf), with the same sign-in count ordering as before;
only the stale usage reading still needs the provider, and is still
dropped when it is listed.
TestPluginSignInClearsLapseWithoutTheList saves two lapsed plugin
accounts with no plugin listed, signs one in again, and checks its mark
went and the other's stayed. On the old plugin_accounts.go it fails:
plugin_fetch_lapse_test.go:83: signed in again, but still lapsed:
"gone@fake's FakeCo sign-in has expired — sign in again"
and passes with the change.
Whether CI's two reds were this empty list and not another path is
inferred from the code, not captured; #2748 stays open until CI has
gone a while without it.
Run on origin/main
|
||
|
|
5b267fbd8e |
provider: moved Command Code accounts take plugin 0.1.14, which can ask for Zero Data Retention (plugins #246)
Raises the commandcode-plan mover's min from 0.1.13 to 0.1.14 so keepMovedCurrent updates every moved user. 0.1.14 (plugins 5f101a5) adds a "Zero Data Retention" switch (auth.options), off by default, and honours CMD_ZDR=1. While it is on, the Provider API and Go's /alpha/generate requests carry x-cmd-zdr: 1, as the CLI sends it. A model with no ZDR upstream reaches the agent as Command Code refused it: a 422 cmd_zdr_no_providers on the Provider API, a 400 typed cmd_zdr_no_providers on /alpha/generate. 0.1.14 is on npm: npm view --prefer-online @magpie-community/opencode-commandcode-auth version says 0.1.14. The publish run 39237235562 published it. That run is red only for middleware-think-tags's trusted publisher (plugins #180). Run: gofmt -l internal/provider (clean); go vet ./internal/provider/ on darwin, GOOS=linux and GOOS=windows (ok); go test -timeout 45m ./internal/provider/ (ok, 431s). The full suite was not run: only the mover's min string changed. Not tried: the switch in a running magpie's editor. |
||
|
|
9fd80b2128 |
library: skills install from any git repository, GitLab and a company's own among them (sunset on Discord)
ProbeSkills took only a GitHub source or a folder. It now also takes any
git repository's address: https/http on gitlab.com or a self-hosted
server (any depth of groups), a GitLab or Gitea page of a folder
(/-/tree/<ref>/<path>, /-/blob/..., /src/branch/...), ssh://,
git@host:group/repo.git, a bare host.name/group/repo, and file://.
Such a source is kind "git" (gitSource, skillgit.go).
It is fetched with the user's own git (proc.FindTool), so their
credential helpers and SSH keys reach an intranet host: git init, then
fetch --depth 1 --no-tags -- <url> <ref|HEAD>, checkout FETCH_HEAD into
a magpie-skill-* folder, .git removed; the same keepProbe/maxFetch path
GitHub's tarball takes.
What the user typed is data: an address starting with - and any
transport:: address (ext::, fd::, file::) are refused before git runs;
the address follows --; git runs with protocol.ext.allow=never and
core.symlinks=false, no shell, GIT_TERMINAL_PROMPT=0, and ssh -o
BatchMode=yes unless the user set their own SSH command (GIT_SSH,
GIT_SSH_COMMAND, core.sshCommand), so a sign-in it can't make fails
instead of waiting. An address with a password or token in it is
refused: library.json is shown and backed up. Git missing, a sign-in
refused, an unknown host key, a missing branch and an unreachable host
each say so plainly (gitError).
Updates: Commit keeps the repository head the skill was fetched at. A
check runs git ls-remote; another head is fetched (once per repository
and ref) and the skill's folder hashed, so a commit elsewhere in the
repository leaves it current and moves Commit on. UpdateSkill and the
edited-skill refusal work as for GitHub; EditedError and the page's
Changed here / Update / replace question name the repository instead of
GitHub. findNew, Group again, icons and the market stay GitHub's only
(documented).
Page, TUI and docs: the add box's placeholder in en/zh/zh-TW/ja/de
(zh: owner/repo、GitHub 或 GitLab 链接、任意 git 仓库地址,或本机上的文件夹),
a git skill's source shown as a link (https) or text (SSH), its own
Update and Check for updates; the TUI's prompt; library.md's Skills and
Skill updates rows. GIT_SSH/GIT_SSH_COMMAND are listed in agentenv's
notAnAgent (TestFolderVarsAreListed).
Tests (fail on the old code: gitSource/gitPath don't exist there, and
skill-git-source.test.cjs fails on the old assets' placeholder, checked
by stashing client.js/i18n.js): TestGitSourceReads,
TestInstallFromGitRepo (a local bare repo over file://: probe, install,
check finds an update, update, a commit elsewhere stays current, an
edit here is refused naming the repo), TestGitTreeURLInstallsFolder,
TestGitMissingSaysSo, TestGitSignInRefusedSaysSo (a local httptest 401,
GIT_CONFIG_NOSYSTEM so no Keychain), TestGitRefusesOptionsAndTransports,
TestGitErrorsSaid. No test reaches the network.
Run (worktree at origin/main
|
||
|
|
eb3f174289 |
agent: Claude Code's auto mode classifier model is set on its Agents row (Linka on Discord)
Claude Code 2.1.302 reads CLAUDE_CODE_AUTO_MODE_MODEL for the model its client-side auto mode classifier checks each action with. It doesn't change server-side auto mode, and a classifier model Anthropic sets for the account comes first. The installed 2.1.303 binary has the variable: unset, Claude Code picks the sonnet tier's model, else Sonnet. It refuses claude-sonnet-5-5, claude-opus-5-5 and claude-opus-5 with a warning and uses its own pick instead. - Claude Code gets an "auto mode" field (key auto_mode, Quiet, follows nothing). It can be set only while Claude Code is routed through magpie, only to one of magpie's models, and is written dashed like the other model keys. Its options leave out the three models Claude Code refuses, and Set refuses them too. - A value the user had before magpie routed Claude Code is stashed with their tiers (claudeOwnEnv). It is taken out while wired in and comes back on Disconnect or Claude Code's own model, unless they have set one again since. The restore loop now skips any claudeOwnEnv key the user wrote again. - magpie's own value goes when magpie steps out. A value the user sets while wired in is never touched. - GUI: an "Auto mode" line in the opened row's Tiers, after Subagents, using the app's model picker. Default is noted as Claude Code's own pick. Strings are translated for zh, zh-TW, ja and de. - Docs: agent-wiring.md and reference.md. Run, in a worktree at origin/main |
||
|
|
9b72add51d |
provider: Codex's zstd encoder keeps two coders, not one per core, and holds ~9 MB instead of ~80
A live gateway (v0.1.1290, 48 minutes up, ~50 Claude Code and Codex
sessions on a 14-core Mac) had a 288 MB heap, and 74 MB of it was the
shared zstd encoder that compresses ChatGPT turns: klauspost's EncodeAll
keeps a coder per GOMAXPROCS, and each keeps its 4 MiB history (2 MiB
window) and tables for the life of the process (pprof inuse_space:
fastBase.ensureHist 56 MB, encoderOptions.encoder 17.8 MB).
The encoder now keeps two coders (WithEncoderConcurrency(2)) in
low-memory mode (WithLowerEncoderMem). A 1 MiB turn encodes in about
half a millisecond, so two keep up. Neither option changes the frame:
measured on 28 concurrent 1 MiB turns on this Mac:
default retained 84.1 MB 13.2ms 28054 bytes round-trips
conc2+lowmem retained 8.9 MB 13.8ms 28054 bytes round-trips
TestCodexZstdHoldsLittle sets GOMAXPROCS 16, encodes 28 turns at once
and fails above 24 MB. With the two options removed by hand it fails
("the encoder holds 88 MB after 28 turns at once"); with them it passes
(-count=5).
Run on
|
||
|
|
ab7ec8c657 |
gui: Manage agents' names sit beside their icons, not at the row's far end
The owner's screenshot (zh, a wide window): each row's name was pushed to the right edge, next to 未隐藏, far from its icon. A row is a <label>, so .editor label, a form field's label rule (text-align: right, 12px, padding-top 5px), reached it and outranked .ag-manage-row; under 560px another rule set labels left, which is why the narrow tests never saw it. The row's rule is now .modal .editor label.ag-manage-row, left-aligned, 13px in the text colour, with its own padding back. Run: - agent-bulk-visibility.test.cjs, which now measures each name's text against its icon at 1240 and 560 wide in every language: 10/10 (Chromium, WebKit; en, zh, zh-TW, ja, de). With the old app.css 0/10, "name beside its icon at 1240: 424,410,435,427". zh screenshots at both widths looked at. - agent-visibility-saving 12/12, panel-fold 6/6 (the other files that open this sheet). The selector matches only .ag-manage-row, which app.js makes only in this sheet, so no other page can reach it. Not tried: the real app window. |
||
|
|
65f5f0153d |
gui: a sign-in's field and its button are one height, 8px apart
The key field in a sign-in (a plugin's key, Copilot GHE's address, a pasted callback, the proxy ask) was 30px tall with its button at the button's own ~24px and 4px beside it: a short button jammed against a tall field (the owner, on OpenCode 2 Free's key). The field is now 28px with no vertical padding, its button 28px with the same 7px corners, 8px apart. Measured (plugin key form, Chromium and WebKit): zh 1100 and en 900: field 28, button 28, gap 8, one row, button's right edge at the form's; de 420: both 44 (the narrow-width touch height), gap 8. Run: - Full GUI suite (2156 tests at ~load 100): red only in codex-predictions (10, the same 10 on origin/main |
||
|
|
129d8b08a5 |
gateway: a schema a tool's $ref reaches goes to Kimi with a type
chaosy on Discord: Codex on Kimi Code k3 failed every request, 400 "not
a valid moonshot flavored json schema … $defs.__schema20 … must be
defined". Moonshot's validator expands each $ref and refuses a target
with no type ("At path 'properties.b': detected infinite recursion
without termination condition"), though the same schema written inline
passes. Codex sends its MCP and Codex App tools as zod's $defs and types
a def with properties or an enum, but leaves a oneOf or allOf def as it
was, so the whole request fails.
kimiToolRefTypes, scoped by isKimi and run in forwardOnce after
kimiToolEnumTypes (chat, Anthropic and Codex's Responses routes all pass
there), writes a type after the brace of each untyped $ref target: the
one its keywords or branches say, a type array when they differ, every
type when nothing does. {} targets, anyOf targets (Kimi refuses a type
beside an anyOf) and pure $ref chains are left alone. kimiToolEnumTypes
now also types an enum of one type plus null as [T,"null"], the one type
array Kimi takes beside an enum. Kimi doesn't count as a moved
subscription, so no plugin path reaches it.
Measured against the real Kimi Code chat endpoint
(api.kimi.com/coding/v1/chat/completions, a key without a plan, so a
schema that passes validation gets 403 access_terminated_error and a
refused one gets 400 first):
- Codex 0.162.1's processed shapes: 400 at properties.b before, 403
after.
- Raw shapes (properties-only, minLength-only, const, [1,null] enum,
description-only and oneOf-of-refs defs): 400 before, 403 after.
- The zod-built Codex App automation_update forms: 403 before and after.
- [T,"null"] plus enum, a type array beside oneOf, and every type beside
a description: 403.
The Anthropic endpoint answers 403 before it validates, so it couldn't
be probed; the same rewrite reaches it.
Tests: TestKimiToolRefTypes posts on /v1/chat/completions, /v1/messages
and /v1/responses to Kimi and to another provider, which gets the tools
unchanged. With the forwardOnce line removed it fails on all three
Kimi routes. TestKimiToolEnumTypes now expects [T,"null"] for
["a",null], and fails with that branch removed.
Run at this head: gofmt -l (clean); go vet ./..., GOOS=linux go vet
-tags nogui ./..., GOOS=windows go vet ./... (clean);
set -o pipefail; HOME=<sandbox> go test -timeout 45m ./... at
|
||
|
|
33dbdcc529 |
plugins: Sign in on Installed takes the reader down to the plugin's sign-in
Sign in on Plugins › Installed (or a plugin card) opens the Providers add
sheet with the plugin's sign-in drawn at the sheet's foot, under every
tile. With many plugins the sheet is taller than the window and the reader
was left at its top, the sign-in out of sight: the click seemed to do
nothing (the owner, on magpie-intelligence-check).
The click now passes its event, so pluginSignIn scrolls the sign-in into
the middle of the view on purpose. In WebKit that alone didn't hold: the
list show() loads redraws the sheet after the scroll, WebKit pulls the view
to 0 while it is drawn, and inside the purpose window that 0 was taken as
the reader's, then backToReader returned there. arrived(v) ends the
purpose window once the scroll is done and keeps where it left the view as
where the reader is, so the redraw is put back to the sign-in.
Run:
- plugin-signin-scrolls.test.cjs (new; 24 signed-in plugins and one
signed out, 900x560, Chromium and WebKit, en and zh): 6/6 pass. On
origin/main 0/6 ("the page went down to the sign-in"); with the scroll
but without arrived(), Chromium passes and WebKit fails 2/2.
- GUI: plugin*, *scroll*, *signin*, builtins: 1033 pass, 0 fail.
- go test -tags nogui ./internal/gui: ok (script budget, guard tests).
No Go changes.
|
||
|
|
224ea7d5be |
catalog: a reset drops what a request built of the old catalog
5351343e7 keeps what a request built of the catalog for the next request within heldFor, dropped by every write magpie makes. A reset of models.dev's catalog (catalog.Reset) wasn't one of them: Sync tells Touched after it, but a Reset alone left the providers' entries with the old windows and output limits for up to a second, and Pi's and Crush's model lists written in that second carried them (TestPiModelsCarryMaxTokens, TestCrushModelsCarryMaxTokens red in the full run: "unknown output sent: ...maxTokens:131072"). Reset now tells Forget (provider.Changed) after it lets go of its lock. Test: TestHoldKeptUntilAWrite gains "the catalog reset". Broken by hand (Reset not telling Forget): red, "the catalog reset: built 0 times, want 1", and both agent tests red again; fixed, the agent tests pass 3 of 3. Run: go test ./internal/catalog -count 1: ok (3.4s); go test ./internal/provider -run TestHoldKeptUntilAWrite: ok; go test ./internal/agent -run 'TestPiModelsCarryMaxTokens|TestCrushModelsCarryMaxTokens' -count 3: ok; go vet ./internal/catalog ./internal/provider. |
||
|
|
627e8e7d95 |
provider: a request's groups are built once under its Hold, not again by each look-up
groupsIn read providers.json's groups, matched each pattern against every model and found the automatic groups over the whole catalog, and every caller did it again: a request to a group asks FindGroup for its route, members and window, and the group list, several times each. Under a Hold the built groups are now kept (heldFrom, keyed on the catalog's entries, dropped by a write as the other held values are), and each caller gets a deep copy (cloneGroups) so a change of its own, such as the TUI's edit before a failed save, never reaches the next. Tests: - TestGroupsBuiltOnceWhileHeld: 40 look-ups under one Hold build the groups 0 more times; a change to a returned group's members isn't the next caller's; a SaveGroup under the Hold is seen. Broken by hand (groupsIn built every time): red, "the groups were built 40 times more in 40 looks under one Hold, want 0". Without the copy: red, "a change to a held group's members reached the next caller" (and TestHeldGroupsAreTheCallers red too). - TestCloneGroupsSharesNothing fills every field of a Group and its Rules by reflection and fails on any slice, map or pointer the copy shares, so a field added later is caught. Broken by hand (Weights not cloned): red, "Group.Weights is shared with the held group". BenchmarkGroupLooksHeld (30 providers x 60 models, 4 FindGroup and 1 Groups under one Hold; -benchtime 200x, two rounds; load average ~450): before 13.8 / 23.9 ms/op 26.2MB/op 41080 allocs/op after 0.18 / 0.14 ms/op 310KB/op 413 allocs/op User+sys CPU of the binary, 300 iterations minus 3: before 4.5/4.2 s (~15 ms per request's look-ups), after 0.08/0.06 s (~0.2 ms). BenchmarkGroupOverhead (200KB, not streamed, 30x): allocs of a group request fell (30x60 g4 72.9K/75.0K -> 60.5K/75.8K, g1 70.9K/73.1K -> 62.4K/68.4K; 12x20 g4 46.1K/45.8K -> 43.7K/44.7K); cpu-ms/op moved within the noise of a machine at load ~450, where a request's wall time passes heldFor and the held values are built again. Run: go vet ./internal/provider; go test ./internal/provider -run 'Group|Hold|Held|Rule|Clone' -count 1: ok (17.0s); go test ./internal/gateway -run Group -count 1: ok (53.1s). |
||
|
|
ec6fba4720 |
gateway: a long body's top level is split at its members once, not by each decode of it
decodeJSON remembered that a body of 32KB or more was valid (validMemo), but each decode of it still walked every byte of the conversation to find its members: a request's readers (the model and stream flag, the metadata, max tokens, the messages, the tools...) decode the same body a dozen times, each into a few members. Where the top level's members are is now remembered with the body's validity (longBody), and fillJSON fills a struct or map at the top from those spans; a member the type doesn't want is passed over without a walk. A body under 32KB, or one not an object, is decoded as before. Test: TestDecodeJSONSplitsALongBodyOnce: 20 decodes of one long body into five types (a struct, a slice inside one, a pointer, a map of RawMessage, a nested struct) split it once, and each gets what encoding/json gives. Broken by hand (members never remembered): red, "split 21 times over 20 decodes, want 1". BenchmarkDecodeReaders (one 200KB body decoded into three small structs, as a request's readers do; -test.cpu 1, user+sys CPU of the whole binary, 3000 iterations minus a 30-iteration run, two rounds; load average ~450, so CPU time, not wall ns/op): before 1.26 / 1.25 s (0.09-0.11 s at 30) ~383 us per request's three decodes after 0.26 / 0.26 s (0.07-0.11 s at 30) ~57 us Allocations are unchanged (25 allocs, ~358B per iteration). BenchmarkGroupOverhead's 200KB request moved within its noise (12x20 p0/m1 22.16 -> 19.30/21.45 cpu-ms/op; 30x60 g4 43.22/48.49 -> 43.86/45.24). Run: go test ./internal/gateway -run 'JSON|Json|Decode|Fill|Memo' -count 1: ok (23.5s). |
||
|
|
2a27fb8da8 |
gateway: a request's body is looked at for web search without a copy, and not parsed for a provider that searches by itself
attempt() asked searchAsked first, on every relayed request, and only
then whether the provider searches by itself. searchAsked looked for
three words with strings.Contains(string(body), …), each conversion a
copy of the whole body (a 211KB body: ~640KB and ms a request), and a
body offering web_search was then parsed whole: Codex offers it on
every turn, so each relayed Codex turn was parsed only to be told
"Codex searches by itself". searchedForIt now asks what is known of the
provider and model first, and searchAsked looks with bytes.Contains.
The same copy in the siblings that look at an error body
(fallback.passing, patience.busy, routing.failure's insufficient_quota)
goes too. lan.go's and the lower-cased look-ups in gateway.go need the
string they make and are left as they are.
Test: TestSearchAskedLooksCheaply. Broken by hand (string(body) and the
old order put back): red, "a 211KB body with no search in it: 3
allocations, want 0" and "a provider that searches by itself: 29
allocations, the body parsed".
BenchmarkSearchedForIt (211KB Responses body; load average ~450):
codex-asks old 2.55-5.02 ms/op 665KB/op 29-30 allocs/op
new 0.1-1.9 us/op 0B/op 0 allocs/op
other-plain old 1.6-4.8 ms/op 663KB/op 3 allocs/op
new 0.26-1.15 ms/op 0B/op 0 allocs/op
Run: go test ./internal/gateway -run
'TestSearchAskedLooksCheaply|TestWebSearchAskedOfEachAPI|Search|Busy|
Passing|Failure|Credit|Quota' -count 1: ok (140s).
|
||
|
|
a1118187b5 |
gateway: who answered a conversation is written to affinity.json behind the answer, once in a while, not on every answer
answered() (and unanswered()) called saveSticks on every request answered: up to 512 conversations sorted, marshalled, written to a temp file and renamed, one answer after another under sticksSaving. Now the stick is in memory at once (stickOf reads the map first) and the file follows within sticksFlushAfter (2s): what is answered meanwhile goes in one write. The gateway's drain (ListenAndServe) and magpie ending on a signal (cli/signals.go, beside FlushServed) write what is waiting, so a restart or the magpie handed over to reads every answer. A crash loses the last 2s, as served.json does since 4f9e8331a. In a test binary the wait is 0 and the file is written at once, as it was (no timer outlives a test; 8215e8275 did the same for served.json). A write waiting for another HOME's file (a test's) is dropped, not written into this one. Test: TestSticksWrittenBehind (2s set by the test): 200 answers write no file, the last is known in memory, flushSticks writes all 200, and a short wait writes by itself. Broken by hand (noteSticks calling saveSticks always): red, "affinity.json written on a request answered". BenchmarkAnswered (512 sticks kept, 200x, 2 runs; load average ~450): old (saveSticks inline) 21.3 / 25.0 ms/op 506KB/op 2140 allocs/op new 2.5 / 5.6 us/op 392-434B/op 8 allocs/op Run: go test ./internal/gateway -run '^TestSticksWrittenBehind$' -count 1: ok. go test ./internal/gateway -run 'TestSticksWrittenBehind|Affinity| Sealed|Stick|Strict' -count 1: ok (57.8s). |
||
|
|
ed3a46d02b |
provider: what a request built of the catalog stays for the next request within a second, not built again for each
Hold dropped everything held when the last request let go, so one
request after another built the catalog again from every provider's
files and accounts (All, entries, the groups' entries, the settings):
a fifth to a third of a request's CPU with 30 providers. What is built
now stays until heldFor (1s) is past, as it already did for requests
that overlapped. It is built again at once when anything it was built
from may have moved:
- Changed() and a plugin change (dropHeld), as before;
- a write that only tells filememo (settings.Save, writePrivate, an
agent's account file): held values carry filememo.Gen(), new here, and
are dropped when it moved;
- providers.json or settings.json written by another process (the CLI's
"magpie group add"): the first Hold of a request stats both and drops
what is held when either changed, so the next request sees it, not a
second later;
- the groups served or gated (GateGroups, ServeGroups): holdGate drops
what is held on both changes (TestGroupsOnAndOff was red without it);
- another environment (a test's HOME), by a hash of os.Environ().
Other files another process writes (an agent's own sign-in file) are
seen within heldFor, as filememo already takes a file found unchanged.
Tests:
- TestHoldKeptForTheNextRequest: five requests one after another build
once. Broken by hand (held.built = nil on the last release put back):
red, "five requests one after another: built 5 times, want 1".
- TestHoldKeptUntilAWrite: each of filememo.Forget, providers.json and
settings.json written behind magpie's back, and GateGroups, builds
again once. Broken by hand, one at a time: the Gen check off, red
"filememo told: built 0 times, want 1"; the stat off, red
"providers.json written by another process: built 0 times, want 1";
holdGate's dropHeld off, red "the groups gated: built 0 times, want 1".
- TestRequestBuildsProvidersOnce now wants 1, 0, then 1 after
Changed() (a request later than 0.9s after the first may rightly
build again on a loaded machine; the test allows it).
BenchmarkGroupOverhead (internal/gateway, 200KB Anthropic body,
stream=false, 100x, two rounds alternating; load average ~450, so the
cpu-ms/op it reports is the measure, not wall ns/op). base is 8215e8275:
12x20 p0/m1 base 25.66 / 24.36 cpu-ms/op 16.8MB 41723-41827 allocs
this 22.13 / 20.67 cpu-ms/op 13.4MB 33771-33969 allocs
12x20 g4 base 30.59 / 30.68 cpu-ms/op 22.5MB 53213-53409 allocs
this 25.91 / 25.60 cpu-ms/op 19.0MB 45213-45613 allocs
30x60 p0/m1 base 54.95 / 53.26 cpu-ms/op 42.5MB 89466-90023 allocs
this 30.80 / 29.27 cpu-ms/op 23.0MB 45853-46928 allocs
30x60 g4 base 66.67 / 73.07 cpu-ms/op 68-70MB 112283-116845 allocs
this 45.59 / 48.38 cpu-ms/op 49-52MB 68540-74905 allocs
Run: go test ./internal/provider -run 'Hold|Group|Changed|Served'
-count 1: ok (91s). go test ./internal/gateway -run
'^(TestGroupsOnAndOff|TestRequestBuildsProvidersOnce)$' -count 1: ok.
The full suite at the head of this series is in its last commit.
|
||
|
|
ae019defed |
provider: in a test binary served.json is written as an answer is noted, so no write outlives its test
4f9e8331a wrote served.json 2s behind the answer. In a test binary that timer outlived the test that answered, and wrote into its temp HOME as testing removed it: BenchmarkGroupOverhead's first case failed 1 run in 6 with "TempDir RemoveAll cleanup: unlinkat …: directory not empty", and TestOTelSessionDedupOnlyUnkeyedLoopback failed the same way in a package run. servedFlushAfter is now 0 in a test binary (testing.Testing(), as partners.go already does), and NoteServed writes at once, after it lets go of servedAt, as it did before 4f9e8331a. TestNoteServedWritesBehind sets the 2s itself. Test: TestNoteServedInATestWritesAtOnce. Broken by hand (writeBehind returning d in a test binary too): red, "not written as the answer was noted: … served.json: no such file or directory". Run: go test ./internal/provider -run 'TestNoteServed|LastServed' -count 1: ok. BenchmarkGroupOverhead's 12x20 p0/m1 case, 6 runs of 100 requests before: 1 failed on the cleanup; see the next commits' records for the runs after. |
||
|
|
8fd74d15bf |
provider: retired.json is looked at on disk once a second, not on every request answered
Every answered request asks Unretire (the gateway's servedCandidate), and
each catalog built asks retiredNow; each was an os.Stat of retired.json
under retired's lock. Only retired.go writes the file (writeRetired, for
Retire and Unretire), and it keeps retired.at and the file's time current
itself, so this process's own retirements are told at once. The file is
now looked at again only after retiredLook (1s): another magpie's write
is seen within it. A config path of its own (another HOME) is read at
once, as before.
Numbers (Apple M4 Pro, loaded by other sessions):
BenchmarkUnretire before 98.8 us/op 640 B/op 5 allocs/op
after 0.46 us/op 320 B/op 3 allocs/op
Test: TestRetiredLooksOnceInAWhile: 200 Unretire+Retired calls look at
the disk at most twice; Retire and Unretire are told at once; a write
another magpie makes is seen once retiredLook passes; a new config path
is read at once. Broken by hand (the throttle disabled): red, "400 looks
at retired.json for 200 requests".
Run: go test ./internal/provider -run TestRetiredLooksOnceInAWhile;
./internal/gateway -run 'Retired|Zen': ok. The full suite run is in the
last commit of this series.
|
||
|
|
e1ebd173e8 |
filememo: a file not there is, while a request holds what was read, not looked for again
A provider with no live model list fetched has no live-models file, and
each request asked after it for each of its models (Provider.Exposed ->
ListedAPIs -> catalog.LiveByID -> readLive), each time an os.Stat that
failed: in a CPU profile of a 30-provider, 60-model catalog, os.Stat was
32% of a request, nearly all of it this. A file found unchanged was
already taken as unchanged for heldFor (1s) within a hold; a file found
missing now is too, in the same generation of Forget. Forget (a write
magpie makes), Look(path) (another's write), the hold's end, a second
gone by, or a stat finding the file there drops it. Unheld, every read
still looks.
Numbers, BenchmarkGroupOverhead, 200KB body, stream=false, 100x each,
binaries alternated twice (Apple M4 Pro, loaded by other sessions):
before (cpu-ms/op, allocs) after
30x60 p0/m1 34.69 / 35.14 95126 32.87 / 31.84 89266
30x60 group/g4 44.33 / 43.88 115303 40.77 / 40.77 109071
12x20 p0/m1 15.75 / 16.30 42535 16.22 / 15.09 41645
12x20 group/g4 18.15 / 18.50 54138 18.16 / 17.76 53118
(about 7-8% of a request's CPU on the larger catalog; within noise on
the small one, which has fewer missing files.)
Test: TestHoldMissing: 100 held reads of a missing file make one stat; a
file written meanwhile isn't seen until Forget, and is seen after Forget,
after Look and after the release; unheld, 3 reads make 3 stats. Broken by
hand (the missing check disabled): red, "100 looks at a file not there,
held".
Run: go test ./internal/filememo ./internal/catalog: ok. The full suite
run is in the last commit of this series.
|
||
|
|
a20d86900d |
provider: what answered a request is written to served.json behind it, once in a while, not on every answer
NoteServed ran on every answered request (servedCandidate): it read
served.json, merged, and wrote it through steady.WriteFile (a synced temp
file renamed over it), all under servedAt's lock, so concurrent answers
queued behind each other's fsync.
Now NoteServed only notes in memory and arms one write for
servedFlushAfter (2s) later; everything noted meanwhile goes in that one
write, merged with what the file holds (another gateway's) and pruned past
servedKeep as before. The file's format is unchanged. This process's
LastServed has a note at once (it merges memory over the file, as it
did); the CLI, a process of its own, sees it within 2s. FlushServed writes
what is pending: the gateway calls it as Serve ends, and the CLI's signal
handler before it dies of the signal. A crash loses at most the last 2s
of notes. A note made under one config path (a test's HOME) is never
written into another's: a path change drops the pending write.
Numbers (Apple M4 Pro, machine loaded by other sessions):
BenchmarkNoteServed before 5.10-5.33 ms/op 7.8 KB/op 82 allocs/op
after 0.64 us/op 352 B/op 5 allocs/op
Test: TestNoteServedWritesBehind notes 200 answers and checks the file is
untouched, LastServed has the latest at once, FlushServed writes it once
(a second flush writes nothing), merged with another gateway's entry, and
that the timer writes it by itself. Broken by hand (origin/main's
served.go with stubs for the new names): red, "written on a request
answered", and the 200 notes took 1.04s.
Run: go test ./internal/provider -run 'TestNoteServedWritesBehind|TestQuotasLastServed|TestCardsLastServed';
./internal/gateway -run TestQuotasLastServedAt; ./internal/cli -run
'TestQuotaJSONLastServedAt|Signal'; ./internal/gui -run
TestServedMovedWakesTheMenuBar: ok. The full suite run is in the last
commit of this series.
|
||
|
|
865b618086 |
gui: a gateway session is listed without its days, which only the stats read (#2776)
gatewayExternal copied every gateway session's days into the
ExternalSession it hands the Sessions list, each agent's manage page
and a session's detail. MergeExternal, which all three go through,
never reads them; only MergeExternalStats does. The Sessions list asks
for every session, so each poll of an open page copied every gateway
session's days. After the Vias fix (the commit before this one), that copy was the
largest allocation an idle open page makes: 5.11 GB of 9.14 GB in 6
minutes on the 720k-call sandbox.
gatewayExternal now leaves the days out, and the stats add them
through gatewayDays. Each model list is made at its size.
TestGatewayListCopiesNoDays lists a session with 365 days: no days in
the listed copy, and gatewayDays has all of them. With the days copy
put back in gatewayExternal by hand: red, "a listed session copied 365
days". TestGatewaySessionHistoryAndCalendar still sees each day's
output in the stats.
720k-call sandbox, idle with an open page's polls every 15 s, this and
the build before it side by side for 10 minutes, load ~190-210, 12
poll rounds each. Allocated from minute 2 to minute 8: gatewayListed
5,440 MB before and 1,000 MB after, the Sessions list handler 5,820 MB
and 2,970 MB, the manage page 2,220 MB and 1,850 MB. The live heap at
the snapshots ran 393-857 MB before and 389-889 MB after, and RSS
406-1176 MB and 357-934 MB, with no trend in either over the 10
minutes.
Run: go test -p 4 -count=1 ./internal/gui/ ./internal/sessions/: ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
2fcd4b33c4 |
usage: one Vias index answers every since, instead of a rebuild from the whole log whenever the since changes (#2776)
Vias kept the lists for one since. The Sessions list asks from its
oldest listed session's start, each agent's manage page from that
agent's oldest, and a session's detail from that session's start, so
an open page's polls almost never asked the kept since, and each ask
read and grouped the whole log again. Idle with an open Sessions page
on the 720k-call sandbox, buildVias allocated 9.1 GB in 8 minutes,
78% of everything allocated, which is most of why the idle process
churned its heap and grew.
The cache now keeps one index from the whole log and each session's
first call. A session whose calls all came at or after the since is
answered from it. A session with calls before its since is answered
from one kept window for that since, built only when such a session
is read. Len counts the sessions with a call since the index's time.
Both are kept per log version and agent list, as before.
TestViasAnswerEverySinceFromOneIndex writes 20,001 sessions and asks
from three sinces in turn, as the three pages do: 2,677 bytes an ask.
On the old cache: red, 11,580,100 bytes an ask. It also checks that a
session with a call on each side of a since counts only the one after
it, and what Len says for a window and for every session.
TestGatewaySessionsCachePricesWindowsAndRewrite's window check and
TestUsageViasSkipsOldHistory stay green.
720k-call sandbox, idle with an open page's polls every 15 s (the
Sessions list, stats, Claude's manage page, Requests, state), before
and after side by side for 12 minutes, load ~170-250. Allocated from
minute 4 to minute 12: buildVias 9,100 MB before, 0 after (built once,
before minute 4). The faster answers let the poll loop run about twice
as often, so the totals (11.6 GB and 10.5 GB) aren't per poll. The
live heap ran 352-641 MB before and 514-724 MB after, and RSS 730-962
and 555-1217 MB; both swing with where a poll is when the snapshot is
taken and the machine's load, and neither shows a trend in 12 minutes.
Run: go test -p 4 -count=1 ./internal/usage/ -run
'Vias|KeptStrings|GatewaySessionsCachePrices|Incremental|Review': ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
34b1757843 |
usage: the kept gateway projection's days and models are lists of their own size (#2776)
buildGatewaySessions grew each session's Daily and Models an item at a
time from empty. The projection is kept for as long as the log is
unchanged, and so was the spare room append had left each list (five
days took eight). slices.Clip in gatewayProjection hides that room from
callers but doesn't free it. On the 720k-call sandbox, that append was
the largest single allocation of the build (319 MB of 1.14 GB), and the
lists are most of what the start keeps for the Sessions page.
Each list is now made at the size its map already counts.
TestGatewayProjectionKeepsNoSpareRoom builds 3000 sessions x 5 days
with one to five models each, and measures the heap the projection
keeps. The bound is its days and models x1.3, plus the sessions' list
and index. Fixed: 9,233,056 bytes, against a bound of 10,478,400. With
the two makes taken out by hand: red, 12,754,488 bytes.
720k-call sandbox, cold start, the four first asks together, the live
heap 20 s after them, back to back: 541 MB before, 479 MB after. The
machine's load was ~250-290 and the answers took ~140 s in both runs,
so their peak RSS (1395 and 1891 MB) measured the load, not this.
Run: go test -p 4 -count=1 ./internal/usage/: ok.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
43bd998b15 |
usage: GatewaySessions hands out the kept projection's lists instead of cloning every session's days for each ask (#2776)
GatewaySessions cloned every session's Models and Daily for each ask,
from the projection kept for exactly these asks. The start's first
asks (the Sessions list, each agent's manage page, the stats) each
cloned them all. In a heap snapshot at the 720k-call sandbox's peak,
cloneGatewaySession held ~447 MB live of the 1362 MB. Every caller
(gatewayExternal, listedGateway) only reads the lists, and copies them
again into its own ExternalSession anyway.
The lists are now the kept projection's, shared and read only, which
GatewaySessions' doc now says. This changes the old contract that a
caller owned its copy. The kept lists are clipped, so an append by a
caller makes a slice of its own and can't write into another's.
gatewaySessionFrom shares the days in a window the same way.
GatewaySessionByID still hands out a clone.
TestGatewaySessionsHandOutTheKeptProjection writes 2000 sessions x 10
days and asks 10 times: 435,215 bytes an ask, against the 368,000-byte
list itself. With the clone put back by hand: red, 3,669,150 bytes an
ask. TestGatewaySessionsCacheRefreshAndOwnership now checks that two
asks share the days, that two callers' appends don't alias each other
or the kept list, and that the kept data is unchanged after them. With
the clone put back it is red too ("each ask has a copy of the days of
its own").
Run: go test -p 4 -count=1 ./internal/usage/ ./internal/gui/: ok (load
~157).
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
6359b2c27c |
usage: Vias hands every caller the one copy it keeps, and a session's list is copied only when read (#2776)
Vias cloned every session's list for each ask, from a cache built for
exactly this. The Sessions list, the manage pages and a session's
detail each asked, and read the lists of the sessions they show, or of
one. Over ~720k calls one ask was ~66 MB.
Vias now answers a ViaIndex over the kept map. Of(key) is a session's
list as a copy of its own, so a caller still can't change the kept
one; Len is how many sessions have one. The three GUI callers and the
tests read through Of.
TestViasHandOutTheKeptCopy writes 20,000 sessions and asks 20 times,
reading one list each: 2,590 bytes an ask. With the clone of every
list put back by hand (under ViaIndex): red, 3,817,492 bytes an ask.
It also changes a list read through Of and checks the next ask still
says 1 call.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
227b864a45 |
usage: CodexModelEffort keeps only the gateway calls a Codex session file's call can be matched to (#2776)
CodexModelEffort built the whole ledger of the period and kept the rows
that carry a Codex thread. Every gateway call became a Record (in
gatewayRecords' slice), a packed row (gatewayMatchesDetails' chunk) and
a priced Row (ledgerMatched), all held at once, though only a gateway
call paired with a Codex session file's call by its response id can
carry a thread. On the 720k-call sandbox this build was 7.6 GB of the
start's 18 GB allocated and most of its peak.
codexEffortRows visits the log once and keeps only the gateway calls
with a response id, request id or session (native, else magpie's) that
one of the session files' calls has, or an agy call when one is agy's.
No other gateway call can change gatewayMatchesDetails' answer: the
request-id match looks up only the locals' ids, the fallback groups are
looked up only by the locals' sessions, and a response id's uniqueness
is counted over every call that has it, all of which are kept. Only the
paired calls are priced into rows, and the rows are the whole ledger's
thread rows in the same order, so the sums (floats included) are the
same.
TestCodexEffortRowsAreTheWholeLedgers compares the rows with the whole
ledger's for All, Today and 7d, with Codex's reader and every agent's:
a pair by response id, an ambiguous response id, a session-and-tokens
match, a call two days old, and unrelated calls around them. With the
session test dropped from matchingRecords by hand it is red (all,
every agent: the session-matched call shows as a row of its own).
TestCodexModelEffortLetsUnrelatedCallsGo builds over 3000 unrelated
gateway calls and allows a visit of the log and a half. With the old
build put back (LedgerOf): red, 18,347,128 bytes against a visit's
1,198,680. With the fix: 1,321,824 against 1,321,744.
720k-call sandbox, cold start, the four first asks together, back to
back (load 48.7 then 14.7, so the times are not comparable; the memory
is what this measures):
before (beb9c40d5): peak RSS 4411 MB, heapSys 5513 MB, live 574 MB
after: peak RSS 2427 MB, heapSys 2413 MB, live 542 MB
manage?agent=codex answered in 41.5 s before, 23.1 s after.
Full suite on this series' final tree (aa678b482 before this note was
added), rebased on origin/main
|
||
|
|
baef679f29 |
sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776)
|
||
|
|
c483feadfd |
usage: OpenCode Zen's card says OpenCode tells no key its balance, and Go at /inference/go gets its plan card (ttmrmx on X)
ttmrmx on X: "magpie 里 OpenCode Zen/Go 这个供应商的余额卡片不显示". Cause, two parts: - An OpenCode Zen key (opencode.ai/zen, /inference) had no balance source, so KeyBalances skipped it without a word and the Usage page drew no card. OpenCode has no balance a key can read. In sst/opencode, packages/console/app/src/lib/inference-proxy.ts serves only the model routes. /zen/v1/balance, /zen/v1/credits, /zen/v1/usage and /zen/v1/billing all 404, and billing.mdx shows the credits only in the console (Overview -> Credits, to owners and admins). No endpoint was invented. - planQuotaSourceOf matched only /zen/go. models.dev now gives Go as opencode.ai/inference/go/openai/v1, so a Go provider saved there got no plan card at all. openCodeGateway() now tells go/zen/other (custom is the user's own) for both URL shapes, and Go at either one reads https://opencode.ai/zen/go/v1/usage. What changed: - A Zen key's card now carries errOpenCodeNoBalance and seeAt (https://opencode.ai/console). It reads "OpenCode doesn't tell an API key its balance — see Zen's credits in the OpenCode console, Overview → Credits", with an "Open the console ↗" button. That is one button with the needsAccessKey "Open settings" one (#1821), so the bytes stay small. - A provider with its own BalanceURL is still asked that URL. - Strings are in zh, zh-TW, ja and de. - coreScriptBudget: rebased onto |
||
|
|
f76201a84a |
plugins: a sign-in page the plugin's CLI opened isn't opened again, Grok's opened twice on macOS (andyfmyth on X)
"magpie里的grok 登录验证 在mac下 似乎每次都会弹两次验证, 在浏览器窗口里". Grok's plugin signs in through `grok login --device-auth`, and Grok Build (1.0.50, the webbrowser crate) opens the device page itself, through NSWorkspace on macOS and ShellExecuteW on Windows. Neither reads $BROWSER; the macOS binary has no "BROWSER" string. magpie then opened the same URL from /api/plugin-signin (desktop), startPluginSignIn/followSignIn (a browser tab) or `magpie plugin login`. Reproduced in a sandbox HOME/GROK_HOME: grok's device-code tab appeared in Chrome with magpie not involved, with and without SSH_CONNECTION. Built-in grok is retired ( |
||
|
|
e7114d3882 |
usage: one gateway session projection is kept, and a range of days is read out of it (#2776)
The gateway's sessions were projected and kept once per `since`, up to
four at once (all time, and each Sessions stats range: today, 7, 30
days...). With 600k calls the all-time projection alone is ~160 MB in
use (pprof inuse_space of buildGatewaySessions on the sandbox below),
and #2776 counted 148 MB for its copies.
Now only the all-time projection is kept. A range that starts at a
local midnight (every stats range does: combinedSessionStats parses
st.From in time.Local) is derived from it: each session's days from that
date on, with its tokens, models, cost and start/last summed from those
days. Each kept day now carries the first and last time of its requests
(unexported, two time.Time) so the derived start and last are exact.
Any other start is built from the log and not kept. The cache is keyed
on the zone too, since the days are local dates.
TestGatewayWindowsShareOneProjection: six days of calls over three
sessions, priced and unpriced models; the all-time read and five ranges
(0, 1, 2, 3 and 7 days back) build one projection between them, and each
range equals a direct build from its midnight (sessions, start, last,
tokens, models, cost within 1e-9, unpriced, days). Broken by hand:
- the midnight path turned off (a build per range, as before): red,
"built 6 projections for one log and 5 ranges, want 1".
- the derived start taken from the whole session: red, codex|even's
Start 2026-10-15 where the build says 2026-10-19.
Cost: the two times per kept day add ~13 MB to the one projection on the
sandbox below (158 -> 171 MB in use), against a whole second projection
(~160 MB) for each range a page asks for.
Measured: the sandbox runs (see the commits before) ask only the 30-day
range, so their heap shows one kept projection on both sides; the
saving is per extra range asked and is shown by the test's build count,
not by those runs.
Run on origin/main
|
||
|
|
cfbd321fc4 |
gui: the start's warm-up reads Codex's per-thread effort when there are Codex sessions (#2776)
The first Sessions page after a start that showed Codex rows read usage.CodexModelEffort cold, from the whole ledger, while the page waited. The warm-up now reads it as its last step, after the stats it already warmed, and only when those stats hold a Codex session; every later ask is answered from what CodexModelEffort keeps per period. The steps move into warmSteps() so a test can run them. TestWarmUpReadsCodexEffort: with Codex keys in the stats the step reads the effort once, with none it reads nothing. With the step removed: red, "read 0 times, want 1". Measured on the same sandbox as the commit before (600k gateway calls, ~4,600 sessions), base |
||
|
|
d7e02ae088 |
sessions: a scan's read buffer is the size of what is left of the file, 1 MiB at most (#2776)
scanAt gave every scan a 1 MiB bufio buffer. A start reads ~4,600 mostly small session files (and reads each again from where it was left), so those buffers were the largest single allocation of a start: 9.4 GB of the 22.4 GB a warm start allocated on the sandbox below. The buffer is now the rest of a plain file plus one byte, at least 16 KiB and at most 1 MiB; a packed (zstd) file keeps 1 MiB. A line longer than the buffer (a file grown since its size was read) is still read whole through scanAt's long-line path. Tests (internal/sessions/scan_buffer_test.go): - TestScanOfASmallFileTakesASmallBuffer: 200 scans of a two-line file allocate under 64 KiB each. With the 1 MiB buffer back: red, "a scan of a two-line file allocated 1048871 bytes". - TestScanReadsALineLongerThanItsBuffer: a line three buffers long, then a short one, are both handed over whole. Measured on a sandbox instance (600k gateway calls, ~4,600 sessions), base |
||
|
|
c381e4cd1e |
sessions: a read is never held by another read's refresh, only by a change to the files (#2776)
A read of the sessions (List, Stats, Manage, the agents' lists, Codex's threads) took dbReadMu, a plain mutex, for the whole call, parse included. The start's warm-up reads every session file with a quarter of the cores, so the first pages and API calls after a start waited for its whole read before they could even look at the cache. - dbReadMu becomes storeMu, an RWMutex: reads take it shared, and only the changes to the files (Delete, a Codex provider move, a Claude project relocation) take it alone. - A file another refresh is reading now is in `parsing`, with a channel closed when its parse is in the cache. A second read serves the parse it already has of such a file, and waits only for one it has never read; it never reads the same file twice at once. - Each parse is published as it finishes, not in checkpoint batches, so a waiting reader gets it at once. - The shared store handles (OpenCode, Hermes, Alma, Cursor) closed at the end of every read; with reads overlapping, one could close a handle another still used. They now live as long as their last user (useDBs). get() and the titles path closed them without the lock at all before. Tests (internal/sessions/refresh_shared_test.go), each broken by hand: - TestReadNotHeldByAnotherRead: the warm-up's parse of 12 grown files is held; List and Manage answer within 10s from the kept parses, each file is parsed once in all, and a later List parses none. With storeMu.Lock in List: red, "List waited for another read of the same files to end". - TestReadWaitsForAFirstReadUnderWay: a file never read is waited for, not served empty, and read once. Without the waits: red, "List answered without the files being read". Without the skip of a file being read: panic, close of nil channel. - TestStoresLiveAsLongAsTheirLastUser: with the release always closing: red, "closed while a read still used it". All three pass with -race. Measured on a sandbox instance (600k gateway calls, ~4,600 Claude Code and Codex sessions, 300 grown since the last start; 4 API calls asked 3.5s after the routes, when the warm-up starts), base |
||
|
|
a77f6ae168 |
sessions: a WorkBuddy reply whose first line spent nothing is one call
Found in the reader audit, not a speed fix. readWorkBuddyCalls replaced
the call before a line whenever the line's messageId was the one the
line before it carried. A zero-token line makes no call but still set
that id. So a reply opening with a zero line:
- as a session's first reply, panicked: index out of range [-1] at
st.Calls[len(st.Calls)-1], which took down the Usage ledger's read;
- after another reply, overwrote that reply's call. m8 50/5, then m9
0/0, then m9 300/20 gave one call (m9) where the Sessions summary
(workbuddyLine: unuse m9's zero, keep m8) counts both.
The call before is replaced now only when it carries the same id.
CodeBuddy and the other WorkBuddy builds read through the same reader.
Test: TestWorkBuddyCallsReplyStartingAtZero writes both cases.
- On the old code: panic, index out of range [-1].
- Broken by hand, with only a len(st.Calls) > 0 check: red, "calls
[m9 300/20], want m8's and m9's".
Run: go test ./internal/sessions -run 'WorkBuddy|CodeBuddy|Buddy'
-count=1 ok. The full-suite record is in the report for this series.
|
||
|
|
ec396be60c |
sessions: a dsh session read for calls is read on, not whole
dsh's calls were read by a whole-file reader: each reply appended to a
session made Usage's ledger read the whole file again and, packed,
decompress every frame of it. parseDsh already reads on from the frame
it left off in (frames.go, 827c304d9); the call reader now does too.
readDshCalls is handed what the last read came to and reads on from its
tail (scanFrames for a packed file, scanAt for a plain one), carrying
dsh's header in dshCarry. It says how many of the calls it gives were
kept from before, so only the new ones are appended to the disk shard
(resumeCallReaders in call_cache.go). The carry is kept in the shard's
state as JSON (callDiskState.Dsh), since the in-memory read is let go
after packing. A fork's inherited end-seed met in a later read drops
what was counted before it and rewrites the shard whole, as the whole
read did by cutting at the last one. A file cut short or replaced
(tail.holds) is read whole. One change from before, as for parseDsh: a
last line not ended by a newline waits for it.
Measured (CPU, getrusage; 50 MB of events, ~3600 calls, a reply
appended between reads; packed: frames of 200 lines; the old reader
measured from a worktree at 432a2ba5e with the same harness; machine at
load ~500):
plain before: 91-109 ms CPU, 0.5-1.3 s wall per read after an append
plain after: 0.6-7.7 ms CPU, 2-129 ms wall
packed before: 214-230 ms CPU, 3.5-4.8 s wall per read after an append
packed after: 1.2-1.5 ms CPU, 13-46 ms wall
first read unchanged (plain ~60-105 ms, packed ~195-215 ms CPU)
Tests: TestDshCallsReadOnlyWhatWasAppended (packed dsh-a) checks where
each read starts (scanHook) and its calls: a frame appended is read
alone; half a frame waits; a frame ending inside a line is read on from
that frame; after resetCalls() the read goes on from the disk shard;
cut short reads from 0. TestDshCallsEndSeedAcrossReads: dsh-c's
end-seed arriving in a later read drops the seeded call, its own is
read on, and the shard holds only that after resetCalls().
Broken by hand: no resume -> both red ("read from 0, want 654"); the
carry not written to the shard -> both red (same); the end-seed not
rewriting the shard -> red ("the fork's own ...: [50 100]").
Run: go test ./internal/sessions -run 'Dsh|Call|Usage|Pi' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
|
||
|
|
da9fc17eb6 |
sessions: a Pi or omp session file read for calls is read on, not whole
Pi's and omp's calls (#1951) were read by a whole-file reader: every time a session file grew by one line, Usage's ledger decoded the whole file again, its header and every message, and rewrote its disk shard. Pi and omp only append to a session file, a line an entry, as Kimi Code's wire file is. Pi and omp are now line readers (lineCallReaders): a file that only grew is read on from the last whole line, and only the calls it adds are appended to the shard. What a later line's call is read with is carried in piCarry on the callFile: the header's cwd, a fork's start (what came before it is its parent's), and the provider and model in use for a compaction's or tool result's usage. That carry is kept in the shard's state too, flat (callDiskState.Pi*), as the in-memory read is let go after packing: a carry that lived only in memory made every append read from 0 again. A shard written before has no carry (piCallsKept false) and its file is read whole once more. Cut shorter, written over, or grown at a changed head: read whole again (prepareCalls' head and prefix hashes, as for Kimi). Measured (CPU, getrusage; one 50 MB Pi session, ~3500 calls, a call appended between reads; the old reader measured from a worktree at 432a2ba5e with the same harness; machine at load ~500): before: 112-153 ms CPU, 1.0-2.5 s wall per read after an append after: 1.1-3.1 ms CPU, 5-57 ms wall per read after an append; first read ~95 ms CPU, as before Test: TestPiCallsReadOnlyWhatWasAppended (a fork, its model set once at the top, compaction usage) checks where each read starts (scanHook) and the calls it gives: an append with a half line after reads from the old end and leaves the half line; finished, it is read; a line older than the fork's start is left out after a resume as on a whole read; the model, provider and cwd stay right on calls read on; after resetCalls() the read resumes from the disk shard; cut shorter and written over read from 0. Broken by hand: piCallsKept always false -> red ("read from 0, want 686"); the carry not written to the shard -> red (same); begin run on every read, the carry lost -> red ("calls [1 2], want [1 2 3]"). Run: go test ./internal/sessions -run 'Pi|Omp|OMP|Call|Usage' -count=1 ok; gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. |
||
|
|
1f411802b8 |
sessions: Droid's and Grok's listings open only the files that changed
Droid's listing opened every transcript to read its first line, for
whether it is a subagent's (callingSessionId), and Grok Build's read and
decoded every session's summary.json for its session_kind and parent.
The listing runs on every 15s poll of Sessions and Usage, so with
thousands of sessions each poll opened thousands of files that had not
changed.
listMemo (listmemo.go) keeps what a listing read from each file by that
file's own size and mtime, not the folded size the listing gives the
session. A listing is a round: a file not seen in it (a session deleted)
is dropped when it ends, so the memo never outgrows the sessions there
are. A read that failed, such as a transcript whose first line is still
being written, is not kept, and the next listing reads it again: a
failed read means unknown, not "nobody's". Reset clears both memos.
Measured (3000 sessions each, one listing after another, CPU by
getrusage, the machine at load ~500):
Droid before: 1103 ms CPU / 8.3 s wall per listing
Droid after: 27-47 ms CPU / 0.05-1.0 s wall (first listing 1166 ms)
Grok before: 649 ms CPU / 4.2 s wall per listing
Grok after: 252-295 ms CPU / 1.8-2.2 s wall (first listing 707 ms)
What Grok's listing still spends is its globs and two stats a session
(updates.jsonl, summary.json), not reads.
Tests: TestDroidListingReadsOnlyChangedTranscripts counts transcript
opens (scanHook): a second listing opens only the half-written one,
appending reopens only that file, a finished first line is then kept,
and a transcript written over without a caller is its own session.
TestGrokListingReadsOnlyChangedSummaries counts summary reads
(grokSummaryHook): none when nothing changed or only the updates grew,
one when the summary is written over, and the key follows it.
Broken by hand: the memo never hit -> both red ("nothing changed: read
map[...all...]"); failed reads kept -> Droid red ("nothing changed: read
map[], want only the half-written one again").
Run: go test ./internal/sessions -run 'Listing|Droid|Grok' -count=1 ok;
gofmt -l and go vet ./internal/sessions clean. The full-suite record is
in the last commit of this series.
|
||
|
|
11b42c0e2e |
sessions: a Kimi Code wire file read for calls is read on, not whole
Kimi Code's calls (#1607) were read by a whole-file reader: every poll of Usage after a session's wire.jsonl grew decoded the whole file again for the one or two records added. Kimi only appends to that file, a record a line, so its calls now go through the line path Claude Code's and Codex's take: lineCallReaders gives readCalls a begin (the session id) and a line reader, and prepareCalls reads a grown file on from where the last read left off, writing only the added calls to the disk shard. A half-written last line waits for the rest; a file cut shorter, or written over, fails the head and prefix checks and is read whole again. That alone did not resume for any main session: Kimi's listing folds state.json's size into the main wire file's, so the prefix hash, taken over the listed size, ran past the end of the file and came back empty, and an empty hash never matches. The hash is now taken over the bytes the reader consumed (Off) rather than the listed size; for a Claude or Codex file with no partial tail the two are the same, so their shards keep their hashes. A title change in state.json still re-lists the file, and now costs a resume, not a whole read. TestKimiCodeForkCountsOnce wrote its subagent files without a final newline, which a line reader keeps as an unfinished line; real wire files end in one (all nine of the reporter's do), so the fixture now does too. Measured (CPU, getrusage; one 50 MB wire.jsonl with a state.json beside it, one record appended between reads, readCalls alone; machine loaded): before: 40-90 ms CPU, 240-980 ms wall per read after an append after: 0.9-1.1 ms CPU, 10-21 ms wall per read after an append; first read ~40-55 ms Test: TestKimiCodeCallsReadOnlyWhatWasAppended (state.json present) checks where each scan starts and what calls come back: appended with a half line after, the half line finished, cut shorter, written over. Broken by hand: no resume for kimi -> red ("read from 0, want 567"); resume without the size/prefix checks -> red ("cut shorter: read from 945, want 0"); the hash over the listed size again -> red ("read from 0, want 567"). Run: go test ./internal/sessions -run 'Kimi|Call|Codex|Claude|Long|Grow| Append|Resume|Prefix|Hash' -count=1 ok (359s); gofmt -l and go vet ./internal/sessions clean. The full-suite record is in the last commit of this series. |
||
|
|
6d3caf6fa4 |
sessions: a Cline session whose manifest alone changed is not read again
Cline keeps a session's messages in one JSON document, rewritten whole,
and its title, start and fork in a manifest beside it, whose size and
mtime are folded into the session file's. Cline rewrites that manifest
on its own (a title given, the session's status touched), and every such
rewrite made the Sessions and Usage pages decode the whole messages file
again, though nothing in it had changed.
parseCline now keeps what its messages were counted from: the messages
file's own size and mtime, and the start and fork time the manifest gave
then, with the first prompt that names the session. When the messages
file is as it was and the manifest still gives the same start and fork,
the counts stand and only the manifest is read again for the id, cwd,
name and title. Messages rewritten (any size or mtime change), or a
start or fork that moved, read them whole again as before. A messages
document can't be read on from where it was: it is rewritten, not
appended to.
Measured (CPU, getrusage; 50 MB messages file, the manifest rewritten
between reads; machine loaded):
before: ~205-290 ms per read after a manifest change
after: 0.1 ms per read after a manifest change; first read ~290 ms
Test: TestClineReadsMessagesOnlyWhenTheyChange counts reads of the
messages file (clineHook) and checks each read against a whole one: a
manifest touched or titled reads none of it, and the title from the
first prompt stays; a message changed, the same size at a later time, a
fork added and the start moved each read it again.
Broken by hand: no resume -> red ("manifest touched: messages read
again"); the start and fork not compared -> red (read on differs from
whole, after the fork); the carried prompt dropped -> red (read on
differs from whole).
Run: go test ./internal/sessions -run Cline -count=1 ok, and the whole
package green at the previous commit; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
|
||
|
|
b3642e7277 |
sessions: a dsh session read before is read on from where it was left, not whole
dsh only appends to a session file, a line at a time or, packed
(.zstd), a frame of lines at a time. Every reply still made the
Sessions and Usage pages read, and for a packed file decompress, the
whole file again: a packed file "can't be read on from the middle of a
frame".
It can be read on from the start of one. frames.go walks a file of zstd
frames without decoding them (RFC 8878: the frame header, then blocks
that each give their length, then the checksum), decodes one frame at a
time, and says where to go on from: the frame the first line not yet
whole starts in, and how far into what it holds. A frame not yet
written whole waits for the next read, and so does a line a frame ends
inside of.
parseDsh keeps a tail (tail.go) and the header it read, and counts each
event as it comes (dshCount) instead of collecting them all first. A
fork's inherited end-seed met in a later read starts the counts over
from the session's start, keeping its title and name, as the whole read
did by cutting at the last one. A file that shrank or was replaced is
read whole again. One change from before: a last line not ended by a
newline now waits for it, like every other appended file's.
Measured (CPU, getrusage; 50 MB of events, a reply appended between
reads; packed: 17 MB of frames; machine loaded):
plain before: ~110-120 ms per read after an append
after: 0.4-2.6 ms per read after an append; first read ~120 ms
packed before: ~190-250 ms per read after an append
after: 0.4-0.5 ms per read after an append; first read ~260 ms
Tests: TestDshReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases.
TestDshPackedReadsOnlyWhatWasAppended appends a frame (read alone), half a frame (waits), a
frame ending inside a line and the frame that ends it (read on from the
first of the two, the line counted once), then cuts the file short and
replaces it with a longer one (read whole). TestDshEndSeedAcrossReads
writes a fork's seeded lines, its end-seed and its own, a read apart
each. Every read on is checked equal to a whole read.
Broken by hand: resume off -> red in both ReadsOnly tests ("after a
line appended to 1308 bytes, read from 0", "after a frame appended to
654 bytes, read from 0"); a line split over two frames resumed at the
second frame -> red (read on differs from whole); the end-seed reset
removed -> red in TestDshEndSeedAcrossReads and TestDsh.
Run: go test ./internal/sessions -count=1 -timeout 45m ok; gofmt -l
and go vet ./internal/sessions clean. The full-suite record is in the
last commit of this series.
|
||
|
|
e03d495f83 |
sessions: a Kimi Code session read before is read on from where it was left, not whole
Kimi Code only appends to a session's wire.jsonl, but every message (and
every rewrite of its state.json, whose size and mtime are folded into
the wire's) made the Sessions and Usage pages read the whole wire again,
a fork's twice: once for its last marker, once to count.
parseKimi is now one pass that keeps a tail (tail.go) and what the read
carries on with: the session's start, whether it is a fork, and the
fork's marker time. A forked marker met in a later read starts the
counts over from it, as a whole read does. Title, cwd and name still
come from state.json on every read, so a state.json-only change reads
none of the wire. A forkedFrom set or cleared reads whole again, and so
does a wire that shrank or was replaced; a half line waits.
Measured (CPU, getrusage; 50 MB wire, a message appended between reads;
machine loaded):
before: ~256-278 ms per read after an append (same as the first read)
after: 0.3-0.6 ms per read after an append
Tests: TestKimiReadsOnlyWhatWasAppended runs the shared append, half
line, cut-short and rewritten-in-place cases on a real wire's events,
then a state.json title change (nothing of the wire read) and a
forkedFrom set (read whole). Every read on is checked equal to a whole
read. TestKimiForkMarkerAcrossReads writes a fork's copied lines, then
its marker, then its own usage, a read apart each: only the fork's own
usage counts.
Broken by hand: resume off -> red ("after a line appended to 29089
bytes, read from 0"); the marker's reset removed -> red in
TestKimiForkMarkerAcrossReads and TestKimiCodeSessionFork.
Run: go test ./internal/sessions -count=1 ok; gofmt -l and go vet
./internal/sessions clean. The full-suite record is in the last commit
of this series.
|