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.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -949,7 +949,11 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
if r.Method == http.MethodPost {
|
||||
var unmask func()
|
||||
var err error
|
||||
w, body, unmask, maskedHits, err = redactedHits(r.Context(), w, body)
|
||||
to := provider.Provider{ID: "codex"} // the ChatGPT backend
|
||||
if on != nil {
|
||||
to = *on
|
||||
}
|
||||
w, body, unmask, maskedHits, err = redactedHits(maskedFor(r.Context(), to, false, nil), w, body)
|
||||
defer unmask()
|
||||
if err != nil {
|
||||
writeError(w, provider.Responses, maskStatus(err), err.Error())
|
||||
|
||||
@@ -1454,7 +1454,7 @@ func (s *Server) countTokens(w http.ResponseWriter, r *http.Request) {
|
||||
// and the one as written where generation sends that, masked only
|
||||
// then (#3973)
|
||||
if _, ms, isGroup := provider.FindGroup(id); !ok || !unredactedRoute(p, isGroup, ms) {
|
||||
rw, b, done, hits, err := redactedHits(r.Context(), w, body)
|
||||
rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), w, body)
|
||||
if err != nil {
|
||||
writeError(w, provider.Anthropic, maskStatus(err), err.Error())
|
||||
return
|
||||
@@ -2038,7 +2038,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
// are, and an observer that wants the bodies is handed a copy masked
|
||||
// when it is first handed one, after the try (maskIn, #3973)
|
||||
if sentWhole = unredactedRoute(p, isGroup, ms); !sentWhole {
|
||||
rw, b, done, hits, err := redactedHits(r.Context(), capture.ResponseWriter, body)
|
||||
rw, b, done, hits, err := redactedHits(maskedFor(r.Context(), p, isGroup, ms), capture.ResponseWriter, body)
|
||||
if err != nil { // fails closed: never sent unmasked
|
||||
log.Printf("gateway: %v", err)
|
||||
call.Status, call.Error = maskStatus(err), err.Error()
|
||||
|
||||
@@ -132,3 +132,56 @@ func TestMaskedConversationKeepsItsCachedPrefix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A text goes as it went only where it went: the system prompt sent to
|
||||
// one provider with a value as written, before a rule found the value,
|
||||
// keeps it as written there, and has it masked on its way to another
|
||||
// provider, which was never sent it (masking's route, maskedFor).
|
||||
func TestMaskedPrefixKeptOnlyOnItsRoute(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
got := map[string][]string{}
|
||||
serve := func(name string) *httptest.Server {
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
got[name] = append(got[name], string(b))
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"m","type":"message","role":"assistant","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"output_tokens":1}}`)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: name, Name: name, Key: "k", Models: []string{"claude-opus-5-5"}, Anthropic: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return up
|
||||
}
|
||||
serve("first")
|
||||
serve("second")
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
const secret = "Zr5routeKeep42q"
|
||||
system := `"system":"You are Claude. Staging deploys with ` + secret + ` for now."`
|
||||
send := func(to, msgs string) {
|
||||
t.Helper()
|
||||
if code, raw := postJSON(t, s, "/v1/messages", `{"model":"`+to+`/claude-opus-5-5","max_tokens":64,`+system+`,"messages":[`+msgs+`]}`); code != 200 {
|
||||
t.Fatalf("%s: %d %s", to, code, raw)
|
||||
}
|
||||
}
|
||||
send("first", `{"role":"user","content":"hi"}`)
|
||||
send("first", `{"role":"user","content":"hi"},{"role":"assistant","content":"ok"},{"role":"user","content":"DB_PASSWORD=`+secret+`"}`)
|
||||
send("second", `{"role":"user","content":"hi"}`)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(got["first"]) != 2 || len(got["second"]) != 1 {
|
||||
t.Fatalf("upstream got %d and %d", len(got["first"]), len(got["second"]))
|
||||
}
|
||||
if !strings.Contains(got["first"][1], "deploys with "+secret) {
|
||||
t.Errorf("the first provider's system prompt, sent with the value as written, was rewritten: %s", got["first"][1])
|
||||
}
|
||||
if strings.Contains(got["second"][0], secret) {
|
||||
t.Errorf("another provider, never sent it, got the value as written: %s", got["second"][0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -315,6 +316,25 @@ func unredactedRoute(p provider.Provider, isGroup bool, ms []provider.Member) bo
|
||||
return true
|
||||
}
|
||||
|
||||
// maskedFor is ctx for masking a request resolved to p, or to the group
|
||||
// whose models are ms, that may go to the providers unredactedRoute walks:
|
||||
// p and each of its fallbacks, or every model of the group. A text sent
|
||||
// on that route before goes on it again as it went (masking.WithRoute),
|
||||
// so a prefix a vendor cached isn't rewritten by what was found in it
|
||||
// since; another route masks it afresh.
|
||||
func maskedFor(ctx context.Context, p provider.Provider, isGroup bool, ms []provider.Member) context.Context {
|
||||
var ids []string
|
||||
if !isGroup {
|
||||
ids = append(ids, p.ID)
|
||||
ms = provider.FallbackModels(p)
|
||||
}
|
||||
for _, m := range ms {
|
||||
ids = append(ids, m.Provider.ID)
|
||||
}
|
||||
slices.Sort(ids)
|
||||
return masking.WithRoute(ctx, strings.Join(slices.Compact(ids), "\x00"))
|
||||
}
|
||||
|
||||
// agentTurnKey marks a request an agent sent (serveAgent, count_tokens,
|
||||
// a Codex turn on its own sign-in), the ones the user's route for masked
|
||||
// requests is for (maskRouteFor); magpie's own asks made on an agent's
|
||||
|
||||
@@ -31,11 +31,24 @@ func Wanted(st settings.Settings) bool {
|
||||
|
||||
func options() redact.Options { return optionsCtx(context.Background()) }
|
||||
|
||||
// optionsCtx is options with the model's wait ending with ctx.
|
||||
// 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)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package masking
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/pii"
|
||||
"github.com/yetone/magpie/internal/redact"
|
||||
"github.com/yetone/magpie/internal/settings"
|
||||
)
|
||||
|
||||
// slowReader is the local model on a slow CPU: a text it is asked about
|
||||
// the first time isn't read in the request's wait (a pii.Partial, nothing
|
||||
// found in it), and it has been read by the next request, which finds
|
||||
// the name in it.
|
||||
type slowReader struct {
|
||||
fake
|
||||
name string
|
||||
mu sync.Mutex
|
||||
read map[string]bool
|
||||
}
|
||||
|
||||
func (m *slowReader) Find(_ context.Context, texts []string) ([][]redact.Found, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
out := make([][]redact.Found, len(texts))
|
||||
missing := 0
|
||||
for i, t := range texts {
|
||||
if !m.read[t] {
|
||||
m.read[t] = true // read after the request stopped waiting
|
||||
missing++
|
||||
continue
|
||||
}
|
||||
if at := strings.Index(t, m.name); at >= 0 {
|
||||
out[i] = []redact.Found{{Start: at, End: at + len(m.name), Label: "private_person", Score: 0.95}}
|
||||
}
|
||||
}
|
||||
if missing > 0 {
|
||||
return out, &pii.Partial{Missing: missing, Of: len(texts)}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// vvrfxyz on X: with masking on, dsh's prompt-cache hits fell. Replayed
|
||||
// on a Linux CPU, a tool's output (customers.csv) the default model
|
||||
// hadn't read in its 2s went with the rules' masking alone, and the next
|
||||
// turn masked a name in it the model had read since: from that message on
|
||||
// the prompt was new to the vendor. A text sent before on a route goes on
|
||||
// it as it went; new text has the name masked, and another route, which
|
||||
// was never sent the text, gets it masked.
|
||||
func TestModelReadingLateKeepsTheSentPrefix(t *testing.T) {
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
if err := settings.Save(settings.Settings{Redact: true, RedactPersonal: true, RedactModelAuto: true, RedactModelName: pii.AstrLinkGuard}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const name = "Fatima Rossi"
|
||||
m := &slowReader{fake: fake{installed: true}, name: name, read: map[string]bool{}}
|
||||
wasPicked, wasFetch, wasDisk := picked, fetch, onDisk
|
||||
picked = func(settings.Settings) pii.Model { return m }
|
||||
fetch = func(pii.Model, bool) {}
|
||||
onDisk = func() bool { return true }
|
||||
t.Cleanup(func() { picked, fetch, onDisk = wasPicked, wasFetch, wasDisk })
|
||||
|
||||
msg := func(role, text string) string {
|
||||
b, _ := json.Marshal(map[string]string{"role": role, "content": text})
|
||||
return string(b)
|
||||
}
|
||||
csv := "1: id,name,company,city\n2: 1000," + name + ",Client 0 GmbH,Berlin\n3: 1001,Kenji Ito,Client 1 SA,Lyon"
|
||||
turn1 := []string{msg("system", "You are dsh."), msg("user", "read customers.csv"), msg("tool", csv)}
|
||||
turn2 := append(append([]string{}, turn1...), msg("assistant", "Read."), msg("user", "who is "+name+"?"))
|
||||
body := func(ms []string) []byte { return []byte(`{"model":"m","messages":[` + strings.Join(ms, ",") + `]}`) }
|
||||
messages := func(b []byte) []string {
|
||||
var q struct{ Messages []json.RawMessage }
|
||||
if err := json.Unmarshal(b, &q); err != nil {
|
||||
t.Fatalf("%v: %s", err, b)
|
||||
}
|
||||
out := make([]string, len(q.Messages))
|
||||
for i, r := range q.Messages {
|
||||
out[i] = string(r)
|
||||
}
|
||||
return out
|
||||
}
|
||||
route := WithRoute(context.Background(), "deepseek")
|
||||
first, _ := Masker{}.JSONHitsContext(route, body(turn1))
|
||||
if !strings.Contains(string(first), name) {
|
||||
t.Fatalf("turn 1: the model hadn't read the tool's output, the rules alone mask it: %s", first)
|
||||
}
|
||||
second, _ := Masker{}.JSONHitsContext(route, body(turn2))
|
||||
a, b := messages(first), messages(second)
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
t.Errorf("turn 2 rewrote message %d the vendor has:\n%s\nwas\n%s", i, b[i], a[i])
|
||||
}
|
||||
}
|
||||
if strings.Contains(b[len(b)-1], name) {
|
||||
t.Errorf("the new turn has the name the model found as written: %s", b[len(b)-1])
|
||||
}
|
||||
|
||||
// another route was never sent the text: masked with what is found now
|
||||
other, _ := Masker{}.JSONHitsContext(WithRoute(context.Background(), "another"), body(turn1))
|
||||
if strings.Contains(string(other), name) {
|
||||
t.Errorf("another route got the name as written: %s", other)
|
||||
}
|
||||
// nor is one without a route (a search, an embedding)
|
||||
if none, _ := (Masker{}).JSONHitsContext(context.Background(), body(turn1)); strings.Contains(string(none), name) {
|
||||
t.Errorf("no route got the name as written: %s", none)
|
||||
}
|
||||
}
|
||||
@@ -462,7 +462,8 @@ func MaskJSON(body []byte, o Options) ([]byte, int) {
|
||||
// number or an address the vendor wrote of its own can be one
|
||||
// masked in another conversation (13800138000 is in many), and
|
||||
// masked, its text would no longer match its signature
|
||||
t, n := apply(t, sentKnownSpans(t, Options{Secrets: o.Secrets}), o.put(), o)
|
||||
ko := Options{Secrets: o.Secrets, Route: o.Route}
|
||||
t, n := apply(t, sentSpans(sentKnown, t, ko, func() []span { return knownSpans(t, ko) }), o.put(), o)
|
||||
total += n
|
||||
return t
|
||||
})
|
||||
|
||||
+73
-35
@@ -262,9 +262,11 @@ func standsAlone(kind, s string, a, b int) bool {
|
||||
return !(is(before, alnum) && is(s[a], alnum)) && !(is(after, alnum) && is(s[b-1], alnum))
|
||||
}
|
||||
|
||||
// A text sent before goes again as it went: the known values found in it
|
||||
// the first time it was masked are the ones masked in it from then on,
|
||||
// and a value that became known since is masked in new text only.
|
||||
// A text sent before goes again as it went: the model's finds in it and
|
||||
// the known values found in it the first time it was masked for a route
|
||||
// are the ones masked in it there from then on. A value that became known
|
||||
// since is masked in new text only, and so is one the model found in the
|
||||
// text only since.
|
||||
//
|
||||
// An agent sends its whole conversation on every turn, and a vendor
|
||||
// caches it by its bytes up to a mark (Anthropic's cache_control, the
|
||||
@@ -274,28 +276,64 @@ func standsAlone(kind, s string, a, b int) bool {
|
||||
// the prefix changed at its first block, and a 400K-token conversation was
|
||||
// written to the cache whole instead of read (audie on Discord: cache_read
|
||||
// 0 and cache_write 412,081 to 426,782 on four turns, ten seconds apart).
|
||||
// Masking it there keeps nothing from the vendor, which was sent that text
|
||||
// as written already.
|
||||
// The local model did the same: a tool's output it hadn't read in the
|
||||
// request's wait (masking's defaultWait, pii.Partial) went with the rules'
|
||||
// masking alone, and the next turn, the model having read it, masked a
|
||||
// name in it, so everything from that message on was a new prompt to the
|
||||
// vendor (vvrfxyz on X: dsh's cache hits fell with masking on; replayed
|
||||
// on a Linux CPU, 12% of the history resent was rewritten).
|
||||
//
|
||||
// What is remembered is a hash of the text and of what o covers, and the
|
||||
// places of the known values in it; nothing of a value. A text no longer
|
||||
// remembered (sentEntries, or magpie started again) is masked with what is
|
||||
// known then.
|
||||
const sentEntries = 1 << 16
|
||||
// Masking it there keeps nothing from the vendor: the text went to it as
|
||||
// written. That holds only where it went, so what is remembered is kept
|
||||
// by Route, the providers the request could reach: on another route (the
|
||||
// user picked another model, a provider of its own) the text is masked
|
||||
// with what is known and found now. Within a route of several providers
|
||||
// (fallbacks, a routing group's members) the text goes to a member that
|
||||
// may not have had it, in the form any of them could have been sent it
|
||||
// the first time. A request with no route (a search's query, an
|
||||
// embedding's input: nothing a vendor caches) keeps the known values it
|
||||
// first went with, and has the model's finds of now.
|
||||
//
|
||||
// What is remembered is a hash of the route, the text and of what o
|
||||
// covers, and the places masked in it; nothing of a value. A text no
|
||||
// longer remembered (sentEntries, or magpie started again) is masked with
|
||||
// what is known and found then; a change to what o covers (a kind turned
|
||||
// on, the model's threshold, the model itself) is another text.
|
||||
const sentEntries = 1 << 17 // a text's model finds and its known values are two
|
||||
|
||||
var sentKnown struct {
|
||||
// What sentSpans remembers of a text: the model's finds in it, or the
|
||||
// known values in it.
|
||||
const (
|
||||
sentModel byte = iota + 1
|
||||
sentKnown
|
||||
)
|
||||
|
||||
var sentMemo struct {
|
||||
sync.Mutex
|
||||
cur, old map[[32]byte][]span
|
||||
}
|
||||
|
||||
// sentKnownSpans is knownSpans for text going to a vendor: the same as the
|
||||
// first time s was masked under what o covers.
|
||||
func sentKnownSpans(s string, o Options) []span {
|
||||
if !o.Secrets && !o.Personal || len(s) < minKnown {
|
||||
return nil
|
||||
// sentSpans is find()'s spans (modelSpans or knownSpans, as what says) for
|
||||
// text going to a vendor: the same as the first time s was masked on
|
||||
// o.Route under what o covers.
|
||||
func sentSpans(what byte, s string, o Options, find func() []span) []span {
|
||||
if !o.Secrets && !o.Personal || what == sentKnown && len(s) < minKnown {
|
||||
if what == sentKnown {
|
||||
return nil
|
||||
}
|
||||
return find()
|
||||
}
|
||||
if what == sentModel && (o.Model == nil || o.Route == "") {
|
||||
// no model: nothing to remember. No route (a search's query, an
|
||||
// embedding's input, nothing a vendor caches): what the model
|
||||
// finds now, wherever it goes
|
||||
return find()
|
||||
}
|
||||
h := sha256.New()
|
||||
fmt.Fprintf(h, "%t\x00%t\x00", o.Secrets, o.Personal)
|
||||
fmt.Fprintf(h, "%d\x00%q\x00%t\x00%t\x00", what, o.Route, o.Secrets, o.Personal)
|
||||
if what == sentModel {
|
||||
fmt.Fprintf(h, "%t\x00%t\x00%g\x00", o.Model != nil, o.NamesByModel, o.MinScore)
|
||||
}
|
||||
kinds := make([]string, 0, len(o.Kinds))
|
||||
for k, on := range o.Kinds {
|
||||
kinds = append(kinds, fmt.Sprintf("%s=%t", k, on))
|
||||
@@ -305,36 +343,36 @@ func sentKnownSpans(s string, o Options) []span {
|
||||
h.Write([]byte(s))
|
||||
var k [32]byte
|
||||
h.Sum(k[:0])
|
||||
sentKnown.Lock()
|
||||
sp, ok := sentKnown.cur[k]
|
||||
sentMemo.Lock()
|
||||
sp, ok := sentMemo.cur[k]
|
||||
if !ok {
|
||||
if sp, ok = sentKnown.old[k]; ok {
|
||||
sentKnownAdd(k, sp) // still in use: kept past the next turnover
|
||||
if sp, ok = sentMemo.old[k]; ok {
|
||||
sentAdd(k, sp) // still in use: kept past the next turnover
|
||||
}
|
||||
}
|
||||
sentKnown.Unlock()
|
||||
sentMemo.Unlock()
|
||||
if ok {
|
||||
return slices.Clone(sp)
|
||||
}
|
||||
sp = knownSpans(s, o)
|
||||
sentKnown.Lock()
|
||||
sentKnownAdd(k, slices.Clone(sp))
|
||||
sentKnown.Unlock()
|
||||
sp = find()
|
||||
sentMemo.Lock()
|
||||
sentAdd(k, slices.Clone(sp))
|
||||
sentMemo.Unlock()
|
||||
return sp
|
||||
}
|
||||
|
||||
// sentKnownAdd is called with sentKnown held. Two generations, as
|
||||
// scrubMemo keeps: when the newer is full it becomes the older.
|
||||
func sentKnownAdd(k [32]byte, sp []span) {
|
||||
if sentKnown.cur == nil || len(sentKnown.cur) >= sentEntries {
|
||||
sentKnown.old, sentKnown.cur = sentKnown.cur, make(map[[32]byte][]span)
|
||||
// sentAdd is called with sentMemo held. Two generations, as scrubMemo
|
||||
// keeps: when the newer is full it becomes the older.
|
||||
func sentAdd(k [32]byte, sp []span) {
|
||||
if sentMemo.cur == nil || len(sentMemo.cur) >= sentEntries {
|
||||
sentMemo.old, sentMemo.cur = sentMemo.cur, make(map[[32]byte][]span)
|
||||
}
|
||||
sentKnown.cur[k] = sp
|
||||
sentMemo.cur[k] = sp
|
||||
}
|
||||
|
||||
// resetSent forgets the texts sent (a test starts from nothing).
|
||||
func resetSent() {
|
||||
sentKnown.Lock()
|
||||
defer sentKnown.Unlock()
|
||||
sentKnown.cur, sentKnown.old = nil, nil
|
||||
sentMemo.Lock()
|
||||
defer sentMemo.Unlock()
|
||||
sentMemo.cur, sentMemo.old = nil, nil
|
||||
}
|
||||
|
||||
@@ -55,6 +55,11 @@ type Options struct {
|
||||
Kinds map[string]bool
|
||||
// Model, where set, finds more in the texts to mask (model.go)
|
||||
Model Model
|
||||
// Route names where a request masked for a vendor may go (the gateway
|
||||
// sets it: the providers a model, its fallbacks or a routing group's
|
||||
// members are served by). A text sent on it before goes on it again
|
||||
// as it went (sentSpans); on another route it is masked afresh.
|
||||
Route string
|
||||
// MinScore is the score the user has Model's finds need (Settings →
|
||||
// Privacy's slider), which Model's own finds are held to already. A
|
||||
// value only the model found, masked before at a lower score, isn't
|
||||
@@ -83,7 +88,8 @@ type Options struct {
|
||||
// found are the spans Model found, by text, for one request's texts
|
||||
found map[string][]Found
|
||||
// sent is masking for a vendor (Mask, MaskJSON): a text masked
|
||||
// before has the known values it had then (sentKnownSpans)
|
||||
// before on Route has the model's finds and the known values it had
|
||||
// then (sentSpans)
|
||||
sent bool
|
||||
}
|
||||
|
||||
@@ -1030,10 +1036,15 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool)
|
||||
}
|
||||
// after the rules', so where a rule finds the same value it keeps the
|
||||
// kind it has always had
|
||||
found = append(found, modelSpans(raw, o)...) // the model was asked about raw
|
||||
if o.sent {
|
||||
found = append(found, sentKnownSpans(s, o)...)
|
||||
// the model was asked about raw
|
||||
now := modelSpans(raw, o)
|
||||
kept := sentSpans(sentModel, raw, o, func() []span { return now })
|
||||
learnLate(raw, now, kept, o, escaped)
|
||||
found = append(found, kept...)
|
||||
found = append(found, sentSpans(sentKnown, s, o, func() []span { return knownSpans(s, o) })...)
|
||||
} else {
|
||||
found = append(found, modelSpans(raw, o)...) // the model was asked about raw
|
||||
found = append(found, knownSpans(s, o)...)
|
||||
}
|
||||
if escaped {
|
||||
@@ -1046,6 +1057,33 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool)
|
||||
return apply(raw, found, put, o)
|
||||
}
|
||||
|
||||
// learnLate makes known what the model finds in raw now that it didn't
|
||||
// the first time raw was sent on o.Route (now, beside kept): raw goes as
|
||||
// it went, but a value in it the model has read since is masked in new
|
||||
// text, as it would be had raw been masked with it (known.go). Nothing
|
||||
// is told (o.Seen): it isn't masked here.
|
||||
func learnLate(raw string, now, kept []span, o Options, escaped bool) {
|
||||
var late []span
|
||||
for _, f := range now {
|
||||
if !slices.ContainsFunc(kept, func(k span) bool { return k.start == f.start && k.end == f.end && k.kind == f.kind }) {
|
||||
late = append(late, f)
|
||||
}
|
||||
}
|
||||
if len(late) == 0 {
|
||||
return
|
||||
}
|
||||
if escaped {
|
||||
late = outsideEscapes(raw, late)
|
||||
}
|
||||
noteScores(raw, late)
|
||||
o.Seen = nil
|
||||
put := o.put()
|
||||
if escaped {
|
||||
put = unescapedPut(put)
|
||||
}
|
||||
apply(raw, late, put, o)
|
||||
}
|
||||
|
||||
// unescapedView is s, JSON text, as long as s and read as the vendor reads
|
||||
// it once unescaped, as far as the finders tell: an escape that stands for
|
||||
// a newline, a tab or another control character has its letter read as
|
||||
|
||||
Reference in New Issue
Block a user