Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

pii: a long text goes to the masking model in overlapping pieces, a piece at a time, each kept (#3682)

yetone8f023b51195e
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index 63dfa8775..34263a16d 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -119,7 +119,7 @@ recorded as a prediction failure (`noPrediction`).
1. `handle(proto)` reads the body and the model (`requestBody`, `requestModel`), then calls `serveAgent`. Every route that reads an agent's body (each API, count_tokens, Gemini's, embeddings, images, videos, System One, the Codex backend path) reads it through `readBoundedRequestBody` in [`request_bounds.go`](../../internal/gateway/request_bounds.go). It decodes a `Content-Encoding` of `gzip` or `zstd` (`decodedBody`; Codex sends zstd to a custom provider's `/v1/responses` too, #1223) and drops the header, so the provider is sent plain JSON, with one exception: a ChatGPT account's turn (POST `CodexBase`/responses, from the accounts loop in `forwardOnce` or relayed by `codexUpstreamOn`) is compressed again with zstd and a window of at most 2 MiB, as Codex's own client sends it (`provider.CodexCompressed`; openai/codex `responses_request_compression` and `http-client/src/request.rs`). It is compressed once the body is final, and again on each try. `/responses/compact`, an API key's requests and every other provider stay plain. Sent plain, a 1.1 MB text-only turn was answered 503 (ylorn on X). The plain body is what magpie keeps and shows, and `codexDropped` judges a reset by the bytes that went on the wire. `codexDropped` also reads Envoy's 507 "exceeded request buffer limit while retrying upstream" (the backend failed and the front couldn't retry a body that large) as that reset, at any size, told as a 503 so magpie, Codex and pi ask again and nobody rests (#2034). The size limit (`defaultBodyLimit`, 512 MB) holds for the decoded bytes (413), and any other encoding is refused 415. It was 128 MB until a long Codex session that had read many images went past it decoded, its inline screenshots resent each turn, and got the 413 on all five of Codex's retries (#1422, `TestImageHeavyCodexTurnIsRead`). magpie's own 413 says it is magpie's gateway limit, with the size, and that the provider was not asked (`overLimit`); `writeError` adds to any 413 it isn't holding that this is a byte limit, not the model's context, and to `/compact` or start a new conversation (`TestOverLimitSaysWhoseAndWhatToDo`). Every shape but Gemini's types a 413 `request_too_large`, Anthropic's own type, which pi's overflow table knows: pi compacts and tries once more rather than stopping on an OpenAI-shaped `api_error` (@wilsonxuuuu on X, `TestPayloadTooLargeSaysRequestTooLargeToPi`). `keyLimited` reads a limited key's compressed body the same way, so its reservation is the decoded size. `serveAgent` runs the [middleware](gateway-middleware.md) chain, then `serve`.
2. `serve` redacts secrets in the request (`redacted`; `redact.MaskJSON` leaves ids alone, and in any text a backend's id (a UUID, or 32 hex digits or more) goes as written: no rule, model label or value known from before masks a piece of one (a phone number at the end of `…-a13800138000`, a card number across a UUID's groups), and a whole one is masked only by the user's own words and rules or as a credential, by the password, API key and token rules or a secret rule whose field is named for one (`api_key=`, `refresh_token`), never one named for an id, a cursor, a request or a digest (`secret_id`, `next_page_token`, `Idempotency-Key`, `secret_hash`), a bare `key`, a serial number, or what the model takes a UUID for (`noIDs`, [`internal/redact/ids.go`](../../internal/redact/ids.go)); and a tool's name and its MCP server's (`namespace`, `server_label`, `server_name`, #3143); the request's tool definitions and output schemas, found by their place in each protocol (top-level `tools`, `tool_choice`, `response_format`, `text`, `generationConfig`, `stream_options`, the client's ids in `client_metadata` and the like, and the tools of a Responses `additional_tools` or `tool_search_output` item), go as written save their descriptions, so a word the user masks can't break a grammar or an enum (#1911); and what the vendor sealed with a signature, a thinking block, Gemini's thoughts or Responses' encrypted reasoning, goes back as the vendor wrote it: only the values masked elsewhere in the request, and secrets masked before, are put back as their placeholders; a value masked once, at least 8 characters long, is masked again wherever a request has it, as an exact match whatever words are around it, so what the vendor wrote about a placeholder doesn't go back with the value in it, `redact/known.go`; a text masked for a vendor before, such as a system prompt or a turn already sent, is masked as it was then, so a value a rule first finds later in a conversation doesn't change the prompt the vendor has cached and rewrite all of it to the cache, `sentKnownSpans`), resolves the model to a provider or a group, and refuses what can't be served. The reply has the values put back on its way to the agent (`redact.Writer`, a stream event by event, a whole body at its end): a placeholder the model wrote as it was given, or as models rewrite one (spaces inside the braces, a brace or both dropped, another case), is the value again when what is left names one magpie made, and one split across events is held until it is whole (`redact.Restore`, `partialTail`, [`internal/redact/redact.go`](../../internal/redact/redact.go)). A request whose provider and fallbacks, or whose group's models, all skip redaction (`unredactedRoute`, `provider.SkipsRedaction`: set *Send requests unmasked*, `Unredacted`, with every address on this machine or the local network) goes to them as the agent wrote it; the log and recent calls keep the masked body. count_tokens and embeddings follow the same rule. What a routing group's Jev is told of the turn (the message, the user's message before it and the reply to it) is masked all the same unless Jev's own provider skips redaction too (`maskedState` in `askJev`, [`decide.go`](../../internal/gateway/decide.go)): a remote Jev is none of the group's members. The masking is the built-in plugin `redact`'s (`gwmw.Masker`, [Plugin runtime](plugin-runtime.md)); when the settings ask for masking and no masker serves, or it fails, the request is a 503 and nothing is sent (`redacted`, `gwmw.Masking`).
- With *Mask personal data* on, each kind in `redact.Categories` ([`internal/redact/more.go`](../../internal/redact/more.go)) is masked unless the user turned it off (`redactKinds` in settings, `Options.Kinds`). On by default: US SSNs, passport numbers, IBANs that pass mod 97, birthdays next to a word that says so (a date over a year ago: one in the last year or ahead is the day an agent runs on, `dateOK`), MAC addresses, and serial numbers next to S/N or the like. Off by default: the user name in a home folder, user@host in a prompt or ssh command, public IPv4 and IPv6 addresses (never private, loopback, link-local, CGNAT or documentation ranges) and cloud bucket names, since agents send them in nearly every request and the model must copy the placeholder exactly inside a path or URL. Context rules run only near their words (`rule.matches`). What reads as an address but ends in a file's extension that no domain has (`…@2x.jpg`, `[email protected]`; `fileExt` in `realEmail`), or a scale before an extension that is a domain too (`[email protected]`, `[email protected]`; `scaleExt`), is a file's name, for the rule and the local model alike (#3029). `[email protected]` is still an address. The Settings rows come from `REDACT_KINDS` in app.js, which `TestRedactKindsAreRedacts` holds to the same ids and defaults.
- - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; `pf-serve-vulkan` runs its MoE in 2048-token chunks, `PF_MOE_CHUNK`, 1.77× faster than its default 4096 on an RX 470/580-class GPU and a little slower on Metal, so Vulkan's alone, and a value the user set is kept, `moeChunk`): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, keeps the last 20000 answers by hash, on disk too (`found-<model>.bin` beside the model: hashes, offsets and labels, never text; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); a turn begun is finished and kept. The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). A model that is on and can't answer (not on disk, didn't start, hung, held back) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).
+ - With *Find with a local model* on (`settings.RedactModel`, this computer's own, kept by `KeepOwn`), a local model finds what no rule can, a name or an address in free text, under the same switches: a name, address, phone, email or account number is personal data, a secret a secret (`modelKinds`, `modelSpans` in [`internal/redact/model.go`](../../internal/redact/model.go)). `MaskJSON` asks it once per request, for every text it would mask, each once (`withModel`); its spans join the rules' with a rule's kind kept where both find a value, and ids a vendor or tool made (`req_…`, `toolu_…`) are never taken, nor a snake_case word as a name (Codex's `sequential_cutoff`, #3144), nor as a secret what names a thing: a UUID, a digest with its algorithm's name, a file's path (`namesThing`; the model takes all three for secrets). The model misses many Chinese names (张伟 after 给, 陈建国 after 客户, however low its threshold) and runs a name it finds on into the words after it (「王芳,她下周一」), so with it on a Chinese name is also found by its surname and a word around it that says a person is meant (客户, 我叫, 给…发, …先生, …说, joined by 和 to another name), and the model's are cut at punctuation and titles ([`zhname.go`](../../internal/redact/zhname.go)); a surname with nothing around it (王国的, 张开的) is left. The model is OpenAI's Privacy Filter as a q8 GGUF (1.6 GB), run by `pf-serve` ([`native/privacy-filter`](../../native/privacy-filter), built from privacy-filter.cpp on ggml and released under `pf-v*` tags; on a GPU it holds the model once, in the device's memory, #3590; `pf-serve-vulkan` runs its MoE in 2048-token chunks, `PF_MOE_CHUNK`, 1.77× faster than its default 4096 on an RX 470/580-class GPU and a little slower on Metal, so Vulkan's alone, and a value the user set is kept, `moeChunk`): Settings → Privacy's On downloads both (`pii.Download`, each checked against its pinned sha256, from hf-mirror first in China, `source.chinaFirst`) and saves the setting only once they are on disk (`/api/privacy-model`, [`privacymodel.go`](../../internal/gui/privacymodel.go)). `pii.Find` starts `pf-serve` on the first request (Metal, Vulkan, else the CPU; one that dies on the GPU, doesn't load there in 40s (`gpuLoadTimeout`, well inside the gateway's 2 minutes), or doesn't answer in time there twice in a row, is started on the CPU, and Settings says why; a request it didn't answer in time once is tried on the GPU again, since a slow request on a weak GPU is no lost GPU (#3682). The GPU is tried again 10 minutes later, doubling to 2 hours while it keeps failing, with no restart (`gpuRetryAfter`), and one that answers is the model's again), joins short texts into 12 KB chunks and maps the spans back, cuts a text over 12 KB into pieces of 12 KB at most that overlap by 1 KB (`pieces`: after a line's end, else a space, else at a rune's start), each kept by its own hash, their spans put back at the text's offsets and merged where pieces overlap (`merge`: one found twice is one, one cut by a piece's end is whole), and asks pf-serve a chunk at a time (#3682: a 480 KB text whole took an RX 470/580 90s and kept nothing when cut off), keeps the last 20000 answers by hash, on disk too (`found-<model>.bin` beside the model: hashes, offsets and labels, never text; written through temp-and-rename, a bad read taken as empty), so a restart doesn't ask the model about every history again (#3682), and ends it after 10 minutes with no request. Its requests take turns on its one pipe (`turn`), and a request reads the cache again when its turn comes; a request waits for its turn only while its context lives (`pii.FindContext`, through `gwmw.ContextTeller`), so one whose client went away leaves the queue (the gateway's 2 minutes leave masking's time out, #3682); the chunk pf-serve is on is finished and kept, so a request sent again asks only about what is left, and between chunks the turn is given up and taken again, so a short request goes before the rest of a long one. The status (`pii.Now`), `pii.Stop` and the idle timer never wait for a load or a request: `srv.mu` is held only to read or set the state, and `Stop` ends a load or a request under way at once. A request held before routing while it waits for the model is answered 504 saying so, and how to send without it (`unroutedMsg`); one of an older tag (`oldTags`, magpie updated since the download) runs until the pinned tag's is fetched (`upgrade`, on its start), which is then started on the next request and the old deleted ([`internal/pii`](../../internal/pii)). A failure names what ended `pf-serve`: magpie's own end of a request it didn't answer in time, else its exit status or signal and its last stderr lines past ggml's startup chatter (`died`, `lastSaid`). After one, requests are held back at once with that failure, not after a load each, until the model is tried again 30s later, doubling to 10 minutes while it keeps failing (`heldBack`, `retryAfter`; lazyeo on Discord, an M2 whose every request waited out the 504). A model that is on and can't answer (not on disk, didn't start, hung, held back) panics, so the request is held back with the 503 above rather than sent with the rules' masking alone (`masking.model`).
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The masker reads the rules from settings on each call (`options` in [`internal/masking`](../../internal/masking/masking.go)), so a change applies to the next request.
- With *Keep a key's form* on (`settings.RedactShape`, `Options.Shape`, under *Mask secrets*; Charles Cao on X), a secret of 16 characters or more, all letters, digits, `-`, `_` or `.`, goes as a made-up key of its form instead of a placeholder: its prefix kept (`sk-proj-`, `ghp_`, `AKIA`, up to four letters and their separator; `keyHead`), the same length and separators, and each other character a random one of its kind (a hex key's any hex digit of its case), drawn from an HMAC of the value under the placeholder key, so one key goes as the same made-up one every turn and a vendor's cache still matches (`shapeOf`, `shaped` in [`internal/redact/shape.go`](../../internal/redact/shape.go)). Personal data, the user's words and anything shorter or with other characters go as placeholders still. A made-up key is kept in the masker's memory with the placeholders, so it is recorded, re-masked in what a vendor sealed, and put back wherever the reply has it, before the placeholders (`restoreShapes`); a stream holds the end of an event that may be the start of one (`shapeTail`, after the last whole one), and a made-up key the vendor sends back unrestored isn't masked again (`outsideShapes`). `TestShapeKeepsForm`, `TestShapeJSON`, `TestShapeStream`. Insights › Masking and Settings' *Try it* mark a made-up key where they mark a placeholder, matching the text against the request's own values only, so a key of the same form the user wrote isn't marked (`maskMatches` in `plugins/redact/page.js`; #3599, masking-records and mask-actions GUI tests).
- What is done with a value found is the user's per kind (#1977, `redactActions` in settings, `Options.Actions`, set by `POST /api/settings/redact-actions`; a kind left out is masked). `redact.Warn` sends it as written: the masker tells it, with a placeholder no one remembers, and it isn't counted as masked. `redact.Block` masks it as any other, and the gateway holds the request back with a 400 that names the kind and the value's hint, never the value (`blocked`, `maskBlocked` in [`redact.go`](../../internal/gateway/redact.go)); nothing is sent and the record is kept as `Blocked` (`noteBlocked`). A value on the *Never mask* list (`redactAllow`, `Options.Allow`, `POST /api/settings/redact-allow`) goes as written when it is the whole value found, in any case, and isn't told; a longer value it is part of is masked. Settings → Privacy's *Try it* posts a text to `POST /api/masking/preview` ([`masking.go`](../../internal/gui/masking.go)), which masks it as a request would be (`redact.Preview`) and remembers nothing: its placeholders stand for nothing afterwards, its values aren't masked later as seen before, and it returns only the masked text and each hit's kind, finder, action, placeholder and hint. The page keeps the text in no storage.
diff --git a/internal/pii/find.go b/internal/pii/find.go
index b618b9136..29e69ba36 100644
--- a/internal/pii/find.go
+++ b/internal/pii/find.go
@@ -5,7 +5,10 @@ import (
"context"
"crypto/sha256"
"fmt"
+ "sort"
+ "strings"
"sync"
+ "unicode/utf8"
"github.com/yetone/magpie/internal/redact"
)
@@ -16,19 +19,23 @@ import (
// asked only about texts it hasn't seen. Those go to it joined into
// chunks of up to chunkSize: one pass over a few joined texts takes about
// what one over a single short text does (100 short messages: 683 ms one
-// by one, 44 ms joined, on an M4 Pro's GPU).
+// by one, 44 ms joined, on an M4 Pro's GPU). A text longer than
+// pieceSize goes in overlapping pieces (pieces), each kept on its own, so
+// a long text is read a piece at a time and what was read is kept even
+// when the rest isn't (#3682).
func Find(texts []string) ([][]redact.Found, error) {
return FindContext(context.Background(), texts)
}
// FindContext is Find for a caller that may stop waiting: when ctx ends
-// (the client went away, the gateway gave up on the request) it returns
-// at once, whether its turn hadn't come or pf-serve is on it. A turn
-// begun is finished all the same and its answers kept, so the request
-// sent again finds them.
+// (the client went away) it returns at once, whether its turn hadn't come
+// or pf-serve is on it. The chunk pf-serve is on is finished all the same
+// and its answers kept, so the request sent again finds them; the chunks
+// after it are left. Between chunks the turn is given up and taken again,
+// so a short request waiting for it goes before the rest of a long one.
func FindContext(ctx context.Context, texts []string) ([][]redact.Found, error) {
loadCache()
- out, miss := cached(texts)
+ out, miss := known(texts, nil)
if len(miss) == 0 {
return out, nil
}
@@ -38,12 +45,7 @@ func FindContext(ctx context.Context, texts []string) ([][]redact.Found, error)
if err := heldBack(); err != nil {
return nil, err
}
- waiting.Add(1)
- select {
- case turn <- struct{}{}:
- waiting.Add(-1)
- case <-ctx.Done():
- waiting.Add(-1)
+ if !takeTurn(ctx) {
return nil, waitErr(ctx)
}
type result struct {
@@ -52,34 +54,69 @@ func FindContext(ctx context.Context, texts []string) ([][]redact.Found, error)
}
done := make(chan result, 1)
go func() {
- defer func() { <-turn }()
- // read again: the requests before this one in turn had most of
- // a history in common with it, and asked already
- out, miss := cached(texts)
- if len(miss) > 0 {
+ held := true
+ defer func() {
+ if held {
+ <-turn
+ }
+ }()
+ // what this call's chunks found, by hash, whatever the cache
+ // lets go of meanwhile
+ got := map[[32]byte][]redact.Found{}
+ // read again: the requests before this one in turn had most of a
+ // history in common with it, and asked already
+ out, miss := known(texts, got)
+ for c := 0; len(miss) > 0; c++ {
+ if c > 0 {
+ // give way to a request waiting for the turn: it goes
+ // before the next chunk
+ <-turn
+ held = false
+ if !takeTurn(ctx) {
+ done <- result{nil, waitErr(ctx)}
+ return
+ }
+ held = true
+ }
// the one ahead may have failed: those queued behind it
// don't each try again, minutes apiece
if err := heldBack(); err != nil {
done <- result{nil, err}
return
}
- chunks, parts := join(texts, miss)
- got, err := classify(chunks)
+ chunks, parts := join(missing(texts, miss, got))
+ if len(chunks) == 0 {
+ done <- result{nil, fmt.Errorf("the local masking model has no text to read for %d texts", len(miss))}
+ return
+ }
+ read, err := classify(chunks[:1])
if err != nil {
done <- result{nil, err}
return
}
- for c, ps := range parts {
- for _, p := range ps {
- out[p.text] = within(got[c], p.at, p.at+len(texts[p.text]))
- }
- }
cache.mu.Lock()
- for _, i := range miss {
- cache.put(sha256.Sum256([]byte(texts[i])), out[i])
+ for _, p := range parts[0] {
+ k := sha256.Sum256([]byte(p.s))
+ got[k] = within(read[0], p.at, p.at+len(p.s))
+ cache.put(k, got[k])
}
cache.mu.Unlock()
saveSoon()
+ // the texts still missing, with this chunk's answers and
+ // what others' requests found meanwhile
+ sub := make([]string, len(miss))
+ for j, i := range miss {
+ sub[j] = texts[i]
+ }
+ o, m := known(sub, got)
+ was := miss
+ miss = nil
+ for j, i := range was {
+ out[i] = o[j]
+ }
+ for _, j := range m {
+ miss = append(miss, was[j])
+ }
}
done <- result{out, nil}
}()
@@ -91,22 +128,70 @@ func FindContext(ctx context.Context, texts []string) ([][]redact.Found, error)
}
}
+// takeTurn waits for the model's turn while ctx lives, counted as
+// waiting; false when ctx ended first.
+func takeTurn(ctx context.Context) bool {
+ waiting.Add(1)
+ defer waiting.Add(-1)
+ select {
+ case turn <- struct{}{}:
+ return true
+ case <-ctx.Done():
+ return false
+ }
+}
+
// waitErr is a request's that stopped waiting for the model.
func waitErr(ctx context.Context) error {
return fmt.Errorf("stopped waiting for the local masking model: %w", context.Cause(ctx))
}
-// cached is what the cache has of texts, and which it hasn't.
-func cached(texts []string) (out [][]redact.Found, miss []int) {
+// known is what is known of texts, from got (this call's answers) and the
+// cache, and which texts it isn't. A text kept whole is taken as it is;
+// a long one is put together from its pieces, once all of them are known,
+// and kept whole then too.
+func known(texts []string, got map[[32]byte][]redact.Found) (out [][]redact.Found, miss []int) {
out = make([][]redact.Found, len(texts))
cache.mu.Lock()
defer cache.mu.Unlock()
+ look := func(s string) ([]redact.Found, bool) {
+ k := sha256.Sum256([]byte(s))
+ if fs, ok := got[k]; ok {
+ return fs, true
+ }
+ if fs, ok := cache.get(k); ok && fits(fs, s) {
+ return fs, true
+ }
+ return nil, false
+ }
for i, t := range texts {
- if fs, ok := cache.get(sha256.Sum256([]byte(t))); ok && fits(fs, t) {
+ if fs, ok := look(t); ok {
out[i] = fs
- } else {
+ continue
+ }
+ ps := pieces(t)
+ if len(ps) < 2 {
+ miss = append(miss, i)
+ continue
+ }
+ var all []redact.Found
+ ok := true
+ for _, p := range ps {
+ fs, have := look(t[p.at:p.end])
+ if !have {
+ ok = false
+ break
+ }
+ for _, f := range fs {
+ all = append(all, redact.Found{Start: f.Start + p.at, End: f.End + p.at, Label: f.Label})
+ }
+ }
+ if !ok {
miss = append(miss, i)
+ continue
}
+ out[i] = merge(all)
+ cache.put(sha256.Sum256([]byte(t)), out[i])
}
return out, miss
}
@@ -122,18 +207,144 @@ func fits(fs []redact.Found, t string) bool {
return true
}
-// chunkSize is how long a chunk of joined texts grows; a longer text
-// goes alone, pf-serve reading it a window at a time.
+// chunkSize is how long a chunk of joined texts grows.
const chunkSize = 12 << 10
+// pieceSize is how long a piece of a long text is at most, and
+// pieceOverlap how much of the piece before it each piece after the first
+// reads again, so a name or a secret cut by one piece's end is whole in
+// the next. 12 KB is 1.6s of an RX 470/580's time, 0.4s of an M4 Pro's,
+// well inside classifyTimeout; a 480 KB text whole was 90s on the RX
+// 470/580, past the gateway's 2 minutes on its CPU, and kept nothing when
+// cut off (#3682).
+const (
+ pieceSize = chunkSize
+ pieceOverlap = 1 << 10
+)
+
+// span is a piece of a text: t[at:end].
+type span struct{ at, end int }
+
+// pieces cuts t into pieces of at most pieceSize, each after the first
+// beginning pieceOverlap before the one before ends. A piece ends after a
+// line's end in its second half, else after a space there, else at a
+// rune's start; the next begins after a line's end in the first half of
+// the overlap, else after a space there, else at a rune's start. A text of pieceSize
+// or less is one piece; an empty one none.
+func pieces(t string) []span {
+ if t == "" {
+ return nil
+ }
+ if len(t) <= pieceSize {
+ return []span{{0, len(t)}}
+ }
+ var out []span
+ for at := 0; ; {
+ end := at + pieceSize
+ if end >= len(t) {
+ return append(out, span{at, len(t)})
+ }
+ half := at + pieceSize/2
+ if i := strings.LastIndexByte(t[half:end], '\n'); i >= 0 {
+ end = half + i + 1
+ } else if i := strings.LastIndexByte(t[half:end], ' '); i >= 0 {
+ end = half + i + 1
+ } else {
+ for end > half && !utf8.RuneStart(t[end]) {
+ end--
+ }
+ }
+ out = append(out, span{at, end})
+ next := end - pieceOverlap
+ if i := strings.IndexByte(t[next:end-pieceOverlap/2], '\n'); i >= 0 {
+ next += i + 1
+ } else if i := strings.IndexByte(t[next:end-pieceOverlap/2], ' '); i >= 0 {
+ next += i + 1
+ } else {
+ for !utf8.RuneStart(t[next]) {
+ next++
+ }
+ }
+ at = next
+ }
+}
+
+// merge puts a long text's spans from its pieces together: spans that
+// overlap (one found in two pieces, or cut by a piece's end in one and
+// whole in the next) become one, its label the longer's, and spans of one
+// label that touch become one. Sorted, with none twice.
+func merge(fs []redact.Found) []redact.Found {
+ sort.Slice(fs, func(i, j int) bool {
+ if fs[i].Start != fs[j].Start {
+ return fs[i].Start < fs[j].Start
+ }
+ return fs[i].End > fs[j].End
+ })
+ var out []redact.Found
+ for _, f := range fs {
+ if n := len(out); n > 0 {
+ last := &out[n-1]
+ if f.Start < last.End || f.Start == last.End && f.Label == last.Label {
+ if f.End-f.Start > last.End-last.Start {
+ last.Label = f.Label
+ }
+ last.End = max(last.End, f.End)
+ continue
+ }
+ }
+ out = append(out, f)
+ }
+ return out
+}
+
+// missing are what of texts[miss] neither got nor the cache has, to ask
+// the model about: the texts whole, and the long ones' pieces, each once.
+func missing(texts []string, miss []int, got map[[32]byte][]redact.Found) []string {
+ var out []string
+ seen := map[[32]byte]bool{}
+ cache.mu.Lock()
+ defer cache.mu.Unlock()
+ for _, i := range miss {
+ t := texts[i]
+ for _, p := range pieces(t) {
+ s := t[p.at:p.end]
+ k := sha256.Sum256([]byte(s))
+ if seen[k] {
+ continue
+ }
+ seen[k] = true
+ if _, ok := got[k]; ok {
+ continue
+ }
+ if fs, ok := cache.get(k); ok && fits(fs, s) {
+ continue
+ }
+ out = append(out, s)
+ }
+ if t == "" {
+ // as before: an empty text is asked about, and kept
+ k := sha256.Sum256(nil)
+ if !seen[k] {
+ seen[k] = true
+ out = append(out, "")
+ }
+ }
+ }
+ return out
+}
+
// sep is put between joined texts: a paragraph's end, so the model reads
// each as a text of its own.
const sep = "\n\n"
-type part struct{ text, at int }
+// part is a text or piece in a chunk: s, at at.
+type part struct {
+ s string
+ at int
+}
-// join puts texts[miss] into chunks, and says where in which each is.
-func join(texts []string, miss []int) (chunks []string, parts [][]part) {
+// join puts texts into chunks, and says where in which each is.
+func join(texts []string) (chunks []string, parts [][]part) {
cur, curParts := "", []part(nil)
flush := func() {
if curParts != nil {
@@ -141,15 +352,14 @@ func join(texts []string, miss []int) (chunks []string, parts [][]part) {
cur, curParts = "", nil
}
}
- for _, i := range miss {
- t := texts[i]
+ for _, t := range texts {
if curParts != nil && len(cur)+len(sep)+len(t) > chunkSize {
flush()
}
if curParts != nil {
cur += sep
}
- curParts = append(curParts, part{i, len(cur)})
+ curParts = append(curParts, part{t, len(cur)})
cur += t
}
flush()
diff --git a/internal/pii/pieces_test.go b/internal/pii/pieces_test.go
new file mode 100644
index 000000000..dfdb16009
--- /dev/null
+++ b/internal/pii/pieces_test.go
@@ -0,0 +1,201 @@
+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.
+func TestMergeAcrossPieces(t *testing.T) {
+ email := func(s, e int) redact.Found { return redact.Found{Start: s, End: e, Label: "private_email"} }
+ 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
+ email(209, 222), // 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
+ })
+ want := []redact.Found{person(10, 15), person(100, 105), email(200, 222), 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)
+ }
+}
diff --git a/internal/pii/serve_test.go b/internal/pii/serve_test.go
index f753e2cdb..fd453ec68 100644
--- a/internal/pii/serve_test.go
+++ b/internal/pii/serve_test.go
@@ -55,11 +55,11 @@ func TestFindJoinsTextsAndMapsBack(t *testing.T) {
func TestJoinSplitsAtChunkSize(t *testing.T) {
long := strings.Repeat("x", chunkSize)
texts := []string{"a", "b", long, "c"}
- chunks, parts := join(texts, []int{0, 1, 2, 3})
+ chunks, parts := join(missing(texts, []int{0, 1, 2, 3}, nil))
if len(chunks) != 3 || chunks[0] != "a"+sep+"b" || chunks[1] != long || chunks[2] != "c" {
t.Fatalf("chunks = %d: %.20q", len(chunks), chunks)
}
- if !reflect.DeepEqual(parts, [][]part{{{0, 0}, {1, 1 + len(sep)}}, {{2, 0}}, {{3, 0}}}) {
+ if !reflect.DeepEqual(parts, [][]part{{{"a", 0}, {"b", 1 + len(sep)}}, {{long, 0}}, {{"c", 0}}}) {
t.Fatalf("parts = %v", parts)
}
}