Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
gateway: masking's time no longer counts toward the 2 minutes before routing (#3682)
yetone16f6e568f4a5
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.mdindex b3f79fee3..63dfa8775 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, or that the gateway answered 504 after 2 minutes, leaves the queue; 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, 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 *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.@@ -274,8 +274,12 @@ recorded as a prediction failure (`noPrediction`).on the Routing page as routing, and gives way to the request's own routeonce one is begun (`noteRoute`, `trace.drop`). It is answered 504 after`unroutedUnknown` (30s) held in no wait magpie knows of, or after- `unroutedMost` (2m) in all (sharwowwow on X: two minutes of spinning- before a 504). The known waits are counted as they happen and their+ `unroutedMost` (2m) in all but masking (sharwowwow on X: two minutes of+ spinning before a 504). Masking's time, its wait for the local model's+ turn with it, counts toward neither (`masked`, `checkMost`): the model+ is bounded per piece it reads (`classifyTimeout`) and per load, and a+ 480 KB request it took 90s over on an RX 470/580, behind the requests+ ahead of it, was answered 504 at 2m every time it was sent (#3682). The known waits are counted as they happen and theirtime added up (`noteWait`, `waited`): the request's body arriving(`waitedBody`, every read of `r.Body`), masking (`noteMasking`), SystemOne's or the decision model's classifier (`askWaited`), an image's@@ -292,7 +296,8 @@ recorded as a prediction failure (`noPrediction`).through `heldWriter`, and nowhere once magpie has answered for it.`TestUnroutedRequestShownThenAnswered`, `TestUnroutedShownGivesWayToItsRoute`,`TestUnroutedUnknownHoldAnsweredSooner`, `TestUnroutedSlowBodyNotCutOff`,- `TestUnroutedMaskingNotCutOff`, `TestUnroutedSlotWaitNotCutOff`.+ `TestUnroutedMaskingNotCutOff`, `TestUnroutedSlotWaitNotCutOff`,+ `TestUnroutedMostLeavesOutMasking`, `TestMaskingModelWaitNotCutOffAtMost`.## Remote magpie APIsdiff --git a/internal/gateway/masking_wait_test.go b/internal/gateway/masking_wait_test.goindex 4f95dda44..884c8393d 100644--- a/internal/gateway/masking_wait_test.go+++ b/internal/gateway/masking_wait_test.go@@ -55,14 +55,15 @@ func (waitingMasker) Writer(w http.ResponseWriter) (http.ResponseWriter, func())return w, func() {}}-// #3682: with Settings → Privacy's local model on, every request after a-// restart waited for it, and was answered after 2m that magpie "held this-// request without routing it to any provider". Its answer says it waited-// for the local masking model, what the model was doing and how to send-// without it, and the wait lets go when magpie answers, rather than keep-// its place in the model's queue.-func TestHeldForTheMaskingModelSaysSo(t *testing.T) {- unroutedLimits(t, 50*time.Millisecond, 500*time.Millisecond)+// #3682: with Settings → Privacy's local model on, a request the model+// was still reading at 2 minutes was answered 504, its work thrown away,+// and so every time it was sent again (480 KB on an RX 470/580 takes the+// model 90s, and its turn waits for the requests ahead). Masking's time no+// longer counts toward unroutedMost: the request waits for the model,+// and its wait lets go when its client does, rather than keep its place+// in the model's queue.+func TestMaskingModelWaitNotCutOffAtMost(t *testing.T) {+ unroutedLimits(t, 20*time.Millisecond, 200*time.Millisecond)fresh(t)if err := settings.Save(settings.Settings{Redact: true}); err != nil {t.Fatal(err)@@ -70,9 +71,9 @@ func TestHeldForTheMaskingModelSaysSo(t *testing.T) {if err := provider.Save(provider.Provider{ID: "probe", Name: "Probe", Chat: "http://127.0.0.1:9/v1", Key: "key", Models: []string{"text"}}); err != nil {t.Fatal(err)}- on, busy := modelOn, modelBusy- modelOn, modelBusy = func() bool { return true }, func() string { return "it is still loading" }- t.Cleanup(func() { modelOn, modelBusy = on, busy })+ on := modelOn+ modelOn = func() bool { return true }+ t.Cleanup(func() { modelOn = on })withoutMasker(t)m := waitingMasker{let: make(chan struct{}), left: make(chan struct{})}t.Cleanup(func() { close(m.let) })@@ -82,26 +83,48 @@ func TestHeldForTheMaskingModelSaysSo(t *testing.T) {s := New()srv := httptest.NewServer(s.Handler())t.Cleanup(srv.Close)- c := &http.Client{Timeout: 20 * time.Second}- resp, err := c.Post(srv.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"probe/text","messages":[{"role":"user","content":"hi"}]}`))- if err != nil {- t.Fatal(err)+ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()+ got := make(chan unroutedReply, 1)+ go func() {+ req, _ := http.NewRequestWithContext(ctx, "POST", srv.URL+"/v1/chat/completions", strings.NewReader(`{"model":"probe/text","messages":[{"role":"user","content":"hi"}]}`))+ req.Header.Set("Content-Type", "application/json")+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ got <- unroutedReply{err: err}+ return+ }+ b, _ := io.ReadAll(resp.Body)+ resp.Body.Close()+ got <- unroutedReply{code: resp.StatusCode, body: string(b)}+ }()+ u := watchedHold(t, s)+ if r := heldPast(t, u, 5*unroutedMost, got); r != nil {+ t.Fatalf("a request waiting for the masking model was answered %d %q %v past unroutedMost", r.code, r.body, r.err)}- b, _ := io.ReadAll(resp.Body)- resp.Body.Close()- body := string(b)- if resp.StatusCode != http.StatusGatewayTimeout || !strings.Contains(body, "waiting for the local masking model") ||- !strings.Contains(body, "it is still loading") || !strings.Contains(body, "turn it off in Settings") || strings.Contains(body, "without routing") {- t.Fatalf("held for the model: %d %s", resp.StatusCode, body)+ if u.masking.Load() == 0 {+ t.Fatal("held past unroutedMost, but not while masking")}+ cancel() // the client goes awayselect {case <-m.left:case <-time.After(10 * time.Second):- t.Fatal("the request's wait for the model went on after magpie answered it")+ t.Fatal("the request's wait for the model went on after its client went away")}- rs := routesOf(s, "probe/text")- if len(rs) != 1 || !strings.Contains(rs[0].Error, "waiting for the local masking model") {- t.Fatalf("its route: %+v", rs)+}++// A masking begun as the rest of a request's wait ran out still says it+// waited for the local masking model, what the model was doing and how to+// send without it; and no longer that what the model read is kept, which+// held only for texts it had finished.+func TestUnroutedMsgSaysTheMaskingModel(t *testing.T) {+ on, busy := modelOn, modelBusy+ modelOn, modelBusy = func() bool { return true }, func() string { return "it is still loading" }+ t.Cleanup(func() { modelOn, modelBusy = on, busy })+ m := unroutedMsg(2*time.Minute, true)+ if !strings.Contains(m, "waiting for the local masking model") || !strings.Contains(m, "it is still loading") ||+ !strings.Contains(m, "turn it off in Settings") || strings.Contains(m, "without routing") || strings.Contains(m, "kept") {+ t.Fatalf("held for the model: %s", m)}}diff --git a/internal/gateway/unrouted.go b/internal/gateway/unrouted.goindex 59f4e518b..3ed9b52ab 100644--- a/internal/gateway/unrouted.go+++ b/internal/gateway/unrouted.go@@ -47,6 +47,16 @@ import (// answered then with the same error; one in those waits still has// unroutedMost. 30s is three times the slowest such work a report has// measured (a cold catalog sync, ~8.5s) and leaves a loaded machine room.+//+// Masking's time, its wait for the local model's turn with it, counts+// toward neither (noteMasking). The model is slow but bounded: each piece+// of text it reads has classifyTimeout, a load gpuLoadTimeout or+// loadTimeout, and one that fails holds requests back at once+// (internal/pii). A 480 KB request on an RX 470/580 took 90s of the+// model's work, more on its CPU, and was answered 504 at 2 minutes, its+// work thrown away, however often it was sent again (#3682). What isn't+// masking still has unroutedMost, so a hook or a describe that hangs+// after masking is still answered.var unroutedShow, unroutedUnknown, unroutedMost = 15 * time.Second, 30 * time.Second, 2 * time.Minute// unroutedWatched is whether a request to path is an agent's turn, which@@ -202,6 +212,15 @@ type unroutedHold struct {excused time.Durationdue boolunknown *time.Timer++ // the same for the maskings under way (noteMasking), whose time+ // counts toward unroutedMost no more: how many, since when, the time+ // spent masking before that, and whether most fired while masking+ mwaits int+ msince time.Time+ mexcused time.Duration+ mdue bool+ most *time.Timer}type unroutedKey struct{}@@ -215,7 +234,8 @@ func noteAsked(ctx context.Context, model string) {}// noteMasking tells ctx's watch its request is being masked, until the-// func it answers is called: a wait it knows of.+// func it answers is called: a wait it knows of, whose time counts+// toward neither unroutedUnknown nor unroutedMost.func noteMasking(ctx context.Context) func() {u, _ := ctx.Value(unroutedKey{}).(*unroutedHold)if u == nil {@@ -223,7 +243,65 @@ func noteMasking(ctx context.Context) func() {}u.masking.Add(1)waited := u.wait()- return func() { waited(); u.masking.Add(-1) }+ u.wmu.Lock()+ if u.mwaits == 0 {+ u.msince = time.Now()+ }+ u.mwaits+++ u.wmu.Unlock()+ var once sync.Once+ return func() {+ once.Do(func() {+ u.masking.Add(-1)+ waited()+ u.masked()+ })+ }+}++// masked ends a masking: the last to end adds its time to mexcused, and+// if most fired meanwhile it is set for what is left of it.+func (u *unroutedHold) masked() {+ u.wmu.Lock()+ defer u.wmu.Unlock()+ if u.mwaits--; u.mwaits > 0 {+ return+ }+ now := time.Now()+ u.mexcused += now.Sub(u.msince)+ if u.mdue {+ u.mdue = false+ u.most.Reset(max(unroutedMost-u.unmaskedLocked(now), 0))+ }+}++// unmaskedLocked is how long the request has been held other than+// masking; wmu is held.+func (u *unroutedHold) unmaskedLocked(now time.Time) time.Duration {+ d := now.Sub(u.f.start) - u.mexcused+ if u.mwaits > 0 {+ d -= now.Sub(u.msince)+ }+ return d+}++// checkMost is most's timer: a request held unroutedMost other than+// masking is answered for; one masking now is looked at again when that+// ends, and one with time left, when that is up.+func (u *unroutedHold) checkMost() {+ u.wmu.Lock()+ if u.mwaits > 0 {+ u.mdue = true+ u.wmu.Unlock()+ return+ }+ if left := unroutedMost - u.unmaskedLocked(time.Now()); left > 0 {+ u.most.Reset(left)+ u.wmu.Unlock()+ return+ }+ u.wmu.Unlock()+ u.giveUp(false)}// noteWait tells ctx's watch its request is in a wait magpie knows of@@ -336,14 +414,14 @@ func (s *Server) watchUnrouted(w http.ResponseWriter, r *http.Request, f *infligf.mu.Unlock()u.wmu.Lock()u.unknown = time.AfterFunc(unroutedUnknown, u.checkUnknown)+ u.most = time.AfterFunc(unroutedMost, u.checkMost)u.wmu.Unlock()show := time.AfterFunc(unroutedShow, u.show)- most := time.AfterFunc(unroutedMost, func() { u.giveUp(false) })return u.w, r, func() {show.Stop()- most.Stop()u.wmu.Lock()u.unknown.Stop()+ u.most.Stop()u.wmu.Unlock()f.mu.Lock()// a timer that fired as the handler returned does nothing now@@ -397,7 +475,7 @@ func (u *unroutedHold) routed() (drop *Route) {// giveUp answers the request with an error, when no route was begun for it// and its handler wrote nothing, ends its context, and says on its route// and in the log what held it. unknown: it was held unroutedUnknown in no-// wait magpie knows of, rather than unroutedMost in all.+// wait magpie knows of, rather than unroutedMost other than masking.func (u *unroutedHold) giveUp(unknown bool) {f := u.ff.mu.Lock()@@ -434,14 +512,15 @@ func (u *unroutedHold) giveUp(unknown bool) {// unroutedMsg is the error of a request held for held before routing:// one held while it was masked, with Settings → Privacy's local model on,// waited for that model (#3682), and is told so, and how to send without-// waiting for it.+// waiting for it. Masking's time no longer counts toward unroutedMost,+// so that is a masking begun as the rest of the wait ran out.func unroutedMsg(held time.Duration, masking bool) string {if masking && modelOn() {why := ""if b := modelBusy(); b != "" {why = " (" + b + ")"}- return fmt.Sprintf("magpie held this request for %s waiting for the local masking model (Settings → Privacy) to mask it%s, so it was stopped rather than sent masked by the rules alone. Send it again: what the model has already read is kept, so it goes quicker. To send requests without waiting for the model, turn it off in Settings → Privacy.", held, why)+ return fmt.Sprintf("magpie held this request for %s waiting for the local masking model (Settings → Privacy) to mask it%s, so it was stopped rather than sent masked by the rules alone. Send it again. To send requests without waiting for the model, turn it off in Settings → Privacy.", held, why)}if masking {return fmt.Sprintf("magpie held this request for %s while masking it (Settings → Privacy), before routing it to any provider, so it was stopped rather than left waiting. Send it again; if it keeps happening, restart magpie and report it with magpie's log, which says where it was held.", held)diff --git a/internal/gateway/unrouted_test.go b/internal/gateway/unrouted_test.goindex ad32c6bf2..07ab240c1 100644--- a/internal/gateway/unrouted_test.go+++ b/internal/gateway/unrouted_test.go@@ -423,3 +423,41 @@ func TestUnroutedQuickRequestLeavesNoTrace(t *testing.T) {}}}++// #3682: masking's time counts toward unroutedMost no more, while what+// comes after it still does. A request masked for well past unroutedMost+// isn't answered; then held by an image's description that never ends,+// it is answered 504 once that wait has had unroutedMost.+func TestUnroutedMostLeavesOutMasking(t *testing.T) {+ unroutedLimits(t, 20*time.Millisecond, 300*time.Millisecond)+ s, _ := slowEyed(t, 0)+ heldSight(t, s)+ if err := settings.Save(settings.Settings{Redact: true}); err != nil {+ t.Fatal(err)+ }+ withoutMasker(t)+ m := gatedMasker{gate: make(chan struct{})}+ var once sync.Once+ open := func() { once.Do(func() { close(m.gate) }) }+ t.Cleanup(open)+ t.Cleanup(gwmw.Mask(m))+ srv := httptest.NewServer(s.Handler())+ t.Cleanup(srv.Close)+ got := posted(srv, strings.NewReader(pastedImage))+ u := watchedHold(t, s)+ if r := heldPast(t, u, 3*unroutedMost, got); r != nil {+ t.Fatalf("answered %d %q %v while it was masked", r.code, r.body, r.err)+ }+ if u.masking.Load() == 0 {+ t.Fatal("held past unroutedMost, but not while masking")+ }+ open()+ select {+ case r := <-got:+ if r.code != http.StatusGatewayTimeout || !strings.Contains(r.body, "without routing") {+ t.Fatalf("held after masking: %d %q %v", r.code, r.body, r.err)+ }+ case <-time.After(20 * time.Second):+ t.Fatal("a request held after masking was never answered")+ }+}diff --git a/internal/pii/serve.go b/internal/pii/serve.goindex 39c711214..e42a346e0 100644--- a/internal/pii/serve.go+++ b/internal/pii/serve.go@@ -101,10 +101,10 @@ var loadTimeout = 3 * time.Minute// gpuLoadTimeout is how long it has on a GPU, where it takes seconds// (0.9-10s on an M4 Pro): one that takes longer is taken for hung, and-// the CPU is tried, until the GPU is tried again. It is well under the 2-// minutes the gateway holds a request for (unroutedMost), so a GPU's-// hung load and the CPU's after it fit in one request's wait: with 3-// minutes for either, every request in a hung load was answered 504.+// the CPU is tried, until the GPU is tried again. With 3 minutes for+// either, every request in a hung load waited out the gateway's 2+// minutes and was answered 504; the gateway no longer counts masking's+// time (#3682), and 40s still keeps a hung GPU's wait short.var gpuLoadTimeout = 40 * time.Second// giveUp is when a load is given up on; a test ends one when its state