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.
This commit is contained in:
yetone
2026-10-28 17:52:53 +08:00
parent 33af28ed6b
commit e296211b8b
5 changed files with 187 additions and 3 deletions
File diff suppressed because one or more lines are too long
+47 -2
View File
@@ -138,15 +138,36 @@ func toGuard() {
})
}
// defaultWait is how long a request waits for the local model on by
// default (not turned on by the user): its turn, its loading, its reading.
// Past it the rules mask alone. AstrLink Guard reads on the CPU, a long
// history it hasn't seen takes minutes there, and one request at a time
// is read: unbounded, every request queued behind the first (shensmart
// on Discord, 10-28: Codex's requests sat "masking…" once the default's
// download finished). What the model read meanwhile is kept, so the next
// request finds it. A var for tests.
var defaultWait = 2 * time.Second
// model is the local model m (internal/pii) as redact's Model, waited for
// until ctx ends, keeping what it is at least min sure of. One that can't
// answer, or isn't waited for any longer, panics where the user turned it
// on (strict), and the request is held back (gwmw.Safely) rather than
// sent with only the rules' masking: the user asked for the model's. On
// by default, it finds nothing then, and the rules mask alone.
// by default, it is waited for defaultWait at most, from now, and finds
// nothing when it fails or that runs out: the rules mask alone.
func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Model {
var by time.Time
if !strict {
by = time.Now().Add(defaultWait)
}
return func(texts []string) [][]redact.Found {
got, err := m.Find(ctx, texts)
ctx := ctx
if !strict {
var cancel context.CancelFunc
ctx, cancel = context.WithDeadline(ctx, by)
defer cancel()
}
got, err := find(ctx, m, texts, strict)
if err != nil && strict {
panic(err)
} else if err != nil {
@@ -164,6 +185,30 @@ func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Mo
}
}
// find is m.Find; on by default, it is given up when ctx ends even where
// m doesn't stop for it (a read of its cache from disk, a load), and m
// finishes on its own.
func find(ctx context.Context, m pii.Model, texts []string, strict bool) ([][]redact.Found, error) {
if strict {
return m.Find(ctx, texts)
}
type res struct {
got [][]redact.Found
err error
}
ch := make(chan res, 1)
go func() {
got, err := m.Find(ctx, texts)
ch <- res{got, err}
}()
select {
case r := <-ch:
return r.got, r.err
case <-ctx.Done():
return nil, ctx.Err()
}
}
// ModelOn says Settings → Privacy's local model masks requests, as the
// user turned it on: only then is a request held back for it (model's
// strict).
+78
View File
@@ -7,6 +7,7 @@ import (
"slices"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/pii"
"github.com/yetone/magpie/internal/redact"
@@ -150,3 +151,80 @@ func TestDefaultModelFailingIsTheRules(t *testing.T) {
}()
model(context.Background(), m, 0.8, true)([]string{"a"})
}
// hangs is a model on disk that never answers: one loading or reading a
// long history on a slow CPU (a Docker container's), or stuck. Find
// ignores ctx, as a read of its cache from disk or a load does.
type hangs struct {
fake
asked, release chan struct{}
}
func (h hangs) Find(context.Context, []string) ([][]redact.Found, error) {
h.asked <- struct{}{}
<-h.release // the test's end
return nil, errors.New("released")
}
// shensmart on Discord (10-28): with the model on by default, a request
// waited for it as long as its client did, "masking…" on the Requests
// page, every one after it queued behind. On by default, it is waited for
// defaultWait at most and the rules mask alone; turned on by the user, the
// request still waits for it (and is held back when ctx ends).
func TestDefaultModelHangingIsTheRules(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactModelAuto: true, RedactModelName: pii.AstrLinkGuard}); err != nil {
t.Fatal(err)
}
m := hangs{fake{installed: true}, make(chan struct{}, 8), make(chan struct{})}
t.Cleanup(func() { close(m.release) })
wasPicked, wasFetch, wasDisk, wasWait := picked, fetch, onDisk, defaultWait
picked = func(settings.Settings) pii.Model { return m }
fetch = func(pii.Model, bool) {}
onDisk = func() bool { return true }
defaultWait = 200 * time.Millisecond
t.Cleanup(func() { picked, fetch, onDisk, defaultWait = wasPicked, wasFetch, wasDisk, wasWait })
body := []byte(`{"input":[{"role":"user","content":"张伟 key sk-ant-api03-` + strings.Repeat("a", 40) + `"}]}`)
type res struct {
b []byte
n int
}
got := make(chan res, 1)
began := time.Now()
go func() {
b, hits := Masker{}.JSONHitsContext(context.Background(), body)
got <- res{b, len(hits)}
}()
select {
case r := <-got:
if took := time.Since(began); took > 5*time.Second {
t.Fatalf("held %s", took)
}
if strings.Contains(string(r.b), "aaaa") || r.n == 0 {
t.Fatalf("the rules didn't mask: %s", r.b)
}
case <-time.After(10 * time.Second):
t.Fatal("on by default, a model that never answers held the request")
}
select {
case <-m.asked:
default:
t.Fatal("the model was never asked")
}
// turned on by the user, the request waits for the model: no bound
done := make(chan any, 1)
go func() {
defer func() { done <- recover() }()
model(context.Background(), m, 0.8, true)([]string{"a"})
}()
<-m.asked
select {
case <-done:
t.Fatal("turned on by the user, the model wasn't waited for")
case <-time.After(3 * defaultWait):
}
}
+7
View File
@@ -91,6 +91,13 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
out, miss := b.known(texts, got)
for c := 0; len(miss) > 0; c++ {
if c > 0 {
// a caller that stopped waiting leaves the chunks after
// this one: the turn isn't taken again for them (a
// select on a free turn and an ended ctx picks either)
if ctx.Err() != nil {
done <- result{nil, waitErr(ctx)}
return
}
// give way to a request waiting for the turn: it goes
// before the next chunk
<-b.turn
+54
View File
@@ -7,8 +7,10 @@ import (
"encoding/binary"
"errors"
"os"
"path/filepath"
"reflect"
"strings"
"sync/atomic"
"testing"
"time"
@@ -264,3 +266,55 @@ func TestCachedSpanOutsideItsTextIsAskedAgain(t *testing.T) {
}
func sumOf(s string) [32]byte { return sha256.Sum256([]byte(s)) }
// A request that stopped waiting leaves the chunks after the one the
// model is on: the model isn't kept reading for no one, holding the turn
// every later request (each waiting a short while on by default) needs.
// The old code took the turn again on a select that could pick either.
func TestStoppedRequestLeavesTheRestOfItsChunks(t *testing.T) {
dir := t.TempDir()
var calls atomic.Int32
first, release := make(chan struct{}), make(chan struct{})
b := &backend{turn: make(chan struct{}, 1), waiting: new(atomic.Int32), cache: newLRU(100), disk: new(diskState),
path: func() string { return filepath.Join(dir, "found.bin") },
heldBack: func() error { return nil },
classify: func(texts []string) ([][]redact.Found, error) {
if calls.Add(1) == 1 {
close(first)
<-release
}
return make([][]redact.Found, len(texts)), nil
}}
t.Cleanup(func() {
b.disk.mu.Lock()
if b.disk.timer != nil && b.disk.timer.Stop() {
b.disk.saves.Done() // the write that won't run now
}
b.disk.timer = nil
b.disk.mu.Unlock()
b.disk.saves.Wait()
})
// three texts of a chunk each
texts := []string{strings.Repeat("a ", chunkSize/2-8), strings.Repeat("b ", chunkSize/2-8), strings.Repeat("c ", chunkSize/2-8)}
ctx, cancel := context.WithCancel(context.Background())
got := make(chan error, 1)
go func() { _, err := b.find(ctx, texts); got <- err }()
<-first
cancel()
if err := <-got; err == nil {
t.Fatal("a stopped request answered")
}
close(release)
// the chunk under way is finished and its turn given back. Nothing
// here waits to send on the turn: a waiting sender would be handed
// it first, and the old code's select would never see it free
waitFor(t, "the turn given back", func() bool { return len(b.turn) == 0 && calls.Load() >= 1 })
// a chunk read after it would be read at once: watch for one a while
for range 40 {
if n := calls.Load(); n != 1 {
t.Fatalf("%d chunks read for a request that stopped after the first", n)
}
time.Sleep(5 * time.Millisecond)
}
waitFor(t, "the turn free", func() bool { return len(b.turn) == 0 })
}