Files
magpie/internal/gateway/transcribe.go
T
yetone e5dd86965b pii: the masking model's requests take turns without holding the status, Stop or a restart (#3682)
After a restart, with Settings → Privacy's local model on, every request
queued for minutes on srv.mu in classify. That lock was held across
start() (up to 3m loading) and the model's answer (30s and more), and
Now(), Stop() and the idle timer took it too. The user saw a 504
"held this request for 2m0s without routing it to any provider".

Now:
- pf-serve's requests take turns through a one-slot channel (`turn`),
  so writes on its one pipe never interleave. srv.mu only guards state.
  Now() never waits: it reports Loading and how many are Waiting. Stop()
  never waits either: it kills a pf-serve that is loading or answering,
  and the request on it fails with errStopped (no retry). Fetch's
  upgrade stops pf-serve only once its turn is free (stopWhenFree).
- A request waits for its turn under its own context (FindContext). The
  gateway passes the request's context through a new gwmw.ContextTeller,
  so a client that went away, or a request the gateway answered 504,
  leaves the queue. A turn already begun still finishes and caches.
- What Find learned is kept on disk (found-<model sha>.bin, beside the
  model): a text's sha256 and its spans' offsets and labels, never the
  text. Written via temp-and-rename. A bad, cut-short or over-long file
  is read as empty, and a cached span that doesn't fit its text is
  asked again. A restart no longer asks about every history again.
- A request waiting for its turn reads the cache again when it gets it,
  so requests queued with the same history ask the model once.
- The guarantee stays: a request the model can't mask is held back, never
  sent masked by the rules alone. A wait that ends panics inside
  gwmw.Safely, as a failed model did, and the request fails closed.
- The 504 for a request held while masking says it waited for the local
  masking model, what the model was doing (loading, or masking another
  request with N waiting), that what it read is kept, and that the model
  can be turned off in Settings → Privacy (unroutedMsg).

Tests (each red on the fix broken by hand, in the sandbox HOME):
- TestStatusAndStopDontWaitForARequest / ...ForALoad: red with Now()
  taking the turn (Now waited), and the suite hung with Stop() taking it.
- TestWaiterLeavesWhenItsContextEnds: red with the waiter ignoring ctx.
- TestQueuedRequestReadsWhatTheOneAheadLearned: red without the re-read.
- TestRestartReadsWhatWasFound: red with loadCache a no-op. It also
  checks the file never holds the text.
- TestBadCacheFileIsReadAsEmpty: red with a cut-short file's entries kept.
- TestCachedSpanOutsideItsTextIsAskedAgain: red without the fits check.
- gateway TestHeldForTheMaskingModelSaysSo: red with the masker handed
  context.Background() (the wait never let go), without noteMasking, and
  with the old message. TestUnroutedMsgNamesTheModelOnlyWhenItIsOn: red
  with the old message.
- TestMaskingOnAndOff's panicky fixture embeds masking.Masker, which now
  has the Context methods. It panics on those too, and still refuses.

Run at this head (base origin/main 098ac9696, fetched before the commit),
in a sandbox HOME, load ~25:
- go test -timeout 45m -count=1 on internal/pii, internal/redact,
  internal/gwmw, internal/gateway, internal/gui and plugins/redact/...:
  all ok, apart from TestMaskingOnAndOff (the fixture above). After its
  fix, internal/gateway and internal/pii were run again whole: ok.
  internal/masking has no tests.
- go test -race -count=1 ./internal/pii/: ok.
- gofmt -l clean; go vet ./... (darwin); GOOS=linux and GOOS=windows
  go vet -tags nogui on the changed packages and internal/gui, and
  go build -tags nogui ./...: ok.

Not tried:
- A real pf-serve and model: everything above ran against the test's
  stand-in pf-serve. A real cold restart with the model on was not timed,
  and neither was Windows CPU.
- pf-serve is not warmed when magpie starts, so the first request after
  an update to the model still waits for its load. That wait now says so
  and can be left.
- The GUI does not show Loading/Waiting yet; GET /api/privacy-model carries
  them (status.loading, status.waiting).
2026-10-26 14:15:53 +08:00

172 lines
5.0 KiB
Go

package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
"io"
"mime"
"mime/multipart"
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/provider"
)
// transcribe serves OpenAI's speech-to-text APIs (#2053):
// POST /v1/audio/transcriptions and /v1/audio/translations. The body is the
// multipart form OpenAI's take (file, model, language, prompt,
// response_format…); it goes to the model's provider at its OpenAI-style
// base + path as the client sent it, boundary and all, and the vendor's
// answer comes back as it said it, in its own type (json, text, srt, vtt).
// Only the form's model, the provider's own id of it, and a prompt masked
// as the settings say are ever rewritten. It is routed, limited and
// recorded as an embeddings call is (serveRetrieval).
func (s *Server) transcribe(path, operation string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
body, admitted := s.requestBody(w, r, provider.Chat)
if !admitted {
return
}
start := time.Now()
a, err := readAudioForm(r.Header.Get("Content-Type"), body)
if err != nil {
writeError(w, provider.Chat, 400, err.Error())
return
}
if a.model == "" {
writeError(w, provider.Chat, 400, "name the model: the form's \"model\" is a magpie model id, provider/model (openai/whisper-1, groq/whisper-large-v3)")
return
}
s.serveRetrieval(w, r, path, operation, start, a.model, a)
}
}
// audioForm is a speech-to-text request: its multipart body as sent, and
// the fields magpie reads or may rewrite.
type audioForm struct {
raw []byte
ctype string // as sent, its boundary in it
boundary string
model string
prompt string
// masked is the prompt as it goes to a vendor, when masking changed it
masked *string
}
// readAudioForm reads the form's model and prompt; the rest of it, the
// audio among it, is left as it is.
func readAudioForm(ctype string, body []byte) (*audioForm, error) {
mt, params, err := mime.ParseMediaType(ctype)
if err != nil || mt != "multipart/form-data" || params["boundary"] == "" {
return nil, errors.New("send the audio as multipart/form-data, as OpenAI's /v1/audio/transcriptions takes it: a file and a model")
}
a := &audioForm{raw: body, ctype: ctype, boundary: params["boundary"]}
mr := multipart.NewReader(bytes.NewReader(body), a.boundary)
for {
p, err := mr.NextRawPart()
if err == io.EOF {
break
}
if err != nil {
return nil, errors.New("the multipart form doesn't parse: " + err.Error())
}
switch p.FormName() {
case "model", "prompt":
if p.FileName() != "" {
continue
}
v, err := io.ReadAll(io.LimitReader(p, 1<<20))
if err != nil {
return nil, errors.New("the multipart form doesn't parse: " + err.Error())
}
if p.FormName() == "model" {
a.model = strings.TrimSpace(string(v))
} else {
a.prompt = string(v)
}
}
}
return a, nil
}
// mask masks the prompt, the form's only text a vendor is sent; the
// audio can't be, and the transcript gets the masked values back.
func (a *audioForm) mask(ctx context.Context, w http.ResponseWriter) (http.ResponseWriter, func(), maskHits, string, error) {
if a.prompt == "" {
return w, func() {}, maskHits{}, "", nil
}
w, masked, done, hits, err := redactedPromptHits(ctx, w, a.prompt)
if masked != a.prompt {
a.masked = &masked
}
return w, done, hits, masked, err
}
// forModel is the form as sent when nothing in it changes; otherwise it is
// written again part by part, under the same boundary, with the model the
// provider's own id and the prompt masked.
func (a *audioForm) forModel(model string) ([]byte, string, error) {
if model == a.model && a.masked == nil {
return a.raw, a.ctype, nil
}
var buf bytes.Buffer
mw := multipart.NewWriter(&buf)
if err := mw.SetBoundary(a.boundary); err != nil {
return nil, "", err
}
mr := multipart.NewReader(bytes.NewReader(a.raw), a.boundary)
for {
p, err := mr.NextRawPart()
if err == io.EOF {
break
}
if err != nil {
return nil, "", errors.New("the multipart form doesn't parse: " + err.Error())
}
pw, err := mw.CreatePart(p.Header)
if err != nil {
return nil, "", err
}
switch {
case p.FormName() == "model" && p.FileName() == "":
io.WriteString(pw, model)
case p.FormName() == "prompt" && p.FileName() == "" && a.masked != nil:
io.WriteString(pw, *a.masked)
default:
if _, err := io.Copy(pw, p); err != nil {
return nil, "", err
}
}
}
if err := mw.Close(); err != nil {
return nil, "", err
}
return buf.Bytes(), mw.FormDataContentType(), nil
}
// answerType is the vendor's own: a transcript asked as text, srt or vtt
// is no JSON.
func (a *audioForm) answerType(got string) string {
if got == "" {
return "application/json"
}
return got
}
// answeredTokens is the output tokens an answer says it counted:
// gpt-4o-transcribe's usage.output_tokens; whisper's answer counts none.
func answeredTokens(b []byte) int {
var a struct {
Usage struct {
Output int `json:"output_tokens"`
} `json:"usage"`
}
if json.Unmarshal(b, &a) != nil {
return 0
}
return a.Usage.Output
}