Files
magpie/internal/gateway/observe.go
T
yetoneandreyoung 4314f4b776 otel: export the gateway key's name as magpie.gateway_key.name (#5751)
reyoung (#5751) shares one magpie through several gateway keys and wants
requests in Langfuse or another collector told apart by key. The ledger
row already had CallerKeyName, but the OTLP allow-list dropped it, and
the observer's root and attempt records never carried it.

Ported from reyoung's 9d82162aa (reyoung/magpie feat/otel-gateway-key-name),
applied unchanged onto current main:
- observeRequest takes access.Caller(r).KeyName when observing begins
  and puts it on every End and Attempt record (CallerKeyName), so the
  root span and every try (failures, retries, fallbacks) carry it with
  no lookup at export time.
- otlp's allow-list grows by this one attribute, on generation and
  ledger spans (otelAttributes, so the duration and token histograms
  too) and on the root span. Omitted when the name is empty. The key's
  id and secret are never sent; provider account names stay out.
- docs/reference.md, plugin-runtime.md and the en/zh/ja privacy pages
  say the name goes to the user's collector.

Added on top: docs/reference.md says each key name multiplies a
metric's series, and that keys sharing a name are counted together.

Review of the fork (read every line; run only on mote): no new address,
dependency or credential; the name is read from the auth context at
request time, the same source appendUsage uses for the ledger row;
reported rows (another computer's) already have the caller key cleared
and never reach observers; session spans of local transcripts have no
key. READMEs (en, zh) mention OTLP only as a feature, with no list of
what is sent, so they are unchanged.

Run on mote (lockf ~/suite.lock), at base c7ebb6f8d plus this change:
- gofmt -l internal/gateway internal/otlp: clean.
- go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go
  vet ./...: ok.
- go test ./internal/otlp ./internal/gateway -run 'TestOTel|TestObserve':
  ok.
- go test -count=1 -timeout 45m ./internal/otlp ./internal/gateway
  ./plugins/otel: ok.
- go test -count=1 -timeout 45m ./... (macOS): every package ok (92),
  exit 0.

Rebased onto 136178803 after that run (5 commits; gateway.go and
prev_response.go, nothing in observe.go, otel*.go or internal/otlp).
The touched packages' run at the pushed head is queued behind mote's
suite lock and was not done before the push.

Broken by hand (each on mote, then restored):
- observeRequest without the name (o := &observed{}):
  TestOTelExportsGatewayKeyName/true red, "span 0: gateway key name ""
  seen 0 times".
- gatewayKeyAttr returning before adding the attribute:
  TestOTelBatchWireAndPrivacy red (attributes lack
  magpie.gateway_key.name) and TestOTelExportsGatewayKeyName/true red.

Not tried: a real Langfuse collector; Windows and Linux runtime runs (vet
only); the site pages are not deployed by this commit.

Co-authored-by: reyoung <728699+reyoung@users.noreply.github.com>
2026-11-09 17:21:48 +08:00

119 lines
4.2 KiB
Go

package gateway
import (
"context"
"net/http"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/usage"
)
// observed is a request the registered observers watch (usage.Observer,
// the gateway's observer point): what each one's Begin answered.
type observed struct {
watches []usage.Watch
routeID int64
// keyName is the gateway key the request came with, by the name the
// user gave it (access.Identity.KeyName), never its secret; "" without
// one. Each span carries it as the ledger's row does (CallerKeyName).
keyName string
}
type observedKey struct{}
// observeRequest asks each observer whether it watches the request. With
// none watching it is nil, and its calls do nothing.
func observeRequest(r *http.Request, kind string, body []byte) (*http.Request, *observed) {
observers := usage.Observers()
if len(observers) == 0 {
return r, nil
}
// the agent it is recorded as, another magpie's own (callerFrom)
agent := callerOf(r).agent
who := access.Caller(r.Context())
q := usage.Request{Header: r.Header, Agent: agent, Session: observedSession(r.Header), Kind: observedKind(agent, kind, body),
Plain: local(r) && who.KeyID == "" && callerOf(r).via == ""}
o := &observed{keyName: who.KeyName}
for _, ob := range observers {
if w := ob.Begin(q); w != nil {
o.watches = append(o.watches, w)
}
}
if len(o.watches) == 0 {
return r, nil
}
return r.WithContext(context.WithValue(r.Context(), observedKey{}, o)), o
}
// Prefer the native client session: routing overrides need not name its store.
func observedSession(h http.Header) string {
if id := nativeSessionOf(h); id != "" {
return id
}
return sessionOf(h)
}
// Claude's tool-less small tasks (titles, suggestions, haiku helpers) may
// reuse the parent session but aren't recorded in its transcript. Keep their
// gateway spans; a model name alone doesn't identify a helper or a subagent.
func observedKind(agent, kind string, body []byte) string {
if kind == "" && (agent == "claude" || agent == "claude-desktop") && small(body) && !hasTools(body) {
return "auxiliary"
}
return kind
}
func (o *observed) end(call Call, millis int64) {
if o == nil {
return
}
rec := usage.Record{RouteID: o.routeID, Time: call.Time, Agent: call.Agent, Model: call.Model, Status: call.Status, Millis: millis, CallerKeyName: o.keyName}
canceledAs(&rec, call.Status, call.Error)
for _, w := range o.watches {
w.End(rec)
}
}
// Called for every routing attempt, including unbilled failures and retries.
// Its timing is the attempt's, not the whole request's ledger duration.
func (o *observed) attempt(call Call, attempt Try, providerID, effort string, held *holdWriter, capture *captureResponseWriter) {
if o == nil {
return
}
u := call.Usage.billed()
rec := usage.Record{RouteID: o.routeID, Time: attempt.Start, Agent: call.Agent,
Provider: providerID, Model: attempt.Model, Requested: call.Model, Served: u.Served, Effort: effort,
Input: u.Input, Output: u.Output, CacheRead: u.CacheRead, CacheWrite: u.CacheWrite, CacheUnknown: u.cacheNotCounted(), Reasoning: u.Reasoning,
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden, CallerKeyName: o.keyName}
canceledAs(&rec, attempt.Status, attempt.Error)
if wanted := usage.ObservedBodies(); wanted != usage.NoBodies {
reply, cut := capture.body.text(), capture.body.truncated
if !held.passing {
data := held.held.Bytes()
cut = len(data) > callBodyLimit
reply = string(data[:min(len(data), callBodyLimit)])
}
// Apply the same capture limit and masking to held responses.
var body capturedBody
body.add([]byte(reply))
bodies := call
bodies.ResponseBody, bodies.ResponseTruncated = body.text(), cut || body.truncated
if wanted == usage.WholeBodies {
if !held.passing {
bodies.wholeOut = held.held.Bytes()
bodies.wholeOutCut = false
} else if capture.whole != nil {
bodies.wholeOutCut = capture.whole.cut()
if data, err := capture.whole.read(); err == nil {
bodies.wholeOut = data
}
}
}
withBodies(&rec, &bodies)
}
for _, w := range o.watches {
w.Attempt(rec)
}
}