Files
magpie/internal/pii/pieces_test.go
T
yetone 2cdbe92ded pii: a value the model found sure once in a text is sure wherever it found it there
wangwu25685333 on X (10-29): of one sentence with an address repeated
400 times, the address was left unmasked "a few times", thought to be
where the text was cut into chunks.

Reproduced with the real model (AstrLink Guard, pure Go, Linux box,
GOMAXPROCS=4) through masking's strict path and redact.MaskJSON, 400
copies of a sentence in one message:
  "Please ship it to 1600 Amphitheatre Parkway, Mountain View, CA 94043
  by Friday." joined by "\n": 346 of 400 left as written; by " " or
  nothing: 0. Two Chinese addresses, any joiner: 0.
It isn't where the text is cut. Guard found the address on every line,
but less surely the more often it had read it in the text: 0.99 alone,
0.59-0.70 at 20 copies, and on 400 the whole address 325 times at 0.50
to 0.90 and split ("1600" at 0.85, the rest at 0.50-0.59) 65 times.
Masking takes 0.8 and over, so it masked only the sure ones, about one
a piece. Joined by "\n" the pieces are alike, so every piece got the
same few sure finds.

Now spread puts each value of 8 bytes or more the model found in a text
(minSpread, as redact's minKnown) wherever else it is in that text,
with its label and the score of its surest find there, then merges. A
value never found sure stays as unsure as it was, and a house number
alone isn't looked for. It runs on each text and piece the model reads
and on a long text's merged pieces, before they are cached. Spans from
the disk cache written before keep their scores until read again.

After, the same probe: 0 of 400 left for every sentence and joiner.

Test: TestValueFoundSureOnceIsSureThroughoutItsText has a stand-in model
that finds an address sure only first in its first read and unsure
after, on 3 and 400 lines, and fails when an address is left unsure,
another value never found sure is raised, or a short one is spread.
Broken by hand: without spread in find.go it fails ("1600 Amphitheatre
Parkway" at 110 scored 0.50).

docs/subsystems/gateway-routing.md says this, the pieces' ends
(landmark) and the turn's order (takeTurn, queue) of the two commits
before.

At ca221e115 with the three pii commits of this push: gofmt -l clean;
go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet
./... and go build ok (mote); go test ./internal/pii/...
./internal/masking ok on mote, on Windows (win-run) and with -race on
Linux (wsl-run). Not run before the push: go test ./... (both mote and
the Linux box were running other sessions' full suites, one a machine).

Not tried: the reporter's own sentence (not in the tweet); 400 copies
spread over 400 messages (each its own text, read alone at 0.99 here);
Privacy Filter (spread is the same for both models, tried on Guard).
2026-10-29 01:28:25 +08:00

312 lines
11 KiB
Go

package pii
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
"unicode/utf8"
"github.com/yetone/magpie/internal/redact"
)
// alices are where each "Alice" in t is, as the stand-in finds them.
func alices(t string) []redact.Found {
var out []redact.Found
for i := 0; ; {
j := strings.Index(t[i:], "Alice")
if j < 0 {
return out
}
out = append(out, person(i+j, i+j+5))
i += j + 5
}
}
// numbered is n lines, each with an Alice and each its own, so no two
// pieces of it are alike.
func numbered(n int) string {
var b strings.Builder
for i := range n {
fmt.Fprintf(&b, "line %d with Alice in it, and some words after\n", i)
}
return b.String()
}
// A long text's pieces: none empty, none over pieceSize, together the
// whole text, each overlapping the one before, cut after a line's end
// where there is one, and at a rune's start where there is no line's end
// or space at all.
func TestPiecesCut(t *testing.T) {
if got := pieces(""); got != nil {
t.Fatalf("empty text: %v", got)
}
if got := pieces(strings.Repeat("x", pieceSize)); !reflect.DeepEqual(got, []span{{0, pieceSize}}) {
t.Fatalf("a text of pieceSize: %v", got)
}
lines := numbered(2000)
cjk := strings.Repeat("张伟的密码是", 6000) // no line's end or space: 3-byte runes
words := strings.Repeat("word ", 20000)
for name, text := range map[string]string{"lines": lines, "cjk": cjk, "words": words} {
ps := pieces(text)
if len(ps) < 2 {
t.Fatalf("%s: %d pieces of %d bytes", name, len(ps), len(text))
}
if ps[0].at != 0 || ps[len(ps)-1].end != len(text) {
t.Fatalf("%s: pieces %v don't cover 0..%d", name, ps, len(text))
}
for i, p := range ps {
piece := text[p.at:p.end]
if piece == "" || len(piece) > pieceSize || !utf8.ValidString(piece) {
t.Fatalf("%s: piece %d %v: %d bytes, valid %v", name, i, p, len(piece), utf8.ValidString(piece))
}
if i == 0 {
continue
}
prev := ps[i-1]
if p.at <= prev.at || p.at >= prev.end || prev.end-p.at > pieceOverlap {
t.Fatalf("%s: piece %d %v after %v: want an overlap of at most %d", name, i, p, prev, pieceOverlap)
}
if name == "lines" && (text[prev.end-1] != '\n' || text[p.at-1] != '\n') {
t.Fatalf("%s: piece %d %v after %v not cut at a line's end", name, i, p, prev)
}
if name == "words" && (text[prev.end-1] != ' ' || text[p.at-1] != ' ') {
t.Fatalf("%s: piece %d %v after %v not cut at a space", name, i, p, prev)
}
}
}
}
// Spans from overlapping pieces: one found twice is one, one cut by a
// piece's end and whole in the next is the whole, labels kept apart where
// spans only touch, and of one label joined, as sure as the surer.
func TestMergeAcrossPieces(t *testing.T) {
email := func(s, e int) redact.Found { return redact.Found{Start: s, End: e, Label: "private_email"} }
sure := email(209, 222)
sure.Score = .99
got := merge([]redact.Found{
person(100, 105), person(10, 15), person(100, 105), // twice, from two pieces
person(200, 205), person(200, 211), // cut by a piece's end, whole in the next
sure, // runs into the name: one, the longer's label
person(300, 305), email(305, 310), // touching, two labels
person(400, 405), person(405, 410), // touching, one label
})
joined := email(200, 222)
joined.Score = sure.Score
want := []redact.Found{person(10, 15), person(100, 105), joined, person(300, 305), email(305, 310), person(400, 410)}
if !reflect.DeepEqual(got, want) {
t.Fatalf("merge =\n%v\nwant\n%v", got, want)
}
}
// #3682: a long text goes to pf-serve a piece at a time, none over
// pieceSize, and what it finds comes back once each, at the text's own
// offsets: a name in two pieces' overlap once, and one a piece's end cut
// in two (a text with no line's end or space to cut at) whole.
func TestLongTextFoundAcrossPieces(t *testing.T) {
log := fakeInstall(t, "ok", false)
lines := numbered(900)
// "Alice" from byte 12286: the first piece is cut at a rune's start at
// 12288, between "Al" and "ice"; the next begins 1 KB before
straddle := strings.Repeat("é", 6143) + "Alice" + strings.Repeat("é", 8000)
got, err := Find([]string{lines, straddle, "hi Alice"})
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got[0], alices(lines)) {
t.Fatalf("lines: %d spans, want %d: %v", len(got[0]), len(alices(lines)), got[0])
}
if !reflect.DeepEqual(got[1], []redact.Found{person(12286, 12291)}) {
t.Fatalf("straddling: %v", got[1])
}
if !reflect.DeepEqual(got[2], []redact.Found{person(3, 8)}) {
t.Fatalf("short: %v", got[2])
}
reqs := fakeLines(t, log, "request")
// a piece is a chunk, joined only with what is left beside it
if want := len(pieces(lines)) + len(pieces(straddle)); len(reqs) < want-2 {
t.Fatalf("%d requests for %d pieces", len(reqs), want)
}
for _, r := range reqs {
// the line quotes the texts, at most a chunk's bytes each
if len(r) > 3*chunkSize {
t.Fatalf("a request of %d bytes", len(r))
}
}
// kept whole, and by its pieces: asked again, nothing goes to pf-serve
n := len(reqs)
again, err := Find([]string{lines, straddle})
if err != nil || !reflect.DeepEqual(again[0], got[0]) || !reflect.DeepEqual(again[1], got[1]) {
t.Fatalf("again: %v", err)
}
if reqs := fakeLines(t, log, "request"); len(reqs) != n {
t.Fatalf("asked again: %d requests more", len(reqs)-n)
}
}
// #3682: a long request whose client went away keeps the pieces pf-serve
// finished, so sent again it asks only about the rest; none is asked
// twice.
func TestLongTextKeepsPiecesWhenStopped(t *testing.T) {
log := fakeInstall(t, "slow", false)
text := numbered(1500)
n := len(pieces(text))
if n < 4 {
t.Fatalf("%d pieces", n)
}
ctx, cancel := context.WithCancel(context.Background())
c := findAsync(ctx, text)
waitFor(t, "a first piece asked", func() bool { return len(fakeLines(t, log, "request")) >= 1 })
cancel()
if r := <-c; r.err == nil {
t.Fatal("a stopped request answered")
}
got, err := Find([]string{text})
if err != nil || !reflect.DeepEqual(got[0], alices(text)) {
t.Fatalf("sent again: %d spans, %v", len(got[0]), err)
}
if reqs := fakeLines(t, log, "request"); len(reqs) != n {
t.Fatalf("%d requests for %d pieces: the stopped one's were asked again", len(reqs), n)
}
}
// #3682: a short request waiting for the model goes between a long one's
// pieces, not after all of them.
func TestShortRequestGoesBetweenPieces(t *testing.T) {
log := fakeInstall(t, "slow", false)
text := numbered(1500)
n := len(pieces(text))
long := findAsync(context.Background(), text)
waitFor(t, "a first piece asked", func() bool { return len(fakeLines(t, log, "request")) >= 1 })
short := findAsync(context.Background(), "hi Alice")
var r found
select {
case r = <-short:
case r = <-long:
t.Fatal("the long request finished first")
}
if r.err != nil || !reflect.DeepEqual(r.fs, [][]redact.Found{{person(3, 8)}}) {
t.Fatalf("short: %v %v", r.fs, r.err)
}
if l := <-long; l.err != nil || !reflect.DeepEqual(l.fs[0], alices(text)) {
t.Fatalf("long: %v", l.err)
}
reqs := fakeLines(t, log, "request")
at := -1
for i, q := range reqs {
if strings.Contains(q, `"hi Alice"`) {
at = i
}
}
if len(reqs) != n+1 || at < 1 || at >= n {
t.Fatalf("the short request was request %d of %d (%d pieces)", at, len(reqs), n)
}
}
// prose is about n bytes of lines of varied length, as a system prompt's
// are, each its own.
func prose(n int) string {
words := []string{"the", "agent", "reads", "files", "before", "it", "edits", "them,", "and", "runs", "tests", "on", "mote", "when", "Alice", "asks."}
var b strings.Builder
x := uint32(7)
for line := 0; b.Len() < n; line++ {
fmt.Fprintf(&b, "%d.", line)
x = x*1664525 + 1013904223
for w := range 4 + x>>27 {
x = x*1664525 + 1013904223
b.WriteString(" " + words[(x>>20+uint32(w))%uint32(len(words))])
}
b.WriteString("\n")
}
return b.String()
}
// wangwu25685333 on X (10-29): every fresh session of an agent sends its
// system prompt again, a line of it changed (a date, a memory, a file in
// its workspace), and the model reads again only the pieces around that
// line, not every piece after it.
func TestEditedTextReadsItsPiecesAgainOnly(t *testing.T) {
text := prose(40 << 10)
for at := 500; at < 20000; at += 1499 {
for _, ins := range []string{"x", "Conversation started: Thursday, October 29", "memory: the user likes tea\n", strings.Repeat("y ", 300)} {
at := strings.IndexByte(text[at:], '\n') + at + 1
edited := text[:at] + ins + text[at:]
r := newReader(t, guardChunk)
if _, err := r.find(context.Background(), []string{text}); err != nil {
t.Fatal(err)
}
r.asked = nil
got, err := r.find(context.Background(), []string{edited})
if err != nil {
t.Fatal(err)
}
want := alices(edited)
for i := range got[0] {
if i < len(want) && (got[0][i].Start != want[i].Start || got[0][i].End != want[i].End) {
t.Fatalf("edit at %d: span %d %v, want %v", at, i, got[0][i], want[i])
}
}
if len(got[0]) != len(want) {
t.Fatalf("edit at %d: found %d, want %d", at, len(got[0]), len(want))
}
read, _ := r.bytes()
if read > 3*guardChunk {
t.Fatalf("%q at %d of %d bytes: %d bytes read again, want at most 3 pieces' (%d)", ins, at, len(text), read, 3*guardChunk)
}
}
}
}
// wangwu25685333 on X (10-29): an address on 400 lines alike was found by
// the model on every line, sure (0.90) on some and unsure (0.50) on most,
// so masking left most as they were. A value found sure once in a text is
// sure wherever it is found again there, in one piece or many; one never
// found sure stays unsure, and a short one (a house number) isn't looked
// for.
func TestValueFoundSureOnceIsSureThroughoutItsText(t *testing.T) {
addr, other, short := "1600 Amphitheatre Parkway", "Elm Street 42", "1600"
r := newReader(t, guardChunk)
r.classify = func(texts []string) ([][]redact.Found, error) {
out := make([][]redact.Found, len(texts))
for i, s := range texts {
for v, score := range map[string]float64{addr: .5, other: .5, short: .5} {
for at := 0; ; {
j := strings.Index(s[at:], v)
if j < 0 {
break
}
f := redact.Found{Start: at + j, End: at + j + len(v), Label: "private_address", Score: score}
if v == addr && at == 0 && strings.HasPrefix(s, "sure ") || v == short && at == 0 {
f.Score = .9 // the model's first in each read
}
if v != short || f.Score == .9 {
out[i] = append(out[i], f)
}
at += j + len(v)
}
}
}
return out, nil
}
line := "Please ship it to " + addr + ", or to " + other + " by Friday. Room 1600.\n"
for _, text := range []string{"sure " + strings.Repeat(line, 3), "sure " + strings.Repeat(line, 400)} {
got, err := r.find(context.Background(), []string{text})
if err != nil {
t.Fatal(err)
}
n := map[string]int{}
for _, f := range got[0] {
v := text[f.Start:f.End]
if v == addr && f.Score != .9 || v == other && f.Score != .5 {
t.Fatalf("%d bytes: %q at %d scored %.2f", len(text), v, f.Start, f.Score)
}
n[v]++
}
lines := strings.Count(text, "\n")
if n[addr] != lines || n[other] != lines || n[short] > len(cut(text, guardChunk)) {
t.Fatalf("%d bytes, %d lines: found %v", len(text), lines, n)
}
}
}