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.
This commit is contained in:
yetone
2026-10-29 13:45:01 +08:00
parent 1b7a087565
commit e61e10535d
7 changed files with 471 additions and 58 deletions
File diff suppressed because one or more lines are too long
+4 -3
View File
@@ -143,9 +143,10 @@ 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
// history it hasn't seen takes minutes there, and a few requests at a
// time are read, on 4 cores at most between them (pii's guardTurn):
// 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
+64 -27
View File
@@ -150,8 +150,19 @@ var guardLoad = func(dir string) (spanFinder, error) {
return m, nil
}
// guardTurn is held by the one request the model reads.
var guardTurn = make(chan struct{}, 1)
// guardTurn is held by each request the model reads, guard.Cores() of
// them at once. They share those cores (guard.Find takes them as it reads
// each window), so a short request goes beside a long one's chunk on a
// core of its own instead of after it, and requests at once never read
// on more cores than one did. One at a time, concurrent agent requests
// queued behind each other (yyhhyyyyyy on Discord, 10-28). Through
// CoreML they meet at its one model, which reads as fast for one
// request as for eight.
var guardTurn = make(chan struct{}, guard.Cores())
// guardLoading is held while the model loads, so requests read at once
// load it once.
var guardLoading sync.Mutex
var guardBackend = &backend{
turn: guardTurn,
@@ -188,28 +199,11 @@ func guardClassify(texts []string) ([][]redact.Found, error) {
func guardClassifyTurn(texts []string) ([][]redact.Found, error) {
gsrv.mu.Lock()
m, gen := gsrv.m, gsrv.gen
if m == nil {
gsrv.loading = true
}
gsrv.mu.Unlock()
if m == nil {
if !guardInstalled() {
gsrv.mu.Lock()
gsrv.loading = false
gsrv.mu.Unlock()
return nil, ErrNotInstalled
}
t := time.Now()
var err error
m, err = guardLoad(guardDir())
gsrv.mu.Lock()
gsrv.loading = false
if err == nil && gsrv.gen == gen {
gsrv.m, gsrv.loadMS = m, int(time.Since(t)/time.Millisecond)
}
gsrv.mu.Unlock()
if err != nil {
return nil, fmt.Errorf("the local masking model didn't load: %w", err)
if m, gen, err = guardLoaded(); err != nil {
return nil, err
}
}
out := make([][]redact.Found, len(texts))
@@ -232,14 +226,57 @@ func guardClassifyTurn(texts []string) ([][]redact.Found, error) {
return out, nil
}
// guardLoaded is the model, loaded by this request unless another
// loaded it meanwhile, and the gen it was loaded in.
func guardLoaded() (spanFinder, int, error) {
guardLoading.Lock()
defer guardLoading.Unlock()
gsrv.mu.Lock()
m, gen := gsrv.m, gsrv.gen
if m == nil {
gsrv.loading = true
}
gsrv.mu.Unlock()
if m != nil {
return m, gen, nil
}
if !guardInstalled() {
gsrv.mu.Lock()
gsrv.loading = false
gsrv.mu.Unlock()
return nil, gen, ErrNotInstalled
}
t := time.Now()
m, err := guardLoad(guardDir())
gsrv.mu.Lock()
gsrv.loading = false
if err == nil && gsrv.gen == gen {
gsrv.m, gsrv.loadMS = m, int(time.Since(t)/time.Millisecond)
}
gsrv.mu.Unlock()
if err != nil {
return nil, gen, fmt.Errorf("the local masking model didn't load: %w", err)
}
return m, gen, nil
}
// guardIdle lets the model go after idleAfter with no request, unless
// one is on it now (it sets the timer again when done).
// one is on it now (it sets the timer again when done): it takes every
// turn there is, and none if one is held.
func guardIdle() {
select {
case guardTurn <- struct{}{}:
defer func() { <-guardTurn }()
default:
return
n := 0
defer func() {
for range n {
<-guardTurn
}
}()
for n < cap(guardTurn) {
select {
case guardTurn <- struct{}{}:
n++
default:
return
}
}
guardUnload()
}
+91 -16
View File
@@ -64,6 +64,11 @@ type backend struct {
// queue are the requests waiting for turn, the least left to read
// first
queue queue
// reading are the texts and pieces requests read now: where turn
// lets more than one read at once, a request with one of them waits
// for that read instead of reading it beside it (subagents started
// at once send one system prompt each)
reading readingSet
}
func (b *backend) size() int {
@@ -225,13 +230,26 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
}
units = keep
}
chunks, parts := joinAt(units, b.size())
chunks, parts, wait, release := b.reading.claim(units, b.size())
if len(chunks) == 0 && wait != nil {
// another request reads what is left: what it finds
// comes through the cache
select {
case <-wait:
case <-ctx.Done():
done <- result{nil, errWaitEnded}
return
}
miss = b.still(texts, miss, got, out)
continue
}
if len(chunks) == 0 {
done <- result{nil, fmt.Errorf("the local masking model has no text to read for %d texts", len(miss))}
return
}
found, err := b.classify(chunks[:1])
if err != nil {
release()
done <- result{nil, err}
return
}
@@ -245,22 +263,9 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
b.cache.put(k, got[k])
}
b.cache.mu.Unlock()
release()
b.saveSoon()
// the texts still missing, with this chunk's answers and
// what others' requests found meanwhile
sub := make([]string, len(miss))
for j, i := range miss {
sub[j] = texts[i]
}
o, m := b.known(sub, got)
was := miss
miss = nil
for j, i := range was {
out[i] = o[j]
}
for _, j := range m {
miss = append(miss, was[j])
}
miss = b.still(texts, miss, got, out)
}
done <- result{out, nil}
}()
@@ -275,6 +280,76 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
}
}
// still is which of texts' miss are still missing, with got (this
// call's answers) and what others' requests found meanwhile; out gets
// what is known of the rest.
func (b *backend) still(texts []string, miss []int, got map[[32]byte][]redact.Found, out [][]redact.Found) []int {
sub := make([]string, len(miss))
for j, i := range miss {
sub[j] = texts[i]
}
o, m := b.known(sub, got)
for j, i := range miss {
out[i] = o[j]
}
var left []int
for _, j := range m {
left = append(left, miss[j])
}
return left
}
// readingSet are the texts and pieces requests read now, by hash, each
// with what is closed when its read ends. Its zero value is empty.
type readingSet struct {
mu sync.Mutex
m map[[32]byte]chan struct{}
}
// claim leaves out of units those another request reads now, and
// claims the first chunk of the rest for this one: the rest's chunks and
// parts (joinAt, at size), what is closed when a read of one left out
// ends (nil when none was), and release, which ends this one's claim
// once what it found is in the cache.
func (r *readingSet) claim(units []string, size int) (chunks []string, parts [][]part, wait <-chan struct{}, release func()) {
r.mu.Lock()
defer r.mu.Unlock()
var rest []string
for _, u := range units {
if c, ok := r.m[sha256.Sum256([]byte(u))]; ok {
if wait == nil {
wait = c
}
continue
}
rest = append(rest, u)
}
chunks, parts = joinAt(rest, size)
if len(chunks) == 0 {
return nil, nil, wait, func() {}
}
if r.m == nil {
r.m = map[[32]byte]chan struct{}{}
}
c := make(chan struct{})
var ks [][32]byte
for _, p := range parts[0] {
k := sha256.Sum256([]byte(p.s))
if _, ok := r.m[k]; !ok {
r.m[k] = c
ks = append(ks, k)
}
}
return chunks, parts, wait, func() {
r.mu.Lock()
for _, k := range ks {
delete(r.m, k)
}
r.mu.Unlock()
close(c)
}
}
// errWaitEnded is find's own word that its caller stopped waiting.
var errWaitEnded = errors.New("the wait ended")
+90
View File
@@ -0,0 +1,90 @@
package guard
import (
"fmt"
"reflect"
"strings"
"sync"
"testing"
"time"
)
// A window takes a core, waiting while every one is held, and of more
// only those free: Finds at once never read on more than Cores()
// between them (yyhhyyyyyy's requests at once, xinvxueyuan's 13 cores).
func TestTakeHoldsOnlyWhatIsFree(t *testing.T) {
c := cap(cores)
if c != Cores() {
t.Fatalf("%d cores to share, Cores() %d", c, Cores())
}
held := 0
for range c - 1 {
held += take(1)
}
got := make(chan int, 1)
go func() { got <- take(c) }()
select {
case n := <-got:
if n != 1 {
t.Fatalf("took %d with one free", n)
}
case <-time.After(10 * time.Second):
t.Fatal("waited for more than the one free")
}
held++
go func() { got <- take(c) }()
select {
case n := <-got:
t.Fatalf("took %d with none free", n)
case <-time.After(50 * time.Millisecond):
}
give(1)
held--
if n := <-got; n != 1 {
t.Fatalf("took %d of the one given back", n)
}
held++
give(held)
if len(cores) != 0 {
t.Fatalf("%d left held", len(cores))
}
if n := take(c); n != c {
t.Fatalf("took %d of %d free", n, c)
}
give(c)
}
// Texts read at once, sharing the cores, find what each finds alone.
func TestFindsAtOnceReadAsOneAtATime(t *testing.T) {
m, err := Load(dir(t))
if err != nil {
t.Fatal(err)
}
m.ml = nil
texts := make([]string, 8)
for i := range texts {
var b strings.Builder
for k := range 3 + 5*i {
fmt.Fprintf(&b, "第%d位联系人:张三,电话 138%08d,邮箱 user%d@example.com。\n", k, (i+1)*k*7919, k)
}
texts[i] = b.String()
}
alone := make([][]Span, len(texts))
for i, s := range texts {
alone[i] = m.Find(s)
}
at := make([][]Span, len(texts))
var wg sync.WaitGroup
for i, s := range texts {
wg.Go(func() { at[i] = m.Find(s) })
}
wg.Wait()
for i := range texts {
if len(alone[i]) == 0 || !reflect.DeepEqual(at[i], alone[i]) {
t.Fatalf("text %d: at once %d spans, alone %d", i, len(at[i]), len(alone[i]))
}
}
if len(cores) != 0 {
t.Fatalf("%d cores left held", len(cores))
}
}
+47 -11
View File
@@ -104,7 +104,8 @@ func Load(dir string) (*Model, error) {
}
// logits are the network's scores for ids, from CoreML when it is there
// and the window is long enough to gain by it, else over procs goroutines.
// and the window is long enough to gain by it, else over procs goroutines
// (0: as many of cores as are free, holding them while it reads).
func (m *Model) logits(ids []int, procs int) []float32 {
if m.ml != nil && len(ids) >= coremlMin {
lg, err := coremlRead(m.ml, m.net, ids)
@@ -115,6 +116,10 @@ func (m *Model) logits(ids []int, procs int) []float32 {
e := err.Error()
m.mlFail.Store(&e)
}
if procs == 0 { // CoreML's reader: a core of cores, and all that are free
procs = take(Cores())
defer give(procs)
}
return m.net.logits(ids, procs)
}
@@ -125,11 +130,42 @@ func (m *Model) logits(ids []int, procs int) []float32 {
// 10-28: a 32-core Linux box spent 45 CPU seconds on each request).
func Cores() int { return max(1, min(4, runtime.GOMAXPROCS(0)/2)) }
// cores are the Cores() the model reads on, shared by every Find at once:
// a window read on the CPU holds one or more, so requests read side by
// side never take more than Cores() between them.
var cores = make(chan struct{}, Cores())
// take holds a core of cores, waiting for one, and up to want-1 more of
// those free now: how many it holds, to give back.
func take(want int) int {
cores <- struct{}{}
n := 1
for n < want {
select {
case cores <- struct{}{}:
n++
default:
return n
}
}
return n
}
func give(n int) {
for range n {
<-cores
}
}
// Find is what the model finds in text, at Floor, each span with its score.
// A text longer than a window is read a window at a time, overlapping,
// and on the CPU those windows are read at once, one a core (of Cores): a
// A text longer than a window is read a window at a time, overlapping.
// On the CPU those windows are read at once, one a core (of Cores()): a
// window's own matmuls split over the cores leave most of each idle in
// the steps between them (a 4-core server read a long prompt for minutes).
// Finds called at once share those cores (cores): a window takes one,
// waiting while others have them all, and splits its matmuls over as many
// more as are free, up to its share of them, so a lone short text is read
// on every core and several texts at once a core each.
func (m *Model) Find(text string) []Span {
toks := m.tok.encode(text)
n := len(toks)
@@ -144,7 +180,7 @@ func (m *Model) Find(text string) []Span {
}
}
lgs := make([][]float32, len(starts))
read := func(w, procs int) {
ids := func(w int) []int {
start := starts[w]
end := min(start+window, n)
ids := make([]int, 0, end-start+2)
@@ -152,22 +188,22 @@ func (m *Model) Find(text string) []Span {
for _, t := range toks[start:end] {
ids = append(ids, t.id)
}
ids = append(ids, 2)
lgs[w] = m.logits(ids, procs)
return append(ids, 2)
}
procs := Cores()
at := min(procs, len(starts))
if m.ml != nil || at == 1 {
if m.ml != nil {
for w := range starts {
read(w, procs)
lgs[w] = m.logits(ids(w), 0)
}
} else {
at := min(Cores(), len(starts))
var next atomic.Int32
var wg sync.WaitGroup
for range at {
wg.Go(func() {
for w := int(next.Add(1)) - 1; w < len(starts); w = int(next.Add(1)) - 1 {
read(w, max(1, procs/at))
procs := take(max(1, Cores()/at))
lgs[w] = m.net.logits(ids(w), procs)
give(procs)
}
})
}
+174
View File
@@ -0,0 +1,174 @@
package pii
import (
"context"
"fmt"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/pii/guard"
"github.com/yetone/magpie/internal/redact"
)
// gateFinder is a model whose reads wait at a gate, counting how many
// are under way at once.
type gateFinder struct {
gate chan struct{}
now, most *atomic.Int32
}
func (f gateFinder) Find(text string) []guard.Span {
n := f.now.Add(1)
for m := f.most.Load(); n > m && !f.most.CompareAndSwap(m, n); m = f.most.Load() {
}
<-f.gate
f.now.Add(-1)
return nil
}
// yyhhyyyyyy on Discord: AstrLink Guard read one request at a time, so
// agents' requests at once queued behind each other. It reads
// guard.Cores() of them at once now, and they load the model once.
func TestGuardReadsRequestsAtOnce(t *testing.T) {
k := cap(guardTurn)
if k != guard.Cores() {
t.Fatalf("%d turns, %d cores", k, guard.Cores())
}
if k < 2 {
t.Skipf("one core to read on here (GOMAXPROCS %d)", guard.Cores())
}
guardSandbox(t)
fakeGuardFiles(t)
var loads, now, most atomic.Int32
loading, gate := make(chan struct{}), make(chan struct{})
guardLoad = func(string) (spanFinder, error) {
loads.Add(1)
<-loading
return gateFinder{gate, &now, &most}, nil
}
var wg sync.WaitGroup
errs := make(chan error, k)
for i := range k {
wg.Go(func() {
_, err := Of(AstrLinkGuard).Find(context.Background(), []string{fmt.Sprintf("request %d", i)})
errs <- err
})
}
waitFor(t, "every request its turn", func() bool { return len(guardTurn) == k })
// the other requests wait for the first's load: watch a while for
// one loading beside it
for range 40 {
if n := loads.Load(); n != 1 {
t.Fatalf("%d loads for requests at once", n)
}
time.Sleep(5 * time.Millisecond)
}
close(loading)
waitFor(t, "every request read at once", func() bool { return now.Load() == int32(k) })
close(gate)
wg.Wait()
close(errs)
for err := range errs {
if err != nil {
t.Fatal(err)
}
}
if loads.Load() != 1 || most.Load() != int32(k) {
t.Fatalf("%d loads, %d read at most at once", loads.Load(), most.Load())
}
}
// The idle timer lets the model go only with no request on it: with one
// turn of several held, it waits for the next timer.
func TestGuardIdleWaitsForEveryTurn(t *testing.T) {
guardSandbox(t)
fakeGuardFiles(t)
var reads atomic.Int32
guardLoad = func(string) (spanFinder, error) { return fakeFinder{nil, &reads}, nil }
if _, err := Of(AstrLinkGuard).Find(context.Background(), []string{"one"}); err != nil {
t.Fatal(err)
}
guardTurn <- struct{}{} // a request on it
guardIdle()
running := Of(AstrLinkGuard).Now().Running
<-guardTurn
if !running {
t.Fatal("let go while a request read it")
}
if len(guardTurn) != 0 {
t.Fatalf("%d turns left held", len(guardTurn))
}
guardIdle()
if Of(AstrLinkGuard).Now().Running {
t.Fatal("kept with no request")
}
}
// Requests read at once don't read one text beside each other: the
// second waits for the first's read and takes its answer (subagents
// started at once send one system prompt each).
func TestOneTextReadOnceAtOnce(t *testing.T) {
dir := t.TempDir()
var calls atomic.Int32
first, release := make(chan struct{}), make(chan struct{})
b := &backend{turn: make(chan struct{}, 2), waiting: new(atomic.Int32), cache: newLRU(100), disk: new(diskState),
path: func() string { return filepath.Join(dir, "found.bin") },
heldBack: func() error { return nil },
chunk: guardChunk,
classify: func(texts []string) ([][]redact.Found, error) {
if calls.Add(1) == 1 {
close(first)
<-release
}
out := make([][]redact.Found, len(texts))
for i, s := range texts {
if j := strings.Index(s, "13800138000"); j >= 0 {
out[i] = []redact.Found{{Start: j, End: j + 11, Label: "private_phone", Score: 0.9}}
}
}
return out, nil
}}
t.Cleanup(func() {
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()
})
texts := []string{"the system prompt, call 13800138000"}
got := make(chan [][]redact.Found, 2)
find := func() {
out, err := b.find(context.Background(), texts)
if err != nil {
t.Error(err)
}
got <- out
}
go find()
<-first
go find()
waitFor(t, "the second request its turn", func() bool { return len(b.turn) == 2 })
// it waits for the first's read: watch a while for a read beside it
for range 40 {
if n := calls.Load(); n != 1 {
t.Fatalf("%d reads of one text", n)
}
time.Sleep(5 * time.Millisecond)
}
close(release)
for range 2 {
out := <-got
if len(out) != 1 || len(out[0]) != 1 || out[0][0].Label != "private_phone" {
t.Fatalf("found %v", out)
}
}
if n := calls.Load(); n != 1 {
t.Fatalf("%d reads of one text", n)
}
}