diff --git a/internal/redact/redact.go b/internal/redact/redact.go index dee30bddf..67963a534 100644 --- a/internal/redact/redact.go +++ b/internal/redact/redact.go @@ -1062,74 +1062,7 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool) i = max(b, a+1) } } - all := rules - if o.Secrets && len(o.Rules) > 0 { - // the user's first: where one of theirs and one of magpie's find - // the same value, it goes by the name they gave it - all = append(customRules(o.Rules), rules...) - } - lower := "" - // split are matches a rule took apart into values of their own - // (rkato@box17 as a user and a host): what another rule found from - // the same place in them, an email, goes - var split []span - for _, r := range all { - if !o.covers(r.cat) { - continue - } - if len(r.markers) > 0 && !containsAny(s, r.markers) { - continue - } - if len(r.fold) > 0 { - if lower == "" { - lower = lowerASCII(s) - } - if !containsAny(lower, r.fold) { - continue - } - } - for _, m := range r.matches(s, lower) { - if len(r.groups) > 0 { - took := false - for g, kind := range r.groups { - if a, b := m[2*g+2], m[2*g+3]; a >= 0 && r.takes(s, a, b, r.groupOK[g]) { - found = append(found, span{a, b, kind, r.by(), 0, false}) - took = true - } - } - if took { - split = append(split, span{m[2], m[1], "", "", 0, false}) - } - continue - } - a, b := m[0], m[1] - for g := 1; 2*g+1 < len(m); g++ { - if m[2*g] >= 0 { - a, b = m[2*g], m[2*g+1] - break - } - if !r.anyGroup { - break - } - } - ok := r.ok - if r.fix != nil { - var good bool - if a, b, good = r.fix(s, a, b); !good { - continue - } - ok = nil - } - if r.takes(s, a, b, ok) { - found = append(found, span{a, b, r.kind, r.by(), 0, false}) - } - } - } - for _, sp := range split { - found = slices.DeleteFunc(found, func(f span) bool { - return f.kind == "EMAIL" && f.start == sp.start && f.end <= sp.end - }) - } + found = append(found, ruleSpans(s, o)...) // after the rules', so where a rule finds the same value it keeps the // kind it has always had if o.sent { @@ -1153,6 +1086,86 @@ func mask(raw string, o Options, put func(kind, v string) string, escaped bool) return apply(raw, found, put, o) } +// ruleSpans are what the rules, magpie's and the user's own, find in s, +// the text the finders read. +func ruleSpans(s string, o Options) []span { + return memoRules(s, o, func() []span { + if len(s) >= ruleMemoMin { + ruleRuns.Add(1) + } + var found []span + all := rules + if o.Secrets && len(o.Rules) > 0 { + // the user's first: where one of theirs and one of magpie's find + // the same value, it goes by the name they gave it + all = append(customRules(o.Rules), rules...) + } + lower := "" + // split are matches a rule took apart into values of their own + // (rkato@box17 as a user and a host): what another rule found from + // the same place in them, an email, goes + var split []span + for _, r := range all { + if !o.covers(r.cat) { + continue + } + if len(r.markers) > 0 && !containsAny(s, r.markers) { + continue + } + if len(r.fold) > 0 { + if lower == "" { + lower = lowerASCII(s) + } + if !containsAny(lower, r.fold) { + continue + } + } + for _, m := range r.matches(s, lower) { + if len(r.groups) > 0 { + took := false + for g, kind := range r.groups { + if a, b := m[2*g+2], m[2*g+3]; a >= 0 && r.takes(s, a, b, r.groupOK[g]) { + found = append(found, span{a, b, kind, r.by(), 0, false}) + took = true + } + } + if took { + split = append(split, span{m[2], m[1], "", "", 0, false}) + } + continue + } + a, b := m[0], m[1] + for g := 1; 2*g+1 < len(m); g++ { + if m[2*g] >= 0 { + a, b = m[2*g], m[2*g+1] + break + } + if !r.anyGroup { + break + } + } + ok := r.ok + if r.fix != nil { + var good bool + if a, b, good = r.fix(s, a, b); !good { + continue + } + ok = nil + } + if r.takes(s, a, b, ok) { + found = append(found, span{a, b, r.kind, r.by(), 0, false}) + } + } + } + for _, sp := range split { + found = slices.DeleteFunc(found, func(f span) bool { + return f.kind == "EMAIL" && f.start == sp.start && f.end <= sp.end + }) + } + return found + }) +} + // 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 diff --git a/internal/redact/rulememo.go b/internal/redact/rulememo.go new file mode 100644 index 000000000..362e9b160 --- /dev/null +++ b/internal/redact/rulememo.go @@ -0,0 +1,80 @@ +package redact + +import ( + "crypto/sha256" + "fmt" + "slices" + "strings" + "sync" + "sync/atomic" +) + +// memoRules remembers what the rules found in a long text. An agent sends +// its whole history on every turn, so without it every turn ran each rule +// over every message before it again: on a long Claude Code session, with +// masking on, most of magpie's CPU went to the rules' regexps (#4353). What +// they find in a text depends on the text, what o covers, the user's own +// rules and the day (dateOK: a date over a year ago can be a birthday), +// and on nothing a request changes, so it is kept by a hash of those. Only +// the hash and the places found are kept, nothing of a value. +const ( + ruleMemoMin = 256 // a shorter text costs less to read than to look up + ruleMemoEntries = 1 << 16 +) + +var ruleMemo struct { + sync.Mutex + cur, old map[[32]byte][]span +} + +// ruleRuns counts the texts of ruleMemoMin bytes or more the rules have +// run over (a test reads it). +var ruleRuns atomic.Uint64 + +func memoRules(s string, o Options, find func() []span) []span { + if len(s) < ruleMemoMin { + return find() + } + h := sha256.New() + fmt.Fprintf(h, "%s\x00%t\x00%t\x00", dateClock().Format("2006-01-02"), o.Secrets, o.Personal) + kinds := make([]string, 0, len(o.Kinds)) + for k, on := range o.Kinds { + kinds = append(kinds, fmt.Sprintf("%q=%t", k, on)) + } + slices.Sort(kinds) + fmt.Fprintf(h, "%s\x00", strings.Join(kinds, ",")) + if o.Secrets { + for _, r := range o.Rules { + fmt.Fprintf(h, "%q:%q:%q;", r.Kind, r.Prefix, r.Regex) + } + } + h.Write([]byte{0}) + h.Write([]byte(s)) + var k [32]byte + h.Sum(k[:0]) + ruleMemo.Lock() + sp, ok := ruleMemo.cur[k] + if !ok { + if sp, ok = ruleMemo.old[k]; ok { + ruleAdd(k, sp) // still in use: kept past the next turnover + } + } + ruleMemo.Unlock() + if ok { + return slices.Clone(sp) + } + sp = find() + ruleMemo.Lock() + ruleAdd(k, slices.Clip(slices.Clone(sp))) + ruleMemo.Unlock() + return sp +} + +// ruleAdd is called with ruleMemo held. Two generations, as sentMemo +// keeps: when the newer is full it becomes the older. +func ruleAdd(k [32]byte, sp []span) { + if ruleMemo.cur == nil || len(ruleMemo.cur) >= ruleMemoEntries { + ruleMemo.old, ruleMemo.cur = ruleMemo.cur, make(map[[32]byte][]span) + } + ruleMemo.cur[k] = sp +} diff --git a/internal/redact/rulememo_test.go b/internal/redact/rulememo_test.go new file mode 100644 index 000000000..a384451d9 --- /dev/null +++ b/internal/redact/rulememo_test.go @@ -0,0 +1,76 @@ +package redact + +import ( + "strings" + "testing" + "time" +) + +func resetRuleMemo() { + ruleMemo.Lock() + ruleMemo.cur, ruleMemo.old = nil, nil + ruleMemo.Unlock() +} + +// TestRulesRunOnceAText: a history masked for a vendor again on the next +// turn has the rules run only over what it did not have before (#4353), +// and comes out as it did. +func TestRulesRunOnceAText(t *testing.T) { + Forget() + resetRuleMemo() + o := Options{Secrets: true, Personal: true, Route: "codex"} + first := codexHistory(40) + want, _ := MaskJSON(first, o) + runs := ruleRuns.Load() + next := codexHistory(41) + got, _ := MaskJSON(next, o) + // the new turn's one long string, its tool's output + if n := ruleRuns.Load() - runs; n != 1 { + t.Fatalf("the rules ran over %d texts for one new turn", n) + } + if !strings.HasPrefix(string(got), string(want[:len(want)-len(`],"stream":true}`)])) { + t.Fatal("the history masked again is not what it was") + } + Forget() + resetRuleMemo() + if again, _ := MaskJSON(next, o); string(again) != string(got) { + t.Fatal("remembered and fresh rule finds differ") + } +} + +// TestRuleMemoKeysWhatTheRulesRead: what the rules found is not taken for +// a text read under other options, the user's own rules or another day. +func TestRuleMemoKeysWhatTheRulesRead(t *testing.T) { + defer func(c func() time.Time) { dateClock = c }(dateClock) + dateClock = func() time.Time { return time.Date(2026, 10, 24, 9, 30, 0, 0, time.Local) } + resetRuleMemo() + text := strings.Repeat("filler words with nothing in them ", 8) + "DOB: 03/05/1990, mail rkato@example.org, token ACME-7f3k9q2w8e4r6t1y" + mine := []Rule{{Kind: "ACME", Prefix: "ACME-", Regex: `ACME-[0-9a-z]{16}`}} + kinds := func(o Options) string { + var out []string + for _, sp := range ruleSpans(text, o) { + out = append(out, sp.kind) + } + return strings.Join(out, ",") + } + secrets := kinds(Options{Secrets: true}) + all := kinds(Options{Secrets: true, Personal: true}) + if secrets == all { + t.Fatalf("personal data on finds what secrets alone do: %q", all) + } + if got := kinds(Options{Secrets: true}); got != secrets { + t.Fatalf("the same options found %q, then %q", secrets, got) + } + if got := kinds(Options{Secrets: true, Rules: mine}); !strings.Contains(got, "ACME") { + t.Fatalf("the user's own rule went unread: %q", got) + } + off := kinds(Options{Secrets: true, Personal: true, Kinds: map[string]bool{"birthday": false}}) + if strings.Contains(off, "BIRTHDAY") || !strings.Contains(all, "BIRTHDAY") { + t.Fatalf("birthdays turned off still found (%q; with them on %q)", off, all) + } + // the day after the date: no birthday, a date an agent runs on + dateClock = func() time.Time { return time.Date(1990, 3, 6, 9, 30, 0, 0, time.Local) } + if got := kinds(Options{Secrets: true, Personal: true}); strings.Contains(got, "BIRTHDAY") { + t.Fatalf("a date of yesterday found as a birthday, as it was 36 years on: %q", got) + } +}