pii: a strict request goes once only what an earlier one sent unread is left (gaubeebangeel on X)
gaubeebangeel on X: with masking on, first tokens on a cloud server
came at 30-40s, 10-15s with it off.
Where the time goes, measured on a 60-turn Claude Code Messages body
(367-414 KB, a 4 KB tool result a turn; TestRealLatencyOfALongSession,
gated on GUARD_REAL_DIR, run in WSL on a Ryzen AI MAX+ 395):
- The rules are not it: 89ms for the body cold, 13ms warm (the rule
memo); 7-11ms on mote's M5 Pro (BenchmarkMaskLongSession,
BenchmarkScrubCodexTurn).
- AstrLink Guard on the CPU is: ~7 KB/s on its 4 cores (GOMAXPROCS=32),
~3 KB/s on one (GOMAXPROCS=2). A turn whose new text the model reads
waits for it: 16 KB of new tool output is 3.0-3.5s on 4 cores and
7.8-8.2s on one. That part is the model's reading and stays.
- With the model turned on (strict, 15s), a resumed or never-read
history was read on every request, until the 15s ran out, though the
vendor had that text already and it goes as it went on the same route
(redact's sentSpans): its finds only feed learnLate. 4 cores: 15.1,
15.0, 15.0, 7.8s, then 0.85s. 1 core: 15s on eight requests in a row,
then 7.9s, then 1.9s.
Now a request with a bound that waits for every text (masking's strict
wait) marks what it goes without, as a Bounded one does (backend.sent),
and once all that is left is what an earlier request sent unread, it is
answered with a *Partial (afterSent): what it adds was read, the rest
has the rules' masking, as on the same route it had. The model reads on
into the backlog after the request, to the request's own bound, and
keeps what it finds for the next one. While it waits, a strict request
counts only what it adds for the queue, so it goes before a backlog
read on by an earlier request. A strict request with no bound still
reads everything; Bounded (the default) is unchanged.
After, same body, same box: 4 cores 15.1s (the first request: all new
text), then 0.97, 1.3, 1.4, 2.3, 3.0, 3.1, 3.1, 3.1, 2.9s; 1 core 15.1s,
then 2.1, 4.6, 4.5, 4.8, 4.7, 4.6, 5.7, 4.5, 4.9s. Those later turns
come back to back, so each shares the CPU with the backlog read on
after the one before; with an agent's think time between them it is
read meanwhile.
What changes in what is masked: on the same route, nothing in what a
text goes as. A value the model would find late in a backlog text masks
new text from the request after the read, not from the one it went
with. On another route (the user picked another provider), a backlog
text has the model's finds of now, none until it is read, and goes with
the rules' masking alone; before, it was read for up to 15s, newest
first.
Run (WSL magpie-desktop, at this commit rebased on 005178104):
go test ./internal/pii ./internal/masking ./internal/redact,
go test -run "Mask|Redact|Privacy|Model|Partial" ./internal/gateway,
go test -race -count=5 on TestStrictRequestGoesBeforeTheBacklog,
TestBounded* and TestNewestTextReadFirst, go vet (linux, windows,
darwin) on pii and masking, and the latency runs above with the real
AstrLink Guard files.
Broken by hand: with early forced false,
TestStrictRequestGoesBeforeTheBacklog goes red ("the request waited for
the history an earlier one sent unread", 20s).
Not run: the full suite (mote and mica each had suites queued on
suite.lock); Privacy Filter (pf-serve) on a CPU, which shares
backend.find; the queue-order change has no unit test of its own (a
fair one races the turn's hand-over), only the latency runs.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -8,6 +8,7 @@ import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
)
|
||||
@@ -176,3 +177,76 @@ func TestGuardReadsShortChunks(t *testing.T) {
|
||||
t.Fatalf("Privacy Filter's chunk is %d bytes", pf.size())
|
||||
}
|
||||
}
|
||||
|
||||
// A request that waits for every text (masking's strict wait) goes once
|
||||
// what it adds is read, and what an earlier request already sent unread
|
||||
// is read after it, to the request's bound. Before, it waited for the
|
||||
// whole backlog, up to its 15s, on every turn after a resumed history:
|
||||
// on a 4-core Linux CPU a 60-turn session waited 15s on each of its
|
||||
// first three requests (gaubeebangeel on X, 11-13).
|
||||
func TestStrictRequestGoesBeforeTheBacklog(t *testing.T) {
|
||||
r := newReader(t, guardChunk)
|
||||
turns := history(40, 3000) // 120 KB the model hasn't read
|
||||
// the first request runs out of its wait after one chunk, the rest
|
||||
// of the history sent unread
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
r.during = func(int) { cancel() }
|
||||
if _, err := r.find(ctx, turns); err == nil {
|
||||
t.Fatal("the first request read the whole history")
|
||||
}
|
||||
r.during = nil
|
||||
// the next: the history and a turn more, a bound far off. Past the
|
||||
// first chunk (the new turn with it) every read waits for gate.
|
||||
gate := make(chan struct{})
|
||||
before, _ := r.bytes()
|
||||
var reads atomic.Int32
|
||||
r.during = func(int) {
|
||||
if reads.Add(1) > 1 {
|
||||
<-gate
|
||||
}
|
||||
}
|
||||
turns = append(turns, "Alice asked again")
|
||||
type res struct {
|
||||
got [][]redact.Found
|
||||
err error
|
||||
}
|
||||
ch := make(chan res, 1)
|
||||
go func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
|
||||
defer cancel()
|
||||
got, err := r.find(ctx, turns)
|
||||
ch <- res{got, err}
|
||||
}()
|
||||
var got res
|
||||
select {
|
||||
case got = <-ch:
|
||||
case <-time.After(20 * time.Second):
|
||||
close(gate)
|
||||
t.Fatal("the request waited for the history an earlier one sent unread")
|
||||
}
|
||||
var p *Partial
|
||||
if !errors.As(got.err, &p) || !errors.Is(got.err, afterSent) {
|
||||
t.Fatalf("the request's answer: %v", got.err)
|
||||
}
|
||||
if last := got.got[len(got.got)-1]; len(last) != 1 {
|
||||
t.Fatalf("what the request added wasn't read: %v", last)
|
||||
}
|
||||
// the backlog is read after it, to the end
|
||||
close(gate)
|
||||
for deadline := time.Now().Add(20 * time.Second); ; {
|
||||
if _, miss := r.known(turns, nil); len(miss) == 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the backlog wasn't read after the request")
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
// its read is over once the turn is free
|
||||
r.turn <- struct{}{}
|
||||
<-r.turn
|
||||
// 26 texts of 3 KB the history has apart, less the first request's
|
||||
if n, _ := r.bytes(); n-before < 70<<10 {
|
||||
t.Fatalf("read %d bytes after the request", n-before)
|
||||
}
|
||||
}
|
||||
|
||||
+65
-22
@@ -60,8 +60,8 @@ type backend struct {
|
||||
// leaves the model finishing the chunk it is on, so a model that reads
|
||||
// on the CPU has short ones.
|
||||
chunk int
|
||||
// sent are the texts and pieces a Bounded request went without the
|
||||
// model's reading (by hash): what a request sent unread before.
|
||||
// sent are the texts and pieces a request went without the model's
|
||||
// reading (by hash): what a request sent unread before.
|
||||
sent sentSet
|
||||
// queue are the requests waiting for turn, the least left to read
|
||||
// first
|
||||
@@ -139,17 +139,20 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
if len(miss) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
// what a Bounded request goes without the model's reading, or with
|
||||
// it, is sent now: what was sent unread before is the backlog
|
||||
// what a request goes without the model's reading, or with it, is
|
||||
// sent now: what was sent unread before is the backlog
|
||||
lenient := IsBounded(ctx)
|
||||
var backlog map[[32]byte]bool
|
||||
if lenient {
|
||||
var ks [][32]byte
|
||||
for _, u := range b.missing(texts, miss, nil) {
|
||||
ks = append(ks, sha256.Sum256([]byte(u)))
|
||||
}
|
||||
backlog = b.sent.mark(ks)
|
||||
var ks [][32]byte
|
||||
for _, u := range b.missing(texts, miss, nil) {
|
||||
ks = append(ks, sha256.Sum256([]byte(u)))
|
||||
}
|
||||
backlog := b.sent.mark(ks)
|
||||
// a request that waits for every text but has a bound (masking's
|
||||
// strict wait) stops waiting once only the backlog is left, and the
|
||||
// backlog is read on after it, to that bound (afterSent)
|
||||
until, early := ctx.Deadline()
|
||||
early = early && !lenient
|
||||
answered := false // early, by find's goroutine
|
||||
// how much of the texts this request has left for the model to read
|
||||
left := func(got map[[32]byte][]redact.Found, miss []int, read int) int {
|
||||
n, old := 0, 0
|
||||
@@ -160,7 +163,15 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
n += len(u)
|
||||
}
|
||||
}
|
||||
return n + min(old, max(0, backlogCap-read))
|
||||
switch {
|
||||
case lenient:
|
||||
return n + min(old, max(0, backlogCap-read))
|
||||
case early && !answered:
|
||||
// it waits for what it adds alone: it goes before the
|
||||
// backlog an earlier request reads on into
|
||||
return n
|
||||
}
|
||||
return n + old
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return b.partial(ctx, texts)
|
||||
@@ -183,6 +194,17 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
<-b.turn
|
||||
}
|
||||
}()
|
||||
// the request is answered once; after an early answer the reading
|
||||
// goes on under rctx, the request's bound without the request
|
||||
answer := func(r result) {
|
||||
if !answered {
|
||||
answered = true
|
||||
done <- r
|
||||
}
|
||||
}
|
||||
rctx := ctx
|
||||
after, stop := context.WithDeadline(context.WithoutCancel(ctx), until)
|
||||
defer stop()
|
||||
// what this call's chunks found, by hash, whatever the cache
|
||||
// lets go of meanwhile
|
||||
got := map[[32]byte][]redact.Found{}
|
||||
@@ -195,8 +217,8 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
// 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, errWaitEnded}
|
||||
if rctx.Err() != nil {
|
||||
answer(result{nil, errWaitEnded})
|
||||
return
|
||||
}
|
||||
// give way to a request waiting for the turn with less
|
||||
@@ -205,8 +227,8 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
n := left(got, miss, read)
|
||||
<-b.turn
|
||||
held = false
|
||||
if !b.takeTurn(ctx, n) {
|
||||
done <- result{nil, errWaitEnded}
|
||||
if !b.takeTurn(rctx, n) {
|
||||
answer(result{nil, errWaitEnded})
|
||||
return
|
||||
}
|
||||
held = true
|
||||
@@ -214,10 +236,14 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
// the one ahead may have failed: those queued behind it
|
||||
// don't each try again, minutes apiece
|
||||
if err := b.heldBack(); err != nil {
|
||||
done <- result{nil, err}
|
||||
answer(result{nil, err})
|
||||
return
|
||||
}
|
||||
units := b.missing(texts, miss, got)
|
||||
if early && !answered && !slices.ContainsFunc(units, func(u string) bool { return !backlog[sha256.Sum256([]byte(u))] }) {
|
||||
answer(result{slices.Clone(out), &Partial{Missing: len(miss), Of: len(texts), Err: afterSent}})
|
||||
rctx = after
|
||||
}
|
||||
if lenient {
|
||||
// the backlog past its cap is left: its texts go with
|
||||
// what the rules find
|
||||
@@ -238,21 +264,21 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
// comes through the cache
|
||||
select {
|
||||
case <-wait:
|
||||
case <-ctx.Done():
|
||||
done <- result{nil, errWaitEnded}
|
||||
case <-rctx.Done():
|
||||
answer(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))}
|
||||
answer(result{nil, fmt.Errorf("the local masking model has no text to read for %d texts", len(miss))})
|
||||
return
|
||||
}
|
||||
found, err := classifySafely(b.classify, chunks[:1])
|
||||
if err != nil {
|
||||
release()
|
||||
done <- result{nil, err}
|
||||
answer(result{nil, err})
|
||||
return
|
||||
}
|
||||
b.cache.mu.Lock()
|
||||
@@ -269,7 +295,7 @@ func (b *backend) find(ctx context.Context, texts []string) ([][]redact.Found, e
|
||||
b.saveSoon()
|
||||
miss = b.still(texts, miss, got, out)
|
||||
}
|
||||
done <- result{out, nil}
|
||||
answer(result{out, nil})
|
||||
}()
|
||||
select {
|
||||
case r := <-done:
|
||||
@@ -371,6 +397,23 @@ func (r *readingSet) claim(units []string, size int) (chunks []string, parts [][
|
||||
// errWaitEnded is find's own word that its caller stopped waiting.
|
||||
var errWaitEnded = errors.New("the wait ended")
|
||||
|
||||
// afterSent is a Partial's Err for a request that waits for every text
|
||||
// (masking's strict wait) answered once all that is left is what an
|
||||
// earlier request already sent without the model's reading. Such a text
|
||||
// goes as it went on the same route (redact's sentSpans): what the model
|
||||
// finds in it now changes nothing in it, and only makes known a value to
|
||||
// mask in text after it (learnLate). So the request goes, and the model
|
||||
// reads on to the request's bound, keeping what it finds for the next
|
||||
// one. Before, a resumed or never-read history was read on every request
|
||||
// until the strict wait's 15s ran out, newest first: on a 4-core Linux
|
||||
// CPU a 60-turn Claude Code session resumed waited 15s, 15s, 15s and 7.8s
|
||||
// on its first four requests, each for text the vendor already had
|
||||
// (gaubeebangeel on X, 11-13: first tokens at 30-40s with masking on,
|
||||
// 10-15s off). On another route (the user picked another provider) such
|
||||
// a text has the model's finds of now, and goes with the rules' alone
|
||||
// until the model has read it.
|
||||
var afterSent = errors.New("what is left was sent before without the model's reading, and is read after the request")
|
||||
|
||||
// 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
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
package pii
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/pii/guard"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
)
|
||||
|
||||
// latencySession is a Messages request on turn n as Claude Code sends
|
||||
// one: a long system prompt, tool definitions, and per turn the user's
|
||||
// words with a reminder, the assistant's prose and a tool call, and its
|
||||
// result, kb KB of it.
|
||||
func latencySession(n, kb int) []byte {
|
||||
prose := "You are an interactive agent that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user. Prefer editing existing files; keep changes small and verify them by running the tests. "
|
||||
var tools []any
|
||||
for i := 0; i < 24; i++ {
|
||||
tools = append(tools, map[string]any{"name": fmt.Sprintf("Tool%d", i), "description": strings.Repeat(fmt.Sprintf("Tool %d reads and writes files in the user's workspace. ", i), 25),
|
||||
"input_schema": map[string]any{"type": "object", "properties": map[string]any{"path": map[string]any{"type": "string", "description": "The absolute path"}}}})
|
||||
}
|
||||
var msgs []any
|
||||
for i := 0; i < n; i++ {
|
||||
var out strings.Builder
|
||||
for j := 0; out.Len() < kb*1024; j++ {
|
||||
switch (i + j) % 4 {
|
||||
case 0:
|
||||
fmt.Fprintf(&out, "/home/ubuntu/projects/api/internal/store/store_%d.go:%d:\terr := db.QueryRowContext(ctx, \"SELECT id, name, email FROM users WHERE id = $1\", id).Scan(&u.ID, &u.Name, &u.Email)\n", j, 40+j)
|
||||
case 1:
|
||||
fmt.Fprintf(&out, "2026-11-13T12:%02d:%02d.%03dZ INFO request id=%08x method=POST path=/v1/orders/%d status=200 dur=%dms\n", j%60, i%60, j%1000, i*7919+j, j, 3+j%90)
|
||||
case 2:
|
||||
fmt.Fprintf(&out, "Author: Wei Zhang <wei.zhang@example.com> commit %040x\n fix: retry the payment webhook when the upstream answers 502 (#%d)\n", i*31337+j, 1000+j)
|
||||
case 3:
|
||||
fmt.Fprintf(&out, " --- PASS: TestOrderFlow/case_%d (0.%02ds) created order %d for customer Maria Garcia, total 129.%02d EUR\n", j, j%100, 5000+j, j%100)
|
||||
}
|
||||
}
|
||||
msgs = append(msgs,
|
||||
map[string]any{"role": "user", "content": []any{
|
||||
map[string]any{"type": "text", "text": fmt.Sprintf("step %d: the order webhook still fails on retries for customer Maria Garcia, look at the logs and fix it", i)},
|
||||
map[string]any{"type": "text", "text": "<system-reminder>The user opened /home/ubuntu/projects/api/internal/store/store.go in the IDE.</system-reminder>"}}},
|
||||
map[string]any{"role": "assistant", "content": []any{
|
||||
map[string]any{"type": "text", "text": fmt.Sprintf("Turn %d. I'll look at the webhook handler and the retry logic, then run the store tests to see where the 502 comes from before changing anything.", i)},
|
||||
map[string]any{"type": "tool_use", "id": fmt.Sprintf("toolu_%024d", i), "name": "Bash", "input": map[string]any{"command": fmt.Sprintf("grep -rn webhook /home/ubuntu/projects/api | head -%d", 50+i)}}}},
|
||||
map[string]any{"role": "user", "content": []any{map[string]any{"type": "tool_result", "tool_use_id": fmt.Sprintf("toolu_%024d", i), "content": out.String()}}},
|
||||
)
|
||||
}
|
||||
b, _ := json.Marshal(map[string]any{"model": "claude-opus-5-5", "stream": true, "max_tokens": 32000,
|
||||
"system": []any{map[string]any{"type": "text", "text": strings.Repeat(prose, 100)}}, "tools": tools, "messages": msgs})
|
||||
return b
|
||||
}
|
||||
|
||||
// TestRealLatencyOfALongSession times masking a long Claude Code
|
||||
// session's requests turn after turn, with the rules alone and with
|
||||
// AstrLink Guard, where GUARD_REAL_DIR names a folder holding its files.
|
||||
func TestRealLatencyOfALongSession(t *testing.T) {
|
||||
d := os.Getenv("GUARD_REAL_DIR")
|
||||
if d == "" {
|
||||
t.Skip("GUARD_REAL_DIR names no AstrLink Guard files")
|
||||
}
|
||||
root := t.TempDir()
|
||||
if err := os.MkdirAll(filepath.Join(root, guardRev[:12]), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, f := range guardFiles {
|
||||
if err := os.Symlink(filepath.Join(d, filepath.Base(f.path)), filepath.Join(root, guardRev[:12], filepath.Base(f.path))); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
oldRoot := guardRoot
|
||||
guardRoot = func() string { return root }
|
||||
t.Cleanup(func() { guardRoot = oldRoot; guardUnload() })
|
||||
var read atomic.Int64
|
||||
oldClassify := guardBackend.classify
|
||||
guardBackend.classify = func(texts []string) ([][]redact.Found, error) {
|
||||
for _, s := range texts {
|
||||
read.Add(int64(len(s)))
|
||||
}
|
||||
return oldClassify(texts)
|
||||
}
|
||||
t.Cleanup(func() { guardBackend.classify = oldClassify })
|
||||
turns, kb, wait, steps := 60, 4, 15, 4
|
||||
fmt.Sscan(os.Getenv("LATENCY_TURNS"), &turns)
|
||||
fmt.Sscan(os.Getenv("LATENCY_KB"), &kb)
|
||||
fmt.Sscan(os.Getenv("LATENCY_WAIT"), &wait)
|
||||
fmt.Sscan(os.Getenv("LATENCY_STEPS"), &steps)
|
||||
model := os.Getenv("LATENCY_MODEL") != ""
|
||||
o := redact.Options{Secrets: true, Personal: true, Route: "anthropic"}
|
||||
if model {
|
||||
o.Model = func(texts []string) [][]redact.Found {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(wait)*time.Second)
|
||||
defer cancel()
|
||||
got, err := guardBackend.find(ctx, texts)
|
||||
var p *Partial
|
||||
if err != nil && !errors.As(err, &p) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(got) != len(texts) {
|
||||
got = make([][]redact.Found, len(texts))
|
||||
}
|
||||
return got
|
||||
}
|
||||
o.MinScore = guard.MinScore
|
||||
o.NamesByModel = true
|
||||
guardClassify([]string{"warm the model"})
|
||||
read.Store(0)
|
||||
}
|
||||
if os.Getenv("LATENCY_WARM") != "" {
|
||||
// the history read before, as a session the model kept up with
|
||||
saved := wait
|
||||
wait = 3600
|
||||
redact.MaskJSON(latencySession(turns, kb), o)
|
||||
wait = saved
|
||||
turns++
|
||||
}
|
||||
for n := turns; n < turns+steps; n++ {
|
||||
body := latencySession(n, kb)
|
||||
read.Store(0)
|
||||
t0 := time.Now()
|
||||
redact.MaskJSON(body, o)
|
||||
t.Logf("turn %d: %d KB body, masked in %v, model read %d KB", n, len(body)>>10, time.Since(t0).Round(time.Millisecond), read.Load()>>10)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user