Commit Graph
44 Commits
Author SHA1 Message Date
yetone b85475e57e pii: pin pf-v4, whose pf-serve maps the model on the CPU
kongbai01203 (plugins#853) saw pf-serve hold ~1.82 GB of private memory
on Windows after the first redaction, until it was ended for idling. On
the CPU path pf-v3 read the whole 1.6 GB q8 GGUF into a malloc'd buffer;
the rest is ~200-270 MB of compute buffers. pf-v4 (691a10446,
weights-paged.patch) maps the file read-only instead, so the weights are
file pages the system can drop and share, not pf-serve's own memory.
Metal and Vulkan load as before.

This pins pf-v4's five zips (sha256 checked against the release's
downloads) and keeps pf-v3 in oldTags, so a user with pf-v3 on disk runs
it until upgrade() has fetched pf-v4. The idle unload stays 10 minutes
after the last request (idleAfter); the reporter's ~25 min was that
timer restarting on each request.

Measured, pf-serve on the CPU, private bytes (commit charge):
- Windows (xiaomi-gpu): v3 1,749 MB after load, 1,822 MB after a 78K-char
  text; v4 200 MB and 273 MB. pf-serve-base the same. Working set v4
  1,363 MB, file pages.
- macOS (mote): physical footprint 1.7-1.8 GB on v3, 209-303 MB on v4.
- Spans (text, offsets, score, all hashed) are identical v3 vs v4 for
  pf-serve, pf-serve-base and pf-serve-vulkan on four texts, 261 to
  78,300 chars. Vulkan on the iGPU: ~1.9-2.1 GB private on both, the
  driver's.
- End to end on Windows through pii.Find with a sandbox XDG_CACHE_HOME
  holding pf-v3 and the model, PF_DEVICE=cpu: magpie downloaded pf-v4
  through the pinned sha, ran it at 220 MB private, and removed pf-v3.

Test: TestRealServeOnTheCPUMapsTheModel (PII_REAL_SERVE, PII_REAL_DIR)
starts the real pf-serve on the CPU, checks the first span of a long
text, and fails when its own memory is over half the model. Broken by
hand by pointing it at pf-v3's binary: red on Windows (1,821 MB), WSL
Linux (1,822 MB) and mote (1,843 MB); green on pf-v4 at 272, 276 and
297 MB. It skips without the env vars, so CI doesn't download 1.6 GB.

Run on mote at 691a10446 plus this change: gofmt -l internal/pii
(clean), GOOS=windows/linux go vet ./internal/pii, go test -count=1
./internal/pii, and under lockf suite.lock go test -count=1
-timeout 45m ./...: every package ok, exit 0 (a first try was cut off
when mote rebooted). Main then gained 2fe4e9c70 in internal/pii
(serve.go, not classifyTimeout); rebased onto c66cdbea9 and run again
there: gofmt, the three go vets and go test ./internal/pii ok on mote,
go test ./internal/pii and the real test ok on Windows (272 MB). The
real test on mote at the rebased head ran out of classifyTimeout's 34s
at load 108 (others' suites; 9.5s on Windows, green on mote before at
normal load) and was not rerun there; the full suite was not rerun at
the rebased head.

Not tried: a machine actually under memory pressure (that the pages are
dropped and read back is the OS's doing), CUDA builds (none shipped),
and linux-arm64/darwin-amd64 beyond their checksums.

Reported-by: kongbai01203
2026-11-08 19:10:44 +08:00
yetone 2fe4e9c70c pii: a GPU the driver reset under an idle pf-serve is loaded again on the GPU, not left on the CPU
kongbai01203 (plugins#853): after ~12 minutes idle the Vulkan pf-serve
exited 3 (vk::DeviceLostError) and Privacy Filter then said "GPU error,
running on CPU" until the GPU was tried again.

Cause: the driver's, not ours. pf-serve sits blocked on stdin while idle
and the idle unload only takes a free turn, so there is no race of ours
with a GPU call; the driver lost or reset the device under it, and the
next GPU call threw (an uncaught vk::DeviceLostError ends in abort, exit
3 on MinGW). magpie then counted one death on the GPU as a lost GPU.

Now one that dies on the GPU is started again on the GPU: a new
pf-serve gets a new device. Only a second death (or hang) in a row on the
GPU moves it to the CPU, until gpuRetryAfter. Status says gpuReset when
the error is a device lost, and gpuAgain when the GPU is tried again;
Settings > Privacy says "On, on the CPU until 14:38: the graphics driver
reset the GPU (device lost)" (and "until {time}" on a GPU failure), in
en, zh, zh-TW, ja and de.

Not changed: the model's size. Privacy Filter has q8 (1.64GB) and f16
only, no smaller quant; AstrLink Guard (39MB) is the small choice.
Its ~1.8GB private on the CPU goes with pf-v4 (mmap, 691a10446), whose
pin is another session's work; on Vulkan the ~1.9GB is the driver's.

Run (mote, through mote-run):
- gofmt -l, go vet (darwin, linux, windows), go test -count=1
  ./internal/pii ./internal/gui ./internal/masking: ok
- GUI: privacy-model, i18n-keys, i18n-en-no-cjk, masking-records in
  chromium and webkit (privacy-model at 1100 and 640, every language):
  219 of 224, then privacy-model 104 of 104 after zh-TW's expected time
  was made 下午02:38 (hhmm's zh-TW form). The one other red is i18n-keys
  "a plugin's words are its own", red on main and filed (#5332, #5426,
  #5482); this change adds no plugin words.
At this head, rebased on 8f6298fb5: gofmt, go vet and go test
./internal/pii ok; privacy-model and i18n-en-no-cjk 108 of 108 in
chromium and webkit.
Rebased after on 37df73b1b (key balances; the one file it shares,
i18n.js, holds other keys there), not run again.
Broken by hand: serve.go put back to HEAD's: TestGPUDeviceLostReloadsOnGPU,
TestGPUDeathMovesToCPU and TestLostGPUTriedAgain red (starts [gpu CPU]).
app.js put back to HEAD's: the new privacy-model test 10 of 10 red
(chromium).
Not tried: a real device lost on a GPU (it can't be forced here); a
crash in pf_free's teardown at idle unload (harmless: end() ignores the
exit status; a fix needs a native change and a new pf tag).
Full suite: not run at push.

Reported-by: kongbai01203
2026-11-08 15:35:59 +08:00
yetone 1cb3dc435a pii: a GPU pf-serve that died says why, not "read |0: file already closed" (#3741)
TestGPUDeathMovesToCPU went red on macOS CI at 778b8e075 with GPUError
"read |0: file already closed". pf-serve's stdout came from
cmd.StdoutPipe, and the goroutine that waits for pf-serve called
cmd.Wait, which closes that pipe's read end once the process exits. When
pf-serve died answering (a lost GPU) and Wait won the race with the read,
the read got os.ErrClosed instead of EOF; reader.fail takes only EOF for
a death, so the raw pipe error became the reason. Users saw it too:
Settings' privacy-filter status showed "file already closed" as why the
GPU was lost, and any answer pf-serve wrote just before exiting could be
dropped with the pipe.

Fix: stdout is magpie's own os.Pipe. pf-serve gets the write end, which
magpie closes after Start, so a read after the exit sees EOF and the
answer or death message is read whole; kill and end close the read end.
A beforeRead seam lets TestGPUDeathReadAfterExit read only after the GPU
pf-serve has exited and been waited for, so the ordering is red without
the fix every time.

Run on mote at this tree (based on 778b8e075):
- go test -race -count=20 -timeout 45m ./internal/pii/...: ok (pii
  1578s). The first try at the default 10m timed out mid-run in
  TestIdleServeEnds (1s in, no hang in the stacks): count=20 under race
  is longer than 10m.
- go test -timeout 45m ./internal/pii/... ./internal/gateway/...: ok
  (gateway 810s).
- gofmt -l internal/pii: empty; GOOS=linux go vet -tags nogui ./...: ok;
  GOOS=windows go vet ./...: ok; go vet ./internal/pii/...: ok.

Broken by hand:
- Old code with a 300ms pause before the read: TestGPUDeathMovesToCPU
  red with the CI's exact "GPUError:read |0: file already closed".
  With the fix and the same pause: green 3 of 3.
- Fix kept but the read end closed right after cmd.Wait (what
  StdoutPipe did): TestGPUDeathMovesToCPU and TestGPUDeathReadAfterExit
  both red with that message.

The issue's four ubuntu tests (TestWarm, TestFindJoinsTextsAndMapsBack,
TestServeStartsWithoutResidencyHeartbeat, TestGPUDeathMovesToCPU's
starts) had another cause, fixed in c84f859dd; ubuntu is green at
778b8e075.

Not tried: a real GPU death on a real pf-serve; the fake's death is
the same exit-after-stderr.

Fixes #3741
2026-11-08 06:51:03 +08:00
yetone e484b4ff26 update: a slow download still moving is never ended by a total time; Bun, Claude Code and pf-serve too
#5572: since 80a47abba a silent download is broken off after 30s and
tried again, but the update's download still had a 10-minute total
(the update client's Timeout, the GUI run's ctx, `magpie update`'s ctx).
A download under ~140 KB/s, still receiving bytes, failed the 83 MB
Windows exe at 10 minutes part way. The stall timer is what ends a dead
one now; nothing ends one that is still moving.

- internal/update: fetch downloads through fileClient, the client without
  its Timeout. The feed and notes keep the 10-minute client. fetch's stall
  timer runs from the ask to the last byte, so a server that never answers
  still ends at stallAfter (30s), and download's retries stay bounded
  (len(retryWaits)+1 = 6 tries), so a connection that keeps going silent
  ends in about 4 minutes.
- internal/gui (Mac Stage, Windows/Linux StageBinary): run's 10 minutes
  (checkWait, a var for tests) bound only LatestIn; the download runs
  under a ctx with no deadline.
- internal/cli `magpie update` (Mac Stage, Windows/Linux ReplaceBinary):
  the same split.
- Siblings with the same fixed cap:
  - new internal/stall: Start(ctx, after) gives a ctx that ends with
    ErrStalled once `after` goes by with no byte read through w.Reader.
  - Bun (internal/plugin getURLOnce): watched with a 60s stall;
    KeepBunUpdated's 10-minute ctx around CheckBun is gone.
  - Claude Code (internal/claudecode downloadOnce, ~200 MB): watched with
    a 60s stall; keepOnce's 30-minute ctx around install is gone.
  - pf-serve (internal/pii upgrade): its 10-minute ctx is gone; get
    already had a 60s stall and the client a 60s header timeout, as the
    model's download (no total) does.
- Left as they are: plugin installs and npm updates (KeepUpdated's 10
  minutes) run `bun install`, whose network is Bun's own, small tarballs;
  rtk (5 min client), skills (2 min client), skilltree and market reads
  are small files; Grok CLI install has no cap of its own (its caller's
  ctx). None of them carries a large download behind a wall-clock total.

Run on mote (mote-run), at 49f207c78 + this change; the targeted
set again after rebasing on d4a221f79 (ok):
- go test ./internal/stall ./internal/update ./internal/claudecode
  ./internal/pii -run 'Stall|Slow|Silen|TestDownload|TestInstall|TestKeep';
  go test ./internal/plugin -run Bun; go test ./internal/gui -run
  TestUpdate: ok
- new: TestSlowButMovingIsReadWhole, TestSilenceIsAStall (no answer, part
  way), TestDownloadSlowButMovingOutlastsTheClientTimeout (client Timeout
  300ms, body ~1.2s: one try, no retry), TestUpdateSlowDownloadOutlastsTheCheckBound
  (checkWait 200ms, body ~600ms: ready), TestDownloadThatGoesSilentIsAStall
  (claudecode), TestBunDownloadThatGoesSilentIsAStall. The silent server
  after its retries stays covered by TestDownloadStallEveryTimeSaysSo
  (6 tries, errStalled).
- go test -race -count=3 ./internal/stall ./internal/update -run
  'Stall|Slow|Silen': ok
- win-run (Windows 11): ./internal/stall ./internal/update
  ./internal/claudecode ./internal/plugin with the same -run, and
  ./internal/gui -run 'TestUpdateSlowDownload|TestUpdateDownloadSaysStepAndSpeed': ok
- wsl-run (Ubuntu 24.04), -tags nogui: the same packages and ./internal/gui
  -run TestUpdate: ok
- gofmt -l; go vet ./...; GOOS=linux go vet -tags nogui ./...;
  GOOS=windows go vet ./...; go build; GOOS=linux go build -tags nogui;
  GOOS=windows go build: clean
- Full suite: run after the push under the suite lock.

Broken by hand: fetch back on `client` fails
TestDownloadSlowButMovingOutlastsTheClientTimeout ("broke off ...
Client.Timeout or context cancellation while reading body"); the GUI's
download back under the check's ctx fails
TestUpdateSlowDownloadOutlastsTheCheckBound (state error, "context
deadline exceeded"); stall's reader not putting the timer off fails
TestSlowButMovingIsReadWhole (50 of 120 bytes); Bun's and Claude Code's
downloads unwatched fail their silent tests at the 20s bound ("context
deadline exceeded").

Not tried: a real update over a slow or throttled link, on any OS; a real
Bun or Claude Code download over one. The Mac's unpack and signature
check now run with no deadline (they had the 10 minutes before).

Fixes #5572
2026-11-07 06:09:42 +08:00
yetone 1fd0bb9670 update: a download whose HTTP/2 transfer broke off tries again over HTTP/1.1
biubiu8802 on X (tweet 2118719081872540038): behind their proxy every
update failed with "download broke off, a network problem", while the
same proxy carried ordinary downloads. Confirmed in the code: download()
retried up to 5 times with Range, but each try went through
netproxy.Dispatch over HTTP/2 again; Dispatch moves a host to HTTP/1.1
only on a TLS record error (recordError: bad record MAC and kin), and
"unexpected EOF" or a stream reset is not one. So a proxy that cuts
HTTP/2 streams part way cut every try the same way.

- netproxy: OverHTTP1(ctx) sends every request under ctx through
  Dispatch's HTTP/1.1 copy (route.h1), kept through With.
  BrokeOff(err) says a transfer broke off (net.Error, unexpected EOF,
  HTTP/2 stream error / GOAWAY / lost connection, a reset; not a
  context that ended). AgainOverHTTP1 runs a download once more over
  HTTP/1.1 after such a failure.
- update: the tries after a broken one go over HTTP/1.1, and still
  resume with Range from the bytes kept.
- Siblings, the other big downloads through Dispatch's client: the
  masking model and pf-serve (pii.fetch, one more try over HTTP/1.1
  from what is on the .part file), Bun's zip (plugin getURLFrom),
  Claude Code's binary (claudecode.download) and the Grok CLI
  (grokDownload) each try once more over HTTP/1.1.
- docs/subsystems/providers-accounts.md names it.

Run (mote, Go 1.26.8, at this tree, base 80ae904c2 = origin/main fetched
just before push):
- TestDownloadBrokenOverHTTP2TriesHTTP1 (httptest TLS HTTP/2 server
  that resets each HTTP/2 stream after 100KB, serves HTTP/1.1 whole):
  red with the update.go line taken out, all six tries over HTTP/2
  ("stream error: ... INTERNAL_ERROR"); green after, asked
  ["HTTP/2.0 ", "HTTP/1.1 bytes=102400-"].
- TestOverHTTP1EveryHost, TestAgainOverHTTP1, TestBrokeOff: green.
- go test ./internal/netproxy ./internal/update ./internal/pii
  ./internal/claudecode ./internal/plugin ./internal/provider: ok.
- go test ./... -count=1 -timeout 45m: 86 ok, gateway 795s and agent
  303s ok; internal/gui red only on two AppKit tests already filed for
  mote's macOS 27: TestMainWindowCorners/macOS_26_SDK (#3949) and
  TestPanelHiddenByWailsMarksPageOutOfSight (#5322). Nothing in gui is
  touched here.
- gofmt -l clean; GOOS=linux and GOOS=windows go vet of the touched
  packages clean.

Not tried: a real proxy that cuts HTTP/2 (the reporter's); the retry of
pii, Bun, Claude Code and Grok against a real host (unit-covered by
AgainOverHTTP1 only); Windows/Linux test runs.
2026-11-06 23:44:58 +08:00
yetone 6abacd46c3 update: an Intel magpie under Rosetta updates to the Apple silicon build
cdredfox on Discord saw magpie at 150% of a core. Their goroutine dump
shows AstrLink Guard running in Go (guard.geluRow) in a darwin/amd64
build on an 8-core Mac. That is the Intel build under Rosetta: no
CoreML, and Go's kernels are translated, several times slower than
Apple silicon's build. AppAsset and BinaryAsset named runtime.GOARCH,
so every update fetched the Intel build again, with no way off it.

- internal/rosetta: Translated (sysctl.proc_translated), moved out of
  pii so the updater reads the same thing. pii's translated is now that
  var; its tests still replace it.
- update: arch() is arm64 for darwin/amd64 under Rosetta. AppAsset and
  BinaryAsset (the darwin CLI) use it. goos/goarch/translated are vars
  that tests set.
  Checked before switching: Stage downloads the zip, ditto unpacks it,
  sameSigner wants the same team, and Install renames it over the
  bundle. Nothing there reads the architecture, and the CLI's
  InstallBinary is a rename too. An arm64 build runs natively on every
  Mac that runs Rosetta.
- pii: Status.Rosetta, set on AstrLink Guard's Now() only. Privacy
  Filter's pf-serve is already Apple silicon's there (target).
- GUI: Settings > Privacy's local model line, while AstrLink Guard runs
  under Rosetta, says "On, slowly under Rosetta: the next update
  installs magpie for Apple silicon" in place of "On, on the CPU". It
  is the same one sub-line, with no new element. en/zh/zh-TW/ja/de.

Not done, as decided: skipping tool outputs for the model, or capping
its cores.

Run (on mote unless named):
- go test -count=1 ./internal/update ./internal/rosetta ./internal/pii:
  ok. On WSL magpie-desktop: the same three, plus go vet of them, ok.
  On Windows (xiaomi-gpu): -run "Rosetta|Asset|GuardNow" on update and
  pii, ok.
- go vet ./... (darwin) and CGO_ENABLED=0 GOOS=windows go vet ./...: ok.
  A Linux cross vet needs cgo for Wails, and WSL has no gtk4, so Linux
  vet covered the changed packages only. gofmt -l: clean.
- node --test privacy-model, i18n-keys, i18n-en-no-cjk (chromium +
  webkit, 5 languages, 1100/640px): 91 of 92. The new rosetta case
  passed in every engine, language and width. The one red is "a
  download is cancelled" (chromium). It passes alone, 1/1 at origin/main
  8eb219354 and 2/2 with this change. Filed as #5292 (wheelTo/viewOf
  return "" after a reload).
- go test -run "Budget|I18n|Lang" ./internal/gui: ok. Core scripts are
  1,530,017, under 1,533,802; no raise.

Broken by hand:
- arch() always the build's: TestRosettaUpdatesToAppleSilicon red (4
  cases), and TestRosettaStagesAppleSiliconsApp red, with Intel's
  2.0-amd64 app installed.
- No Rosetta in guardModel.Now(): TestGuardNowSaysRosetta red.
- The app.js line off: privacy-model's rosetta case red ("On, on the
  CPU").

Not tried:
- A real Rosetta process. mote has no Rosetta (no oahd); an x86_64 test
  binary built there didn't start. The translated check is the sysctl
  pii has used since the pf-serve fix, but this commit never saw it
  return 1.
- A real update from an Intel release to an arm64 one. The stage test
  swaps ad-hoc signed fake bundles through the real
  Stage/sameSigner/Install.
2026-11-05 08:25:53 +08:00
ggbdpq b9fc90a940 test(pii): a first request's wait waits for the fake pf-serve's start (#3860)
waitFor's 10s bar covers everything up to a first request reaching the
stand-in pf-serve, the stand-in's start included. A cold start alone
took 6s of it on the reporter's machine (the warm runs 2.7s), so on a
loaded machine the start ate the whole bar and the wait died as
"a first piece asked: never" - the request was never the slow part.

The waits that time a first request now wait for the stand-in's start
line first (the way TestStatusAndStopDontWaitForALoad already waits
for "pf-serve starting"): the start gets a bar of its own, and the
request's bar times only the request. The six first-request waits of
the package get it; the second-request and cache-file waits keep their
bars, their stand-in is up by then.

Fixes #3860

Generated-by: GLM-5.3-Flash (ZCode)
2026-11-01 16:43:21 +08:00
yetone 1c3591b5d1 guard: the local masking model reads text a third faster on amd64 (mrwl666)
mrwl666 (Discord #help, v0.1.2554, Docker on a 2-core EPYC) saw one
core at 100% for 2-3 s on every request with masking and AstrLink Guard
on, and took it for every message of a ~66k-token conversation being
scanned again. It isn't. Probed on the Linux VM (GOMAXPROCS=2, taskset
-c 0,1) with a 50-60 turn Chat session of ~4 KB tool results, ~240-270 KB
a body:

- rules masking (MaskJSON without the model): 5-11 ms a turn;
- the history is cached by hash (LRU + found-<rev>.bin), and a turn
  hands the model only what it added. Bounded caps that at 4 KB;
- the request waits masking's 2 s defaultWait for the model on that
  text, and guard.Cores() is 1 on a 2-core box, so one core runs the
  int8 BERT at about 1 KB a second. That is the spike.

This change makes the model's CPU cheaper; it does not take the 2 s
wait away. AVX2 kernels for the int8 dot products (dot4, attention
scores), exp in softmax and the GELU epilogue, picked at start when
the CPU has AVX2, plus plain compares in place of the builtin float
min/max (a third of the non-matmul time, for their NaN/±0 rules).
Every float op is the same per lane and in the same order as the Go
code (release builds are GOAMD64=v1, no FMA), the int8 sums are exact,
mix32 and the softmax sum keep their order, so the model finds the
same spans with the same scores to the bit.

Numbers, Linux VM (AMD Ryzen AI MAX+ 395), one core of guard:
  guard.Find on 4,247 bytes: 4.05 s before, 2.75 s after (same 20 spans)
  turn 50-57 with the model: MaskJSON wall 2.0 s both (the wait), CPU
  after the wait 0.1-3.0 s before, 0.0-2.0 s after
mote (M5 Pro, arm64, rules path, unchanged by this):
  BenchmarkMaskLongSession chat 10.3-11.7 ms, responses 10.8-13.0 ms,
  messages 12.1-13.9 ms per turn of a ~260 KB body

Tests:
- TestKernelsSameBits: the AVX2 exp/GELU/scores give Float32bits equal
  to the Go code, edge values included. Broken by hand: swapping two
  adds in the asm exp made it red (0x175156d6 vs 0x175156d5).
- TestMaxAndRangeAsBuiltins: maxOf/rangeOf agree with the builtins on
  ±0 and NaN. Red with maxOf's NaN check taken out.
- TestModelSameWithoutAVX2 (needs MAGPIE_GUARD_DIR): the real model
  finds the same spans on ~6 KB of mixed text with AVX2 and with SSE2.
- TestSessionTurnReadsOnlyWhatItAdds (internal/pii): turn 61 of a
  275 KB session, after turn 60, has the model read only turn 61's text
  (5.2 KB for 4.6 KB added). It passes on the old code too: it guards
  the claim above, not this speedup. Red (10.5 KB, earlier turns read
  again) with the cache lookup in known() turned off by hand.
- BenchmarkMaskLongSession (internal/redact): Chat, Responses and
  Messages sessions with large tool results, turn 61 after turn 60.

Run at this tree (7b6b7492a + this):
- mote: go vet ./internal/pii/... ./internal/redact, GOOS=linux amd64
  (-tags nogui), GOOS=windows amd64, GOOS=linux arm64 guard: ok.
  go test -count=1 -timeout 45m ./internal/pii/... ./internal/redact: ok.
- WSL magpie-desktop (amd64, AVX2) with MAGPIE_GUARD_DIR: the same
  packages ok (guard 28.9 s, model tests included); the three kernel
  tests again under GOMAXPROCS=2 taskset: ok.
- Windows xiaomi-gpu: the same packages ok (no model dir there).

Not tried: the reporter's EPYC itself or Docker; AVX-VNNI or AVX-512
(would need the EPYC generation; VPDPWSSD is exact, so it could come
next); mix32 on AVX2 (more accumulators change its sum order, so not
byte-identical); the full ./... suite. For no spike at all, the model
can be turned off with rules masking kept on.
2026-11-01 15:51:18 +08:00
yetone 4179cf2d8f pii: a CPU without AVX2 runs pf-serve-base, and Rosetta Apple silicon's pf-serve
echo_yip on X: Settings → Privacy's model never started, "pf-serve
(Metal): signal: illegal instruction" and the same on the CPU. x86's
pf-serve needs AVX2, FMA, F16C and BMI2, which a Celeron, a Pentium or
a Mac before Haswell lacks, and so does Rosetta before macOS 15, where
the Intel DMG on Apple silicon ran the Intel pf-serve.

- arch.go: target() is darwin-arm64 for magpie's Intel build under
  Rosetta (sysctl.proc_translated, rosetta_darwin.go), so Apple
  silicon's pf-serve, with Metal, is fetched and run. The Intel one
  already on disk is kept until the arm64 one is (tagDirs; start
  fetches it first, for at most 5 minutes, and falls back), then
  removed with the old tags.
- fullX86 asks golang.org/x/sys/cpu for AVX, AVX2, FMA and BMI2. Where
  one is missing, candidates() runs only pf-serve-base, the SSE4.2
  build the previous commit adds, when it is on disk.
- pf-v3 (privacy-filter run 41256502056 at 697335d8e) is pinned;
  pf-v2 and pf-v1 are old tags, so pf-v2 runs until pf-v3 is
  downloaded. On a CPU without AVX2 that first start still fails, and
  the retry after the download runs pf-serve-base.

Run at this commit: go test ./internal/pii/... on mote, ok; go build
./... ok; go vet ./internal/pii/... for linux, windows and darwin/amd64
ok; gofmt -l clean. Broken by hand: with candidates()'s fullX86 branch
and start()'s fetch turned off, TestBaseWhereTheCPULacksAVX2 ("starts =
[start pf-serve-vulkan MTL0]") and TestRosettaRunsAppleSiliconsServe
("started from [path pf-v9-darwin-amd64]") go red.

pf-v3's five zips, downloaded from the release and hashed here, match
its SHA256SUMS and the pins. A throwaway probe (not committed) set a
temp dir as pii's folder with the pinned model, fetched pf-v3 through
ensureServe from GitHub and masked an English and a Chinese text:
  Linux (magpie-desktop), x86 with AVX2: pf-v3-linux-amd64, Vulkan
    first, name/email/phone found
  mote, Apple M5 Pro: pf-v3-darwin-arm64, Metal, the same spans
  this Mac under Rosetta (arch -x86_64, the darwin/amd64 test binary,
    sysctl.proc_translated 1): target darwin-arm64, fetched
    pf-v3-darwin-arm64 and masked with Metal, the same scores as mote
  Windows (xiaomi-gpu): pf-v3-windows-amd64, Vulkan, name/email/phone
    found
The previous commit's qemu -cpu Nehalem run is where pf-serve-base
starts and pf-serve dies with SIGILL.

Not tried: the full go test ./... (only internal/pii changed); a real
CPU without AVX2; a Mac before macOS 15, where Rosetta has no AVX;
the GUI's Settings → Privacy page on a pf-v2 to pf-v3 upgrade.
2026-11-01 08:46:20 +08:00
yetoneandSunnyRx 7b883cc617 pii: a panic in the local model fails its request instead of ending magpie (#4553)
#4553's panic took the process down because it ran on a goroutine no
recovery covered. Every goroutine on the path now hands a panic back:

- pii's worker calls classify through classifySafely, which recovers,
  logs the stack, and returns "the local masking model failed reading
  this request (...)" as that request's error. It sets no retry
  hold-back, so the next request is tried as usual. Warm in
  astrlink.go and serve.go goes through it too.
- guard.Model.Find's per-window workers and bert.go's parallel carry a
  panic back to the caller (type carried), and give(procs) is deferred
  so a panicking window doesn't keep its cores.
- masking.find's goroutine recovers into the same error.

The gateway's mask calls already run in gwmw.Safely; the pf-serve model
runs in its own process.

Tests: TestGuardPanicFailsOnlyItsRequest (the error, the next request
masks its phone, Now().Failed stays empty), TestParallelCarriesAPanic,
TestFindCarriesAWindowsPanic (real model, a cut word table makes a
window worker panic; the caller sees it and no core is held),
TestModelPanicIsTheRequestsError (masking).

Broken by hand, each red: no classifySafely, the pii test binary
crashes; no recover in masking.find, the masking binary crashes; no
carry in parallel, TestParallelCarriesAPanic fails; no carry in Find,
the guard binary crashes (slice bounds [:5736192] capacity 384); give
not deferred, "3 cores still held after the panic".

Run: as in the stack's first commit (mote: gofmt, vet x3, the pii,
masking and gateway packages at -timeout 45m; Windows: pii, masking,
gateway Embeddings).

Not tried: a panic injected on the CoreML path (macOS, its own
binding); the full ./... suite.

Co-authored-by: SunnyRx <7306148+SunnyRx@users.noreply.github.com>
2026-10-31 18:22:49 +08:00
yetoneandSunnyRx 8a64f52561 pii: text with a run of stray continuation bytes is cut into pieces without reading past its end (#4553)
cut backs a piece's end up to a rune start with
`for !utf8.RuneStart(t[next]) { next++ }`. A run of continuation bytes
(0x80-0xbf) reaching the text's end has no rune start, so the loop read
t[len(t)] and panicked on the same worker goroutine as #4553, for any
text over a piece long (12KB+). It now stops at the text's end.

Test: TestPiecesCutMalformed (continuation runs, 0xff runs, stray
bytes between CJK; checks the pieces cover the text, stay in size,
overlap as before and always advance).

Broken by hand: the unbounded loop back makes TestPiecesCutMalformed
panic, index out of range [36864].

Run: as in the stack's first commit (mote: gofmt, vet x3, the pii,
masking and gateway packages at -timeout 45m; Windows: pii, masking).
Not tried: the full ./... suite.

Co-authored-by: SunnyRx <7306148+SunnyRx@users.noreply.github.com>
2026-10-31 18:22:49 +08:00
12483d83d2 pii: a stray byte in a request no longer panics AstrLink Guard's tokenizer (#4553)
normalize stepped each rune by utf8.RuneLen(r). For a malformed byte
that is RuneLen(RuneError) = 3, while the byte itself is 1 long, so an
Embedding input like "hello \xff" (the reporter's) sliced past the
text's end at tokenizer.go:266. The panic ran on the pii worker
goroutine ((*backend).find.func2), outside the request's recovery, so
the whole magpie process exited. Both loops (the mapper and the
grapheme fallback) now step by utf8.DecodeRuneInString's size.

The patch is ggbdpq's, the same one SunnyRx proposed on the issue.

Tests: TestNormalizeMalformedBytes (with the reporter's "hello \xff"
and an encode bounds check), TestNormalizeMappedMalformedByte,
TestModelFindsAroundMalformedBytes (real Guard model 7216b6a3b897,
spans in bounds, the phone still found), and
TestEmbeddingsWithAStrayByteUnderAstrLinkGuard in the gateway: the
reporter's body {"model":"lib/embed-1","input":["hello \xff","world"]}
returns 200, the next request's phone is masked, the model is Running.

Red on main: TestModelFindsAroundMalformedBytes panics "slice bounds
out of range [:3] with length 1" at tokenizer.go:266; the gateway test
on main's code ends the test binary with the reporter's trace through
(*backend).find.func2 (mote, macOS). On Windows (xiaomi-gpu, go1.26.8)
with main's tokenizer and this stack's recovery, the gateway test is
red with the same tokenizer.go:266 trace, caught as a 503.

Run (mote, sandbox HOME, MAGPIE_GUARD_DIR = a copy of the real model):
gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... ok; go test -tags nogui -timeout 45m
-count=1 ./internal/pii/... ./internal/masking/ ./internal/gateway/.
Windows via win-run: ./internal/pii/... ./internal/masking/ ok, and
-run Embeddings ./internal/gateway/ ok.

Not tried: a built binary or a live gateway with a real upstream; the
full ./... suite. The gateway test writes the model into the cache
folder named for guardRev's first 12 characters.

Co-authored-by: ggbdpq <ggbdpq@gmail.com>
Co-authored-by: SunnyRx <7306148+SunnyRx@users.noreply.github.com>
2026-10-31 18:22:49 +08:00
yetone d9459a5371 pii: pf-serve loads a model under a user folder named outside ASCII (Windows)
AIMetaPhD on X (Windows, Chinese user name): Settings → Privacy's
Privacy Filter said "the local masking model didn't start:
pf-serve-vulkan.exe: failed to read GGUF: C:\Users\<mojibake>\.cache\
magpie\privacy-filter\privacy-filter-q8-80efc1803eda.gguf", the same for
pf-serve.exe. pf-serve's main takes a narrow argv, which on Windows is
in the ANSI code page (936 on a Chinese system); ggml_fopen reads the
name as UTF-8 and the GPU's weights are reopened through a narrow
ifstream, so no device could open it, and its error came back in
GBK, which magpie read as UTF-8.

startOne now runs pf-serve in the model's folder and gives it the
model's file name (modelName, ASCII), never the path. That works with
the pf-v2 binaries users already have. A pf-serve error that names the
file is shown with the whole path, in UTF-8. The stand-in pf-serve in
the tests now refuses a model path with a byte outside ASCII and opens
the file from where it runs, as the real one does. TestModelInFolder-
NotASCIILoads and TestModelErrorNamesWholePath put the model under
"用户 Ünïcode". The native side (wide argv, and ggml_fopen in
weights-once.patch) is #4342. pf-serve is the only native helper magpie
starts. AstrLink Guard's CoreML paths are darwin cgo, which is UTF-8.

Run:
- Real use on xiaomi-gpu (Windows 11, zh-CN, ACP 936): the real pf-v2
  pf-serve zip and the real 1.6 GB model (both sha256 match the pins)
  under C:\Users\yeton\runs\pf-测试用户\.cache\magpie\privacy-filter.
  A temporary test (not committed) pointed dir there and called Find
  through win-run. Vulkan (AMD Radeon 8060S) loaded in 3.7s and found
  the person and the email. Forced onto the CPU, it loaded in 7.0s with
  the same finds. Broken by hand (the old full-path argv), it gave the
  reporter's exact error, the folder in mojibake, on both programs.
- Broken by hand on mote: with the old argv, both new tests are red.
- win-run go test ./internal/pii/...: ok (the real test included).
  wsl-run go test ./internal/pii/: ok.
- mote: gofmt ok; GOOS=darwin/linux/windows go vet -tags nogui ./...
  ok; GOOS=windows go vet ./internal/pii/... ok.
- mote: go test -count=1 -timeout 45m ./... at base e863f520c: every
  package ok except internal/gui's TestMainWindowCorners/macOS_26_SDK.
  That is #3949 (macOS 27 on mote), and gui is untouched here.
- After rebasing onto 9e8c22dad (7632e1be1 changed internal/redact and
  internal/masking): pii, redact and masking were run 4 times.
  redact's TestMoreKinds was red once with its output lost, then
  passed 3 runs, -count=8 alone and -count=3 of the package. Filed as
  #4345. pii and masking were ok every time.

Not tried: the GUI on the reporter's real machine. No GUI file changed:
the GUI shows the error text the Go code sends, which is now UTF-8.
2026-10-30 10:53:28 +08:00
yetone e61e10535d privacy: AstrLink Guard reads several requests at once, on 4 cores between them
yyhhyyyyyy (Discord, 10-28) saw an agent's parallel requests queue behind
Guard's one turn and asked for a concurrency setting (16). The turn now has
guard.Cores() places (half GOMAXPROCS, 4 at most). The cores are shared: a
process-wide pool of Cores() tokens, each window takes one before it reads
and more only while they are free (guard.take), so requests together never
use more cores than one did (the 4-core cap of 10-28, xinvxueyuan and
shensmart). The model loads once (guardLoading), the idle unload waits for
every place (guardIdle), and a text one request is reading another waits
for instead of reading it too (backend.reading). On CoreML windows are read
one at a time; only windows under coremlMin or after a failure take CPU
tokens.

No setting: measured, the bound is cores, not the request count.
Bench (zz bench, not committed): requests/s at 1/2/4/8 concurrent.
- Linux (WSL magpie-desktop, Ryzen AI Max+ 395, Cores()=4):
  512 B  shared 4.2/6.1/8.1/8.4 on 1.9-3.9 cores, rss ~150 MB
         one turn (before) 4.2 whatever came
         unshared 4.4/8.8/14.1/20.4, on 12 cores at 8
  4 KB   shared 0.6/0.5/0.6/0.7 (one 4 KB already reads 3 windows on 3.6 cores)
         unshared 0.6/1.1/1.7/2.2, 20 cores and 521 MB at 8
- Windows (xiaomi-gpu, same box, busy with other runs):
  512 B  shared 7.5/9.2/11.3/12.1 on <=3.8 cores; unshared 5.1/9.6/15.9/24.1 on 13 cores
  4 KB   shared 0.7/0.8/0.8/0.8; unshared 0.9/1.2/1.8/2.4, 18 cores, 519 MB
- mote (M5 Pro, load 25-45): CoreML 4 KB 23.0/19.6/25.1/24.9, a model a
  worker 15.7/25.6/25.5/23.4, rss ~190 MB flat: the GPU is the bound.
  CPU unshared 4 KB at 8: 953 MB.

Tests: turns_test.go (TestGuardReadsRequestsAtOnce, TestGuardIdleWaitsForEveryTurn,
TestOneTextReadOnceAtOnce), guard/cores_test.go (TestTakeHoldsOnlyWhatIsFree,
TestFindsAtOnceReadAsOneAtATime: concurrent finds equal serial ones).
Broken by hand, each red: one turn ("1 turns, 4 cores"), no load lock
("4 loads"), idle taking one place ("let go while a request read it"), no
in-flight check (TestOneTextReadOnceAtOnce), take waiting for more (10s
timeout fail).

Run:
- wsl-run: go test ./internal/pii/... ok; -race -count=3 ./internal/pii ok;
  -race guard TakeHolds/FindsAtOnce ok.
- mote-run: gofmt -l internal clean; GOOS=darwin/linux/windows go vet
  ./internal/pii/... ./internal/masking/ ok; MAGPIE_GUARD_DIR=real model
  go test ./internal/pii/... ./internal/masking/ ok (CoreML).
- win-run: go test ./internal/pii/... ./internal/masking/ with the real model ok.
- mote-run full go test -timeout 45m ./... of this and the commit before
  (at c3462d5fe): red only in TestClaudeAccountsSpentFallBackToCodex
  (#2858, #2859), TestGatewayHookWaitsForStartingHost (#2871), both ok
  alone after, and AppKit window tests in internal/gui (#2645, #4125), red
  the same alone at origin/main e15b2277c on mote.
Not tried: a real agent's parallel requests through the gateway.
2026-10-29 13:45:01 +08:00
yetone 1b7a087565 privacy: Settings names what reads AstrLink Guard, CoreML on its device or the CPU
yyhhyyyyyy (Discord, 10-27) saw Settings say "On, on the CPU" while Guard
read through CoreML. The status now names the backend in use: CoreML on the
device most of the compiled program's estimated cost is on, read from
CoreML's own compute plan (MLComputePlan, macOS 14.4+; coreml.Plan,
coreml.Most, Model.Device), or the CPU, and after a CoreML read fails the
CPU with why (guard.Backend, mlFail; Status.Via, Device, GPUError; pmSub in
app.js, 5 words in zh, zh-TW, ja and de).

On mote (M5 Pro, macOS 27) the plan reads Neural Engine 0.000, GPU 1.000,
CPU 0.000, so Settings says "On, with CoreML on the GPU".

No budget raised: on main after #4133 moved Web search's rows out, app.js
is 1,294,410 bytes with this change, under its 1,311,735.

Tests: coreml/plan_test.go TestMost; guard/coreml_test.go TestBackend,
TestFailedCoreMLReadIsSaid, TestCoreMLPlanNamesADevice (real model);
astrlink_test.go TestGuardNowNamesItsBackend; privacy-model.test.cjs
"AstrLink Guard says what runs it".

Run:
- mote-run: gofmt -l internal clean; GOOS=darwin/linux/windows go vet
  ./internal/pii/... ok; MAGPIE_GUARD_DIR=real model go test
  ./internal/pii/... ok; go test -run Budget ./internal/gui ok (again after the rebase
  onto d5eac64f2).
- wsl-run (mote's pboard is down, #4125, browser launches hang there):
  privacy-model, i18n-keys, gui-de, gui-ja, gui-zh-tw,
  privacy-hides-accounts: 101 of 101 pass, the new test in chromium and
  webkit, en/zh/zh-TW/ja/de at 1100px and 640px.
- mote-run full go test -timeout 45m ./... with the next commit: reds named
  there, each with an issue.
Not tried: a Mac whose plan picks the Neural Engine.
2026-10-29 13:45:01 +08:00
yetone 2cdbe92ded pii: a value the model found sure once in a text is sure wherever it found it there
wangwu25685333 on X (10-29): of one sentence with an address repeated
400 times, the address was left unmasked "a few times", thought to be
where the text was cut into chunks.

Reproduced with the real model (AstrLink Guard, pure Go, Linux box,
GOMAXPROCS=4) through masking's strict path and redact.MaskJSON, 400
copies of a sentence in one message:
  "Please ship it to 1600 Amphitheatre Parkway, Mountain View, CA 94043
  by Friday." joined by "\n": 346 of 400 left as written; by " " or
  nothing: 0. Two Chinese addresses, any joiner: 0.
It isn't where the text is cut. Guard found the address on every line,
but less surely the more often it had read it in the text: 0.99 alone,
0.59-0.70 at 20 copies, and on 400 the whole address 325 times at 0.50
to 0.90 and split ("1600" at 0.85, the rest at 0.50-0.59) 65 times.
Masking takes 0.8 and over, so it masked only the sure ones, about one
a piece. Joined by "\n" the pieces are alike, so every piece got the
same few sure finds.

Now spread puts each value of 8 bytes or more the model found in a text
(minSpread, as redact's minKnown) wherever else it is in that text,
with its label and the score of its surest find there, then merges. A
value never found sure stays as unsure as it was, and a house number
alone isn't looked for. It runs on each text and piece the model reads
and on a long text's merged pieces, before they are cached. Spans from
the disk cache written before keep their scores until read again.

After, the same probe: 0 of 400 left for every sentence and joiner.

Test: TestValueFoundSureOnceIsSureThroughoutItsText has a stand-in model
that finds an address sure only first in its first read and unsure
after, on 3 and 400 lines, and fails when an address is left unsure,
another value never found sure is raised, or a short one is spread.
Broken by hand: without spread in find.go it fails ("1600 Amphitheatre
Parkway" at 110 scored 0.50).

docs/subsystems/gateway-routing.md says this, the pieces' ends
(landmark) and the turn's order (takeTurn, queue) of the two commits
before.

At ca221e115 with the three pii commits of this push: gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... and go build ok (mote); go test ./internal/pii/...
./internal/masking ok on mote, on Windows (win-run) and with -race on
Linux (wsl-run). Not run before the push: go test ./... (both mote and
the Linux box were running other sessions' full suites, one a machine).

Not tried: the reporter's own sentence (not in the tweet); 400 copies
spread over 400 messages (each its own text, read alone at 0.99 here);
Privacy Filter (spread is the same for both models, tried on Guard).
2026-10-29 01:28:25 +08:00
yetone 43a9d04400 pii: of the requests waiting for the local model, the one with the least left to read goes next
wangwu25685333 on X (10-29, v0.1.1840, Linux, i5-7500 4c/4t, AstrLink
Guard on): requests of 1.4K tokens waited 8.5s for the model behind a
fresh session's 31.5K, and their client gave up at 20s.

The model's turn was a buffered channel, and the requests blocked
sending on it took it in the order they came. A long request gives the
turn up between chunks (4 KB for Guard, about a second or more on 4
cores), but a short request that came after another long one waited
a chunk of each long request ahead of it.

Now each request waiting says how much it has left to read (the bytes
of its texts and pieces neither got nor the cache has; of a Bounded
request's backlog, no more than it will read), and only the one with
the least left (the first to come of those with as little) sends on the
turn; the others wait for the queue to change. The channel stays, so
Warm and guardIdle take the turn as they did. Privacy Filter's pf-serve
turn is the same backend and gets the same order.

Measured with the real model (AstrLink Guard, pure Go) on the Linux box
(wsl magpie-desktop) with GOMAXPROCS=4 taskset -c 0-3, a 5 KB request
sent 1.5s after long requests (a 110 KB system prompt each, cold):
  alone:          2.47s before, 2.54s after
  behind 1 long:  5.49s -> 4.91s
  behind 2 long:  8.29s -> 4.50s
(after: the chunk on the model when it came, then its own two chunks;
before, 8.3s is the reporter's 8.5s.)

What this leaves as it was: masking's waits (2s for the model on by
default, then the rules alone; 15s for a model the user turned on) and
its log line when the rules mask alone (notePartial, once a minute) are
unchanged. Most of the reporter's case was fixed after v0.1.1840 (tool
definitions not read v0.1.1871, the 2s and 15s waits v0.1.1874 and
v0.1.1886, newest first and a 4 KB chunk v0.1.1891, windows in
parallel v0.1.1864).

Order is by bytes left, not by age: a long request waits while shorter
ones keep coming. With masking's waits bounding every request, a long
one waits until its wait ends and the rules mask the rest.

Test: TestShortRequestGoesBeforeLongOnes puts a long request (4 chunks)
on the model, another long one waiting, then a short one, and fails
unless the short one is read second. Broken by hand: with find.go of
the previous commit it fails, read in the order d, h, hi Alice, c, g...
(the second long request's chunk first). Run -race -count=20 with the
turn tests (TestStopped*, TestWaiter*, TestQueued*) on mote: ok.
Run (mote): go test ./internal/pii/... ./internal/masking ok; gateway
-run 'Mask|Redact|PII|Guard|Model' ok.
At ca221e115 with the three pii commits of this push: gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... and go build ok (mote); go test ./internal/pii/...
./internal/masking ok on mote, on Windows (win-run) and with -race on
Linux (wsl-run). Not run before the push: go test ./... (both mote and
the Linux box were running other sessions' full suites, one a machine).

Not tried: a real Hermes client with its 20s timeout; the reporter's
4c/4t i5 (the Linux box is a 32-core AVX-512 machine held to 4 cores).
2026-10-29 01:28:25 +08:00
yetone 40593e898c pii: a long text's pieces end where its own text says, so an edited system prompt is read again around the edit only
wangwu25685333 on X (10-29, v0.1.1840, Linux, i5-7500 4c/4t): a fresh
Hermes session of 31.5K tokens spent 98.8s in the local model (AstrLink
Guard) and 2.3s upstream, and every new session (cron opens one each
time) read the same ~30K of system prompt again.

The cache by content was already there (#3682: sha256 of each text or
piece -> spans, in memory and in found-<rev>.bin, no text), and tool
definitions are no longer read (a5315c70d). What made a fresh session
miss it is how a long text is cut: a piece ended after the last line's
end in its second half, so its end was a distance from the piece's
start. A line of the prompt edited (Hermes puts its date, memory and a
workspace snapshot in the prompt) moved every later piece's ends by as
many bytes, and every piece after the edit was new to the cache.

Now a piece ends after the line's end (else space) in that second half
whose 48 bytes before it hash least (FNV-1a): the text's own choice. Once
one end meets an end of before, the rest are the same pieces, known by
hash. The rune-start fallback (no line's end or space in 2 KB) is
unchanged.

Measured, pieces new to the cache after one edit (4 inserts x 2
deletes at every ~1 KB) of three texts, guardChunk pieces (cut only):
  39 KB of AGENTS.md/LESSONS.md/code-standards: mean 3.92 -> 1.65,
    worst 13 of 13 -> 5 of 18
  68 KB of LESSONS.md/agent-wiring.md: 2.80 -> 1.63, worst 14 -> 6
  58 KB of prose(): 4.96 -> 1.64, worst 20 of 20 -> 4 of 28
The cost: pieces are 3/4 as long on average, so a cold read reads
142% of the text where it read 130% (overlaps). Tried and dropped:
a narrower window (3/4 of the piece: 2.49 mean, worst 9) and the last
line's end whose hash is 0 mod K (K 4..32: worst 9 to 15 at the
small K, no better than this at 32).

The real model (AstrLink Guard, int8, pure Go) on the Linux box with
GOMAXPROCS=4 taskset -c 0-3 (wsl magpie-desktop), a 110 KB Hermes-like
system prompt (about 28K tokens; AGENTS.md, code-standards, LESSONS.md
and two subsystem pages, a memory section, a date line):
  cold:                         59.9s -> 62.4s
  a line added at 10/25/50/75%: 3.06/4.77/1.79/2.49s ->
                                1.35/2.93/1.65/2.48s (mean 3.03 -> 2.10)
  memory line + date changed:   2.83s -> 2.72s
  the same prompt again:        0s both (the cache by hash)
On mote (CoreML) the cold read is 1.3s both ways.

Test: TestEditedTextReadsItsPiecesAgainOnly reads a 40 KB prompt-like
text, then the same with a line inserted at 14 places x 4 inserts, and
fails when more than 3 pieces' bytes are read again or a span is lost.
Broken by hand: with find.go of origin/main it fails ("Conversation
started: ..." at 536: 53573 bytes read again, want at most 12288).

Run (mote): go test ./internal/pii/... ./internal/masking ok; gofmt -l
clean.
At ca221e115 with the three pii commits of this push: gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... and go build ok (mote); go test ./internal/pii/...
./internal/masking ok on mote, on Windows (win-run) and with -race on
Linux (wsl-run). Not run before the push: go test ./... (both mote and
the Linux box were running other sessions' full suites, one a machine).

Not tried: the reporter's own Hermes prompt (it is on their machine);
the measure is on this repo's docs and on prose(); a CJK text with no
line's end or space for 2 KB still cuts by distance.
2026-10-29 01:28:25 +08:00
yetone 6a074fc132 pii: the default's local model reads what a request adds first, a backlog 4 KB a request, on 4 cores at most
shensmart and xinvxueyuan on Discord (10-28): with the local model on by
default, a long history kept the CPU high; the model off, 5-15%.

What was heavy (measured, TestLiveHistoryCost below): not re-reading.
A text read once is kept by hash (cache, on disk too), and a warm turn
costs what the rules alone do. The heavy case is a history the model
hasn't read (a resumed session, or one from before the model was on),
on the CPU path (Linux, Windows, Docker). Each request's 2 s wait was
spent reading that history oldest first on every core (threads =
GOMAXPROCS-1, windows at once = GOMAXPROCS), the newest turn last, and
the 12 KB chunk in flight was finished past the wait. A 32-core Linux
box spent 33-60 CPU seconds a request, 13 cores busy for as long as
requests came, and the backlog was still unread after 30 requests.
Nothing ran on after the last request (1 ms CPU in the 20 s after).

Now:
- guard.Cores: AstrLink Guard reads on half of GOMAXPROCS, 4 at most.
- backend.missing reads a request's unread texts newest first (the last
  text, a long one's last piece, first).
- AstrLink Guard's chunk is 4 KB (backend.chunk), not 12 KB, so what a
  request leaves the model finishing past its wait is about a second.
- pii.Bounded (masking's default, not a model the user turned on):
  what a request went without reading is remembered by hash
  (backend.sent); a request after it reads what it adds first, and that
  backlog backlogCap (4 KB) at most, nothing found for the rest (the
  rules mask it, as past the 2 s wait). The answer past the wait with
  what was read is 874b86653's (pii.Partial), unchanged.
- A model the user turned on (strict) still reads everything, within
  874b86653's strictWait.
- Not done: OS priority (nice) for the model's threads; the core cap
  is the bound.

Measured, TestLiveHistoryCost (internal/masking, gated on
MAGPIE_GUARD_FILES, no network): a 2,041,658-byte Codex Responses
body (2,032,267 bytes at the rebased tree), 200 turns (repo files as tool output, doc paragraphs as answers,
Chinese names and an email every 10 turns), 30 requests 3 s apart, a
turn more each, model never having read it, then 20 s idle.

WSL2 Ubuntu 24.04 on xiaomi-gpu (32 cores, CPU path):
  before: 33-60 CPU-s a request (44.0, 38.3, 50.4, 42.8, 54.3 ...),
          session 23m16.8s CPU over 1m48s (1293% of a core),
          wall median 2.759s, max 3.07s; 20 s after: 1 ms
  after:  6.3-9.2 CPU-s a request, session 4m1.5s over 1m30s (268%),
          wall median 2.389s, max 2.438s; 20 s after: 1 ms
  warm turn after a full read: 876ms wall / 5.284s CPU before; after
          the rebase the "full read" is strict and stops at 874b86653's
          15 s, so that line is not a warm turn (2.41s / 7.9s); before
          the rebase, at a full read, 1.28s / 3.04s (4 cores, not 31)
  rules alone: 394 / 384 ms CPU
mote (M5 Pro, CoreML):
  before: requests 1-3 2.2 CPU-s each, then ~0.45; session 18.7s CPU
          over 1m30s (21%); warm 396ms / 380ms
  after:  request 1 2.12 CPU-s, then 0.44-0.62; session 17.2s CPU
          (19%); wall median 562ms; warm 476ms / 465ms

On the CPU path a turn adds about 15 KB here, more than 4 cores read
in 2 s, so each request still spends its wait (now on 4 cores, newest
text first) and the backlog isn't reached until turns get shorter;
on CoreML the backlog is gone after the first request.

Tests, each red with its part of the change undone by hand:
- TestNewestTextReadFirst (pii): red on the old code as it stands
  ("read first: a a a ..."); red again with the last piece not first.
- TestBoundedReadsTheBacklogALittleARequest: backlog cap removed, the
  second request read 75169 bytes.
- TestGuardReadsShortChunks: red with guard's chunk unset (12288).
- TestReadsOnFewCores (guard): Cores at 32 and 1 procs.
- TestDefaultModelIsBounded (masking): red with the default's ctx not
  Bounded ("on by default, the model wasn't asked Bounded").
- TestJoinSplitsAtChunkSize now expects the newest-first order.

Rebased onto 874b86653 (strictWait, pii.Partial), which made the
same partial-answer change; mine was dropped for its. Everything below
was run again at the rebased tree.

Run at this tree: gofmt -l clean; go vet darwin, GOOS=linux and
GOOS=windows -tags nogui on internal/pii/..., internal/masking,
internal/redact; go test -count=1 -timeout 45m of those on mote,
wsl-run (magpie-desktop) and win-run (xiaomi-gpu), all ok; internal/gwmw ok;
-race -count=5 of the pii/masking turn, wait, partial and bounded tests
on mote ok; internal/gateway, internal/gui -run
'Mask|Redact|Privacy|PII' ok; TestLiveHistoryCost on mote and WSL. Not run: the full ./... suite.
Not tried: a real Codex session through a live gateway.
2026-10-28 19:53:35 +08:00
yetone 874b86653d masking: the model the user turned on is waited 15s at most, and what it read is kept (xRayySummers on X)
xRayySummers on X (0.1.1877, Linux, AstrLink Guard turned on in
Settings -> Privacy): in one minute masking took 1.2s to 290s, and each
request whose wait ended was "gateway: masking failed, so nothing was
sent".

Cause: the model reads on the CPU one chunk at a time on one turn,
about 6 KB a second on 8 Linux cores. A burst of requests with text it
hadn't read (new tool results, subagents at once) queued behind each
other, and the turn goes round between chunks, so all of them finished
near the end of the burst. Turned on by the user, the wait had no
bound, and when anything ended it (the client, a deadline) masking.model
panicked: the request was held back whole, and even the finds already
cached for its history were thrown away (backend.find returned nil).
Not a reload (60-90ms) and not a lock in redact.

Now:
- pii.FindContext, when the wait ends, answers with what was known of
  the texts (its cache: earlier turns' history, chunks read meanwhile)
  and a *pii.Partial saying how many it hadn't read.
- masking.model waits at most strictWait (15s) for the user's model,
  defaultWait (2s) for the default's as before. Past it, the model's
  finds mask what it read and the rules mask the rest alone; the request
  goes. Nothing the rules mask goes as written. Logged once a minute.
- A model that fails (not on disk, didn't load, held back after a
  failure) still holds the user's requests back, as before: broken, not
  busy.
- masking.find gives a model that doesn't stop for ctx 100ms (handBack)
  to hand back what it knew, so a partial answer racing ctx.Done isn't
  dropped.
- docs/subsystems/gateway-routing.md says so, with the numbers below.

Run:
- Reproduced with the real AstrLink Guard (guard-7216b6a3) on Linux
  (wsl-run, magpie-desktop, GOMAXPROCS=8), a throwaway test not
  committed: load 63-87ms, reload on a request 57ms, a 125 KB history
  20.8s first read and 66us cached; six requests at once with 67-145 KB
  of new text each took 62, 91, 92, 108, 108 and 110s on the old code.
  With this change each went at 15.0s with the history's 14 finds and
  the model's finds for 1 to 4 of its 9 texts.
- mote-run at df9376592 plus this change: gofmt -l clean; go vet of
  internal/pii, masking, gateway for darwin, GOOS=linux and
  GOOS=windows ok; go test -timeout 45m ./internal/pii/...
  ./internal/masking/... ./internal/redact/... ./internal/gwmw/...
  ./internal/gateway/ all ok (gateway 459s).
- wsl-run and win-run: go test ./internal/pii/... ./internal/masking/...
  ok.
- After the rebase onto origin/main (no overlap in these files): the
  same pii and masking tests again through mote-run, ok.

Broken by hand, each red:
- backend.partial back to `return nil, waitErr(ctx)`:
  TestStoppedRequestKeepsWhatWasRead fails (no Partial).
- strict mode waiting with no deadline:
  TestStrictModelStalledIsTheRulesForWhatItDidntRead fails at its bound
  ("held the request with no bound").
- strict mode panicking on a Partial as the old code did: the same test
  fails ("held back").

Not tried: the reporter's machine, and a real Claude Code burst through
the gateway with the model on; the reproduction called the model's
backend directly.
2026-10-28 19:17:41 +08:00
yetone e296211b8b masking: the default's local model is waited for 2s at most, then the rules mask alone
shensmart on Discord (10-28, magpie in Docker on Linux, web UI remote):
Codex's requests sat "masking…" on the Requests page from about ten
minutes into use. ae0327945 (v0.1.1858) turned the local model on by
default: once its download finished it was recorded (RedactModelAuto)
and warmed, and every request then waited for it. Under the default
model() passed the request's own ctx to m.Find, so the wait (for the
one-at-a-time turn, the load, and a whole uncached history read 12 KB a
chunk on the CPU) lasted as long as the client did, and the unrouted
watch doesn't count masking time. AstrLink Guard is pure Go on the CPU,
so it runs in a container, slowly; a slow model was the hold, not one
that failed (that one already fell back to the rules).

- masking.model: not turned on by the user (strict false), the model
  is waited for defaultWait (2s) from the request's masking start, and
  given up even where Find doesn't stop for ctx (a goroutine and a
  select); then it finds nothing and the rules mask alone. Turned on by
  the user, unchanged: the request waits, and is held back on failure.
- pii backend.find: a caller that stopped waiting leaves the chunks
  after the one under way, instead of a select on a free turn and an
  ended ctx taking either, so a stopped read doesn't hold the turn every
  later request's 2s needs. The chunk under way is still finished and
  kept, so the next request finds it.

Run (mote, Go 1.26.8):
- gofmt -l clean; go vet of internal/masking and internal/pii, and
  GOOS=linux and GOOS=windows vet of both.
- go test -count=1 ./internal/masking ./internal/pii ./internal/redact: ok.
- At the rebased head (on 0b99b8fbe): go build -tags nogui ./..., vet
  as above, go test -count=1 of masking, pii, pii/guard, redact: ok.
- go test -count=5 for the new and nearby tests (TestDefaultModel*,
  TestNoModelYet*, TestModel*, TestStoppedRequestLeaves*): ok.
- go test -count=30 -run TestStoppedRequestLeavesTheRestOfItsChunks
  ./internal/pii: 30 of 30 ok.

Broken by hand: both new tests were run on the old masking.go and
find.go, with only a defaultWait var added so the tests compile.
TestDefaultModelHangingIsTheRules was red 20 of 20 ("on by default, a
model that never answers held the request", at its 10s bar).
TestStoppedRequestLeavesTheRestOfItsChunks was red 19 of 30: 2 or 3
chunks were read for a request that stopped after the first.

Not tried: a real Docker container with the downloaded AstrLink Guard
and a real Codex history; the reporter's machine. The masking page's
原文/对照 buttons are disabled with no word why when the original body
isn't held (a restart, over 4 MB, out of the last 100): not changed
here, filed as #4045.
2026-10-28 17:52:53 +08:00
yetone aca0f0d8a1 guard: a long text's windows are read at once, one a core (niuniu_8964 on X)
码妞 on X: on a 4-core server in the Docker image, with AstrLink Guard,
Claude Code's requests sat at 脱敏中 for minutes, load 1.78. Guard read a
long text's 510-token windows one after another, and split only each
window's matmuls and attention over GOMAXPROCS-1 goroutines; the layer
norms, biases, GELU and quantizing between them ran on one core. A
2-CPU container got one thread for all of it.

Find now reads every window's logits first, min(GOMAXPROCS, windows) at
once, each with GOMAXPROCS/that many goroutines of its own, then merges
them in window order as before, so what it finds is the same. A window's
procs are passed down (logits, encode, matmul, attention, parallel) in
place of the package's threads. CoreML (a Mac) still reads one window at
a time.

Measured on magpie-desktop (WSL, Ryzen AI Max+ 395), 69,495 bytes of
docs, 22,488 tokens, ~59 windows:
  GOMAXPROCS=4: 23.86s before, 17.90s now
  GOMAXPROCS=2: 48.8s before, 30.50s now
  GOMAXPROCS=1: 50.0s before, 57.0s now (the same code path; noise)

Run:
- wsl-run with MAGPIE_GUARD_DIR at the pinned model (rev 7216b6a3):
  TestWindowsAtOnceReadAsOneByOne (new: 200 synthetic contact lines, over
  4 windows, read at GOMAXPROCS 1 and 4, spans DeepEqual), TestModelFinds,
  TestKernelsMatchGo, TestTokenizerMatchesHF, TestDecodeBIO: ok.
- mote-run: go vet ./internal/pii/..., GOOS=linux and GOOS=windows go vet
  of it, go test -race ./internal/pii/..., go test ./internal/pii/...
  ./internal/redact/...: ok.
- win-run go test ./internal/pii/guard: ok.

Broken by hand: swapping the first two windows' logits after the wait
made the new test red ("windows at once found 800 spans, one by one
800": the same count, different spans).

Not tried: the reporter's own server, or a real Claude Code request
through the Docker image; TestCoreMLMatchesGo (needs the model on a
Mac) was only compiled. The full suite wasn't run: nothing outside
internal/pii/guard calls what changed but Find.
2026-10-28 17:15:16 +08:00
yetone 02cbdf5bdc pii: pf-serve-vulkan keeps the engine's 4096-token MoE chunk; 2048 was slower (#3682)
7279bdc28 gave pf-serve-vulkan PF_MOE_CHUNK=2048 on the strength of a
1.77x speed-up yunwang2442-creator measured on an RX 470 (Windows,
Vulkan). Their re-test on 0.1.1696 found that number came from runs
hours apart: the same version read the same 480 KB text in 67s at 07:44
and 128-135s after 16:00. Interleaved A/B in one session, same text,
4096 was faster every time:
  96 KB in pieces  2048 25.4-25.8s   4096 24.0-24.2s
  24 KB in pieces  2048 6.2-6.5s     4096 6.0s
  96 KB whole      2048 36.1-36.7s   4096 32.7-33.8s
  480 KB whole     2048 175.6s       4096 161.6s
with the same spans either way. On Metal 2048 was ~6% slower already
(7279bdc28's own numbers). So no pf-serve gets a PF_MOE_CHUNK from
magpie now; one the user set is still inherited through os.Environ,
as before.

moeChunk and vulkanMoEChunk are gone. TestVulkanServeGetsMoEChunk is
now TestServeKeepsMoEChunkUnlessUserSets: pf-serve-vulkan sees no
PF_MOE_CHUNK, and a user's 3072 reaches both.
docs/subsystems/gateway-routing.md says the same.

Run at this head (on 90258cf20):
- gofmt -l internal/pii: clean
- go vet -tags nogui ./internal/pii/ for GOOS linux, windows, darwin: ok
- go test -timeout 45m ./internal/pii/: ok (25.2s)
- Broken by hand: with HEAD's serve.go and the new test,
  TestServeKeepsMoEChunkUnlessUserSets/vulkan fails ("moechunk
  pf-serve-vulkan 2048", want no value); green with this serve.go.

Not tried: a Vulkan GPU here (none on this machine); the numbers above
are the reporter's, from their RX 470. Other GPUs aren't measured;
PF_MOE_CHUNK stays the override for one where 2048 is faster.
2026-10-28 00:50:09 +08:00
yetone a47596ea61 privacy: AstrLink Guard is the default local model; its menu stands apart from the switch
Settings > Privacy's "Find with a local model" row put the model menu 2px
from the Off/On switch (.prefs .val's gap): two bordered boxes touching.
The row's .val now has an 8px gap.

With no model picked, pii.Choose is AstrLink Guard. Before, it was Privacy
Filter whenever the model was on or Privacy Filter was on disk. Now
Privacy Filter is chosen only while the model is on, Privacy Filter is
downloaded and AstrLink Guard isn't, so a request isn't held back. In
that case masking.picked starts AstrLink Guard's 38 MB download
(toGuard, tried again an hour after a failure). Once it is on disk,
AstrLink Guard is saved as the pick, unless the user picked a model in
between, and Privacy Filter is let go.

Existing users:
- Privacy Filter on with no pick: moved to AstrLink Guard after the
  download. Privacy Filter stays on disk and can be picked again.
- Privacy Filter explicitly picked: unchanged.
- Model off: the menu now shows AstrLink Guard.

Run at this tree, on origin/main:
- go test ./internal/pii ./internal/masking: ok. TestChoose is updated,
  with Privacy Filter on disk both off (Guard) and on (PF).
- go test ./internal/gui -run 'Budget|I18n': ok.
- privacy-model.test.cjs, chromium + webkit, every language, 1100/640:
  64/64. The new gap check fails with the CSS line removed (gap 2).
- gofmt, vet (darwin, linux nogui, windows), linux and windows builds:
  ok.

Not tried: toGuard's real download and switch-over. It needs the
network, and no test covers it.
2026-10-27 23:18:24 +08:00
yetone f0ffee34ce guard: on a Mac AstrLink Guard runs through CoreML, 512 tokens in 12ms where the CPU takes 400
yyhhyyyyyy on X asked for CoreML. internal/pii/guard now runs the
encoder (everything after the embeddings) as a CoreML program on a Mac
with macOS 13 or later, on the Neural Engine or GPU (MLComputeUnitsAll).
bert.go still does the embeddings and stays the path everywhere else.

- coreml_gen.py builds the program with coremltools' MIL builder from
  the pinned int8 model: the int8 weights dequantized, float16 compute.
  The repo keeps only the graph (coreml.mlmodel, 112KB) and coreml.json
  (each blob's offset, weight.bin's size and sha256). On each Mac the
  weights are written from the model already downloaded (coremlWeights,
  float16 rounded to nearest even as numpy does), checked against that
  sha256, compiled once into <model dir>/coreml/<sha>.mlmodelc (about 5s,
  41MB), and opened from there after that (40-170ms). Nothing new is
  downloaded or hosted.
- The cgo lives in internal/pii/guard/coreml, because guard has Go
  assembly. Without cgo or off darwin it is a stub (Available false).
- A window under 16 tokens (coremlMin) stays on the CPU, which is faster
  there (8 tokens: 8.7ms CPU, 12.5ms CoreML; 16: 17 vs 13). A Mac before
  macOS 13, a failed write, compile or open, or a failed run goes to the
  CPU too. Model.MLErr keeps why.

Accuracy against the publisher's fp32 ONNX (onnxruntime): CoreML's
probabilities are within .067, the CPU's within .129, and both agree
with fp32's labels on the same tokens. The CPU quantizes activations as
the int8 model does and CoreML doesn't; fake quantization in the program
was tried and didn't match the CPU (.75 on CPU fp32, .70 on GPU,
unstable in fp16), so it was dropped. A span near the threshold can fall
the other side: TestModelFinds' go.mod module path is a common_secret at
.814 on CoreML, .788 on the CPU and .785 in fp32, so on a Mac it is
masked at the default 0.8. TestModelFinds now tests bert.go alone
(m.ml = nil), and TestCoreMLMatchesGo holds CoreML to it.

Run (M4 Pro, macOS 26.2, under load ~50):
- gofmt -l internal/pii: clean. go vet ./internal/pii/... with GOOS
  darwin, linux, windows and CGO_ENABLED=0: clean.
- MAGPIE_GUARD_DIR=<pinned model> go test ./internal/pii/...
  ./internal/redact/... ./internal/masking/... -count=1: ok. In guard:
  TestHalfRounds, TestCoreMLWeights (weight.bin's sha256),
  TestCoreMLMatchesGo (99%+ argmax agreement on a 512-token window, the
  same spans as the CPU with scores within .2; loaded in 6.3s cold,
  17ms for 512 tokens), TestCoreMLFailureFallsBack and TestModelFinds.
- TestMaskEval/astrlink-guard replayed with outputs recorded through
  CoreML: the same verdicts at the default threshold; scores moved a
  little and one account_number span at .508 is new, under 0.8.
  eval-astrlink.json stays the CPU's recording.

Broken by hand: half() rounding ties up instead of to even turns
TestHalfRounds red; a wrong sha256 in coreml.json makes Load fall back to
the CPU with MLErr set, find the same spans and leave the compiled
program in place (TestCoreMLFailureFallsBack).

Not tried: an Intel Mac, macOS 13 or 14 (only 26.2), the real app's GUI
with Find with a local model on (the gateway path calls the same Find).
2026-10-27 15:01:32 +08:00
yetone 31abac2a9f guard: TestModelFinds keeps what masking keeps, at MinScore
Since ea7c0067e Find gives spans down to Floor (0.5), and masking
drops those under the threshold. TestModelFinds took every span Find
gave, so the go.mod line's module path, a common_secret at .79, came
in and the test was red. It runs only with MAGPIE_GUARD_DIR set, so
neither the suite nor CI ran it, and ea7c0067e's run didn't either.

Run: MAGPIE_GUARD_DIR=<the model> go test ./internal/pii/guard -v,
every test ok; TestModelFinds was red at origin/main before.
2026-10-27 15:01:32 +08:00
yetone ea7c0067e0 privacy: each local model's confidence threshold is the user's to set
Yayoi_no_yume on X asked for the privacy model's threshold to be
adjustable: they read it as fixed at 0.5, and from their own use find
0.85-0.95 right for AstrLink. The 0.5 is Privacy Filter's (pf-serve's
argv default); AstrLink Guard already masked at its publisher's 0.8.

Both models now find at a floor of 0.5 (pii.Floor) and give each span
its score: Guard's least token probability (rounded through float32,
so a span read back from the cache file sits on the same side of a
threshold), pf-serve's own. masking.model keeps the spans at
pii.Threshold or over: settings.RedactModelScore[model] when it is in
[0.5, 1), else the model's MinScore (Privacy Filter 0.5, AstrLink
Guard 0.8). Settings -> Privacy shows a Confidence threshold row under
the model (app menu, 0.5 to 0.95 and Default), /api/privacy-model
takes do:"score". The setting is this computer's own, like the model.

The defaults stay. TestMaskEval's cases, rules + model + magpie's
checks, by threshold:

  Privacy Filter 0.5-0.8   masked 41/42  kept 112/113
  Privacy Filter 0.85-0.95 masked 40/42  (a Chinese name lost)
  AstrLink Guard 0.5-0.7   masked 42/42  kept 112/113
  AstrLink Guard 0.8-0.85  masked 41/42  (a phone in a tool result)
  AstrLink Guard 0.9       masked 40/42
  AstrLink Guard 0.95      masked 40/42  kept 113/113

The model alone does raise fewer false alarms higher up (Privacy
Filter's found-in-keep falls from 47 at 0.5 to 27 at 0.95, Guard's
from 8 to 2), but the checks after it drop most of those already, so
a higher threshold mostly costs values that should be masked.

Cache file: found-<model>.bin is now "pfound02" with a float32 score
per span. A "pfound01" file is still read, each span with score 1, so
texts cached before mask as they did and aren't asked again. For those
texts a higher threshold drops nothing and a lower one doesn't add a
Guard span scored 0.5-0.8 until the cache turns over (20000 answers).
merge() keeps the surer score of spans it joins. The eval recordings
(eval-model.json, eval-astrlink.json) were made again with scores,
from a scratch cache, the live found files untouched.

Run in the worktree at 11dcc743f + this change:
- go vet / gofmt -l on the touched packages: clean
- go test -count=1 -timeout 45m ./internal/pii/... ./internal/masking
  ./internal/redact ./internal/settings ./internal/gui ./internal/gateway: all ok (gateway 546s, rerun
  after an earlier run hit "no space left on device" on this machine;
  every failure in that run was a TempDir mkdir). This run caught
  TestSettingsSaveKeepsWhatItDoesNotSend wanting RedactModelScore set;
  it is now
- GUI: privacy-model.test.cjs 64/64 (chromium + webkit, 5 languages,
  1100 and 640px; the new threshold menu test among them),
  i18n-keys 4/4, redact-kinds, redact-rule-edit,
  redact-rule-row, redact-shape, redact-words-any-case all pass.
  masking-records 82/82, routing-masking 10/10, privacy-usage-stats 4/4,
  mask-actions 22/22. privacy-hides-accounts was 3/4 once (webkit en,
  page.goto's 5s at load ~290, the class of #3525, commented there),
  then 4/4 three times. Not run: the rest of the GUI suite.
Rebased on 508911e43 (which touched internal/pii fetch and mirror): at
that head, go build ./..., Linux and Windows go vet of pii, masking,
settings and redact, gofmt -l, and go test of pii/..., masking, redact,
settings and gui all ok; gateway not run again after the rebase.
Broken by hand: masking.model keeping every span (TestModelThreshold
  red); Threshold taking any value (TestModelThreshold red); the cache
  writing 1 for every score (TestRestartReadsWhatWasFound red); merge
  not keeping the surer score (TestMergeAcrossPieces red, after its
  joined span was made surer than the one it joins).
Not tried: the real app's window, Windows, Privacy Filter on a GPU
with the new score read (pf-serve itself is unchanged; it always sent
the score).
2026-10-27 14:10:33 +08:00
yetone 3a89dd53c0 pii: the masking model downloads through magpie's proxy, and from hf-mirror when huggingface.co fails (hh0592821 on Discord)
hh0592821 (China) couldn't download the local masking model: "EOF",
"x509: certificate is valid for *.facebook.com ... not huggingface.co",
"net/http: TLS handshake timeout", while the same file came through
their proxy outside magpie.

Cause: internal/pii's download client cloned http.DefaultTransport when
the package loaded, before netproxy.Install set its Proxy, so it kept
only ProxyFromEnvironment. An app started from the Dock has no
HTTPS_PROXY, so the proxy set in magpie and the system's were both
skipped, and the request went direct to a poisoned huggingface.co. Every
other client magpie builds (update, mcp_check, mcpauth, gateway/mcp)
sets t.Proxy = netproxy.Func; pii was the only one built at init without
it. And hf-mirror was asked only with the 「国内镜像」 switch on.

Fix:
- pii's client: t.Proxy = netproxy.Func, through netproxy.Dispatch,
  ResponseHeaderTimeout kept.
- source.URLs: a masking model's file (the two pinned repos' /resolve/
  paths, https, no query; modelMirror) has hf-mirror after
  huggingface.co with the switch off and no MAGPIE_MIRRORS; with the
  switch on it stays first, once. fetch still checks each file against
  its pinned sha256, so a mirror can't hand over anything else.
- docs/subsystems/gateway-routing.md says both.

Checked against the real mirror (curl, outside the tests): hf-mirror.com
serves AstrLink Guard's three files at 7216b6a3 with their pinned sizes
and sha256 (model_int8.onnx 330781 0a070d31..., model_int8.onnx_data
37124608 0ba34216..., tokenizer.json 1502881 0cf3b235...). For Privacy
Filter's gguf it answers 308 back to huggingface.co, so the mirror
helps AstrLink Guard (the default) only.

Tests, none reaching the network: TestFetchGoesThroughMagpiesProxy (proxy
set in Settings is an httptest server; a fetch of a TEST-NET-1 URL is
answered by it), TestModelFromTheMirrorWhenHuggingFaceFails (huggingface.co
failing with the reporter's certificate error, a handshake timeout and
EOF: the file comes from hf-mirror; a mirror file that isn't the pinned
one fails the checksum), TestModelMirrorWithoutTheSwitch,
TestModelFallsToTheMirror (source).

Broken by hand, each red then restored: without t.Proxy =
netproxy.Func, TestFetchGoesThroughMagpiesProxy is red (context deadline,
direct dial); with modelMirror out of URLs, the three mirror tests are
red.

Run: the full suite (go test -tags nogui -timeout 45m ./..., sandbox
HOME) at 7065e3734, this change on the zoecats commit on 11dcc743f,
while the disk was full (1 GB free, other sessions' runs and a 57 GB
shared Go cache): internal/pii 134s, internal/source and 69 more
packages ok; agent, gateway and library red only on "no space left on
device" (TempDir and file writes); provider on the synctest crash open
as #3632. Rerun at that head: internal/pii, internal/source and
internal/netproxy ok, and the gateway's 429/patience tests ok.
The previous commit's full run at its base had every package ok but
provider (#3632).
gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
GOOS=windows go vet ./... clean; go build for darwin, linux (nogui) and
windows ok.

Not tried: a download from China through a real poisoned DNS, or with
the reporter's proxy; ModelScope for Privacy Filter's gguf.
2026-10-27 13:20:52 +08:00
yetone 92cf0b68df docs: the two local models and how one is picked (#3578)
gateway-routing's masking paragraph, the pii package comment, and the
site's masking page in en, zh and ja name AstrLink Guard, the default,
and Privacy Filter, and say what the picker beside the switch does.

Run again after rebasing the stack onto f2aa7fe34 (the backend commit now
carries #3682's chunk-at-a-time find, and serve_test.go calls pf.missing):
gofmt clean; go build; GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./... (amd64) and arm64 for internal/pii clean; go test -race
internal/pii/... ok; go test internal/pii/..., masking, redact, settings,
source, gwmw ok; gateway -run 'Mask|Redact|Privacy|PII|Unmasked' ok; GUI
privacy-model, i18n-keys, account-mask, mask-actions 74/74 (both engines).
internal/gui: one -count=1 run red with its log lost, two green; -count=2
red on TestDesktopSubagentModelNotice, which fails the same on origin/main
f2aa7fe34 from its second run on (#3787, Claude Desktop, not touched here).
2026-10-27 02:01:17 +08:00
yetone 31da93ccdc gui: pick the local model from the app's menu (#3578)
Settings → Privacy's "Find with a local model" row gets a picker
beside its switch, the app's own menu (openProtoMenu), not a select:
AstrLink Guard ("Chinese and English, few false alarms in code") and
Privacy Filter ("OpenAI's, masks more ordinary values in code"), each
with its size and whether it is downloaded. It shows only when there
is more than one model. Progress and Cancel follow whichever model is
downloading. Words in zh, zh-TW, ja and de.

privacy-model.test.cjs's new test opens the menu in chromium and
webkit, every language, at 1100 and 640px: both names, the note
translated, the one in use ticked, the menu inside the window, the
pick posted as pick astrlink-guard, and nothing scrolled.

Run at the pushed head: privacy-model and i18n-keys (48/48); mask-*,
masking-records, privacy-*, redact-*, text-size and click-scroll
GUI files in both engines (248/248); TestCoreScriptBudget and the app.js budget
pass without a raise.
2026-10-27 02:01:16 +08:00
yetone 0db804999e pii: AstrLink Guard as a second local model (#3578)
pii.Model is a local model (ID, Supported, Installed, Size, Find, Now,
Download, Cancel, Warm, Stop, Remove); pii.Models lists Privacy Filter
and AstrLink Guard, pii.Of finds one by id. pii.Choose decides which
one runs: the user's pick; else Privacy Filter for a user who has it on
or downloaded, so no one's model changes under them; else AstrLink
Guard, the default for everyone who turns the model on from now on.

Why AstrLink Guard as the default. On 234 segments of real code and
config (131 KB: Go, TS, lockfiles, go.sum, CI and agent configs),
Privacy Filter found 100 spans in 26 segments, 39 after redact's checks
(38 go.sum hashes and "Zed"); AstrLink Guard found 2, 1 after the
checks. On the masking eval (42 values to mask, 113 to keep), the
model alone: Privacy Filter 40/42 and 47/113 wrongly, AstrLink Guard
38/42 and 3/113; with the rules and checks both are 41/42 and 1/113.
It is 39 MB, not 1.6 GB, runs on any CPU in magpie's process, and
needs no native helper.

Its three files come from Hugging Face at revision 7216b6a3 (v0.1.3),
each checked against the sha256 in the publisher's SHA256SUMS:
int8/model_int8.onnx 0a070d31…, int8/model_int8.onnx_data 0ba34216…,
int8/tokenizer.json 0cf3b235…; from hf-mirror first in China, as
Privacy Filter's are. It is loaded on the first request and let go
after 10 minutes with none; a failure holds requests back with the
same backoff as Privacy Filter's. Its labels are named as Privacy
Filter's, so redact's checks read both alike.

TestGuardFilesAreThePublishers holds each pinned path and sha256 to
the publisher's SHA256SUMS lines (testdata); it is red with the
tokenizer at the repo root, which is a 404 (found by a real download).

Run: go test -race -count=2 ./internal/pii ./internal/source; a real
download from huggingface.co into a sandbox HOME through
Of(Choose("", false)).Download (8.7s), then Find: 张伟, 13800138000,
zhangwei@example.cn, 北京市朝阳区建国路88号 and an sk-proj key found,
nothing in a go.sum line or "gpt-5.1-codex, go 1.26.8, README.md";
load 104 ms, three texts in 177 ms. All at the pushed head.
Not tried: a real download on Windows or Linux.
2026-10-27 02:01:16 +08:00
yetone 27b4f41264 pii: a model's find, cache and download as a backend of its own
No change in behaviour: Privacy Filter's turn, waiting count, answer
cache, on-disk found file and download state move into a backend and
a dlState, so a second model can have its own of each.

Run: go test -race -count=3 ./internal/pii at the pushed head.
2026-10-27 02:01:16 +08:00
yetone 6e9820a3a4 pii/guard: run AstrLink Guard's int8 model in Go (#3578)
AstrLink Guard (QuantumNous/astrlink-guard, Apache-2.0, on Microsoft's
MIT Multilingual-MiniLM-L12-H384) is a 36.9M-parameter BERT token
classifier for Chinese and English: 21 BIO labels (email, phone,
account, payment_card, ip_address, url, common_secret, private_address,
private_date, private_person), 512-token windows overlapping by 128,
a 0.8 score floor. Its int8 ONNX is 37 MB.

This package runs it with no new dependency and nothing native: an ONNX
protobuf reader for the graph and its external data (onnx.go), the
XLM-R Unigram tokenizer from tokenizer.json (tokenizer.go), and the
encoder with int8 x int8 matmuls (bert.go) on NEON/SDOT kernels on
arm64, SSE2 on amd64 and Go elsewhere (kernel*). Word embeddings stay
quantized (15 MB in memory, not 61 MB). uax29 moves from an indirect to
a direct requirement for the tokenizer's pre-split.

Checked against onnxruntime on the publisher's files: the same spans
on 69 of 71 eval texts, 232 of 234 real code segments and 24 of 25
positive samples; the rest differ by a span edge at the score floor.
One 512-token window takes ~0.5s CPU on arm64 and ~1.2s under Rosetta
on amd64, on a box at load ~100.

Run: go test ./internal/pii/guard (kernels against the Go reference,
tokenizer against the publisher's tokenizer on testdata/tokens.json),
gofmt -l, go vet, GOOS=linux go vet -tags nogui and GOOS=windows go
vet on amd64 and arm64, at the pushed head.
2026-10-27 02:01:16 +08:00
yetone 8f023b5119 pii: a long text goes to the masking model in overlapping pieces, a piece at a time, each kept (#3682)
A text over 12 KB was sent to pf-serve whole. On a weak GPU one such
text could take longer than classifyTimeout, so the request failed and
nothing was kept, and every other request waited behind it.

Now find.go cuts a long text into pieces of at most 12 KB (pieceSize).
Each piece overlaps the one before by up to 1 KB, cut after a line's
end where there is one, else after a space, else at a rune's start.
- Each piece is cached on its own, so a request stopped part way and
  sent again asks only about the pieces not done yet.
- Spans are shifted to the text's offsets and merged: overlapping
  spans become one with the longer one's label, and same-label spans
  that touch are joined.
- pf-serve gets one chunk per call. The turn is given up between
  chunks, so a short request waiting for the model goes next instead
  of after the whole long one.

Run:
- go test -count=1 ./internal/pii/: ok.
- gofmt -l and GOOS=linux/windows go vet ./internal/pii/: clean.
- go test -count=1 -timeout 45m ./internal/pii/... ./internal/gateway/...
  at f8b58fb48 (this change on origin/main 865df2472): pii ok 31s,
  gateway ok 571s. GOOS=linux/windows go vet of every package without
  Wails (88), and GOOS=windows go vet ./...: clean.
- Real model (pf-serve v2 Metal, q8 model from ~/.cache, M4 Pro) on a
  96 KB generated text with names, emails, phones and keys, sent whole
  and in its 9 pieces: 2208 spans either way, 2206 the same. 2 were
  found only whole and 2 only in pieces, none at a cut (model context,
  not the split). Pieces took 1.23s against 2.06s whole.

Broken by hand:
- No yield between pieces: TestShortRequestGoesBetweenPieces red.
- No cache put per piece: TestLongTextKeepsPiecesWhenStopped red.
- merge as a no-op: TestMergeAcrossPieces and
  TestLongTextFoundAcrossPieces red.
- pieceOverlap = 0: TestLongTextFoundAcrossPieces red (the name cut
  in two was not found).

Not tried: a real weak GPU (Vulkan) with a long text, and span quality
on a real PII corpus. The comparison above uses generated text.
2026-10-27 01:14:23 +08:00
yetone 16f6e568f4 gateway: masking's time no longer counts toward the 2 minutes before routing (#3682)
yunwang2442-creator: a 480 KB request the local masking model takes 90s
over on an RX 470/580 (more on its CPU, and more behind the requests
ahead of it in the model's one turn) was answered 504 at unroutedMost,
2 minutes from its arrival, its masking cut off, and the same again
each time it was sent.

unroutedMost now counts the request's time other than masking: a
masking (noteMasking), its wait for the model's turn with it, is
tracked like the known waits, and most's timer (checkMost) looks again
when the last masking ends, with what is left. unroutedUnknown is as
before.

Reconciled with 5a94eec3a, not taken as the report wrote it: the report
asked for unroutedMost to count only unknown waits. Next to the 30s
unknown bound that is dead code (unknown fires first), and a known wait
that hangs (a plugin's gateway hook, an image description never ending)
would be held for good, the heyusaku6 case. So only masking is left out.
Masking stays bounded inside internal/pii: classifyTimeout per request
to pf-serve, gpuLoadTimeout/loadTimeout per load, and a model that keeps
failing holds requests back at once (heldBack, retryAfter); a client
that leaves lets go of the turn's queue (FindContext).

The masking 504 message no longer says "what the model has already
read is kept, so it goes quicker": a request cut off mid-read had
nothing kept. It is reached now only by a masking begun as the rest of
the wait ran out.

TestHeldForTheMaskingModelSaysSo, which held a request at the model
past unroutedMost and expected the 504, is now
TestMaskingModelWaitNotCutOffAtMost (no answer past 5x unroutedMost;
the model's wait lets go when the client leaves) and
TestUnroutedMsgSaysTheMaskingModel (the message's words).
TestUnroutedMostLeavesOutMasking: masked 3x unroutedMost, not answered;
then held by an image description that never ends, answered 504.

Run: go test -count=1 -run 'Unrouted|Masking|Held|Mask'
./internal/gateway/ ok; go test ./internal/pii/ ok; gofmt -l clean;
GOOS=linux and GOOS=windows go vet of both ok. Full gateway and pii
run before the push, recorded in the last commit of this set.
Broken by hand: checkMost counting from arrival again
(TestMaskingModelWaitNotCutOffAtMost and TestUnroutedMostLeavesOutMasking
red, 504 while masked); checkMost never giving up
(TestUnroutedMostLeavesOutMasking and TestUnroutedRequestShownThenAnswered
red).
Not tried: a real long request through a real pf-serve on a weak GPU.
2026-10-27 01:14:23 +08:00
yetone dd5b0ab311 pii: a GPU too slow for one request is tried again, and a lost GPU comes back without a restart (#3682)
yunwang2442-creator's RX 470/580 (Vulkan): a 480 KB request ran past
classifyTimeout, magpie ended pf-serve, and classifyTurn set srv.cpu on
any GPU error. Nothing cleared it short of a restart of magpie, so every
request after it ran on a CPU about 3x slower. A slow request is not a
lost GPU.

Now:
- ended for taking too long on the GPU (h.slow), the try again is on
  the GPU; a second one in a row is a lost GPU, and the CPU is tried;
- a GPU that dies answering, or whose load hangs (cebd0d4c3, kept), is
  lost at once, as before;
- a lost GPU is tried again after gpuRetryAfter: 10 minutes, doubling to
  2 hours while it keeps failing. The CPU's pf-serve makes way for the
  GPU's at that request; one that fails moves back to the CPU, for
  longer;
- a GPU that answers clears cpu, gpuLost and the count.

Tests (fake pf-serve modes gpuhang, gpuhangonce, gpudiesonce):
TestGPUTimeoutStaysOnGPU, TestGPUHungTwiceMovesToCPU,
TestLostGPUTriedAgain, TestGPURetryAfter; they use gpuInstall, so the
GPU is Vulkan's off macOS.

Run: go test -count=1 ./internal/pii/ ok; the four with gpuInstall's
Linux branch forced on macOS, ok; gofmt -l clean; GOOS=linux and
GOOS=windows go vet ./internal/pii/ ok.
Broken by hand: the slow request's GPU retry removed (TestGPUTimeout-
StaysOnGPU and TestGPUHungTwiceMovesToCPU red); the gpuAgain retry
turned off (TestLostGPUTriedAgain red); a GPU's answer not clearing
the state (TestLostGPUTriedAgain red).
Not tried: a real Vulkan GPU, or a real GPU hang; the GPU's reload on a
retry is a fake's here.
2026-10-27 01:14:23 +08:00
yetone c84f859dd0 pii: the GPU tests start pf-serve-vulkan off macOS, so they pass on Linux (#3741)
TestFindJoinsTextsAndMapsBack, TestGPUDeathMovesToCPU,
TestServeStartsWithoutResidencyHeartbeat and TestWarm were red on
ubuntu CI (run 40351272355 at 80857a66c, and earlier). The cause:
cebd0d4c3 made candidates() put a GPU pf-serve first only where there is
one, pf-serve-vulkan or macOS's Metal pf-serve. The tests installed
pf-serve alone and expected it on the GPU ("start pf-serve MTL0"), which
holds on macOS only; on Linux it is the CPU's alone.

gpuInstall installs macOS's pf-serve there and pf-serve-vulkan elsewhere,
and says the GPU's start line; the four tests use it. The code isn't
changed.

Run: go test ./internal/pii/ (ok, macOS). The Linux branch forced on
macOS (gpuInstall's darwin check made false, so pf-serve-vulkan is
installed as on Linux): the four tests pass. GOOS=linux and
GOOS=windows go vet ./internal/pii/ ok.
Not tried: a Linux machine itself (no Docker daemon here); the next CI
run is the check.
2026-10-27 01:14:22 +08:00
yetone 7279bdc28b pii: pf-serve-vulkan runs its MoE in 2048-token chunks unless the user set PF_MOE_CHUNK (#3682)
yunwang2442-creator (#3682, Windows, RX 470/580-class 8 GB GPU through
Vulkan, q8 model): with privacy-filter.cpp's default PF_MOE_CHUNK (4096)
a 480 KB text took 159s and was killed at classifyTimeout's 150s; with
2048 it took 90s, and 2048 was 1.77x faster at every size from 24 KB to
480 KB and the fastest of 1024/1536/2048/2560/3072 on 48 KB.

What PF_MOE_CHUNK is (privacy-filter.cpp at the pinned 735a6c286,
src/model.cpp and docs/cpu-perf.md): the MoE FFN runs over the window's
tokens in chunks of this many; per-token, so exact (no halo). Its default
is the forward window (4096), where it is inert. So 2048 changes speed
only, not what is found.

Measured here, M4 Pro, Metal, the real pf-v2 pf-serve and q8 model run
directly (not through magpie, ~/.config/magpie untouched), interleaved
A/B, two rounds of two runs, at load ~250 from other sessions:
  24 KB: 4096 0.40-0.43s, 2048 0.44-0.45s, 1024 0.49-0.66s
  96 KB: 4096 1.86-1.92s, 2048 1.98-2.15s, 1024 2.22-2.27s
  spans the same (5) at every setting.
So 2048 is ~6% slower on Metal: magpie sets it for pf-serve-vulkan only.
macOS's Metal pf-serve and the CPU's keep the engine's default. A
PF_MOE_CHUNK in magpie's environment (set, even empty) is the user's and
is inherited by every pf-serve, never overridden (moeChunk).

Run: go test ./internal/pii/ -run 'TestVulkanServeGetsMoEChunk|
TestServeStartsWithoutResidency' (ok). The full ./internal/pii/...
./internal/gateway/... run is recorded on the last commit of this stack.
Broken by hand: moeChunk ignoring the user's value -> the "user's own"
case red (2048 where 3072 was set); moeChunk never matching Vulkan ->
the "vulkan" case red.
Not tried: a real Vulkan GPU (none here; the 1.77x is the reporter's
measurement), an NVIDIA or Intel GPU through Vulkan, where 2048 may be
slightly slower as on Metal.
2026-10-27 01:14:22 +08:00
yetone cebd0d4c35 pii: a hung GPU load moves to the CPU, a failure says what ended pf-serve, and a failing model holds requests back at once
lazyeo on Discord (Apple M2, 16 GB, macOS 27.0.1, since v0.1.1577): with
Settings → Privacy's local model on, every request, even the first after
a restart, waited out the gateway's 2-minute 504 ("still loading"), and
Settings showed "pf-serve ended: ggml_metal_device_init: tensor API
disabled for pre-M5 and pre-A19 devices … recommendedMaxWorkingSetSize".
Their goroutine dump has startOne(path, cpu=true): a GPU pf-serve had
failed and every request was loading the CPU one.

What was wrong:
- macOS had one pf-serve candidate, the Metal one; a load that hung on
  the GPU waited out loadTimeout (3m) with no CPU to fall back to.
- The error was pf-serve's stderr, which on every pre-M5 Mac starts with
  ggml's Metal init lines (the CPU mode too), so a kill by magpie's own
  classify watchdog read as a Metal crash. On an M4 Pro the CPU mode
  reads ~1.4 KB/s, below classifyTimeout's 4 KB/s, so a slower Mac's CPU
  pf-serve is killed by magpie on larger requests.
- Each failed request left the next one to load again, so a model that
  keeps failing held every request for its full 2 minutes.

Changes (internal/pii):
- candidates(): the GPU one (Vulkan, or macOS's Metal pf-serve), then
  pf-serve with PF_DEVICE=cpu. A GPU load gets gpuLoadTimeout (40s, inside
  the gateway's 2m); a GPU that fails or hangs moves the run to the CPU
  and sets gpuLost, as one dying in classify already did.
- died(): "didn't answer in Xs (N KB on the CPU), so magpie ended it"
  when the watchdog killed it, else "ended (exit status/signal)", then
  the last 3 stderr lines that aren't ggml/Metal/Vulkan startup chatter
  (a line saying error/fail/assert/abort is always kept).
- After a failure, FindContext holds requests back at once with that
  error (before and after taking the turn), until a retry 30s later,
  doubling to 10m while it keeps failing; a success or Stop resets it.
  The request is still held, not sent masked by the rules alone; the
  message says how to turn the model off.
- pii.go's comment and docs/subsystems/gateway-routing.md say so.
- Tests: a cleanup race in fakeInstall, and the seam above (cache.go
  gets disk.saves).

Run (worktree at origin/main a6c808b68 + this, sandbox HOME):
- go test -count=1 ./internal/pii/ ok; -race -count=1 ok (54.7s).
- Broken by hand, each red, then restored:
  - old candidates (macOS Metal alone, plain one not forced to CPU):
    TestHungGPULoadMovesToCPU both subtests "didn't load in 3s on the
    GPU" and TestVulkanThatWontStartFallsBack starts = [vulkan MTL0,
    pf-serve MTL0].
  - not remembering the fallen-back GPU: TestHungGPULoadMovesToCPU red
    (starts = [CPU] only after Stop, GPUError empty).
  - old died(): TestEndedForSlownessSaysSo and
    TestDeathSaysExitAndLastWords red with the M2's Metal lines as the
    error.
  - heldBack() returning nil: TestFailedModelHoldsRequestsBackAtOnce red
    ("didn't answer in 300ms", a queued request loaded again).
- Real pf-serve and model (pf-v2-darwin-arm64) on an M4 Pro, macOS 26.2,
  outside magpie: GPU load 9.9s cold / 0.86s warm, 200 KB in 2.3s; CPU
  load ~20s, 50 KB in 36.4s; the CPU mode's stderr also has the
  "tensor API disabled for pre-M5" lines.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... ok; go build for darwin, linux (nogui),
  windows ok.
- After the first full run, TestHungGPULoadMovesToCPU was red at load
  ~220 (the stand-in hadn't logged its GPU start inside a 3s budget). It
  now gives the GPU load up once the stand-in has started on it
  (`giveUp`, a seam over time.After), not after a duration: 8 of 8 green
  at load 220, and still red with the old candidates.
- -race then caught fakeInstall's cleanup restoring dir while the disk
  cache's 2s save timer, already fired, was writing (cleanup stopped
  only a timer that hadn't fired). disk.saves now counts a timer's
  write until it is done, and cleanup waits on it. -race -count=3
  ./internal/pii/ ok (143.9s).
- go test ./internal/gateway/ ./internal/redact/ ./plugins/redact/ ok
  (gateway 601.5s); internal/masking has no tests.
- Full suite: not completed. go test ./... -timeout 45m at 18:06
  (load 118, no other Go suite running) failed to build 16 packages and
  failed TestWarm, proc's TestEndProbesThenExitLeavesNothing and
  settings' TestSaveConcurrent, all "no space left on device": the
  disk was at 189 MB free (900 of 926 GB used, not by this run). By the
  time space came back, other sessions' suites were running (a gateway
  run, a -p 3 multi-package run, the GUI suite), so a second full run
  would have broken one suite per machine. Every package that ran and
  isn't named above was ok.
- Rebased on 7d075df9d (pushed head's parent): go build and
  go test ./internal/pii/ ./internal/redact/ ok there.

Not tried: an M2 or macOS 27 (no such machine), so why lazyeo's GPU
pf-serve failed first is still unknown; the new error and gpuLost will
show it. No known llama.cpp/ggml issue for macOS 27 or the pre-M5 tensor
line turned up. A CPU too slow for a large request is still killed by
classifyTimeout; it now says so and holds the requests after it back at
once.
2026-10-26 18:36:27 +08:00
yetone e5dd86965b pii: the masking model's requests take turns without holding the status, Stop or a restart (#3682)
After a restart, with Settings → Privacy's local model on, every request
queued for minutes on srv.mu in classify. That lock was held across
start() (up to 3m loading) and the model's answer (30s and more), and
Now(), Stop() and the idle timer took it too. The user saw a 504
"held this request for 2m0s without routing it to any provider".

Now:
- pf-serve's requests take turns through a one-slot channel (`turn`),
  so writes on its one pipe never interleave. srv.mu only guards state.
  Now() never waits: it reports Loading and how many are Waiting. Stop()
  never waits either: it kills a pf-serve that is loading or answering,
  and the request on it fails with errStopped (no retry). Fetch's
  upgrade stops pf-serve only once its turn is free (stopWhenFree).
- A request waits for its turn under its own context (FindContext). The
  gateway passes the request's context through a new gwmw.ContextTeller,
  so a client that went away, or a request the gateway answered 504,
  leaves the queue. A turn already begun still finishes and caches.
- What Find learned is kept on disk (found-<model sha>.bin, beside the
  model): a text's sha256 and its spans' offsets and labels, never the
  text. Written via temp-and-rename. A bad, cut-short or over-long file
  is read as empty, and a cached span that doesn't fit its text is
  asked again. A restart no longer asks about every history again.
- A request waiting for its turn reads the cache again when it gets it,
  so requests queued with the same history ask the model once.
- The guarantee stays: a request the model can't mask is held back, never
  sent masked by the rules alone. A wait that ends panics inside
  gwmw.Safely, as a failed model did, and the request fails closed.
- The 504 for a request held while masking says it waited for the local
  masking model, what the model was doing (loading, or masking another
  request with N waiting), that what it read is kept, and that the model
  can be turned off in Settings → Privacy (unroutedMsg).

Tests (each red on the fix broken by hand, in the sandbox HOME):
- TestStatusAndStopDontWaitForARequest / ...ForALoad: red with Now()
  taking the turn (Now waited), and the suite hung with Stop() taking it.
- TestWaiterLeavesWhenItsContextEnds: red with the waiter ignoring ctx.
- TestQueuedRequestReadsWhatTheOneAheadLearned: red without the re-read.
- TestRestartReadsWhatWasFound: red with loadCache a no-op. It also
  checks the file never holds the text.
- TestBadCacheFileIsReadAsEmpty: red with a cut-short file's entries kept.
- TestCachedSpanOutsideItsTextIsAskedAgain: red without the fits check.
- gateway TestHeldForTheMaskingModelSaysSo: red with the masker handed
  context.Background() (the wait never let go), without noteMasking, and
  with the old message. TestUnroutedMsgNamesTheModelOnlyWhenItIsOn: red
  with the old message.
- TestMaskingOnAndOff's panicky fixture embeds masking.Masker, which now
  has the Context methods. It panics on those too, and still refuses.

Run at this head (base origin/main 098ac9696, fetched before the commit),
in a sandbox HOME, load ~25:
- go test -timeout 45m -count=1 on internal/pii, internal/redact,
  internal/gwmw, internal/gateway, internal/gui and plugins/redact/...:
  all ok, apart from TestMaskingOnAndOff (the fixture above). After its
  fix, internal/gateway and internal/pii were run again whole: ok.
  internal/masking has no tests.
- go test -race -count=1 ./internal/pii/: ok.
- gofmt -l clean; go vet ./... (darwin); GOOS=linux and GOOS=windows
  go vet -tags nogui on the changed packages and internal/gui, and
  go build -tags nogui ./...: ok.

Not tried:
- A real pf-serve and model: everything above ran against the test's
  stand-in pf-serve. A real cold restart with the model on was not timed,
  and neither was Windows CPU.
- pf-serve is not warmed when magpie starts, so the first request after
  an update to the model still waits for its load. That wait now says so
  and can be left.
- The GUI does not show Loading/Waiting yet; GET /api/privacy-model carries
  them (status.loading, status.waiting).
2026-10-26 14:15:53 +08:00
yetone 5df62c5cda pii: pf-serve is pf-v2, which holds the model once on a GPU (#3590)
pf-v2 is 642d430ec's pf-serve (weights-once.patch): on Metal and
Vulkan the GGUF is read straight into the device's buffer instead of
also kept whole in a CPU copy. serveSHA pins pf-v2's five zips, each
checked against the release's SHA256SUMS.

A user who turned the model on before has pf-v1 on disk, in a folder
named for its tag. pf-v1 now still counts as installed and is run
(oldTags), and starting it fetches pf-v2 in the background (upgrade):
once fetched, the running pf-v1 is ended so the next request starts
pf-v2, and pf-v1's folder is deleted. One that can't be fetched leaves
pf-v1 running and is tried on the next start. A fresh download fetches
pf-v2 and deletes an old tag's folder.

Run:
- go test ./internal/pii ./internal/redact (ok), -run TestLoopGuard
  ./internal/gateway and -run Privacy ./internal/gui (ok, the doc and
  the settings route); go build; GOOS=linux and GOOS=windows go vet
  -tags nogui ./internal/pii; gofmt -l clean.
- TestOldServeRunsUntilUpgraded and TestUpgradeThatFailsKeepsTheOld
  are red with `go upgrade()` taken out of start (not upgraded / never
  tried) and with binDir looking at serveTag alone (the old pf-serve
  not taken for installed).
- Real: a sandbox cache with the released pf-v1 darwin-arm64 and the
  real model, pii.Find through it: pf-v1 answered, pf-v2 was fetched
  from the real release, pf-v1's folder deleted, the next request
  started pf-v2 (ps shows its path), 1664 MB phys_footprint idle.
- pf-v2's released darwin-arm64 probed alone: 1680 MB idle (pf-v1 4777
  MB), spans identical to pf-v1's; load ~1 s both, alternated 3 times.

Not tried: the upgrade on Windows, where the old folder can only be
deleted after its pf-serve ends (upgrade ends it first; a folder left
is deleted on a later start).
2026-10-25 20:03:57 +08:00
yetone d2e0ea393d pii: pf-serve starts with ggml's Metal residency heartbeat off (#3185)
macOS's Energy Impact puts magpie at the top while CPU stays at ~6%
(#3185). Energy Impact counts wakeups, and an idle pf-serve (the
privacy filter's llama.cpp child) woke 134-146 times a second: ggml's
Metal backend keeps a residency set alive with a heartbeat. pf-serve
stays up for 10 minutes after each masked request, so any masking user
pays that most of the day. GGML_METAL_NO_RESIDENCY=1 turns the residency
set off.

Measured with proc_pid_rusage (ri_interrupt_wkups, ri_energy_nj) on an
M4 Pro, idle pf-serve, 20s windows:
- before, pf-serve pf-v1 as magpie starts it today: 140.0 and 138.5
  wakeups/s, 2.67 mW; the user's live v0.1.1370 pf-serve child read
  134-142/s
- after, pf-serve started through pii.Find at this commit: 0.4, 0.3,
  0.3 wakeups/s, 0.02 mW
- GGML_METAL_RESIDENCY_KEEP_ALIVE_S=0 or 1 instead: 143-146/s, no help
- latency: hot requests 51-78ms either way; the first request after a
  5-60s idle spell 57-77ms before, 105-518ms after; 90s idle through
  pii.Find at this commit 56-183ms

Run at this commit:
- go test -count=1 ./internal/pii/ ok;
  TestServeStartsWithoutResidencyHeartbeat red with the env line put
  back to os.Environ() ("residency " on both starts), green with it
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/pii/ ok,
  gofmt -l clean

Also measured: current main in a sandbox HOME with clones of the real
Claude/Codex sessions and magpie cache (no logins), window open, after
warm-up: main process 1.1-2.2 wakeups/s, 0.9-1.9 mW; its WebContent
0.5/s and GPU 0.3/s. The app.js intervals and the Go tickers were read
and are already held while the document is hidden or cheap.

Not tried: the full suite (an env-only change to one package); a
logged-in instance. The user's live v0.1.1370 main process reads 69-217
wakeups/s and 25-120 mW, which the sandbox at main (no logins) doesn't
reproduce, so its source is still unknown; Vulkan/Linux pf-serve (the
variable is Metal's only and ignored there).
2026-10-25 18:40:25 +08:00
yetone 07ecdda10f gui: Settings > Privacy turns the local model on, and says where it runs (#1977) 2026-10-18 23:41:19 +08:00
yetone c0dad80da1 redact, pii: a local model finds what the masking rules can't (#1977)
WIP on pf/serve, recovered after the scratchpad holding it was wiped.
internal/pii downloads OpenAI's Privacy Filter (q8 GGUF, sha256 pinned)
and pf-serve, runs it on the GPU first, and answers redact's Model;
settings.RedactModel turns it on, per computer. Off by default.

Run: go vet and go test -race on internal/redact, pii, source,
settings (all ok). Not yet released: pf-serve's serveSHA is empty
until pf-v1 is tagged.
2026-10-18 23:12:41 +08:00