ac4af582301a4e8a29245dbba767eba31334ddf9
14
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
f99b227c27 |
filememo: a parse is kept under a struct key, not a joined string
read joined kind + "\x00" + path into a new string for every read,
and Look scanned every key with HasSuffix of another joined string.
A read is asked for each model of each provider a poll lists, so the
keys alone were 33 MB of what twenty window polls allocated with
real accounts (m2463 profile). seen is now keyed by
memoKey{kind, path}; a held read and Look allocate nothing.
Test: TestHeldReadAndLookAllocateNothing. 50 files in a long folder,
under Hold: AllocsPerRun of a read found unchanged is 0, and of Look
0; a write then Look reads the new value.
Run on mote, at this tree on
|
||
|
|
68c413ea05 |
filememo: a file written just now is read again into one buffer
A file whose time is under two seconds old is read again on every read and compared with the bytes parsed, since a second write inside a clock tick can leave the same time and size. Each of those reads made a new buffer. As magpie starts, Codex's sync writes ~/.codex/config.toml, and every read of it for the next two seconds made one. With the owner's real 1.45 MB config.toml, v0.1.2432's startup profile has readCodexStoreSetting reading it ~155 times (226 MB) and the TOML table spans ~89 times (129 MB). That is 381 MB of the 1.37 GB allocated before the window's first poll, and the peak RSS with it. Now a read that finds the same size and time reads into a buffer kept on the entry while its bytes are, and gives the buffer back when they match. A read beside it takes the buffer out first, so it reads into one of its own. Bytes that differ are parsed from that read's buffer, which no one else has. Nothing changes in what is looked at: the file is still read and compared each time until it settles. steady.ReadThereInto is ReadThere into a caller's buffer. TestRecentFileReadAgainIntoOneBuffer (a 1.2 MB file stamped now): 20 reads allocate under a quarter of the file each, it is parsed once, 8 readers at once each get the right length, and a write of the same size and time is seen and kept as its own bytes. Broken by hand on mote, with the buffered path off, it is red (1191002 bytes a read). Run at 8ce36a0ef (on |
||
|
|
5160809d2e |
agent: a catalog sync's round looks at each file once; a write reads the disk (#1665)
A catalog sync asked about each agent's files many times a round (GetJSON, GetTOMLTop, settings.load from each agent's Sync): on Windows an empty sandbox's start stat'ed settings.json 1065 times and config.toml 569 in 25s, almost all from SyncCatalog. Each round now holds what was read (filememo.Hold), as the GUI's read-only requests and the gateway already do. What a hold serves may be up to a second old, so nothing is written from it any more: - edit.Read, which every Set*/Del* helper and the agents' own read-modify-write code start from, looks at the disk even under a hold (filememo.ReadNow). The getters (GetJSON, GetJSONRaw, GetJSONItem, GetEnvFile, GetYAMLTop, the YAML getters, GetTOMLTop's line reader) read through the hold. - settings: a write's load under fileMu (lockFile) reads the disk too. Before this, a GUI request's hold could already hand a Set* stale bytes; that is closed as well. WriteAtomic forgot every held file even when it left the file as it was, and a sync writes each agent's files each round, almost always unchanged: it now forgets only after a real write. Measured on xiaomi-gpu (Windows 11), as in the steady commit before this one (second start, 27s, stats counted by an uncommitted build): before 2307 stats, sync 1318 of them, round 1308ms this alone 1787 stats, sync 864, round 1273ms with steady's 988 stats, sync 96, round 96ms First start of an empty sandbox: 2448 stats before, 1041 after. Run: - TestHeldReadIsNotWhatAWriteIsMadeFrom (json, toml, yaml), TestUnchangedWriteKeepsWhatIsHeld, TestHeldSettingsAreNotWhatAWriteIsMadeFrom: with edit.Read and the settings write load put back on the held read and WriteAtomic's Forget removed by hand, json and yaml lost the other app's key, the settings case wrote "light" over "dark", and the forget case went red; green with the change, on mote. - mote, at the pushed head: gofmt -l internal clean; GOOS=linux/windows/ darwin go vet of steady, edit, filememo, settings and agent clean; go test -count=1 of steady, edit, filememo, settings, agent, provider, catalog and library ok; internal/gui red only on TestMainWindowCorners (#3949, macOS 27, red on main before this). - xiaomi-gpu: go test of edit, filememo and settings ok. |
||
|
|
4842f69be5 |
filememo: a write in a synctest bubble no longer crashes the next test (#3632)
|
||
|
|
de49433ff8 |
filememo: another process's writes to magpie's files are watched for, not polled every 5s (#3185)
An idle magpie still woke a dozen times on each 5s beat: the loops that follow plugins.yml, settings.json, providers.json, the plugin list, tools and access each looked at the disk for what the CLI or a second magpie wrote. The gateway now watches those files' folders (fsnotify: FSEvents, inotify, ReadDirectoryChangesW), and a change from another process wakes the same loops at once, as magpie's own writes do (filememo.Written). With the watch running the loops look for a change they missed only once a minute (OthersEvery); where the folders can't be watched, or the watch errs, they go on looking every 5s. Run at |
||
|
|
091153bf71 |
idle: the loops following magpie's files wake on its own writes, not a 1-2s poll (#3185)
An idle `magpie serve` (no providers, no requests) woke 12-13 times a
second. A runtime trace showed the wakers were polling loops: the
middleware observer's refresh every 1s, pluginrt.KeepFresh's stat of five
files every 2s, OTel's session watch every 2s and its exporter tick every
5s, all with nothing to do.
Now filememo.Forget, which every write magpie makes of settings,
providers, sign-ins and caller keys already calls, also closes a channel
(filememo.Written). The plugins.json, tools and plugins.yml saves call it
too. The middleware observer, KeepFresh and OTel's session watch wait on
it, and look every filememo.OthersEvery (5s) only for what another
process (the CLI, a second magpie) wrote. Each takes the channel before
it looks, so a write made during a look isn't missed. middleware's
current() also reloads at once when filememo's generation moved, rather
than after its 1s skip. OTel's session watch waits 5s, not 2s, while
sessions aren't exported, and its exporter's timer runs only while a
batch holds something.
Measured: sandbox HOME, MAGPIE_ADDR=127.0.0.1:3481, `magpie serve`,
proc_pid_rusage (idle + interrupt wakeups) over 30s after 40s warm-up,
old (
|
||
|
|
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.
|
||
|
|
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.
|
||
|
|
206dc085be |
provider: a magpie run from a terminal that only lists accounts no longer writes logins.json, and every change to it is made under a lock the gateway holds too, so a token the gateway just refreshed is never written back over (#1674, FaintGhost)
Every CLI command that reached Logins() (magpie ls, providers, sessions,
usage) ran rememberLogins, whose 30-second throttle (loginsSeenAt) lives
in the process, so in a new process it never held: each run moved Seen on
for the signed-in Codex and Claude accounts and wrote logins.json back.
loginsMu was an in-process mutex, so that read-modify-write could
interleave with the gateway's renewSavedLogin: the CLI reads, the gateway
writes a refreshed sign-in, the CLI writes what it read. Codex/OpenAI
refresh tokens are single use, so the account would be signed out.
- rememberLogins writes nothing when the only change is Seen and the saved
Seen is less than seenEvery (10 minutes) old (onlySeenMoved, comparing
with what was read, IDs and order normalised as writeLogins writes them;
sortLogins is split out of writeLogins for that).
- internal/filelock (new): davsync's TryLock/Unlock (flock; LockFileEx on
Windows) moved here and davsync uses it; Lock(path, wait) and
filelock.Mutex, a sync.Mutex that also holds the OS lock on a lock file.
A lock another magpie holds is waited for up to filelock.Wait (10s),
then gone on without, as before, so a stuck magpie never hangs others.
- loginsMu is a filelock.Mutex on logins.json.lock, so all 107 existing
Lock sites (every writeLogins is under one) are cross-process with no
change at the call sites. Taking it calls filememo.Look (new), so the
read under it isn't a parse filememo.Hold kept from before another
magpie's write. savedTokenMu holds logins.json.renew.lock the same way:
two magpies never refresh one saved account at once.
- Siblings: caller-keys.json (access.mu: magpie keys from the CLI vs the
window; a lost revoke would bring a key back) and mcp-signins.json
(mcpauth.fileMu, plus mcp-signins.json.renew.lock around renew, since
library's MCP check renews from the CLI too) get the same lock.
plugin-auth.json already has one (plugin-auth.json.lock, shared with
host.js). Not covered: providers.json (33 store sites with no
in-process lock either; user-entered keys, nothing refreshed there),
migrations.json/settings.json (no credentials), and the agents' own
files (~/.codex/auth.json etc.: the agent itself writes them without
any lock of ours, so a magpie-only lock can't make them safe).
Tests:
- TestReadOnlyRunLeavesLogins: Codex and Claude signed in, Seen a minute
old, file time set back; three "new processes" of Logins("")/codex/
claude/All() leave logins.json's bytes and mtime as they were. Seen an
hour old is written; Codex's own refresh is written at once.
- TestLoginsKeepAnotherMagpiesWrite: between this process's read and write
(beforeLoginsWrite hook) a second test process (TestLoginsOtherMagpie,
os.Args[0] -test.run) renews the saved work@ account's refresh token;
both the renewed token and this process's change are in the file.
- TestLoginsReadAfreshUnderLock: with filememo.Hold held, a write
filememo never heard of is seen by a read under loginsMu.
- TestLockAcrossProcesses (filelock): a holder subprocess makes Lock wait
and give up after its wait; killed, the lock is free; a Mutex holds it.
Broken by hand: onlySeenMoved bypassed -> TestReadOnlyRunLeavesLogins
FAIL "a run that only listed the accounts wrote logins.json"; the file
lock taken out of filelock.Mutex.Lock -> TestLoginsKeepAnotherMagpiesWrite
FAIL "the other magpie's renewed sign-in was written over"; Locked hook
emptied -> TestLoginsReadAfreshUnderLock FAIL. Each restored, green.
Ran: gofmt -l (nothing); go vet ./..., GOOS=linux go vet -tags nogui
./..., GOOS=windows go vet ./...; go build, GOOS=linux go build -tags
nogui, GOOS=windows go build; go test -tags nogui -count=1 ./... under a
temp HOME with pinned caches: all ok but internal/provider, whose
TestReadOnlyRunLeavesLogins failed at that point from its own fixture
(two rewrites of one size given the same mtime read as unchanged by
filememo); fixed in the test, then internal/provider, access, mcpauth,
filememo, filelock and davsync -count=1 all ok, and the three new provider
tests -race -count=10 ok.
Not tried: the reporter's Linux arm64 box with a real systemd gateway and
real Codex accounts; Windows (LockFileEx path) only vetted and built, not
run on the Windows box.
|
||
|
|
d5619d5a92 | windows: an account list read while another magpie writes it is waited for, not taken for no accounts (Packing1 on Discord, Windows 11: 早上更新重启后之前登录的Antigravity订阅供应商和账号都没了 … 整行都没了,供应商里面antigravity直接消失了) — on Windows a file being renamed over (every write magpie makes: a temp file renamed onto it) is, for a moment of up to ~2ms, "The system cannot find the file specified" to anyone else looking at it, with MoveFileEx and with POSIX-semantics renames alike. filememo.Read gave that back as an error, readLogins as no accounts, and whatever change came next (any account's read-modify-write) wrote the empty list back: every built-in account gone, its subscription with it. Measured on Windows 11 (10.0.0.132): one process replacing a 200 KB file, another stat-ing and reading it, saw the file "not there" in a few windows each 20 s. Now steady.Stat and steady.ReadThere wait out a moment of a file not there (15 tries a millisecond apart, Windows only), and filememo looks through them, remembering a file found not there so one that really isn't costs the wait once. A magpie started by an update now waits for the one it replaces before its start-up moves write any file (AwaitPredecessor at the top of run, not only in the GUI). TestLoginsKeptWhileAnotherMagpieWrites (Windows: two writers replacing logins.json, readLogins never without the Antigravity account) failed 1 in 3 and 2 in 8 runs on the old code ("read as no accounts 8 times"), passed 11 of 11 on this; filememo's TestReadWhileReplaced the same (1180 misses on the old code); TestStatWaitsOutAReplace everywhere. A real update in a sandbox home on the Windows box, magpie-cli 0.1.880 → 0.1.942 from the release, kept the account and logins.json byte for byte. go vet (darwin, and windows nogui), builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui -count=1 ./... under a temp HOME pass. | ||
|
|
2a4042a94d | perf: magpie opens and shows the Agents page in a fraction of the time it took (Junjie Zhou on Discord: 8 个 agent 30 个 provider … 每次我打开的时候都会很慢,要好几秒。setting 页面秒进后 我切换到 agent 就有问题) — at start, writing the agents' model lists (agent.SyncCatalog) built every provider's catalog thousands of times with nothing held, each build reading migrations.json, settings and groups again: 6000+ file reads and ~8.5s of CPU in the first 8s with the owner's 30-odd providers, all competing with the first /api/state and the Agents page. Now SyncCatalog, magpieModels and main's start-up moves run under provider.Hold, migrations, groups, settings and a provider's fetched models are held for a second like the rest, and filememo.Hold lets a GET /api/* not stat a file it confirmed unchanged within the last second (any magpie write, Changed() or a recent mtime still reads it again). A big ~/.codex/config.toml parsed in quadratic time (the TOML parser's Shape counts newlines from the start for every key): a 3 MB one took 5.4s, now 0.04s (tomlShaper). theInstalled reads through edit.Read's memo. Measured with a copy of the owner's magpie config and agent configs under a sandbox HOME, the real server in WebKit: CPU in the first 8s 8.59s → 0.39s, page up 475 → 75ms, Agents rows drawn 775 → 325ms after start; the agents' written model files are unchanged (pi byte for byte, opencode the same models). TestTOMLShaperMatchesParser, TestTOMLBigFileParsesInLinearTime (fails on the old code), TestHold (filememo), TestHoldReadsMigrationsOnce. go vet, builds (darwin, GOOS=linux nogui, GOOS=windows) and go test -tags nogui ./... under a temp HOME pass. | ||
|
|
21702d01ff |
Add German translation; harden paths against unset env vars (#770)
* Add German translation and harden paths against unset env vars Add a German locale to the GUI, tray menu, usage alerts and website home page, and refuse to start when the home folder is unset or relative so nothing is written under the working folder; the pi plugin no longer adopts the user's PI_CODING_AGENT_DIR, and an inherited APPIMAGE no longer selects portable mode. Scripts refuse to run from the wrong folder or empty a shared out folder, and a new internal/testenv sandboxes every test package from the user's real files, which also fixes the Claude picker and Termux installer tests on Windows. * Makefile: know magpie's folder by its go.mod, so paths with spaces work The check compared $(CURDIR) with $(dir $(abspath …)), which make splits on spaces, so a checkout under 'My Projects' or 'John Doe' refused every target. It now reads go.mod relative to the working folder and wants magpie's module there: make -C and a symlinked Makefile work, make -f from another folder still stops before any recipe runs. * i18n: German for the strings main added since, with a parity test 75 strings main added (group order, patterns, slow-start wait, usage caps, RTK savings …) get their German, and two that main dropped go. gui-de.test.cjs checks, as gui-ja does, that de has every zh string with its placeholders and tags, and that the window reads in German when picked or on a German system. * appdir: ignore relative folder variables when reading, keep them for children CheckEnv no longer unsets anything. magpie reads the XDG folders, APPDATA/LOCALAPPDATA and every agent's folder variable through appdir.Getenv/LookupEnv, which pass over a relative value; the environment stays as it is, so the agents magpie starts get the variable as the user set it. That covers what proc.UserPath lends from the login shell too, which is set after main's check and reached the desktop app unchecked. On Windows a path rooted on the current drive (\Users\x, Git Bash's /c/x) counts as usable, and magpie version and help answer without a home, before run makes any folder. * Sandbox the tests main added since internal/wslrun gets testenv's TestMain, and four tests main added that set HOME alone set their home with testenv.SetHome, so on Windows they don't read the runner's profile through USERPROFILE. * agentenv: PI_CONFIG_DIR and OPENCODE_DB take relative names on purpose omp puts $PI_CONFIG_DIR under the home and OpenCode a relative $OPENCODE_DB in its data folder, so neither depends on the working folder: appdir no longer passes them over. * i18n: German for the Library's multi-select and System One's decision API The 19 strings main added since (#791's skill multi-select, the decision API snippets) get their German; the one main replaced (four APIs → five APIs) goes. * appdir: tidy the import into magpie's group; say what Go makes of /c/x The appdir import joins the group of magpie's own imports where a file has one. rooted's comment now says that Go takes a Git Bash path like /c/x as \c\x on the current drive, not C:\x. |
||
|
|
7dd809002b | accounts: on Linux an account put first is read first at once, and on Windows a file being replaced isn't read as none (goal: 插件订阅 provider 跟内置的所有逻辑都要一模一样, run on Windows and Linux) — the provider tests run on the Windows test box and in WSL found two bugs of magpie's own files. Linux stamps a file's time from a clock a tick (a few milliseconds) coarse, and filememo took same time and size for the same file: two accounts swapped (Devin, Grok, WorkBuddy, ZCode, Claude…) read back in the old order, so magpie kept using the account the user had just moved down, and a moved-back plugin's accounts read as before. A file written within the last two seconds is now also compared by its bytes. On Windows a file being renamed over refuses to open for a moment ("Access is denied"), and one held open refuses to be renamed over: plugin-auth.json, plugins.json and the plugin providers read as nothing (a usage fetch right after a move showed no cards), logins.json failed to save, and host.js, reading plugin-auth.json as {}, would have written the other accounts away on the next sign-in. New internal/steady waits such a read or rename out (half a second at most, Windows only); filememo, edit.WriteAtomic, writePrivate, Kiro's writes and the plugin store go through it, host.js retries its read and rename, and the plugin store writes its files by a rename. Tests: USERPROFILE beside HOME in the test homes, the fake devin (a shell script) skipped on Windows, plugin-auth.json's mode bits unchecked there. TestReadSameSizeSameTick fails on Linux and TestRenameOverAFileHeldOpen/TestReadAFileHeldOpen on Windows without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; on Linux (WSL) the provider and plugin packages pass whole (13 failed before), on Windows the plugin package and the move/plugin/Grok/Devin/usage tests pass 10 times over (TestMoveToPlugin failed one run in a few before); 15 built-in tests that assume Unix (mode bits, Keychain, shell-script CLIs) still fail there, as before. | ||
|
|
ea5d089b4a | gui: the Agents and Providers pages open at once again — the Providers page worked out each agent's model and routing group again for every provider (every provider's models read again each time, Alma asked over HTTP each time), so it took 25s with many providers; now once per page. What is parsed from a file is kept until the file changes (Codex's models cache, the vendors' model lists, ~/.claude.json's account, and an agent's TOML config — Codex's can run to megabytes of trusted projects, and was parsed again for every field); and what Alma answers when magpie only shows what it is on is reused for five seconds, as its providers take most of a second each time, while a change and what it reads first still ask Alma. /api/providers 25s → 0.02s, /api/state 7s → 0.1s |