shensmart and xinvxueyuan on Discord (10-28): with the local model on by
default, a long history kept the CPU high; the model off, 5-15%.
What was heavy (measured, TestLiveHistoryCost below): not re-reading.
A text read once is kept by hash (cache, on disk too), and a warm turn
costs what the rules alone do. The heavy case is a history the model
hasn't read (a resumed session, or one from before the model was on),
on the CPU path (Linux, Windows, Docker). Each request's 2 s wait was
spent reading that history oldest first on every core (threads =
GOMAXPROCS-1, windows at once = GOMAXPROCS), the newest turn last, and
the 12 KB chunk in flight was finished past the wait. A 32-core Linux
box spent 33-60 CPU seconds a request, 13 cores busy for as long as
requests came, and the backlog was still unread after 30 requests.
Nothing ran on after the last request (1 ms CPU in the 20 s after).
Now:
- guard.Cores: AstrLink Guard reads on half of GOMAXPROCS, 4 at most.
- backend.missing reads a request's unread texts newest first (the last
text, a long one's last piece, first).
- AstrLink Guard's chunk is 4 KB (backend.chunk), not 12 KB, so what a
request leaves the model finishing past its wait is about a second.
- pii.Bounded (masking's default, not a model the user turned on):
what a request went without reading is remembered by hash
(backend.sent); a request after it reads what it adds first, and that
backlog backlogCap (4 KB) at most, nothing found for the rest (the
rules mask it, as past the 2 s wait). The answer past the wait with
what was read is 874b86653's (pii.Partial), unchanged.
- A model the user turned on (strict) still reads everything, within
874b86653's strictWait.
- Not done: OS priority (nice) for the model's threads; the core cap
is the bound.
Measured, TestLiveHistoryCost (internal/masking, gated on
MAGPIE_GUARD_FILES, no network): a 2,041,658-byte Codex Responses
body (2,032,267 bytes at the rebased tree), 200 turns (repo files as tool output, doc paragraphs as answers,
Chinese names and an email every 10 turns), 30 requests 3 s apart, a
turn more each, model never having read it, then 20 s idle.
WSL2 Ubuntu 24.04 on xiaomi-gpu (32 cores, CPU path):
before: 33-60 CPU-s a request (44.0, 38.3, 50.4, 42.8, 54.3 ...),
session 23m16.8s CPU over 1m48s (1293% of a core),
wall median 2.759s, max 3.07s; 20 s after: 1 ms
after: 6.3-9.2 CPU-s a request, session 4m1.5s over 1m30s (268%),
wall median 2.389s, max 2.438s; 20 s after: 1 ms
warm turn after a full read: 876ms wall / 5.284s CPU before; after
the rebase the "full read" is strict and stops at 874b86653's
15 s, so that line is not a warm turn (2.41s / 7.9s); before
the rebase, at a full read, 1.28s / 3.04s (4 cores, not 31)
rules alone: 394 / 384 ms CPU
mote (M5 Pro, CoreML):
before: requests 1-3 2.2 CPU-s each, then ~0.45; session 18.7s CPU
over 1m30s (21%); warm 396ms / 380ms
after: request 1 2.12 CPU-s, then 0.44-0.62; session 17.2s CPU
(19%); wall median 562ms; warm 476ms / 465ms
On the CPU path a turn adds about 15 KB here, more than 4 cores read
in 2 s, so each request still spends its wait (now on 4 cores, newest
text first) and the backlog isn't reached until turns get shorter;
on CoreML the backlog is gone after the first request.
Tests, each red with its part of the change undone by hand:
- TestNewestTextReadFirst (pii): red on the old code as it stands
("read first: a a a ..."); red again with the last piece not first.
- TestBoundedReadsTheBacklogALittleARequest: backlog cap removed, the
second request read 75169 bytes.
- TestGuardReadsShortChunks: red with guard's chunk unset (12288).
- TestReadsOnFewCores (guard): Cores at 32 and 1 procs.
- TestDefaultModelIsBounded (masking): red with the default's ctx not
Bounded ("on by default, the model wasn't asked Bounded").
- TestJoinSplitsAtChunkSize now expects the newest-first order.
Rebased onto 874b86653 (strictWait, pii.Partial), which made the
same partial-answer change; mine was dropped for its. Everything below
was run again at the rebased tree.
Run at this tree: gofmt -l clean; go vet darwin, GOOS=linux and
GOOS=windows -tags nogui on internal/pii/..., internal/masking,
internal/redact; go test -count=1 -timeout 45m of those on mote,
wsl-run (magpie-desktop) and win-run (xiaomi-gpu), all ok; internal/gwmw ok;
-race -count=5 of the pii/masking turn, wait, partial and bounded tests
on mote ok; internal/gateway, internal/gui -run
'Mask|Redact|Privacy|PII' ok; TestLiveHistoryCost on mote and WSL. Not run: the full ./... suite.
Not tried: a real Codex session through a live gateway.
179 lines
5.6 KiB
Go
179 lines
5.6 KiB
Go
package pii
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"testing"
|
|
|
|
"github.com/yetone/magpie/internal/redact"
|
|
)
|
|
|
|
// fakeReader is a backend whose model finds "Alice" wherever it is, and
|
|
// keeps what it was asked.
|
|
type fakeReader struct {
|
|
*backend
|
|
mu sync.Mutex
|
|
asked []string
|
|
// during, when set, runs in each read
|
|
during func(n int)
|
|
}
|
|
|
|
func newReader(t *testing.T, chunk int) *fakeReader {
|
|
dir := t.TempDir()
|
|
r := &fakeReader{}
|
|
r.backend = &backend{turn: make(chan struct{}, 1), waiting: new(atomic.Int32), cache: newLRU(10000), disk: new(diskState),
|
|
path: func() string { return filepath.Join(dir, "found.bin") },
|
|
heldBack: func() error { return nil },
|
|
chunk: chunk,
|
|
classify: func(texts []string) ([][]redact.Found, error) {
|
|
r.mu.Lock()
|
|
r.asked = append(r.asked, texts...)
|
|
n := len(r.asked)
|
|
r.mu.Unlock()
|
|
if r.during != nil {
|
|
r.during(n)
|
|
}
|
|
out := make([][]redact.Found, len(texts))
|
|
for i, s := range texts {
|
|
for at := 0; ; {
|
|
j := strings.Index(s[at:], "Alice")
|
|
if j < 0 {
|
|
break
|
|
}
|
|
out[i] = append(out[i], redact.Found{Start: at + j, End: at + j + 5, Label: "private_person", Score: 0.9})
|
|
at += j + 5
|
|
}
|
|
}
|
|
return out, nil
|
|
}}
|
|
t.Cleanup(func() {
|
|
r.disk.mu.Lock()
|
|
if r.disk.timer != nil && r.disk.timer.Stop() {
|
|
r.disk.saves.Done()
|
|
}
|
|
r.disk.timer = nil
|
|
r.disk.mu.Unlock()
|
|
r.disk.saves.Wait()
|
|
})
|
|
return r
|
|
}
|
|
|
|
// bytes is how much the model was asked to read, and how many times.
|
|
func (r *fakeReader) bytes() (n, reads int) {
|
|
r.mu.Lock()
|
|
defer r.mu.Unlock()
|
|
for _, s := range r.asked {
|
|
n += len(s)
|
|
}
|
|
return n, len(r.asked)
|
|
}
|
|
|
|
// history is n turns of about size bytes each, the last named "turn n".
|
|
func history(n, size int) []string {
|
|
var out []string
|
|
for i := range n {
|
|
out = append(out, "turn "+strings.Repeat("x", 3)+string(rune('A'+i%26))+" "+strings.Repeat("words go here ", size/14))
|
|
}
|
|
return out
|
|
}
|
|
|
|
// An agent's history is oldest first, and what is new in a request is
|
|
// at its end: that is read first, so what a request waits for is what
|
|
// it adds, not the history behind it. Before, the oldest text was read
|
|
// first, and a history not read yet kept the newest turn waiting behind
|
|
// it on every request (xinvxueyuan and shensmart on Discord, 10-28).
|
|
func TestNewestTextReadFirst(t *testing.T) {
|
|
r := newReader(t, 0)
|
|
texts := []string{strings.Repeat("a ", chunkSize/2-8), strings.Repeat("b ", chunkSize/2-8), "Alice wrote: " + strings.Repeat("c ", chunkSize/2-16)}
|
|
if _, err := r.find(context.Background(), texts); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(r.asked) != 3 || !strings.HasPrefix(r.asked[0], "Alice") {
|
|
t.Fatalf("read first: %.20q of %d", r.asked[0], len(r.asked))
|
|
}
|
|
// a long text's last piece goes first too
|
|
r = newReader(t, 0)
|
|
long := strings.Repeat("a ", pieceSize) + " Alice " + strings.Repeat("z ", 100)
|
|
if _, err := r.find(context.Background(), []string{long}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if !strings.Contains(r.asked[0], "Alice") {
|
|
t.Fatalf("a long text's first piece read first: %.20q", r.asked[0])
|
|
}
|
|
}
|
|
|
|
// A Bounded request reads what it adds to a history, and of what an
|
|
// earlier request went without the model's reading, backlogCap at most.
|
|
// Before, every request read on into the whole history not read yet, on
|
|
// every core, for as long as requests came.
|
|
func TestBoundedReadsTheBacklogALittleARequest(t *testing.T) {
|
|
r := newReader(t, guardChunk)
|
|
turns := history(40, 3000) // 120 KB the model hasn't read
|
|
// the first request stops waiting after one chunk, as one does at
|
|
// its 2 s
|
|
ctx, cancel := context.WithCancel(Bounded(context.Background()))
|
|
r.during = func(int) { cancel() }
|
|
got, err := r.find(ctx, turns)
|
|
var p *Partial
|
|
if !errors.As(err, &p) {
|
|
t.Fatalf("a Bounded request that stopped waiting: %v", err)
|
|
}
|
|
if len(got) != len(turns) {
|
|
t.Fatalf("%d answers for %d texts", len(got), len(turns))
|
|
}
|
|
first, _ := r.bytes()
|
|
if first > guardChunk {
|
|
t.Fatalf("the first request read %d bytes after it stopped waiting", first)
|
|
}
|
|
r.during = nil
|
|
// the next turn: the history and a turn more, no deadline at all
|
|
turns = append(turns, "Alice asked again")
|
|
before, _ := r.bytes()
|
|
got, err = r.find(Bounded(context.Background()), turns)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
read, _ := r.bytes()
|
|
read -= before
|
|
if read > len("Alice asked again")+backlogCap+guardChunk {
|
|
t.Fatalf("the second request read %d bytes of a history the first left: the backlog wasn't capped", read)
|
|
}
|
|
if !strings.Contains(strings.Join(r.asked, "|"), "Alice asked again") || len(got[len(got)-1]) != 1 {
|
|
t.Fatalf("what the request added wasn't read: %v", got[len(got)-1])
|
|
}
|
|
// it is read still, a little a request
|
|
for range 3 {
|
|
before, _ := r.bytes()
|
|
if _, err := r.find(Bounded(context.Background()), turns); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
n, _ := r.bytes()
|
|
if n-before == 0 || n-before > backlogCap+guardChunk {
|
|
t.Fatalf("a request read %d bytes of the backlog", n-before)
|
|
}
|
|
}
|
|
// turned on by the user, a request reads all of it
|
|
if _, err := r.find(context.Background(), turns); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, miss := r.known(turns, nil); len(miss) != 0 {
|
|
t.Fatalf("%d texts unread after a request that waits for all", len(miss))
|
|
}
|
|
}
|
|
|
|
// AstrLink Guard reads in short chunks: a request that stops waiting
|
|
// leaves the model finishing the chunk it is on, on the CPU about a
|
|
// second of 4 KB where 12 KB took several.
|
|
func TestGuardReadsShortChunks(t *testing.T) {
|
|
if guardBackend.size() > 4<<10 {
|
|
t.Fatalf("AstrLink Guard's chunk is %d bytes", guardBackend.size())
|
|
}
|
|
if pf.size() != chunkSize {
|
|
t.Fatalf("Privacy Filter's chunk is %d bytes", pf.size())
|
|
}
|
|
}
|