31da93ccdca03073513d2e1d73efdfd50bd14f6a
193
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
de54b4ff99 |
codex: threads started on OpenAI are listed while magpie is Codex's provider
notnico64 on Discord (Linux, magpie desktop): with Codex connected to
magpie, `codex resume` said "No sessions yet". Codex's resume picker
(tui/src/resume_picker.rs picker_provider_filter) lists only threads
whose model_provider is the one Codex is on now, with no opt-out, and
the filesystem scan checks each rollout's session_meta, not just the
state DB row. With no ChatGPT sign-in (also an API key, magpie API, an
account out of allowance, another machine/WSL) magpie writes
model_provider = "magpie", so every thread started on "openai" vanished
from the list. Nothing in it is Linux-only; macOS does the same.
Now, when magpie becomes Codex's provider and Codex was on OpenAI
before (not on a provider of the user's), the threads on "openai" move
to "magpie": the state DB row and the rollout's session_meta, rewritten
in place (both ids are 6 bytes), the file's mtime kept so the picker's
order holds, with no trash copy. At the Disconnect bringBack relabels
them back the same way before its usual mover. Threads Codex has
already packed (.zst, a week after the last turn) are left alone:
rewriting gigabytes of history at a switch isn't worth it (the owner's
~/.codex/sessions is 51GB, 11,591 of 12,255 rollouts packed). Files
written within ActiveWindow, outside this Codex home, or without their
id in the name are skipped too.
Run:
- Real Codex 0.162.1 in a sandbox HOME/CODEX_HOME (never ~/.codex):
without model_provider the picker listed only the openai thread;
with model_provider = "magpie" only the magpie one (the report).
After RelabelCodexThreads(home, "openai", "magpie") the same picker
listed both threads.
- TestCodexThreadsFollowMagpieIn (new) is red on the old code:
"connected: thread ...c1 on "openai", want "magpie"".
- go test -tags nogui -timeout 45m ./internal/agent ./internal/sessions
at this head: ok agent 480s, ok sessions 41s (rebased on
|
||
|
|
b30734f964 |
sessions: Antigravity CLI (agy) conversations are listed, with title, folder, tokens and resume (RickyWei, #1718)
agy's conversations were on no Sessions page: internal/sessions had no lister for them, only the calls reader of #2097. Now each ~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript_full.jsonl is a session (agy.go). Its steps give the start and last times, the first prompt (taken out of agy's <USER_REQUEST> wrapper), prompts, replies, tool calls, and tokens under the model "agy", since no step names one. A step written again replaces its tokens, read on or read whole. The title and folder come from the conversation's conversation_summaries.db row: title, and workspace_uris through agyFolder, which turns file:///C:/... and file:///c%3A/... into C:\... and a host into \\host\share on Windows. agy writes the title after the transcript, so the row is the file's rev. The database is read again only when it or its -wal changed, and a failed read keeps the rows read before. A row with conversations/<id>.db and no transcript (#1718's case) is listed from the row alone, with no tokens and no conversation to open. Resume is "agy --conversation <id>". When agy is set to use magpie, it is the agent's launch command (gateway variables and --model, the PowerShell form on Windows) with --conversation after it, through sessions.AgyStart, which package agent sets. The transcript (user text, thinking, text, tool calls, tool results) can be opened and searched. Format read from real files: agy 1.3.5 and 1.4.7 in a sandbox HOME against a fake Gemini endpoint, with plain replies, a read_file tool call with thinking, invalid tool calls, and a conversation picked up again with --conversation from another folder. testdata/agy-sessions is three of those conversations with paths rewritten to /work. Resume tried for real in the sandbox: `agy --conversation <id> -p again` from another folder appended steps 2-4 to the same transcript and kept the row's folder. Interactive `agy --conversation <id>` (in tmux) showed the earlier turns. Run at this tree, rebased on origin/main: - gofmt -l internal clean - go vet: darwin; GOOS=linux -tags nogui; GOOS=windows - GOOS=windows go build ./...; GOOS=linux go build -tags nogui ./... - go test -count=1 ./internal/sessions ./internal/gui ./internal/agent: ok before the row-only change. After it, sessions ok, and gui had one red, TestMainWindowCorners killed at its 40s deadline at load ~300 (#1936). It passes alone (47s). - GUI (playwright 1.62.0, chromium and webkit, en and zh): i18n-keys, gui-de, gui-ja, gui-zh-tw, session-terminal, sessions-bar-names, sessions-manage, sessions-talk, sessions-toolbar: 49 of 49. No GUI asset changed. Tab names come from the agent registry. Fails without the change (broken by hand, each one red): - agyFiles out of allFiles: TestAgySessions, TestAgyTitleLater, TestAgyTranscript - agy out of refresh's DBRevision check: TestAgyTitleLater - no dropUse of a rewritten step: TestAgyGrows (4510 input, want 3010) - AgyStart ignored: TestAgySessions (wired resume) - drive letter not handled: TestAgyFolder - agy out of HasTranscript: TestAgySessions, TestAgyTranscript - the row-only listing off: TestAgyRowOnly; readable() off: TestAgyRowOnly Not tried: agy on Windows. The Windows box (10.0.0.132) didn't answer ssh, so the Windows paths are covered by unit tests only (agyFolder, the Set-Location resume form). A wired resume through magpie's real gateway was not tried. Not done: subagents (parent_conversation_id), which I never saw agy write. The model name, which is only in conversations/<id>.db's protobuf (#3147). Deleting an agy session from magpie. agy in WSL: #3595. Side effect: agy's self-updater ran in the sandbox and replaced the live ~/.local/bin/agy, 1.3.5 -> 1.4.7. |
||
|
|
120264a49f |
sessions: a Codex line's marks are read in one pass, not one bytes.Contains each (#3493)
callHead and codexCallLine asked of every rollout line, with a
bytes.Contains each, whether it held "type":"user_message",
"role":"user", "type":"function_call_output" and nine more: up to twelve
passes over the line in each, a line of megabytes of tool output
included. A CPU profile of a cold usage read on Windows (20,807 Codex
rollouts, 44GB, magpie web in a sandbox home on the Windows box) put 37%
of its 270s of samples in that bytes.Contains (indexbody).
cxMarksOf reads them all in one pass: it walks each `":"` that ends a key
(in a JSON string the quotes are escaped, so never one inside a string),
and records the "type" values and the user's role it finds. It finds
what each value's own pass found: the same line, anywhere in it.
Run:
- TestCxMarksAsContains: twelve lines (long escaped strings holding the
values, a nested value past a long string, "subtype"/"xtype" keys,
"role":"users", empty and cut lines) give the same marks as a
bytes.Contains of each. Red when the role is not recorded (3 lines).
- Every line of the owner's real ~/.codex/sessions, read only: 619
files, 20,059 lines, 4.3GB, 0 lines whose marks differ.
- BenchmarkCxMarks, a 1MB exec_command_end line: 0.36ms a line, from
11.2ms.
- Windows box, cold (.cache\magpie removed), magpie web, 3 rounds each,
alternating, origin/main
|
||
|
|
c26a418d23 |
agent: an import app's status magpie can't read is unknown, not "not added"
Agent.Added now returns (added, known). Cindy's reader turned any
failure (a locked, corrupt or unreadable cindy-local-v1.db) into "Not
added", which told a user who had added magpie that they hadn't. Now
an unreadable database is unknown: /api/agents leaves `added` out and
the row shows the "confirm it there" hint, as it does for Lody. A
stopped WSL distro's app is unknown too, not "not added".
Cindy's database is also read without writing beside it. A mode=ro
open of a WAL database while Cindy was closed made cindy-local-v1.db-wal
and -shm in Cindy's own folder. It now goes through
sessions.OpenUntouched, which is what the Cursor reader already did
(immutable with no log, from a copy with one), moved out of
openCursorStore so both share it.
The CLI's list still offers `magpie cindy add` when the status is
unknown; it never said magpie was missing.
Run: go test ./internal/agent ./internal/sessions ./internal/cli ok;
go test ./internal/gui -run 'Import|Lody|Cindy|Agents' ok.
Broken by hand: Cindy's reader put back on the mode=ro open made
TestCindyHasClosedWALAndUnreadable red ("Cindy's folder changed:
cindy-local-v1.db -> cindy-local-v1.db,cindy-local-v1.db-shm,
cindy-local-v1.db-wal"); api.go ignoring `known` made
TestImportStatusUnreadableIsUnknown red. Both restored, both green.
Not tried: a real Cindy install; the read is tested on fixture
databases only.
|
||
|
|
67a137744f |
sessions: a call shard is written in frames of 2048 calls (#3493)
writeCalls wrote a shard's whole state as one frame, whatever its
size. The largest Codex session on the test copy (52,500 calls) was one
8MB gob frame, and decoding it allocated ~100MB and held ~70MB at once,
which is most of the gap between a cold warm-up's memory peak and a
warm one's.
A write now splits its patches into frames of framePatches (2048).
Every frame but the last has More set, and each carries Calls, the
file's call count after the write, so loadCalls sizes its slice once.
A file whose last frame has More was cut off mid-write and reads as
nil, the same as a bad CRC. A shard read from a frame over
framePatches (the old format) is written again in frames once, at its
first load (loadKept), so existing caches shrink their peak too.
Run at this tree (
|
||
|
|
04439c8592 |
sessions: the warm-up lists the Codex rollouts once for all its reads (#3493)
The warm-up at start ran three reads within about two seconds: the stats of every day, the stats of 30 days and the Requests page. Each listed every Codex rollout again through codexFiles, about 12k lstat()s and ~47 MB allocated a time. codexFiles now keeps its listing while only the warm-up reads (quiet: inside Warm, no page asking) and for 10s at most, the age statsFor's memo already answers with. Each caller gets its own copy. A page asking meanwhile, and every read outside the warm-up, lists fresh, and Warm drops the kept listing when it ends. Measured on the owner's real sessions (sbpairs: Claude Code and Codex history, warm index), the gui warm-up harness inside sessions.Warm, run alternately with the parent |
||
|
|
b686a8dfec |
sessions: a call shard's frames are read into a buffer kept between shards (#3493)
A cold Requests build (the first start after an update that changed the usage package's source, so the request chunks are made again) reads every call shard, ~15.7k on the real data copy. Each frame was read into a new byte slice and decoded into a new callFrame, so gob made a new Patches and Strings slice for every one. loadCalls now takes a frameBuffer from a pool. gob decodes a slice that has room in place, and leaves a field of the zero value as the field was, so each patch and string of the last frame is cleared before the next is decoded in. Nothing read out points into the buffer: gob copies strings and byte slices, and a patch's call is copied into the file's calls. Measured on the real data copy (sbpairs), warm-up harness TestZZWarm, requests-v1.bin removed before each run so every run is a cold build, three runs each: allocated through step 3 2139/2214/2182 MB -> 2001/2041/2044 MB loadCalls (cum, step 2) 781 MB -> 583 MB peak footprint 374-441 MB -> 371-419 MB, within noise Warm starts unchanged (step 2 ~690 MB either way). Run at this head: go test ./internal/sessions ./internal/usage ok; -race -count=2 of the LoadedCalls, CallCache, Shard and Frame tests ok; GOOS=linux and windows go vet -tags nogui ./internal/sessions ok; gofmt clean. TestLoadedCallsKeepNothingOfTheLastShard reads a shard with tokens, a session and a compaction, then one with none, three times; broken by hand (the patches not cleared) it fails. Not tried: Linux and Windows real-data runs. |
||
|
|
15f0d4cdeb |
sessions: a Claude Code session goes on in Codex, and a Codex one in Claude Code
0xPlato on X asked for conversations to carry across agents, at least on
one machine. A session row's Continue in (换 Agent 继续) now offers Codex
for a Claude Code session and Claude Code for a Codex one, when the other
is installed. Picking it converts the session then: a new session in the
target's own store, which its own resume opens. Listing converts nothing.
- Claude Code to Codex: a rollout in CODEX_HOME/sessions/YYYY/MM/DD with
session_meta (model_provider from config.toml now, no
base_instructions, so Codex uses its own), response_items and the
event_msg user/agent messages the TUI shows. Codex indexes it on
resume itself.
- Codex to Claude Code: CLAUDE_CONFIG_DIR/projects/<cwd>/<uuid>.jsonl,
lines chained by parentUuid, assistant model "<synthetic>" so usage
counts no call for them.
- Carried: user and agent text, pasted images, shell calls natively
(Bash and exec_command) with their output, other tools as the agent's
text (name, input, result in fences, cut at 64 KiB). Dropped: thinking,
reasoning, signatures, encrypted content, Claude Code's own and Codex's
context messages. After a compaction only what replaced the history.
- The source is only read. The new file goes through temp, sync, rename
and never over an existing path. Asking again for an unchanged file
gives the same session (memo by path, target, size, mtime).
- POST /api/sessions/carry {agent, id, to, open}: copies the resume line,
or with open (Mac app) opens it in the session terminal. The details
pane's Continue in line converts from its copy button too.
- Read-only and WSL sessions get no offer. Pi, omp, OpenCode, Kimi,
Cursor and the rest are not converted.
Run (worktree at
|
||
|
|
b027ca264d |
sessions: a pass over every session looks at Codex's title index once (#3493)
assemble and assembleListed asked CodexTitles for each Codex session, and each ask took the index's lock and stat'ed session_index.jsonl. A start's stats step assembles every session, so on the owner's data (sbpairs copy: ~10G Claude, ~50G Codex rollouts) CodexTitles was 60ms of step 0's 860ms CPU profile. codexTitleOf gives a pass one function that looks at the index on its first ask and again only when another reader loaded a different index in between; every caller of assemble and assembleListed makes one per pass, beside its pricer(). Run at this head (rebased on origin/main below): - zzwarm step 0 CPU profile on the sbpairs real data: CodexTitles, codexTitlesAt and loadCodexTitles 60ms -> absent; statsRead 340ms -> 270ms cum. Wall times at load 40-76 were within noise both ways. - TestCodexTitleOfLooksOnce: no index, an index made mid-pass not seen in that pass, seen in the next, a rename mid-pass keeps the first name. Broken by hand (re-ask on every call): red at "an index made after the first ask". - go test ./internal/sessions ./internal/usage ./internal/gui ok; -race ./internal/sessions ok; GOOS=linux/windows go vet -tags nogui ./internal/sessions ok; gofmt clean. Not changed: gui's own CodexTitles callers (trace.go, context.go) ask for a few ids at a time already. Not tried: a Linux or Windows real-data run. |
||
|
|
73d17f90ce |
codex: every CODEX_HOME folder's sessions count, its account renewed there
phantom3792 on X: with several ChatGPT accounts kept the way Codex supports, magpie counted only the default profile's usage, and the accounts added from the other profiles read no quota. Codex's mechanism, from openai/codex at 970111f6cb62: - One sign-in per folder. In codex-rs/login/src/auth/storage.rs the sign-in is $CODEX_HOME/auth.json, or the keychain item that compute_store_key(codex_home) names. - Sessions live in the same folder. rollout/src/lib.rs writes sessions/ and archived_sessions/ under codex_home. - `--profile <name>` only lays $CODEX_HOME/<name>.config.toml over config.toml (config/src/loader/mod.rs), and the sign-in stays shared. So a second account is Codex run with CODEX_HOME=~/.codex-work, and magpie read only the folder it runs with. There were two causes: - Sessions: codexFiles() walked CodexDir() alone. The sessions list, traces and the usage ledger (sessions.Calls) never saw other folders' rollouts. - Quota: an account added by importing another folder's auth.json is refreshed from magpie's copy. The import rotates the refresh token, which leaves two holders of one token, and whichever refreshes first signs the other out. The saved account goes "sign-in has expired" and its quota read fails. The fix: - appdir.CodexHomes finds the folders: CodexHome first, then folders named codex* or .codex* in the home folder or beside CodexHome, or one level down in one (~/.codex-profiles/work), that hold auth.json or sessions/. - sessions: codexFiles and Dirs read every folder. - provider: rememberLogins saves each folder's account with Home set to it (codexHomeLogins). The one ~/.codex is signed in to stays that folder's. - renewSaved renews such an account where that folder's Codex keeps it (codexHeldIn, as heldByCodex does for ~/.codex). This one funnel covers quota, gateway, warm-up, keep-alive and revoked sign-ins. codexLoginAuth reads its expiry from the same place. - switchSavedLogin, NextLogin's spares and forgetLogin leave such an account alone. Their errors name the folder and the CODEX_HOME=... codex command. - docs/subsystems/providers-accounts.md gains a row. Run (worktree at |
||
|
|
13f9070135 |
sessions: a kept file of one day holds that day's models once (#3493)
A long history's kept parses held 28MB live after a start's decode of
sessions.json (15,624 files). 15,345 of them have exactly one day, and
that day's model map is the file's own, so every such file held two
equal maps of ~700B each. decodeCache's share now points the day at the
file's map when they are equal.
A kept state is never written: use, unuse and dropUse are the only
writers of Models, and every parser (sessions.go, calls.go, calls_dsh,
dsh, droid, grok, kimi, cline) writes a clone, which copies the two
maps apart.
Run, at this head on
|
||
|
|
42ab935516 |
usage: requests-v1.bin is of the code that makes rows, not of the binary
The file of the session files' chunks was named by the binary's own
stat key, so every upgrade, and magpie ships several a day, read every
session file again on its first Requests page: on a 15.6k-shard history
warm-up step 2 went from ~0.8-0.9s (read from the file) to 1.6-1.9s and
~1.3GB more allocation. It is named now by the call shards' version
(sessions.CallCacheVersion, which already decides whether a shard of the
calls is read) and a SHA-256 of this package's non-test source, which
the binary carries (go:embed *.go, ~750KB with the tests, which the name
leaves out). Of the last 99 releases, 17 changed that source; the other
82 keep the file. Prices, names and settings are in the file's meta as
before. When the embedded source can't be read the name is the binary's,
as it was.
Measured (real history, sbpairs): one test binary wrote the file, a
second binary at another path (the old key differs) read it: step 2
0.79s and 1001MB alloc, against 1.63s and 2285MB cold.
Run at this tree (
|
||
|
|
89dc164765 |
sessions: sessions.json is written a file's parse at a time
A save marshalled the whole index into one buffer: 22.8MB for a long
history (15,624 files), grown by doubling to ~85MB of allocation a save,
and a save follows every refresh that read a changed session file, so a
start while agents run, and a Sessions or Usage poll after any call. It
is written through a json.Encoder into a 256KB buffer handed to a 1MB
bufio.Writer on the temp file, keys in json.Marshal's order and escaped
as it escapes them, so the file is the same bytes.
Measured on the real sessions.json (sbpairs, 22,836,803 bytes):
json.Marshal 54-73ms and 85MB alloc; encodeCache 51ms and 14MB alloc;
the output equal byte for byte.
Run at this tree (
|
||
|
|
ce60cb9908 |
sessions: TestDecodeFrameKeepsDefinitions is skipped under -race
The test counts what a kept gob Decoder saves, and under -race sync.Pool
lets a quarter of what is put in it go, so the kept Decoder is often a new
one: 158 allocations a frame against 478, over the 1/4 bar. It skips on
raceOn as the package's other pool tests do (TestScanFramesReadsALongFrameOnce).
Run: go test -race -count=1 ./internal/sessions: was red on this test at
|
||
|
|
432393217a |
sessions: a shard's gob definitions are compiled once, not once a shard (#3493)
Every call shard's frame is its own gob stream: callFrame's type definitions, then the frame. loadCalls made a gob.Decoder for each, so each of a start's ~15.6k shards compiled the same definitions again. A cold Requests build (every upgrade, since requests-v1.bin is keyed on the binary) spent ~400 MB of its allocation and most of its GC there. decodeFrame keeps one Decoder in a pool along with the definition bytes it has read, and hands it only the value message when a frame's definitions are byte for byte those. A frame of other definitions gets a new Decoder; a Decoder that failed is dropped; bytes left over after the frame are an error, as before. Measured on a copy of real data (15,656 shards, 117 MB), cold step 2 of the GUI warm-up (QueryPage(All)): allocation 2190 -> 1968 MB, CPU 5.51 -> 3.92 s, maxrss 448 -> ~410 MB. Wall stays ~2.2-2.6 s: the serial row building on the consumer goroutine is the limit, next. Run at this head ( |
||
|
|
94503901c0 |
sessions: a string many kept files repeat is held once
decodeCache's Unmarshal made a string for every file's title, cwd and model names, however many files gave the same one. On the real history copy (sbpairs, 27,699 kept files) 23,689 sessions a script ran carry one ~420-byte prompt as their title. The kept parses held 54 MB after a collection, 11 MB of it such copies. Each decode worker now takes those fields (title, cwd, first, named, model, provider, msg_model, msg_day, codex_nickname, and the Codex identity's role and parents) through unique.Make, so the parses hold 44 MB. The decode took 104-114 ms, as it did (121 ms when measured for |
||
|
|
e2dbb03405 |
sessions: the kept parses are decoded on a few goroutines at start
One json.Unmarshal of sessions.json (40MB, 27,679 files on a long
history) took 310 to 440ms of every start before the first page (#3493).
decodeCache checks the file is valid JSON (gjson), reads its version and
zone, splits the files without copying them, and decodes each file's
parse with json.Unmarshal on up to 8 goroutines. The result is what one
Unmarshal gave: a key given twice is its last, and the file is refused
where it was refused (bad JSON, another version or zone, no files, a
parse that doesn't decode). Only the keys are copied out of the read.
Real data (sandbox copy of the live sessions.json, load ~60): Unmarshal
311ms, decodeCache 121ms, reflect.DeepEqual the same 27,679 parses.
Run at
|
||
|
|
500aa70965 |
sessions: listing the session files stats them on a few goroutines and sweeps the shard folder once a minute
Every Requests page lists every session file again
(CallSourcesAndCodexIdentities), and on a busy machine that listing was
most of a warm page after the pairing memo (#3493): ~130ms for 15.6k
Codex rollouts and the Claude Code transcripts, of which the lstat of
each rollout was half, stat()ing each Claude file a sixth, and
pruneCalls a sixth: it read the ~16k-shard cache folder and sha256'd
every path on each call.
- statFiles stats the files a walk found on up to 8 goroutines (from 512
files), keeping the walk's order and leaving out what is gone or no
regular file, as before. Codex's still take their info from the walk's
entry (free on Windows), Claude Code's from os.Stat.
- pruneCalls still drops the in-memory entries of gone files each call,
but looks over the shard folder (and hashes the paths for it) at most
once a minute, and at once when the cache folder moved. Temps already
waited an hour; an orphan shard waits up to a minute more.
Run at
|
||
|
|
22a7f86c9b |
sessions: the Requests page walks the Codex folders once a rebuild
readRequestState asked CallSources and then CodexIdentities, and each walked ~/.codex/sessions and archived_sessions, lstat()ing every rollout. Over the 12,069 rollouts of a real Codex folder that was two walks of ~75ms on every rebuild, which runs on each 5s refresh while an agent works. CallSourcesAndCodexIdentities walks once and hands the list to both; CallSources and CodexIdentities stay as they were for their other callers. Run at this head: - go test -timeout 45m ./internal/sessions ./internal/usage ./internal/usageapi: ok. TestCodexIdentityParentChainsAndSummaryCache now checks the one-walk pair equals CallSources and CodexIdentities. - GOOS=linux and GOOS=windows go vet -tags nogui on both packages, gofmt. - Real data (sandbox HOME over the owner's ~/.codex, 12,069 rollouts, ~416k rows): CPU profile of two rebuilds, codexFiles 0.31s before, 0.12s after. Wall times on a loaded machine were 1.0-2.1s both ways, too noisy to compare. Not tried: Windows or WSL folders (wslFiles is still walked as before). |
||
|
|
0e643b14e4 |
sessions: a screenshot's line is read thinned, not gathered whole (#3318)
A cold read of the sessions gathered every long line it read whole
(takeLong), to take a timestamp, a folder and a session id off it. In a
10GB Claude projects folder and a 50GB Codex sessions folder the lines
behind that were Claude Code tool results holding a screenshot twice
(message and toolUseResult), Claude Code's api-request-blob lines (up to
15MB) and 154 Codex prompts with screenshots (5 to 15MB a line). Spread
over the read's workers they held 130 to 154MB live at its peak.
scanThin hands such a line on thinned, a chunk at a time, never whole:
- Claude (summary and calls): a user line whose message is a tool result,
or a line of Claude Code's own other than a title or summary (both read
only for keys, timestamp, folder and session id), has every string cut
to 4KB.
- Codex (summary): a line the head lets through has only its data: URLs
cut; a prompt's text is kept whole.
Every byte outside a string is kept, an escape is kept whole or not at
all, and a cut never splits a rune, so the line stays JSON and a search
for a quoted key finds what it found before. Lines over maxLine are still
passed over.
Run:
- TestThinnerKeepsJSON: 200 rounds of random chunk splits (1 to 7 and up
to 9000 bytes) over a line with escapes, \u surrogate pairs and CJK;
red when escapes are ignored.
- TestThinToolResultReadsTheSame: claudeLine (main and not) and
claudeCallLine give the same state thinned as whole over two 3MB tool
results; a thinned read allocates under 3MB (red at 7.9 to 8.4MB with
the thinning off).
- TestThinCodexKeepsPromptText: codexHead+codexBody give the same state
with a 3MB image cut, the 21KB prompt kept whole; red when every
string is cut.
- go test ./internal/sessions ./internal/gui ./internal/usage
-timeout 45m: sessions and usage ok; gui red in
TestRestartHandsTheGatewayOver (12 of 13 requests answered, a reset),
which is #3451; alone -count=3 ok.
- GOOS=linux and windows go vet -tags nogui ./internal/sessions, gofmt.
- Real use: magpie web --gateway under a sandbox HOME whose
.claude/projects and .codex/sessions are the owner's real ones (10GB
and 50GB), caches cold, /api/sessions?limit=50 then the 7 and 30 day
overview (load ~40 on the machine):
before (
|
||
|
|
ccf403bda9 |
sessions: the Sessions list keeps a Claude file's window in sessions.json, read on after a restart (#3493)
The summary's Claude revision window (state.Claude) was json:"-", and a Claude file's parse with no window starts again from byte 0. So after every restart, which is every update, the Sessions list read each grown Claude session from its first line: the live 2 GB session on the owner's machine took seconds of the first list. state.Claude now goes into sessions.json as its bounded window (claudeUsageState MarshalJSON/UnmarshalJSON, the entries in eviction order; window() and claudeWindowOf are shared with the calls .rev sidecar). It is bounded by claudeRevisionEntries and trimSummaryRevisions as in memory. A sessions.json from an older magpie has no "claude" and reads from the start as before; an entry without a contribution is skipped, so a bad window never loses the whole index. #697 kept message maps out of the index because they were unbounded; the window is bounded now, so TestClaudeNativeReplayAcrossReadersAndRestart checks the kept window's weight instead of its absence, and TestQoderUsageAfterWindowLoss's restart case strips "claude" from sessions.json to stand for an older index. Real data (a sandbox HOME with the owner's real ~/.claude and ~/.codex, read only): cold Sessions list after a restart with the live sessions grown, 6.3s with the 2 GB file reparsed -> 0.77-0.96s over three runs, only small subagent files reparsed. sessions.json: 7 windows, ~1 MB of 21.7 MB. Run at this tree: go test -count=1 -timeout 45m ./internal/sessions ./internal/usage ./internal/usageapi ./internal/gui ok (sessions after the two test updates); go test -race ./internal/sessions ok; GOOS=linux and windows go vet -tags nogui ./internal/sessions ok; gofmt clean. TestClaudeSummaryReadOnAfterRestart is red with the tag back at "-" (the summary is read again from its start, its marker lost). |
||
|
|
ff6f3188bd |
sessions: a grown Claude file is read on after a restart, with the window it had (#3493)
A Claude Code session's revision window lived in memory alone, so after
magpie started again (every update), or let a ninth live session's
window go, each Claude file that had grown was read again from its
first line. On the owner's real ~/.claude a live 2 GB session and a
372 MB one were read whole for the first Requests page: 2.4 GB, 7.4s.
The window is bounded (claudeRevisionEntries), so readCalls now keeps
it beside the file's shard (<hash>.rev, temp and rename, ~60 KB), with
the Off and ContentHash of the read that made it. A read whose old
state has no window takes it from there when both match, and reads on.
A file no longer being worked on drops its window as before, and its
.rev with it; pruneCalls takes away a .rev whose shard is gone.
Measured (internal/gui handler, sandbox HOME with the owner's real
~/.codex and ~/.claude, 15,553 sources): the first ledger week after a
restart 7.4s -> 1.7-2.4s across three restarts; 14 .rev files, 8-67 KB.
Run at this tree: go test -count=1 -timeout 45m ./internal/sessions
./internal/usage ./internal/usageapi ok; GOOS=linux and windows go vet
-tags nogui ./internal/sessions ok. TestClaudeFileReadOnAfterRestart is
red with withCallRevisions turned off ("read again from its start"),
and checks the calls read on equal a read from the start, a revised
recent message included.
The Sessions summary's own Claude window, in memory alone the same way,
is kept by the next commit.
|
||
|
|
f8fa8147ba |
sessions: a page-asked first read uses half the cores, not twice them (#3238)
The index's cold scan with a page waiting started min(max(8, 2*NumCPU),
32) readers, as if reading waited on the disk. On an SSD decoding and
parsing is the work: on the Windows box (32 cores) a cold start over
6751 real Codex session files (15156 MB) with /api/sessions waiting
held 2154% CPU, the ~2000% the reporter saw, while other apps ran
beside it. Now max(2, NumCPU/2) readers; the quiet warm-up's NumCPU/4
slots are unchanged.
Run:
- TestAskedIndexReadsWithHalfTheCores: ok; with the old count put back
by hand it fails ("the index read 28 files at once, want 2 to 7").
- go test -count=1 ./internal/sessions/: ok (64s).
- gofmt -l clean; go vet darwin, GOOS=linux and GOOS=windows -tags nogui
clean for internal/sessions.
- On the Windows box (32 cores), a cold read of 14051 session files
(~44 GB) with a page waiting, magpie built from this commit's parent
against this one: peak CPU 1634% -> 1172% (about 900-1100% sustained),
peak working set 1612 MB -> 1108 MB, ~22s -> ~27s to read them all.
|
||
|
|
ea9454d2d8 |
usage: count two ids of one model as one, magpie model alias (SlouchyQuill507 on Discord)
A vendor names one model two ways (deepseek-v4.1-flash and deepseek-flash),
and Usage, Usage > Sessions and `magpie usage` showed two rows. Now:
magpie model alias deepseek-v4.1-flash deepseek-flash
magpie model alias deepseek-v4.1-flash (what it is counted as)
magpie model alias deepseek-v4.1-flash --reset
magpie model aliases
kept as settings.json "usageAliases" {from: to}. Off until one is written.
Ids match as routing groups match them (provider.sameModel: vendor/ prefix,
case, "_", snapshot date), at every provider; a chain is followed to its
end; an alias to itself, a loop, or a flag as an id is refused. A loop
written into the file by hand counts each model under its own id.
Display only: requests, agents' model lists, /v1/models, routing groups,
Same as and prices never read it. Each call is priced by the id it was
made under and only then counted under the alias; the alias's own price
is never put on the other id's calls, and a merged row is priced only
when every id in it is. Applied in usage summarize/direct (Models
groups), the gateway sessions projection (alias read before
gatewayCache's lock; the cache key hashes usageAliases), and
sessions.List/Get/Find/Stats (read before storeMu/mu, merged into new
slices so the memo is untouched; ModelEffort rows merged too). A failed
settings.json read keeps the last aliases read, and SetUsageAlias refuses
to write over an unreadable file (EditUsageAliases under fileMu). The GUI
settings save carries usageAliases. No GUI control.
Not aliased: the Requests ledger's per-request model and its model
filter, which show each call's own id.
Run (worktree at
|
||
|
|
85534cd078 |
codex: threads started on magpie come back to the provider Codex is on
kaizaoji on X (10-22, zwaydot's Codex thread): after using magpie with Codex and then disconnecting or editing the config, projects say their context doesn't exist, and earlier threads can't be read. Cause: Codex lists threads per provider. app-server thread/list filters on the current model_provider when the caller names none (thread_processor.rs), and the TUI resume picker does the same; no setting turns that off. magpie sets model_provider = "magpie" with an API-key sign-in, with no sign-in, with a ChatGPT account out of allowance (codex.out), in the "magpie API" login mode and for a gateway on another machine. Every thread started then is tagged "magpie" in its rollout's session_meta and in state_5.sqlite. After Disconnect (or a hand edit back to openai) Codex lists only "openai" threads, so those threads are gone from resume and from the app. Not done: routing through the built-in openai provider with openai_base_url instead of switching model_provider. The built-in requires OpenAI auth, so with no sign-in the TUI shows its login screen; with an API key Codex skips /models (#322, why |
||
|
|
60fff9a7e5 |
sessions: Droid's sessions can be deleted from the Sessions page (zachzhao1984 on Discord)
zachzhao1984 on Discord: some agents' sessions can't be deleted on the Sessions page. Droid was one of them. What changed (internal/sessions/manage.go): "droid" is Deletable. A Droid session goes to the trash whole: its transcript, its .settings.json beside it, and a subagent's two files. Nothing of another session goes with it, and Restore puts them all back. A session written to just now is left alone (ErrActive), as for every other agent. The package comment now also says why OpenCode, ZCode, Grok Build, Kimi Code and Claude Desktop (Cowork) sessions stay list-only. Guarded by internal/sessions/droid_manage_test.go (TestDroidDeleteRestore). Broken by hand: - "droid" taken out of Deletable: FAIL "droid not deletable". - The .settings.json no longer added to the session's paths: FAIL "a session just written: <nil>". The settings file isn't counted as the session's, so a write to it no longer holds the delete back. Record for this push: 13 commits on origin/main |
||
|
|
ba1dc7f975 |
tests: a decoder test counts its cheapest read, so another goroutine's allocations don't fail it (#3283)
TestPackedScanKeepsItsDecoder went red on macOS CI at |
||
|
|
9572a35761 |
usage: dsh sessions in Context go by their titles (Kumo31 on Discord)
Usage -> Context listed DeepSeek Harness sessions as "magpie-a",
"magpie-f" and so on, while Usage -> Sessions showed their titles. Real
dsh 0.2.0-rc.2 sends no session header on its chat-completions and
messages routes. The gateway therefore keys each request by
conversationID, a hash of the first user message. contextOf joined
titles on agent + session id, and a hash never matches a dsh session
id. The responses route sends session_id and was already joined.
- The dsh reader (sessions) records the ids the gateway gives a
session's requests: the first typed user/message and the
session/title-llm-request message. Each is hashed in the forms dsh
sends it: a string, and a text part with or without a cache mark.
The text goes through a JSON.stringify-compatible encoder (jsString),
because encoding/json escapes <, > and &. These ids are
Session.Convs; cacheVersion goes to 22.
- contextOf (joinConvs) puts a route that names no session under the
session its conv id came from. An id two sessions share is left as
it is. The title call merges in and is skipped as a tool-less side
call. The existing title join then finds the session.
Fixture: internal/sessions/testdata/dsh-gateway holds two real dsh
session files and the four requests that dsh sent for them to a fake
upstream: a turn and a title call on each of the completions and
messages routes, headers and body as captured. Only the cwd is
rewritten to /work/proj.
Siblings: other agents that send no session header have the same gap,
but none was run to see what it sends. Filed as #3263.
Run at bc11b8a5f (on origin/main
|
||
|
|
572a1757cc |
sessions: a path listed twice in one read is read once, so the start's warm-up no longer quits magpie (#2932)
Since |
||
|
|
c358e76607 |
zcode: on Windows, write where ZCode reads, %HOME% before %USERPROFILE%
Gearclickist on Discord: magpie connects ZCode without an error, but
ZCode on Windows never lists magpie as a provider; on a Mac it does.
ZCode 3.14.3 (the same JS in the Mac and Windows builds, diff -rq of the
extracted app.asar) picks its data folder from setting.json's dataBaseDir,
then ZCODE_DATA_BASE_DIR, then process.env.HOME, and only then
os.homedir() (USERPROFILE). magpie used Go's home, which on Windows is
USERPROFILE. With HOME set (Git Bash, MSYS2, Emacs and the like), ZCode
reads %HOME%\.zcode\v2\provider_config.json and magpie wrote
%USERPROFILE%\.zcode\v2\..., a folder ZCode never opens. On a Mac HOME is
Go's home too, so the two always met.
appdir.ZCodeHome gives %HOME% on Windows when it is set, absolute, and
the folder asked about is USERPROFILE (a folder given on purpose is
kept). The agent target, the ZCode credential and team readers and the
library target use it. ZCode's CLI database stays under USERPROFILE (seen
on Windows below), so the sessions reader is unchanged; its comment says
why.
Run:
- go test ./internal/agent/ -run TestZCode; the new
TestZCodeOnWindowsUsesTheHomeZCodeReads forces zcodeOS=windows with
HOME and USERPROFILE apart. Broken by hand (ZCodeDataIn(home) back in
zcode()): red, "ZCode's folder on Windows with HOME set: .../001/.zcode
... want .../003/.zcode".
- gofmt -l; go vet for darwin, linux (-tags nogui) and windows.
- Windows box, sandbox folders only, HOME and USERPROFILE set apart:
ZCode 3.14.3 for Windows, extracted and started there, kept its logs,
workspace and provider_config.json under HOME\.zcode\v2 and only
cli\db under USERPROFILE. The old magpie.exe's `zcode provider magpie`
wrote profile\.zcode\v2\{config,provider_config}.json (the bug); this
build's wrote home\.zcode\v2\..., beside ZCode's own files, and nothing
under the profile.
- Full suite (go test -timeout 45m ./..., one at a time on the box):
68 packages ok, exit 0, at d87be7f13 and again after rebasing onto
|
||
|
|
e68a0b1db5 |
sessions: a prompt's title reads only as far as it keeps, not through a regexp and runes of the whole prompt
title collapsed white space with regexp's \s+ over the whole prompt and
then made runes of all of it to cut at 160. A pasted file as the prompt
went through both whole: sessions.title was 0.45 GB of a cold start's
first 2 minutes (cxPrompt 334 MB, ccPrompt 112 MB). It now collapses and
counts in one pass and stops at 160 characters, then looks only for
whether anything but space follows. The result is the same: each run of
\t \n \f \r and space one space, Unicode space trimmed at both ends, a
byte not UTF-8 kept as it was in a short title and U+FFFD in a cut one.
The regexp `space` had no other user and is gone.
Run:
- TestTitleAsBefore (new): equal to the old code on the edge cases
(159/160/161 characters, \v and NBSP and U+0085 at the ends, invalid
bytes, CJK) and on 20,000 random strings of those runes.
- TestTitleOfALongPromptAllocatesItsTitle (new, a ~900 KB prompt): red
with title pointed back at the old code ("50 allocations"); green now,
at most 8 allocations and 4 KB.
- go test ./internal/sessions/ ok, and with -race ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.
|
||
|
|
4c0afc26d7 |
sessions: scan buffers and zstd decoders are kept on a small shelf across garbage collections, let go after 10 s unused
The line readers, long-line buffers and zstd decoders scans use were kept
only in sync.Pools, and a pool lets what it holds go at every second
collection. A cold start collects about once a second (155 GCs in its
first 2 minutes), so the pools were mostly empty when asked. A probe
build counted, in those 2 minutes: 611 new 1 MiB line readers, 205
long-line buffers taken from an empty pool (114 more from one too small,
833 MB in all) and 281 new zstd decoders (~3 MiB each).
A shelf keeps up to 4 of each (per line-reader size class; long lines up
to 4 MiB, longer ones still go to the pool), takes before the pool and
gives back before it, and lets everything go once nothing was taken or
given back for 10 s, so an idle magpie holds none of it. A full long-line
shelf keeps the larger buffer.
Run:
- TestLineReaderKeptAcrossCollections, TestLongLineKeptAcrossCollections
(new): with the shelves' takes removed both are red ("a 1 MiB line
reader was made again after three collections", "a 2 MiB long-line
buffer ..."); green now. TestShelfFullKeepsTheLarger,
TestShelfLetsGoWhenIdle (new, waits for the state, 10 s bar).
- go test ./internal/sessions/ ok; -race ok (the first try raced on a
test writing the idle time as a global under a live timer; it is a
field of the shelf now); -race -count=20 on the new tests ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.
- Cold start in a sandbox HOME (startheap-home, calls and sessions
caches removed), serve --web, run until the caches stop growing; both
wrote the same 6,437 files, 70,069,451 bytes. With this and the two
commits before (objectEnd, prefixHash), two runs each, alternating:
old: 12.57 / 11.92 GB allocated, 145 / 149 GCs, CPU 2:01 / 1:55,
settled at 213 / 192 s
new: 7.38 / 7.23 GB allocated, 85 / 87 GCs, CPU 1:52 / 1:50,
settled at 191 / 161 s
RSS at the end is unchanged (714-748 MB): the peak is the warm-up
listing holding every row, not these buffers.
|
||
|
|
002b4eb080 |
sessions: prefixHash reads into one pooled buffer instead of io.CopyN's
io.CopyN made a new buffer for every call, and for each of the 16
samples of a long file (64 KB a call). Every session and call log is
hashed this way on a cold start: io.copyBuffer via prefixHash was 0.78 GB
of 11.57 GB allocated in the first 2 minutes. It now reads into a pooled
64 KB array: ReadFull for a short prefix, ReadAt for each sample. A
sample short of its window is still unknown (""), as CopyN's error was.
The hash is byte-for-byte the same, so stored sample-v1 hashes still
match.
Run:
- TestPrefixHashUnchangedAndUnbuffered (new): equal to the old
CopyN code at 0, 1, 4095, 4096, 65535, 65536, 65537, 1 MiB and 3 MiB,
and "" past the end as before; with prefixHash pointed back at the old
code it is red, "hashing a long log allocated 65 KB"; green now (under
-race the pool drops some puts, 13 KB, so the bar is 24 KB).
- go test ./internal/sessions/ with -race ok; -race -count=5 on the new
test ok.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok.
|
||
|
|
a0f3b33b1f |
sessions: a Claude reply's tool blocks and usage are decoded from their object, not by a decoder copying the rest of the line
ccTools and ccReply's usage each opened a json.Decoder over the rest of the line, and the decoder copies what it reads ahead into its own buffer. A long tool input was copied once per tool block and once for usage. In a cold-start heap profile (11.57 GB allocated in the first 2 minutes) this was the largest site: Decoder.refill, 1.6 GB, via ccReply/ccTools. objectEnd now finds the end of the object (brackets outside strings) and json.Unmarshal decodes only those bytes, which still checks them. Run: - TestClaudeReplyDecodesWithoutCopyingTheLine (new; a 1 MiB tool input plus a Skill tool through claudeLine): red on the old decoder path, "a 1024 KB reply allocated 4100 KB to read"; green now, under 256 KB. - TestObjectEnd (new): nesting, braces and escapes in strings, unterminated, a leading space, empty. - go test ./internal/sessions/ ok, and with -race ok (79s); -race -count=5 on the new tests ok. - gofmt -l clean; GOOS=linux and GOOS=windows go vet -tags nogui ok. |
||
|
|
efd1b697e4 |
sessions: a cached file's calls are read into a slice made for them
loadCalls appended each decoded patch to a nil slice, so every cached
file's calls grew through append's steps. In a warm start's 30s
alloc_space profile (sandbox HOME, ~380k calls) that append was 509 MB,
the largest single site. Each frame now grows the slice once by its
patch count (slices.Grow), which a frame of new calls fills exactly.
TestLoadedCallsAreSizedOnce: 3000 cached calls came back in a slice of
3246 on the old code (red, run with the change stashed); 3006 now, the
allocator's size class. It also reads back a second appended frame.
go test -tags nogui ./internal/sessions/ ./internal/usage/: ok.
At 8b48dc5d6 (this commit and the two beside it, on
|
||
|
|
4896fc3ba1 |
codex: a thread magpie compacted goes on after magpie is quit or disconnected (LukeMa on X)
When magpie answers Codex's compaction itself (a magpie model, Codex's
own models through magpie's accounts, a CC Switch table), the item it
returns carries encrypted_content "magpie1:"+base64(summary). Codex keeps
it in the rollout (a response_item, and the compacted checkpoint's
replacement_history) and replays it with every later turn. Sent to the
ChatGPT backend directly, it is refused: "The encrypted content for item
cmp_magpie_1 could not be verified ... invalid_encrypted_content"
(probed with a real request on gpt-5.6-luna; the same summary as a user
message was answered).
Codex's remote compaction v2 keeps exactly one Compaction item, so magpie
can't answer with a plain message instead. sessions.PortCodexRollouts
writes each of magpie's items in a rollout as the message it stands for
(codexsummary.Message: Codex's summary prefix, a newline and the summary,
as a user message), which is what Codex's own local compaction stores and
what the gateway already sends in its place, so it reads the same through
magpie and goes on without it.
- Only magpie's compaction items change; other lines keep their bytes,
the file its line count, mode and time. An unreadable one is left out
of a list with its replacement_history_metadata entry, as Codex's own
ghost-snapshot strip does.
- Published as Codex publishes a compressed rollout: temp file and
rename, under thread-writer-locks/.coordination.lock and only with the
thread's lock free. A thread a Codex has open is left for a later pass.
A Codex home without thread-writer-locks is left alone.
- .jsonl.zst rollouts are read and written packed.
- Passes: 2 minutes after the GUI or magpie serve starts and every 10
minutes; on Codex Disconnect (3s); as the GUI quits (3s). The first
pass reads rollouts written since 2026-09-24; later ones only what
changed since the last whole pass, plus what was left held
(codex-portable.json in magpie's folder).
Run at this series' head (on origin/main
|
||
|
|
10939ebdf1 |
sessions: a dsh frame is read into one buffer of its own size
scanFrames reads a dsh session (zstd frames, a batch of whole lines
each) frame by frame, and readFrame took each frame's bytes by growing
its buffer a block at a time (blocks are at most 128 KiB). A frame with
a pasted image is megabytes long, and growing to it by append allocated
several times what it read (3.7 times on the first case below).
- frameSize finds a frame's length from its headers alone (frame
header, then each block's 3-byte header, then the checksum), read
ahead with ReadAt without moving the file, and readFrame makes its
buffer that large at once. The buffer is still reused across frames.
- frameHeaderLen and blockLen are readFrame's own header arithmetic,
moved out so both read the format the same way.
- A skippable frame, or one the file doesn't hold whole yet, has size
0, and readFrame reads it as before: a frame still being written
waits for the next read, and a size that turned wrong (the file
rewritten in between) only makes the buffer grow again.
scanFrames runs on dsh session reads (dsh.go's session list and
calls_dsh.go's calls), cold once per file and then on from the last
frame read.
Measured (TotalAlloc of scanFrames over a whole dsh file, 3 runs
each, all within 2%):
session before after
3 frames, images of 1/3/5 MiB (9.4 MB) 34.85 MB 18.93 MB
(3.69x) (2.01x)
one frame, a 6 MiB image (the test below) 38.4-39.5 MB 12.6-13.7 MB
pprof (memprofilerate 1) put readFrame's take at 24.8 MB of the first
case's 34.9 MB. What is left is the frames once and DecodeAll's output.
Tests (internal/sessions/frames_size_test.go):
- TestFrameSizeIsWhatReadFrameReads: frameSize equals what readFrame
reads for frames with and without a checksum, a 3 MiB and a 2 MiB
line, and is 0 for a skippable frame and a frame cut short.
- TestScanFramesLongLinesUnchanged: the lines scanFrames hands over
equal a whole-stream decode's, for a 5 MiB line with an empty line
after it, a 3 MiB line split across two frames, and a 1 MiB line;
and with the last frame half written, the read stops at the frame
before it and reads on, once it is whole, to the same lines.
- TestScanFramesReadsALongFrameOnce: a scan of one frame with a 6 MiB
line allocates at most the frame plus the line plus 2 MiB. With
frameSize's hint replaced by 0 (the old growth) it is red 3 of 3:
"a scan of a 6291688-byte frame allocated 38445616/39495688/39495704
bytes, want at most 14680367". Passed -count=10.
Run at this commit's tree on origin/main
|
||
|
|
bb5930b71b |
sessions: a trace poll reads a long line once, at its own size
TraceReader.Poll, which the OTel exporter runs each tick while session
export is on, read every appended line with bufio.ReadBytes through a
4 KiB reader. Every line was a copy of its own, and a line longer than
4 KiB (a function output, a pasted image in a Codex rollout) was gathered
in 4 KiB clones and then copied whole: about twice the line.
- Lines are read through the pooled line reader every other session
reader uses (scanBuffer's size, 16 KiB to 1 MiB), with ReadSlice. A
line the buffer holds is handed to the cursor in it; the cursor's
parse copies what it keeps (encoding/json copies into RawMessage and
strings), so nothing outlives the read.
- A longer line is gathered into one buffer made at its length, read
ahead with lineLen as scanAt does, and reused for the next long line
of the same poll. It is dropped when the poll returns.
- A line with no newline yet (half-written) is left for the next poll,
as before. When the read ahead finds no end the gathering stops at
once instead of growing the line first. A file rewritten between the
read ahead and the read only grows the buffer again, never cuts a
line.
Measured (TotalAlloc of one cold Poll, a fresh TraceReader over one
Codex rollout in a sandbox CODEX_HOME, 5 runs averaged, 3 runs each,
all equal to within 0.1%):
rollout bodies before after
3 turns, images of 1/3/5 MiB (9.5 MB) off 38.2 MB 28.7 MB
on 57.3 MB 47.6 MB
300 turns, 20 KB images (9.9 MB, 760 spans) off 35.6 MB 20.8 MB
on 60.0 MB 45.1 MB
pprof (memprofilerate 1) puts ReadBytes at 18.7 MB per poll before and
the new read at 9.2 MB after, exactly the long lines read once. The rest
is the cursor's own parse (RawMessage copies of payload and content),
which this change leaves alone.
Tests (internal/sessions/trace_lines_test.go):
- TestNextTraceLineReadsWhatReadBytesRead: lines and end offset equal
ReadBytes' for long lines (1/3/5 MiB, past the 1 MiB buffer), a line
of the buffer's size, empty lines, CRLF, a short and a long unended
last line, no line yet, an empty file; from 0 and from the first
line's end.
- TestNextTraceLineWaitsForALongLineToEnd: a 3 MiB line without its
newline is not read, and is read whole once it has one.
- TestTracePollOfLongLinesIsUnchanged: the spans Poll exports (bodies
off and on) from a rollout with 3 and 2 MiB images, written in three
parts that end inside long lines, are reflect.DeepEqual to those a
cursor fed the whole file's ReadBytes lines exports.
- TestTracePollReadsALongLineOnce: a poll of a 6 MiB reasoning line
allocates at most 2.5 times the line (12.6-13.7 MB over -count=20).
With Poll's ReadBytes loop put back by hand it is red 3 of 3: "a poll
of a 6291589-byte line allocated 19025024 bytes, want at most
15728972".
Run at this commit's tree on origin/main
|
||
|
|
c84864ffcc |
sessions: tests swap the time zone only after the background cache writer is done
go test -race -count=3 ./internal/sessions/ failed in TestOpenCodeSubagents: testenv.Zone (via inZone) wrote time.Local while saveCache's goroutine, started by List() in an earlier iteration, read it in os.MkdirAll -> time.Unix (sessions.go:717 -> writeCache :761). inZone, the only place this package's tests change the zone, now drains the writer before the swap and again before it is put back. The same drain written by hand in TestHermesStatsIncludesRecentUsageForOldTranscript is dropped: inZone does it for every caller. Run: go test -race -run 'TestOpenCodeSubagents|TestHermes' -count=20 ./internal/sessions/ ok (184s); before, -count=3 failed with the race. |
||
|
|
85e4c693ee |
sessions: a packed rollout's long line is gathered once, at its own size
scanAt reads a line longer than its 1 MiB read buffer as several chunks. For a plain file, |
||
|
|
9afdeb89cd |
sessions: TestManageReadsOnlyTheAgentsItShows counts parses without a data race
Its parseHook did parsed++ while refresh's readers called it from several
goroutines at once, so `go test -race ./internal/sessions/` was red on
origin/main
|
||
|
|
5466cc7604 |
sessions: a packed Codex rollout whose stamp changed is decompressed once at start, for both Sessions and Requests
The start's warm-up (gui warmSessions) parses every changed session file
for the Sessions page (statsFor -> refresh -> parse), then reads every
changed file's calls for Requests (usage.QueryPage -> prefetchSources ->
ReadCallSource -> readCalls). A packed rollout (.jsonl.zst) is decompressed
whole for each read, so when the Codex app repacked all 11,591 of them on
10-20 every one was decompressed and scanned twice (~48 GB of zstd read
twice; 75 GB of zstd allocation in 67 min, 37.8 GB on each path through
scanAt).
refresh's reader now takes a packed Codex rollout's calls along
(callsAlong) when their shard is stale too: one scanAt, each line shown to
both heads (codexHead, callHead) exactly as on a scan of its own, and
handed to codexBody and/or codexCallLine as each head asked. The calls
are then written and kept as readCalls would (writeCalls, keepCalls under
the generation check), so the Requests read that follows finds an
up-to-date shard. The ride holds the file's calls lock, taken before the
read slot as readCalls takes it, so a readCalls of the same file waits for
the ride rather than read it again, and no lock order is reversed. A scan
that fails leaves the calls to readCalls, as before. Plain rollouts, other
agents and a file whose calls are already current are read as before.
The warm-up already reads with a quarter of the cores (quiet.go: readSlot,
#1665) on both paths; this halves the work done under that cap, nothing
more is changed there.
Verified (sandbox HOME, Go caches pinned):
- TestPackedRolloutReadOnceForSessionsAndCalls (new): 3 packed rollouts
(the two fixtures + a 40-call one). Calls-then-sessions scans each twice
(the reference); sessions-then-calls with nothing kept, and again after
every file's mtime changes, scans each once, and the calls, List and
StatsAt are reflect.DeepEqual to the reference. With callsAlong replaced
by nil in refresh it fails: "first read: ...zst scanned 2 times, want
once" for all 3 files, and the same after repacking (6 errors). Restored:
ok. -race -count=20: ok.
- Real rollouts: copies of 120 and of 180 of ~/.codex/sessions' packed
rollouts (528 MB / 739 MB compressed), warm-up order (List, StatsAt, then
ReadCallSource with 8 readers), with nothing kept ("cold") and after every
mtime changed ("stamp"); old = callsAlong nil:
120 files, full speed: zst scans 240 -> 120; wall cold 0.84/0.90s ->
0.52/0.48s, stamp 0.99/0.70s -> 0.43/0.52s; alloc 0.45-0.48 GB ->
0.43-0.44 GB cold, 0.38-0.41 GB -> 0.38-0.39 GB stamp.
180 files, inside sessions.Warm (3 readers of 14 cores): zst scans
360 -> 180; wall cold 1.97/2.18s -> 1.48/1.59s, stamp 1.89/2.22s ->
1.35/1.63s; alloc 0.57-0.63 GB both ways.
Lists, stats and every source's calls, JSON-encoded, are byte-identical
old vs new in all four phases (cmp).
Allocation hardly moves: in a pprof of the 120-file run, 482 MB of ~800
MB is scanAt gathering lines longer than its 1 MiB buffer (the packed
rollouts' multi-MB session_meta lines), which only one of the two
readers ever gathered, and zstd's own history buffers are 120-144 MB.
What the change saves is the second decompression: CPU and disk reads.
- gofmt -l on the changed files: nothing. GOOS=linux go vet -tags nogui
./... ok; GOOS=windows go vet -tags nogui ./... ok.
- go test -timeout 45m ./internal/sessions/ ./internal/usage/
./internal/gui/: ok 13.8s / 17.1s / 81.7s. go test -race
./internal/sessions/: ok 44.5s after the next commit's test fix (red on
origin/main
|
||
|
|
21c2ab6fa5 |
sessions: packed session files are decompressed by decoders kept between reads
Why: a live heap profile of v0.1.1296 (pid 554, up 67 min) allocated
173 GB, 75 GB of it in zstd decoding, through sessions.scanAt from both
usage.prefetchSources (ReadCallSource → readCalls) and sessions.refresh
(parse). openLines made a new zstd decoder for every packed file it
opened, and a decoder's first frame allocates its window: the Codex app
packs rollouts with a 2 MiB window, which a low-memory decoder holds in
3 MiB, plus ~350 KB of block buffers. scanFrames (dsh .zstd) did the same
on every read on.
What was found, on 180 real packed rollouts (360 MB, copied with their
times) and the profile:
- An unchanged packed file (same size and time) is not opened again by
either path, while magpie runs or after it starts from what it saved
(Saved, Reset): 180 scans each path cold, 0 on every later round. A
changed one is read again alone.
- The 75 GB was each path's one full pass over all 11,591 packed rollouts
at the app's start, both caches invalid for them then: about 3.4 MB a
file for each path's decoder, and its 1 MiB copy buffer to pass over
what came before off.
- dsh files are already read on from their last whole frame
(TestDshPackedReadsOnlyWhatWasAppended, TestDshCallsReadOnlyWhatWasAppended).
What changed:
- openLines takes a decoder from a pool (streams) and Resets it onto the
file; zstdFile's Close Resets it to nil and puts it back. Read or Close
after Close is os.ErrClosed. IOReadCloser isn't used, since its Close
closes the decoder for good.
- scanFrames decodes frames with a pooled decoder of its own pool
(frameDecoders): a decoder that has read a stream holds its block
decoder, which DecodeAll would wait for. Its reader comes from
lineReader's pooled buffers, not a new bufio.Reader.
- scanAt passes over what comes before off in a packed file through its
pooled line reader (Discard), not io.CopyN's buffer of its own.
- Decoder options and window limits are unchanged, so what is read is
the same; an idle pooled decoder is let go by the garbage collector
with the pool, and as many are held at once as files are read at once,
as before.
Numbers:
- go test -bench 'PackedScan|DshFrames' -benchtime 40x, before → after:
- an 8 MB Codex rollout, 2 MiB window, scanAt from 0: 3,364,175 →
110,902 B/op, 25 → 6 allocs/op;
- a 6 MB dsh session of 8-line frames, scanFrames whole: 1,959,606 →
491,117 B/op, 63 → 22 allocs/op;
- the same, read on from its last frame: 182,087 → 74,361 B/op, 34 → 9
allocs/op.
- TestPackedScanKeepsItsDecoder (a warmed scan): 3,330,508 → 452 bytes.
- The 180 real rollouts, read cold by List, CallSources and
ReadCallSource: 1,294 and 1,299 MB → 375 and 386 MB allocated (two
runs each). The sessions and calls read (177 sessions, 306 calls) are
byte for byte the same JSON before and after.
Tests (packed_decoder_test.go):
- TestPackedScanKeepsItsDecoder and TestDshFramesKeepTheirDecoder fail on
the old code (3,330,508 and 181,995 bytes) and with either Put taken
out by hand (3,330,344 and 165,539 bytes). Skipped under -race, where
sync.Pool drops what it is given.
- TestPackedScanSameThroughAKeptDecoder: lines and places through kept
decoders are what a decoder of its own reads, for a large file after a
small one cut short, read on from a line, past the end, and by 8
readers at once.
- TestUnchangedPackedNotReadAgain passes on the old code too (it held
already). It fails when refresh's or readCalls's size-and-time check is
broken by hand for packed files.
Run, at this commit's tree:
- go test -timeout 45m -count=1 ./internal/sessions/ ./internal/usage/:
ok (79s, 39s).
- go test -race -count=3 -run 'TestUnchangedPacked|TestPackedScan|
TestDshFrames|TestCodexPacked|TestDsh.*Packed|TestDsh.*Append|Frame'
./internal/sessions/: ok.
- gofmt -l internal/sessions: nothing. GOOS=linux go vet -tags nogui
./... and GOOS=windows go vet -tags nogui ./...: exit 0.
- go test -tags nogui -timeout 45m -count=1 ./... under a scratch HOME,
GOPATH, GOMODCACHE and GOCACHE pinned: exit 0, every package ok (65,
no FAIL); gateway 802s, agent 733s, provider 355s, sessions 273s,
usage 92s.
Not tried: in the running app; on real dsh files (none on this machine,
so the profile's zstd was all Codex .zst). Why both caches were invalid
for the packed rollouts at that start is not found here.
|
||
|
|
2bd1dc81d6 |
sessions: a scan's read buffer is reused from a pool, not allocated per scan
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, while ~157 MB was live. bufio.NewReaderSize made
~3.5 GB of it: each scan made its own buffer, up to 1 MiB (scanBuffer)
for a big file, and threw it away at the end. The earlier commits cut
how often unchanged files are scanned. This one removes the buffer
cost for the scans that still happen: a first read, a grown file, the
calls ledger.
What changed:
- scanAt takes its bufio.Reader from lineReader. lineReader keeps a
sync.Pool per power-of-two size from 16 KiB to 1 MiB and gives the
reader back (Reset to nil) when the scan returns.
- A line from the reader was already valid only for the callback that
got it: long lines are copied into `long`, and callers that keep a
line copy it.
- Tests run with poisonReleased set in TestMain. A buffer given back
is overwritten with 0xFF, so a caller that kept a line past its
scan reads garbage and fails, rather than reading the next scan's
bytes in a user's magpie.
- sync.Pool drops items at random under -race, so the allocation test
is skipped there (race_on_test.go / race_off_test.go).
Tests:
- TestScansShareTheirBuffers scans a ~2.4 MB file 50 times and needs
under 128 KiB allocated per scan.
- TestALineKeptPastItsScanIsGarbageInTests checks the poison.
- Broken by hand: with the pool off (a new reader every time), the
first test goes red with "a scan of a 2.4 MB file allocated 1049911
bytes". Green again once restored.
- The whole sessions package passes with the poison on.
Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500. Cold
StatsAndNative(0) reads every file once:
| Code | Allocated | Allocations | Time |
| --- | --- | --- | --- |
| origin/main
|
||
|
|
42e6aee534 |
sessions: the stats and id lookups don't build every session's subagents
Why: in a 48-minute heap profile of the user's magpie,
gui.combinedSessionStats → statsFor → StatsAndNative → statsIn
allocated 3.9 GB, and gui.warmSessions → Warm 5.7 GB. Their scans went
through assemble → subagentsOf → ccTask: the stats built every
session's subagents (each one's task read from its file), only to
count tokens and tell which sessions are listed. Every statsFor call
in the profile came from the warm-up's steps.
What changed:
- assemble is split. assembleListed holds the part that decides
whether a session is listed and gives its agent, id, title, models
and usage. assemble adds resume, carry, transcript and subagents on
top.
- These callers now use assembleListed: the stats' native-key and
summary loops (stats.go), Titles, the Codex provider lookup
(codex_provider.go) and manage's id lookup.
- List, One and manage's listing still use assemble.
- The docs/subsystems/gateway-sessions.md subagent section says
which callers build subagents.
Tests:
- TestStatsReadNoSubagentFile writes a subagent with no meta and no
task in its first lines, then simulates a restart (Saved, Reset,
memos cleared). It then runs StatsAndNative(0), StatsAndNative(30)
and StatsFor(7) three times and expects 0 scans of that file. List
still shows the subagent.
- Broken by hand: the stats back on assemble make it go red with
"the stats read an unchanged subagent's file 1 times". Green again
once restored.
Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. The whole series against origin/main dee5c9d75; this
commit is the change to the stats rows.
| Pass | origin/main | This series |
| --- | --- | --- |
| warm StatsAndNative(0) | 596.7 MB, 157,195 allocs, 6.2–9.0 s | 28.9 MB, 73,976 allocs, 0.08–1.1 s |
| warm StatsAndNative(30) | 594.9 MB, 6.8 s | 28.7 MB, 0.8 s |
| restart StatsAndNative(0) | 3,106.7 MB, 509,239 allocs, 30.0 s | 48.2 MB, 241,721 allocs, 1.9 s |
| restart StatsAndNative(30) | 594.9 MB, 9.6 s | 28.7 MB, 0.5 s |
Run at the final tree of this series:
- gofmt -l internal: nothing.
- GOOS=linux and GOOS=windows go vet -tags nogui ./...: clean.
- go test -count=1 -timeout 45m ./internal/sessions/ ./internal/gui/:
- sessions: ok, 366.7s.
- gui: only TestMainWindowCorners failed, "measuring the windows:
signal: killed". It also fails alone on an untouched origin/main
export, at load ~500. Filed as #1936 and #2645. Every other gui
test passed.
- go test -race -count=3 on the new tests: ok.
|
||
|
|
a23fbaeadf |
sessions: a subagent's file is read for its task only when its meta names none, once per change
Why: a 48-minute heap profile of the user's magpie allocated 6.3 GB
in sessions.scanAt, 3.5 GB of it from ccTask. The user has 3,174
Claude Code subagent files, 1,798 of them over 1 MB. Two things
caused it:
- subagentsOf titled each one `cmp.Or(m.Description,
ccTask(f.path))`. Go evaluates both arguments, so every subagent's
file was read for a first user line that was then thrown away
whenever the meta file had a description, which is nearly always.
- ccTask kept only a found task. A file whose first 16 lines name
none was read again on every ask.
What changed:
- Claude Code and Kimi subagent titles read the file only when the
meta (or the spawn record) gives no description.
- ccTask keeps what it read, a task or none, with the file's size and
mtime from before the read. An unchanged file isn't read again. A
grown, rewritten (even at the same size), or touched file is read
again from its first lines.
- A read that fails keeps the last good result, and a deleted file
gives "".
- A line appended while the file is being read changes the size, so
the next ask reads it.
- The docs/subsystems/gateway-sessions.md subagent section says so.
Tests:
- TestSubagentTaskReadOnlyWhenTheFileChanges counts scans through
scanHook for these cases:
- first ask: 1 scan;
- unchanged: 0;
- grown with a task: 1, then 0 once found;
- grown after the task: 1;
- rewritten shorter: 1;
- rewritten with no task: 1;
- same size with a new mtime: 1;
- a task appended past line 16: 1 scan, still "";
- appended during the read: found on the next ask;
- deleted: "", 0 scans.
- TestSubagentWithMetaTaskIsNotReadForIt lists a session after a
simulated restart (Saved, Reset, memos cleared) and expects 0 scans
of a subagent whose meta names its task.
- Broken by hand:
- ccTask back to keeping only a found task (`t.task != ""`) makes
the first test go red: "unchanged, no task yet: 1 scans, want 0".
- The title back to cmp.Or makes the second go red: "the list read
a subagent's file 1 times for a task its meta names".
- Both green again once restored.
Measured on a read-only APFS clone of the user's ~/.claude/projects
and ~/.codex/sessions/2026/10, in a sandbox HOME, at load ~500 from
other sessions. Times are noisy; allocations are not. Restart, then
List(All):
| Code | Allocated | Allocations |
| --- | --- | --- |
| ccTask keep, title still cmp.Or | 153.9 MB | 270,838 |
| this commit too | 25.8 MB | 109,854 |
| origin/main
|
||
|
|
a7e2c72358 |
sessions: a line longer than the read buffer is gathered once, at its own size (#2515)
scanAt gathered a line longer than its read buffer by appending one
buffer's worth at a time. Past 256 elements append grows a slice by
1.25x, so an 8 MiB line allocated ~37 MB, and a line past maxLine was
gathered to 32 MiB before being dropped (~175 MB allocated). The session
list and the call readers both read every session file this way at a
start, so a history whose prompts carry pasted screenshots (each a
multi-MB base64 line) allocated GBs in scanAt alone.
On the first overflow of a plain file's line, scanAt now reads ahead
(ReadAt, which moves nothing) to the line's end and gathers it into one
buffer of exactly that size. A line longer than maxLine plus the buffer
is stepped over at once, as before, but without being gathered first. A
packed (zstd) file, or a line with no end yet, keeps the old path.
Tests (internal/sessions/scan_buffer_test.go):
- TestScanGathersALongLineOnce: an 8 MiB line and a short one are both
handed over whole, and the scan allocates at most 1.5x the line.
Fixed: 9,451,632 bytes for an 8,388,633-byte line (bound 12,582,949).
With the read-ahead turned off by hand: red, "allocated 36856408
bytes".
- TestScanStepsOverATooLongLineUngathered: a maxLine+4 MiB line is
stepped over and the next line read, with at most 8 MiB allocated.
Fixed: 1,049,032 bytes. Turned off by hand: red, "allocated 175179080
bytes".
Measured: a sandbox `magpie web` on a fixture HOME (150 Claude Code
sessions, each with six 4 MiB pasted-image prompts, 3.5 GB), main and
panel pages loaded in Playwright Chromium, heap profile at ~2.5 min,
macOS at a load average of ~290, two runs each:
allocated in scanAt peak RSS
base
|
||
|
|
81a24cf8fe |
groups: a found group is listed as auto/<model id as the vendor spells it>
ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.
What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
public one). Every old form is still accepted as input forever:
provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
gateway (validateModel), keys, stats, affinity and usage, so both ids
route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
(allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
exists, found groups are listed by their old id (AutoRefsOn) and
auto/<x> means that provider's model. Documented in
docs/subsystems/gateway-routing.md.
Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).
Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.
Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
gateway, whose failures were the tests' expected ids (updated here)
and two regressions now fixed (bare ids; desktop models hiding groups
by prefix). Every failing test passes on rerun. Load average was
~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
10.19s), and it fails the same in a git-archive export of
|
||
|
|
baef679f29 |
sessions: every other reader of a session file sizes its buffer by what is left of it, as scanAt does (#2776)
|
||
|
|
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 |