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.
This commit is contained in:
yetone
2026-10-28 19:17:41 +08:00
parent 7c900f468f
commit 874b86653d
5 changed files with 279 additions and 39 deletions
File diff suppressed because one or more lines are too long
+79 -28
View File
@@ -6,7 +6,9 @@ package masking
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"sync"
"sync/atomic"
@@ -148,29 +150,51 @@ func toGuard() {
// 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 is waited for defaultWait at most, from now, and finds
// nothing when it fails or that runs out: the rules mask alone.
// strictWait is how long a request waits for the local model the user
// turned on. Past it, what the model has read of the request is masked
// with its finds and the rest by the rules alone, and the request goes:
// nothing is sent as written that the rules would mask. Unbounded, a
// burst of requests with text the model hadn't read (new tool results, a
// resumed conversation, subagents at once) queued behind each other a
// 12 KB chunk at a time, AstrLink Guard reading about 6 KB a second on 8
// cores of a Linux CPU, and each request that stopped waiting was held
// back whole: xRayySummers on X saw waits of 1.2s to 290s in one minute
// and "masking failed, so nothing was sent" for each request it ended.
// What the model reads meanwhile is kept, so the next turn, which sends
// the same history, finds it. A var for tests.
var strictWait = 15 * time.Second
// model is the local model m (internal/pii) as redact's Model, keeping
// what it is at least min sure of, waited for until ctx ends or the wait
// runs out: defaultWait for the model on by default, strictWait for one
// the user turned on (strict), from now. A wait that runs out, or a ctx
// that ends, keeps what the model had read of the texts by then (a
// pii.Partial), and the rules mask the rest alone. A model that fails
// (didn't load, isn't on disk, held back after a failure) panics where
// the user turned it on, and the request is held back (gwmw.Safely)
// rather than sent with only the rules' masking: the user asked for the
// model's, and it is broken, not busy. On by default, it finds nothing
// then: 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)
wait := defaultWait
if strict {
wait = strictWait
}
by := time.Now().Add(wait)
return func(texts []string) [][]redact.Found {
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 {
ctx, cancel := context.WithDeadline(ctx, by)
defer cancel()
got, err := find(ctx, m, texts)
var p *pii.Partial
switch {
case errors.As(err, &p):
notePartial(p, wait)
if len(got) != len(texts) {
got = make([][]redact.Found, len(texts))
}
case err != nil && strict:
panic(err)
} else if err != nil {
case err != nil:
return make([][]redact.Found, len(texts))
}
out := make([][]redact.Found, len(got))
@@ -185,13 +209,33 @@ 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)
// partialLogged is when notePartial last wrote to the log, so a burst of
// requests past their wait writes one line.
var partialLogged atomic.Int64
// notePartial logs, at most once a minute, that a request went with the
// model's finds for only part of it.
func notePartial(p *pii.Partial, wait time.Duration) {
if p.Missing == 0 {
return
}
now := time.Now().Unix()
if t := partialLogged.Load(); t != 0 && now-t < 60 || !partialLogged.CompareAndSwap(t, now) {
return
}
log.Printf("masking: the local model read %d of a request's %d texts in %s (%v); the rules masked the rest alone, and the model keeps reading for the next request", p.Of-p.Missing, p.Of, wait, p.Err)
}
// handBack is how long find waits, once ctx ends, for m to answer with
// what it knew by then (internal/pii's backend does at once, from its
// cache) before giving up on it.
const handBack = 100 * time.Millisecond
// find is m.Find, given up when ctx ends even where m doesn't stop for
// it (a read of its cache from disk, a load): m is given handBack to
// answer with what it had read, then it is a pii.Partial with nothing
// read, and m finishes on its own.
func find(ctx context.Context, m pii.Model, texts []string) ([][]redact.Found, error) {
type res struct {
got [][]redact.Found
err error
@@ -205,13 +249,20 @@ func find(ctx context.Context, m pii.Model, texts []string, strict bool) ([][]re
case r := <-ch:
return r.got, r.err
case <-ctx.Done():
return nil, ctx.Err()
}
t := time.NewTimer(handBack)
defer t.Stop()
select {
case r := <-ch:
return r.got, r.err
case <-t.C:
return nil, &pii.Partial{Missing: len(texts), Of: len(texts), Err: 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).
// user turned it on: only then is a request held back for a model that
// fails, and waited for it strictWait (model's strict).
func ModelOn() bool { return settings.Shared().RedactModel }
// ModelBusy says what the local model is doing that a request may wait
+96 -3
View File
@@ -169,8 +169,8 @@ func (h hangs) Find(context.Context, []string) ([][]redact.Found, error) {
// 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).
// defaultWait at most and the rules mask alone; turned on by the user, it
// is waited for longer (strictWait).
func TestDefaultModelHangingIsTheRules(t *testing.T) {
h := t.TempDir()
t.Setenv("HOME", h)
@@ -215,7 +215,12 @@ func TestDefaultModelHangingIsTheRules(t *testing.T) {
t.Fatal("the model was never asked")
}
// turned on by the user, the request waits for the model: no bound
// turned on by the user, the request waits for the model longer
// than the default's wait (strictWait; its end is
// TestStrictModelStalledIsTheRulesForWhatItDidntRead's)
wasStrict := strictWait
strictWait = time.Hour
t.Cleanup(func() { strictWait = wasStrict })
done := make(chan any, 1)
go func() {
defer func() { done <- recover() }()
@@ -228,3 +233,91 @@ func TestDefaultModelHangingIsTheRules(t *testing.T) {
case <-time.After(3 * defaultWait):
}
}
// partly is a model that read the first text (a history it saw before)
// and not the rest when the wait ended: the burst ahead of it in the
// queue (xRayySummers on X).
type partly struct{ hangs }
func (p partly) Find(ctx context.Context, texts []string) ([][]redact.Found, error) {
p.asked <- struct{}{}
<-ctx.Done()
out, missing := make([][]redact.Found, len(texts)), 0
for i, s := range texts {
if strings.Contains(s, "new tool result") {
missing++
} else if k := strings.Index(s, "Liu Xiang"); k >= 0 {
out[i] = []redact.Found{{Start: k, End: k + 9, Label: "private_person", Score: 0.9}}
}
}
return out, &pii.Partial{Missing: missing, Of: len(texts), Err: ctx.Err()}
}
// xRayySummers on X (magpie 0.1.1877, Linux, AstrLink Guard turned on):
// in a burst of requests with text the model hadn't read, one waited
// 290s, and each that stopped waiting was "masking failed, so nothing
// was sent". Turned on by the user, the model is waited for strictWait
// at most: what it read is masked with its finds, the rest by the rules,
// and the request goes. Nothing the rules mask goes as written. The old
// code waited with no bound, and held the request back when the wait
// ended.
func TestStrictModelStalledIsTheRulesForWhatItDidntRead(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, RedactModel: true, RedactModelName: pii.AstrLinkGuard}); err != nil {
t.Fatal(err)
}
stalled := hangs{fake{installed: true}, make(chan struct{}, 8), make(chan struct{})}
t.Cleanup(func() { close(stalled.release) })
var m pii.Model = stalled
wasPicked, wasFetch, wasDisk, wasWait := picked, fetch, onDisk, strictWait
picked = func(settings.Settings) pii.Model { return m }
fetch = func(pii.Model, bool) {}
onDisk = func() bool { return true }
strictWait = 200 * time.Millisecond
t.Cleanup(func() { picked, fetch, onDisk, strictWait = wasPicked, wasFetch, wasDisk, wasWait })
key := "sk-ant-api03-" + strings.Repeat("a", 40)
mask := func(body []byte) ([]byte, int, any) {
type res struct {
b []byte
n int
p any
}
got := make(chan res, 1)
go func() {
var r res
defer func() { r.p = recover(); got <- r }()
b, hits := Masker{}.JSONHitsContext(context.Background(), body)
r.b, r.n = b, len(hits)
}()
select {
case r := <-got:
return r.b, r.n, r.p
case <-time.After(20 * strictWait):
t.Fatal("turned on by the user, a model that never answers held the request with no bound")
}
return nil, 0, nil
}
// a model that never answers: the rules mask alone
b, n, p := mask([]byte(`{"input":[{"role":"user","content":"new tool result: key ` + key + `"}]}`))
if p != nil {
t.Fatalf("held back: %v", p)
}
if strings.Contains(string(b), "aaaa") || n == 0 {
t.Fatalf("the rules didn't mask: %s", b)
}
// a model that read the history and not the new text: its find is
// masked there, and the rules mask the new text
m = partly{stalled}
b, _, p = mask([]byte(`{"input":[{"role":"user","content":"Liu Xiang said deploy"},{"role":"user","content":"new tool result: key ` + key + `"}]}`))
if p != nil {
t.Fatalf("held back: %v", p)
}
if strings.Contains(string(b), "Liu Xiang") || strings.Contains(string(b), "aaaa") {
t.Fatalf("what the model read wasn't masked with its find, or the rest not by the rules: %s", b)
}
}
+43 -7
View File
@@ -4,6 +4,7 @@ import (
"container/list"
"context"
"crypto/sha256"
"errors"
"fmt"
"sort"
"strings"
@@ -29,8 +30,9 @@ func Find(texts []string) ([][]redact.Found, error) {
}
// FindContext is Find for a caller that may stop waiting: when ctx ends
// (the client went away) it returns at once, whether its turn hadn't come
// or pf-serve is on it. The chunk pf-serve is on is finished all the same
// (the client went away, or the caller's own bound) it returns at once,
// whether its turn hadn't come or pf-serve is on it, with what was known
// of the texts by then and a *Partial. The chunk pf-serve is on is finished all the same
// and its answers kept, so the request sent again finds them; the chunks
// after it are left. Between chunks the turn is given up and taken again,
// so a short request waiting for it goes before the rest of a long one.
@@ -63,13 +65,13 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
return out, nil
}
if ctx.Err() != nil {
return nil, waitErr(ctx)
return b.partial(ctx, texts)
}
if err := b.heldBack(); err != nil {
return nil, err
}
if !b.takeTurn(ctx) {
return nil, waitErr(ctx)
return b.partial(ctx, texts)
}
type result struct {
out [][]redact.Found
@@ -95,7 +97,7 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
// 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)}
done <- result{nil, errWaitEnded}
return
}
// give way to a request waiting for the turn: it goes
@@ -103,7 +105,7 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
<-b.turn
held = false
if !b.takeTurn(ctx) {
done <- result{nil, waitErr(ctx)}
done <- result{nil, errWaitEnded}
return
}
held = true
@@ -152,12 +154,46 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
}()
select {
case r := <-done:
if r.err == errWaitEnded {
return b.partial(ctx, texts)
}
return r.out, r.err
case <-ctx.Done():
return nil, waitErr(ctx)
return b.partial(ctx, texts)
}
}
// errWaitEnded is find's own word that its caller stopped waiting.
var errWaitEnded = errors.New("the wait ended")
// Partial is Find's error when its caller stopped waiting (ctx ended)
// before the model had read every text. What Find returns with it is
// what was known of each text by then, read before or meanwhile, by
// this request or another's; a text the model hadn't read has nil, as
// one it found nothing in has. Before, such a wait gave nothing at all,
// not even for texts read turns ago, and a caller holding a request back
// for the model held it back whole (xRayySummers on X: a burst of
// requests with text the model hadn't read queued for up to 290s, and
// each that stopped waiting was "masking failed, so nothing was sent").
type Partial struct {
// Missing of Of texts the model hadn't read
Missing, Of int
Err error
}
func (p *Partial) Error() string {
return fmt.Sprintf("the local masking model read %d of %d texts in time: %v", p.Of-p.Missing, p.Of, p.Err)
}
func (p *Partial) Unwrap() error { return p.Err }
// partial is what is known of texts now that ctx ended, and a Partial
// that says how much isn't.
func (b *backend) partial(ctx context.Context, texts []string) ([][]redact.Found, error) {
out, miss := b.known(texts, nil)
return out, &Partial{Missing: len(miss), Of: len(texts), Err: waitErr(ctx)}
}
// takeTurn waits for the model's turn while ctx lives, counted as
// waiting; false when ctx ended first.
func (b *backend) takeTurn(ctx context.Context) bool {
+60
View File
@@ -318,3 +318,63 @@ func TestStoppedRequestLeavesTheRestOfItsChunks(t *testing.T) {
}
waitFor(t, "the turn free", func() bool { return len(b.turn) == 0 })
}
// xRayySummers on X: a request that stops waiting for the model (its
// caller's bound, a burst ahead of it in the queue) gets what was known
// of its texts, the history the model read turns ago with it, and a
// Partial saying how much wasn't read. The old code gave nil and an
// error, so its caller had no finds at all, and one holding the request
// back for the model held it back whole.
func TestStoppedRequestKeepsWhatWasRead(t *testing.T) {
dir := t.TempDir()
stall, 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) {
out := make([][]redact.Found, len(texts))
for i, s := range texts {
if strings.Contains(s, "new tool result") {
close(stall)
<-release // the model, slow on a long text
}
if k := strings.Index(s, "Alice"); k >= 0 {
out[i] = []redact.Found{{Start: k, End: k + 5, Label: "private_person", Score: 0.9}}
}
}
return out, nil
}}
t.Cleanup(func() {
close(release)
waitFor(t, "the turn free", func() bool { return len(b.turn) == 0 })
b.disk.mu.Lock()
if b.disk.timer != nil && b.disk.timer.Stop() {
b.disk.saves.Done()
}
b.disk.timer = nil
b.disk.mu.Unlock()
b.disk.saves.Wait()
})
history := "user: ask Alice about the deploy"
if got, err := b.find(context.Background(), []string{history}); err != nil || len(got[0]) != 1 {
t.Fatalf("history: %v %v", got, err)
}
ctx, cancel := context.WithCancel(context.Background())
res := make(chan error, 1)
var got [][]redact.Found
go func() {
var err error
got, err = b.find(ctx, []string{history, "new tool result " + strings.Repeat("x ", 100)})
res <- err
}()
<-stall
cancel()
err := <-res
var p *Partial
if !errors.As(err, &p) || p.Missing != 1 || p.Of != 2 || !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want a Partial with 1 of 2 missing", err)
}
if len(got) != 2 || !reflect.DeepEqual(got[0], []redact.Found{{Start: 10, End: 15, Label: "private_person", Score: 0.9}}) || len(got[1]) != 0 {
t.Fatalf("got %v, want the history's Alice and nothing for the unread text", got)
}
}