Files
magpie/internal/masking/masking.go
T
yetone 7632e1be1d redact: a text sent on a route goes on it as it went, the model's late finds too (vvrfxyz on X)
vvrfxyz on X: "脱敏功能是不是会降低缓存命中率 我开了脱敏后 dsh命中率暴跌".

Cause: the local model (AstrLink Guard, on by default) is waited for
2s a request (masking's defaultWait). A tool's output it hasn't read
by then goes with the rules' masking alone (pii.Partial). On the next
turn the model has read it, finds the names in it, and the same history
text now goes with {{PERSON_…}} in it. Everything from that message on
is a new prompt to the vendor, so its prefix cache misses. 50f52b540
(10-23) kept the known values of a text sent before as they went, but
not the model's finds.

Reproduced with real dsh 0.2.1-rc.2 (headless profile, sandbox HOME):
three turns in one session (read team.md, customers.csv and
notes/standup.md; check contracts.md; summarise the customers) through
a sandbox magpie with masking and the default model on, to a recording
Chat Completions upstream. dsh's own request bodies were recorded and
replayed in order, 3s apart, through a fresh sandbox magpie (found
cache cleared) on Linux (WSL2 magpie-desktop, -tags nogui).
- Old (origin/main without this change): "the local model read 5 of a request's
  7 texts in 2s". At request 7, message 6 (customers.csv's tool output)
  changed at byte 252: "1000,Fatima Rossi,Client 0 GmbH" became
  "1000,{{PERSON_2rmvxto6}},Client 0 GmbH". 4,793 of that request's
  18,380 history bytes were sent as before (26%). Over the whole
  conversation 97,815 of 111,402 resent bytes (87.8%) were the same.
  It happened on both runs.
- New: 108,378 of 108,378 (100%), the same Partial in the log.
- On mote (M5 Pro, CoreML) the model read everything inside 2s. Old
  code kept 100% of the prefix over the same 3 turns, and after a
  restart of magpie too (suspect 3, the key and the in-memory maps,
  was not the cause). Suspects 1 (known values) and 4 (re-encoding)
  were not the cause either: every other request kept its prefix byte
  for byte.

Fix:
- redact: sentKnownSpans becomes sentSpans. It remembers, per text and
  options, both the known values and the model's finds the text first
  went with (sentModel, sentKnown). The key now includes Options.Route,
  and for the model also the threshold, whether there is a model, and
  NamesByModel.
- learnLate: what the model finds in such a text since is made known
  (placeholder, scores) without being put in the text, so new text has
  it masked as before.
- The gateway gives masking each request's route (maskedFor,
  masking.WithRoute): the providers its model, the model's fallbacks or
  a group's members are served by, the same set unredactedRoute walks.
  Codex's own sign-in passes "codex", or the account's provider.
- A request with no route (search, embeddings, a text prompt) keeps
  the model's finds of now, and its known values as before.

Trade-off: a name the model reads late in a text sent before keeps
going as written on that route. That route's vendor was sent it as
written already. Within a route of several providers (fallbacks, a
group), a member that wasn't the first to get it may be sent it in
that form, as it could have been on the first turn's failover. In the
Linux replay, customers.csv's ~110 names stay as written on later
turns, where old code masked them from turn 2 on. The new turns'
masking is unchanged (the same placeholder counts in messages 9, 12
and 14). Another route, never sent the text, gets it masked with what
is known and found now. That is stricter than before for known values,
which were kept whatever the vendor. The alternative, waiting for the
model before any text goes, is what defaultWait was cut to 2s to stop
(shensmart, 10-28).

Tests:
- TestModelReadingLateKeepsTheSentPrefix (internal/masking): a model
  that reads a text only after its first request. Turn 2's history must
  be byte-identical, the name masked in new text, and masked on another
  route and with no route.
- TestMaskedPrefixKeptOnlyOnItsRoute (internal/gateway): a system
  prompt kept as written on its provider, masked on another.
- Broken by hand on mote, each red:
  - sentModel not remembered: "turn 2 rewrote message 2";
  - learnLate removed: "the new turn has the name the model found as
    written";
  - maskedFor returning ctx without a route: "another provider, never
    sent it, got the value as written".
  Each was green restored. TestMaskedConversationKeepsItsCachedPrefix
  and TestSentTextKeepsItsMasking stay green.

What was run, at this commit on origin/main 4b4c4a806, on mote
(after rebasing on e863f520c, which touches internal/gateway: gofmt, vet
of gateway/masking/redact, redact and masking whole, and gateway -run
"Mask|Redact|Sent|Effort|Route" ok again):
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: clean.
- Targeted at this head: go test ./internal/redact ./internal/masking
  ./internal/gateway (ok), with the two new tests and
  TestMaskedConversationKeepsItsCachedPrefix, TestSentTextKeepsItsMasking.
- Full suite (go test -timeout 45m ./...) was still running on mote at
  push (load ~110, other sessions), pushed per the ship-at-once rule; its
  result goes on the release and any red gets its own issue.
- GUI suite not run: no GUI file, API or string changed.

Not tried: vvrfxyz's own machine and vendor (DeepSeek's real cache_hit
counts), and Windows.
2026-10-30 10:26:50 +08:00

387 lines
13 KiB
Go

// Package masking is Settings → Privacy's masking as the gateway's masker
// (gwmw.Masker): secrets, personal data and the user's own words go to a
// vendor as placeholders (internal/redact), and come back as they were.
// It reads the settings on each call. plugins/redact serves it.
package masking
import (
"context"
"errors"
"fmt"
"log"
"net/http"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/pii"
"github.com/yetone/magpie/internal/redact"
"github.com/yetone/magpie/internal/settings"
)
// Masker masks as the settings say, read on each call.
type Masker struct{}
// Wanted says settings st ask for anything to be masked.
func Wanted(st settings.Settings) bool {
return st.Redact || st.RedactPersonal || len(st.RedactWords) > 0
}
func options() redact.Options { return optionsCtx(context.Background()) }
// routeKey holds where a request masked on ctx may go (WithRoute).
type routeKey struct{}
// WithRoute is ctx for masking a request that may go only to route (the
// providers its model, the model's fallbacks or a routing group's members
// are served by): a text sent on it before goes as it went there
// (redact.Options.Route).
func WithRoute(ctx context.Context, route string) context.Context {
return context.WithValue(ctx, routeKey{}, route)
}
// optionsCtx is options with the model's wait ending with ctx, for the
// route ctx has (WithRoute).
func optionsCtx(ctx context.Context) redact.Options {
st := settings.Shared()
o := redact.Options{Secrets: st.Redact, Personal: st.RedactPersonal, Kinds: st.RedactKinds, Words: st.RedactWords, WordsAnyCase: st.RedactWordsAnyCase, WordsWhole: st.RedactWordsWhole, Rules: st.RedactRules,
Actions: st.RedactActions, Allow: st.RedactAllow, Shape: st.RedactShape}
o.Route, _ = ctx.Value(routeKey{}).(string)
if (st.Redact || st.RedactPersonal) && ModelWanted(st) {
// until the model is on disk the rules mask alone, and nothing is
// held back for a download (it is started here)
if m := picked(st); m.Installed() {
o.MinScore = pii.Threshold(st.RedactModelScore, m)
o.Model = model(ctx, m, o.MinScore, st.RedactModel)
o.NamesByModel = m.ID() == pii.AstrLinkGuard
} else {
fetch(m, st.RedactModel)
}
}
return o
}
// ModelWanted says st has masking ask the local model: the user turned it
// on, or left it as it is, on by default. One who had a model downloaded,
// or picked, with it off before it was on by default had turned it off.
func ModelWanted(st settings.Settings) bool {
switch {
case st.RedactModel:
return true
case st.RedactModelOff:
return false
case st.RedactModelAuto:
return true
}
return st.RedactModelName == "" && !onDisk()
}
// onDisk says a local model is downloaded; a var for tests.
var onDisk = func() bool {
for _, m := range pii.Models() {
if m.Installed() {
return true
}
}
return false
}
// fetched is when fetch last started each model's download, by id, so a
// failed one is tried again an hour later rather than on every request.
var fetched = struct {
sync.Mutex
at map[string]time.Time
}{at: map[string]time.Time{}}
// fetch downloads m, the model masking would ask but isn't on disk, and
// warms it once it is; the model on by default (on is false: the user
// didn't turn it on) is saved as the default's (UseDefaultRedactModel),
// unless the user picked or turned it off in between. Never in a test,
// which stays off the network (a test swaps it). A var for tests.
var fetch = func(m pii.Model, on bool) {
if !m.Supported() || testing.Testing() {
return
}
fetched.Lock()
t, ok := fetched.at[m.ID()]
if ok && time.Since(t) < time.Hour {
fetched.Unlock()
return
}
fetched.at[m.ID()] = time.Now()
fetched.Unlock()
m.Download(func() {
if on {
m.Warm()
} else if ok, err := settings.UseDefaultRedactModel(m.ID()); ok && err == nil {
m.Warm()
}
})
}
// picked is the local model st has masking use; a var for tests. One
// that is Privacy Filter only because no model was picked (pii.Choose)
// starts AstrLink Guard's download, the default, and is moved onto it
// once that is done.
var picked = func(st settings.Settings) pii.Model {
id := pii.Choose(st.RedactModelName, true)
if st.RedactModelName == "" && id == pii.PrivacyFilter {
toGuard()
}
return pii.Of(id)
}
// guardTried is when toGuard last started a download, so a failed one is
// tried again an hour later rather than on every request.
var guardTried atomic.Int64
// toGuard downloads AstrLink Guard, then saves it as the pick, unless the
// user picked a model in between, and lets Privacy Filter go.
func toGuard() {
now := time.Now().Unix()
if t := guardTried.Load(); t != 0 && now-t < 3600 || !guardTried.CompareAndSwap(t, now) {
return
}
g := pii.Of(pii.AstrLinkGuard)
g.Download(func() {
if settings.Load().RedactModelName == "" && settings.UseRedactModel(pii.AstrLinkGuard) == nil {
pii.Of(pii.PrivacyFilter).Stop()
g.Warm()
}
})
}
// 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 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
// strictWait is how long a request waits for the local model the user
// turned on. Past it, what the model has read of the request is masked
// with its finds and the rest by the rules alone, and the request goes:
// nothing is sent as written that the rules would mask. Unbounded, a
// burst of requests with text the model hadn't read (new tool results, a
// resumed conversation, subagents at once) queued behind each other a
// 12 KB chunk at a time, AstrLink Guard reading about 6 KB a second on 8
// cores of a Linux CPU, and each request that stopped waiting was held
// back whole: xRayySummers on X saw waits of 1.2s to 290s in one minute
// and "masking failed, so nothing was sent" for each request it ended.
// What the model reads meanwhile is kept, so the next turn, which sends
// the same history, finds it. A var for tests.
var strictWait = 15 * time.Second
// model is the local model m (internal/pii) as redact's Model, keeping
// what it is at least min sure of, waited for until ctx ends or the wait
// runs out: defaultWait for the model on by default, strictWait for one
// the user turned on (strict), from now. A wait that runs out, or a ctx
// that ends, keeps what the model had read of the texts by then (a
// pii.Partial), and the rules mask the rest alone. A model that fails
// (didn't load, isn't on disk, held back after a failure) panics where
// the user turned it on, and the request is held back (gwmw.Safely)
// rather than sent with only the rules' masking: the user asked for the
// model's, and it is broken, not busy. On by default, it finds nothing
// then: the rules mask alone.
func model(ctx context.Context, m pii.Model, min float64, strict bool) redact.Model {
wait := defaultWait
if strict {
wait = strictWait
}
by := time.Now().Add(wait)
return func(texts []string) [][]redact.Found {
if !strict {
// what is new in it first, a backlog a little a request
ctx = pii.Bounded(ctx)
}
ctx, cancel := context.WithDeadline(ctx, by)
defer cancel()
got, err := find(ctx, m, texts)
var p *pii.Partial
switch {
case errors.As(err, &p):
notePartial(p, wait)
if len(got) != len(texts) {
got = make([][]redact.Found, len(texts))
}
case err != nil && strict:
panic(err)
case err != nil:
return make([][]redact.Found, len(texts))
}
out := make([][]redact.Found, len(got))
for i, fs := range got {
for _, f := range fs {
if f.Score >= min {
out[i] = append(out[i], f)
}
}
}
return out
}
}
// partialLogged is when notePartial last wrote to the log, so a burst of
// requests past their wait writes one line.
var partialLogged atomic.Int64
// notePartial logs, at most once a minute, that a request went with the
// model's finds for only part of it.
func notePartial(p *pii.Partial, wait time.Duration) {
if p.Missing == 0 {
return
}
now := time.Now().Unix()
if t := partialLogged.Load(); t != 0 && now-t < 60 || !partialLogged.CompareAndSwap(t, now) {
return
}
log.Printf("masking: the local model read %d of a request's %d texts in %s (%v); the rules masked the rest alone, and the model keeps reading for the next request", p.Of-p.Missing, p.Of, wait, p.Err)
}
// handBack is how long find waits, once ctx ends, for m to answer with
// what it knew by then (internal/pii's backend does at once, from its
// cache) before giving up on it.
const handBack = 100 * time.Millisecond
// find is m.Find, given up when ctx ends even where m doesn't stop for
// it (a read of its cache from disk, a load): m is given handBack to
// answer with what it had read, then it is a pii.Partial with nothing
// read, and m finishes on its own.
func find(ctx context.Context, m pii.Model, texts []string) ([][]redact.Found, error) {
type res struct {
got [][]redact.Found
err error
}
ch := make(chan res, 1)
go func() {
got, err := m.Find(ctx, texts)
ch <- res{got, err}
}()
select {
case r := <-ch:
return r.got, r.err
case <-ctx.Done():
}
t := time.NewTimer(handBack)
defer t.Stop()
select {
case r := <-ch:
return r.got, r.err
case <-t.C:
return nil, &pii.Partial{Missing: len(texts), Of: len(texts), Err: ctx.Err()}
}
}
// ModelOn says Settings → Privacy's local model masks requests, as the
// user turned it on: only then is a request held back for a model that
// fails, and waited for it strictWait (model's strict).
func ModelOn() bool { return settings.Shared().RedactModel }
// ModelBusy says what the local model is doing that a request may wait
// on, for the error of one that waited too long: "" when nothing.
func ModelBusy() string {
st := settings.Shared()
return busy(picked(st).Now())
}
func busy(st pii.Status) string {
var what string
switch {
case st.Loading:
what = "it is still loading"
case st.Running:
what = "it is masking another request"
default:
return ""
}
if st.Waiting > 0 {
what += fmt.Sprintf(", with %d more waiting for it", st.Waiting)
}
return what
}
func (Masker) JSON(body []byte) ([]byte, int) {
o := options()
if !o.Secrets && !o.Personal && len(o.Words) == 0 {
return body, 0
}
return redact.MaskJSON(body, o)
}
func (Masker) Text(s string) (string, int) { return redact.Mask(s, options()) }
// JSONHits is JSON, with what it masked (gwmw.Teller).
func (m Masker) JSONHits(body []byte) ([]byte, []gwmw.Hit) {
return m.JSONHitsContext(context.Background(), body)
}
// JSONHitsContext is JSONHits, its wait for the model ending with ctx
// (gwmw.ContextTeller).
func (Masker) JSONHitsContext(ctx context.Context, body []byte) ([]byte, []gwmw.Hit) {
o := optionsCtx(ctx)
if !o.Secrets && !o.Personal && len(o.Words) == 0 {
return body, nil
}
var hits []gwmw.Hit
o.Seen = told(&hits)
out, _ := redact.MaskJSON(body, o)
return out, hits
}
// TextHits is Text, with what it masked.
func (m Masker) TextHits(s string) (string, []gwmw.Hit) {
return m.TextHitsContext(context.Background(), s)
}
// TextHitsContext is TextHits, its wait for the model ending with ctx.
func (Masker) TextHitsContext(ctx context.Context, s string) (string, []gwmw.Hit) {
o := optionsCtx(ctx)
var hits []gwmw.Hit
o.Seen = told(&hits)
out, _ := redact.Mask(s, o)
return out, hits
}
func (Masker) Value(p string) (string, bool) { return redact.Value(p) }
// told adds each value found to hits, with its hint: the value itself
// stays in redact's memory, or, sent as written, nowhere.
func told(hits *[]gwmw.Hit) func(redact.Hit) {
return func(h redact.Hit) {
*hits = append(*hits, gwmw.Hit{Kind: h.Kind, By: h.By, Placeholder: h.Placeholder, Action: h.Action, Head: h.Head, Len: h.Len})
}
}
// Preview is s as the settings would send it, and what was found in it,
// with nothing remembered: no placeholder is kept for the replies, and
// none of its values is masked again later as one seen before. With
// masking off it is as masking would be turned on (Off says so), so the
// user can try it first.
func Preview(s string) (out string, hits []gwmw.Hit, off bool) {
o := options()
if !o.Secrets && !o.Personal && len(o.Words) == 0 {
o.Secrets, o.Personal, off = true, true, true
}
o.Seen = told(&hits)
out = redact.Preview(s, o)
return out, hits, off
}
func (Masker) Restore(s string, escaped bool) string { return redact.Restore(s, escaped) }
func (Masker) Writer(w http.ResponseWriter) (http.ResponseWriter, func()) {
rw := redact.NewWriter(w)
return rw, rw.Finish
}
var (
_ gwmw.Teller = Masker{}
_ gwmw.ContextTeller = Masker{}
)