Commit Graph
4 Commits
Author SHA1 Message Date
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 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 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