Files
magpie/internal/redact/model_test.go
T
yetone ea7c0067e0 privacy: each local model's confidence threshold is the user's to set
Yayoi_no_yume on X asked for the privacy model's threshold to be
adjustable: they read it as fixed at 0.5, and from their own use find
0.85-0.95 right for AstrLink. The 0.5 is Privacy Filter's (pf-serve's
argv default); AstrLink Guard already masked at its publisher's 0.8.

Both models now find at a floor of 0.5 (pii.Floor) and give each span
its score: Guard's least token probability (rounded through float32,
so a span read back from the cache file sits on the same side of a
threshold), pf-serve's own. masking.model keeps the spans at
pii.Threshold or over: settings.RedactModelScore[model] when it is in
[0.5, 1), else the model's MinScore (Privacy Filter 0.5, AstrLink
Guard 0.8). Settings -> Privacy shows a Confidence threshold row under
the model (app menu, 0.5 to 0.95 and Default), /api/privacy-model
takes do:"score". The setting is this computer's own, like the model.

The defaults stay. TestMaskEval's cases, rules + model + magpie's
checks, by threshold:

  Privacy Filter 0.5-0.8   masked 41/42  kept 112/113
  Privacy Filter 0.85-0.95 masked 40/42  (a Chinese name lost)
  AstrLink Guard 0.5-0.7   masked 42/42  kept 112/113
  AstrLink Guard 0.8-0.85  masked 41/42  (a phone in a tool result)
  AstrLink Guard 0.9       masked 40/42
  AstrLink Guard 0.95      masked 40/42  kept 113/113

The model alone does raise fewer false alarms higher up (Privacy
Filter's found-in-keep falls from 47 at 0.5 to 27 at 0.95, Guard's
from 8 to 2), but the checks after it drop most of those already, so
a higher threshold mostly costs values that should be masked.

Cache file: found-<model>.bin is now "pfound02" with a float32 score
per span. A "pfound01" file is still read, each span with score 1, so
texts cached before mask as they did and aren't asked again. For those
texts a higher threshold drops nothing and a lower one doesn't add a
Guard span scored 0.5-0.8 until the cache turns over (20000 answers).
merge() keeps the surer score of spans it joins. The eval recordings
(eval-model.json, eval-astrlink.json) were made again with scores,
from a scratch cache, the live found files untouched.

Run in the worktree at 11dcc743f + this change:
- go vet / gofmt -l on the touched packages: clean
- go test -count=1 -timeout 45m ./internal/pii/... ./internal/masking
  ./internal/redact ./internal/settings ./internal/gui ./internal/gateway: all ok (gateway 546s, rerun
  after an earlier run hit "no space left on device" on this machine;
  every failure in that run was a TempDir mkdir). This run caught
  TestSettingsSaveKeepsWhatItDoesNotSend wanting RedactModelScore set;
  it is now
- GUI: privacy-model.test.cjs 64/64 (chromium + webkit, 5 languages,
  1100 and 640px; the new threshold menu test among them),
  i18n-keys 4/4, redact-kinds, redact-rule-edit,
  redact-rule-row, redact-shape, redact-words-any-case all pass.
  masking-records 82/82, routing-masking 10/10, privacy-usage-stats 4/4,
  mask-actions 22/22. privacy-hides-accounts was 3/4 once (webkit en,
  page.goto's 5s at load ~290, the class of #3525, commented there),
  then 4/4 three times. Not run: the rest of the GUI suite.
Rebased on 508911e43 (which touched internal/pii fetch and mirror): at
that head, go build ./..., Linux and Windows go vet of pii, masking,
settings and redact, gofmt -l, and go test of pii/..., masking, redact,
settings and gui all ok; gateway not run again after the rebase.
Broken by hand: masking.model keeping every span (TestModelThreshold
  red); Threshold taking any value (TestModelThreshold red); the cache
  writing 1 for every score (TestRestartReadsWhatWasFound red); merge
  not keeping the surer score (TestMergeAcrossPieces red, after its
  joined span was made surer than the one it joins).
Not tried: the real app's window, Windows, Privacy Filter on a GPU
with the new score read (pf-serve itself is unchanged; it always sent
the score).
2026-10-27 14:10:33 +08:00

160 lines
6.6 KiB
Go

package redact
import (
"regexp"
"slices"
"strings"
"testing"
)
// fakeModel finds each of values wherever a text has it, under its label,
// with a space before it as the model takes one in; asked are the texts it
// was asked about.
type fakeModel struct {
values map[string]string // value → label
asked [][]string
}
func (f *fakeModel) find(texts []string) [][]Found {
f.asked = append(f.asked, texts)
out := make([][]Found, len(texts))
for i, t := range texts {
for v, label := range f.values {
for at := 0; ; {
j := strings.Index(t[at:], v)
if j < 0 {
break
}
a := at + j
if a > 0 && t[a-1] == ' ' {
a--
}
out[i] = append(out[i], Found{Start: a, End: at + j + len(v), Label: label})
at += j + len(v)
}
}
}
return out
}
// What the model finds and no rule does is masked, under the switch its
// kind is under: a name or an address with personal data, a secret with
// the secrets.
func TestModelFindsWhatRulesDont(t *testing.T) {
const name, addr, secret = "Rina Kowalczyk", "42 Larchmont Ave, Springfield", "correct horse battery staple"
f := &fakeModel{values: map[string]string{name: "private_person", addr: "private_address", secret: "secret"}}
s := "Ask " + name + " at " + addr + "; the vault phrase is " + secret + "."
out, n := Mask(s, Options{Personal: true, Secrets: true, Model: f.find})
if n != 3 || strings.Contains(out, name) || strings.Contains(out, addr) || strings.Contains(out, secret) {
t.Fatalf("%d masked: %q", n, out)
}
if !strings.Contains(out, "Ask {{PERSON_") || !strings.Contains(out, " at {{ADDRESS_") || !strings.Contains(out, "is {{SECRET_") {
t.Fatalf("kinds, or the space before each taken in: %q", out)
}
if back := Restore(out, false); back != s {
t.Fatalf("round trip: %q", back)
}
if out, _ := Mask(s, Options{Secrets: true, Model: f.find}); !strings.Contains(out, name) || !strings.Contains(out, addr) || strings.Contains(out, secret) {
t.Fatalf("personal data off: %q", out)
}
if out, _ := Mask(s, Options{Personal: true, Model: f.find}); strings.Contains(out, name) || !strings.Contains(out, secret) {
t.Fatalf("secrets off: %q", out)
}
// nothing on, nothing asked
f.asked = nil
if out, _ := Mask(s, Options{Model: f.find}); out != s || f.asked != nil {
t.Fatalf("all off: %q, asked %q", out, f.asked)
}
}
// A name the model found, masked once, is a known value of personal data:
// with personal data off it goes as it is, though secrets are on.
func TestModelKnownValueIsPersonal(t *testing.T) {
const name = "Rina Kowalczyk-Brandt"
f := &fakeModel{values: map[string]string{name: "private_person"}}
if out, _ := Mask("from "+name, Options{Personal: true, Model: f.find}); strings.Contains(out, name) {
t.Fatalf("not masked: %q", out)
}
if out, _ := Mask("to "+name, Options{Secrets: true}); !strings.Contains(out, name) {
t.Fatalf("a name masked as a secret with personal data off: %q", out)
}
if out, _ := Mask("to "+name, Options{Personal: true}); strings.Contains(out, name) {
t.Fatalf("a known name not masked again: %q", out)
}
}
// What the model often gets wrong is left alone: a vendor's or a tool's
// id taken for a secret or an account, a secret shorter than a rule's, a
// one-letter name, a label magpie doesn't mask (a date, a URL).
func TestModelSpansFiltered(t *testing.T) {
keep := map[string]string{
"req_011CSzQ8mXv3kBR2": "secret",
"toolu_01AbCdEfGhIjKl": "account_number",
"hunter2": "secret",
"J": "private_person",
"2026-10-18": "private_date",
"https://example.org": "private_url",
}
f := &fakeModel{values: keep}
s := "see req_011CSzQ8mXv3kBR2 and toolu_01AbCdEfGhIjKl, pw hunter2, J said on 2026-10-18 at https://example.org"
if out, n := Mask(s, Options{Personal: true, Secrets: true, Model: f.find}); out != s || n != 0 {
t.Fatalf("%d masked: %q", n, out)
}
// a span outside the text, or splitting a character, is no span
bad := func([]string) [][]Found {
return [][]Found{{{Start: -1, End: 3, Label: "secret"}, {Start: 0, End: 99, Label: "secret"}, {Start: 1, End: 4, Label: "private_person"}}}
}
if out, _ := Mask("é名字abc", Options{Personal: true, Secrets: true, Model: bad}); out != "é名字abc" {
t.Fatalf("bad spans: %q", out)
}
}
// A span the model starts at the delimiter before a value is the value's:
// a phone number in JSON or a CSV row is masked, and the delimiter goes as
// written (#3591, from the evaluation's json-contact and tool-result-mixed).
func TestModelSpanLeavesDelimiters(t *testing.T) {
f := &fakeModel{values: map[string]string{
`":"+86 139 1234 5678`: "private_phone",
`,+81 90-1234-5678`: "private_phone",
`,rina.k@fastmail.com`: "private_email",
`"Wei Zhang"`: "private_person",
}}
o := Options{Personal: true, Model: f.find}
for _, c := range []struct{ in, want string }{
{`{"name":"Wei Zhang","phone":"+86 139 1234 5678"}`, `^\{"name":"\{\{PERSON_[a-z2-7]{8}\}\}","phone":"\{\{PHONE_[a-z2-7]{8}\}\}"\}$`},
{"Rina,rina.k@fastmail.com,+81 90-1234-5678\n", `^Rina,\{\{EMAIL_[a-z2-7]{8}\}\},\{\{PHONE_[a-z2-7]{8}\}\}\n$`},
} {
if out, _ := Mask(c.in, o); !regexp.MustCompile(c.want).MatchString(out) {
t.Errorf("%q went as %q", c.in, out)
}
}
}
// A request's texts go to the model once, together, each once: never its
// ids, kinds or tools' definitions, which are never masked, nor what a
// vendor sealed with a signature.
func TestModelAskedOnceForRequest(t *testing.T) {
const name = "Rina Kowalczyk"
f := &fakeModel{values: map[string]string{name: "private_person"}}
body := `{"model":"claude-x","tools":[{"name":"lookup","description":"find ` + name + `","input_schema":{"type":"object"}}],` +
`"messages":[{"role":"user","content":"hi ` + name + `"},{"role":"assistant","content":[{"type":"thinking","thinking":"about ` + name + `","signature":"sig"},{"type":"text","text":"hi ` + name + `"}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":"ok"}]}]}`
out, n := MaskJSON([]byte(body), Options{Personal: true, Model: f.find})
if len(f.asked) != 1 {
t.Fatalf("asked %d times: %q", len(f.asked), f.asked)
}
got := slices.Clone(f.asked[0])
slices.Sort(got)
// "ok" is too short to hold anything
if want := []string{"find " + name, "hi " + name}; !slices.Equal(got, want) {
t.Fatalf("asked about %q, want %q", got, want)
}
// the description and the two messages; the thinking block goes back
// as the vendor wrote it but for the value masked elsewhere
if strings.Contains(string(out), "hi "+name) || strings.Contains(string(out), "find "+name) || n < 3 {
t.Fatalf("%d masked: %s", n, out)
}
}