Files
magpie/internal/gateway/otel.go
T
geoqiao 3a9d73c5c6 gateway: a plugin's deferred usage is billed with its step, never told as the prompt
The Cursor plugin collects a tool step's late usage event with the
conversation's next step. It used to add it to that step's prompt_tokens,
which agents read as how full their context is: pi saw 366940 tokens
(181270 + 185670) on a 300k window where 185670 were in use, and compacted.
The plugin now reports it apart, as usage.magpie_deferred (yetone/magpie#1053).

The gateway parses the field into Usage.Deferred and adds it only where it
bills: the usage records (6 sites in serve), the OTel attempt span and route
pricing, as a tier before the request's own, so promptCounted still reads the
request's own prompt. What a client is told (Usage.chat, the Anthropic
encoding) stays the request's own. A reply without the field is handled as
before. docs/subsystems/provider-plugins.md describes the field.

Verified: go test -tags nogui ./... (50 packages ok, sandbox HOME, caches
pinned); gofmt; go vet on darwin, linux (nogui) and windows; go build on the
same three. The new tests were broken by hand and each went red: billed()
ignoring Deferred, cUsage dropping the field, routeUsage without the tier,
Usage.add forgetting it, the decoder ignoring a usage with only a deferred
part, the usage records and the OTel span not using billed(). Not tried: a
real Cursor account on this checkout; the plugin side was run against real
Cursor (composer-2.5, forced late events), where the deferred totals matched
the dashboard's events token for token.

Picked from geoqiao/magpie cursor-deferred-usage (595d6384c), as PRs here
are collaborators-only. Rebased over the service-tier logging (#1784),
keeping its TierAsked/TierSent/TierServed beside billed() at the three
usage.Record sites, and Usage's Tier beside Deferred. Run on this tree:
go test -tags nogui -timeout 40m ./internal/gateway and ./internal/provider
(sandbox HOME); gofmt -l; go vet darwin, GOOS=linux -tags nogui,
GOOS=windows. billed() forced to ignore Deferred: 3 tests and 5 subtests
of deferred_usage_test.go go red.
2026-10-13 14:50:48 +08:00

146 lines
4.9 KiB
Go

package gateway
import (
"context"
"crypto/rand"
"encoding/hex"
"net/http"
"strings"
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/usage"
)
type otelRequestKey struct{}
type otelRequest struct {
root usage.OTelSpan
routeID int64
agent, session string
sessionCandidate, decided, suppressed bool
}
// Decide once, before exporting any attempt, so a transcript discovered
// during the request cannot leave an exported attempt without its root.
func (t *otelRequest) skip() bool {
if t == nil {
return true
}
if !t.decided {
t.suppressed = t.sessionCandidate && usage.OTelSessionFresh(t.agent, t.session)
t.decided = true
}
return t.suppressed
}
func otelID(size int) string {
b := make([]byte, size)
rand.Read(b)
return hex.EncodeToString(b)
}
// Accept W3C version 00 only; malformed or zero IDs start a fresh trace.
// Context is used locally and never forwarded with provider credentials.
func otelParent(value string) (traceID, parentID string) {
parts := strings.Split(value, "-")
if len(parts) != 4 || parts[0] != "00" || len(parts[1]) != 32 || len(parts[2]) != 16 || len(parts[3]) != 2 {
return "", ""
}
for _, part := range parts[1:] {
if strings.ToLower(part) != part {
return "", ""
}
if _, err := hex.DecodeString(part); err != nil {
return "", ""
}
}
if parts[1] == strings.Repeat("0", 32) || parts[2] == strings.Repeat("0", 16) {
return "", ""
}
return parts[1], parts[2]
}
// Prefer the native client session: routing overrides need not name its store.
func otelSessionOf(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 otelCallKind(agent, kind string, body []byte) string {
if kind == "" && (agent == "claude" || agent == "claude-desktop") && small(body) && !hasTools(body) {
return "auxiliary"
}
return kind
}
func beginOTelRequest(r *http.Request, kind string, body []byte) (*http.Request, *otelRequest) {
if !usage.OTelEnabled() {
return r, nil
}
agent, session := agentOf(r), otelSessionOf(r.Header)
candidate := kind == "" && local(r) && access.Caller(r.Context()).KeyID == "" && callerOf(r).via == "" && otelCallKind(agent, kind, body) == ""
if candidate && usage.OTelSession(agent, session) {
return r, nil
}
traceID, parentID := otelParent(r.Header.Get("traceparent"))
if traceID == "" {
traceID = otelID(16)
}
t := &otelRequest{root: usage.OTelSpan{TraceID: traceID, SpanID: otelID(8), ParentID: parentID, Root: true}, agent: agent, session: session, sessionCandidate: candidate}
return r.WithContext(context.WithValue(r.Context(), otelRequestKey{}, t)), t
}
func (t *otelRequest) end(call Call, millis int64) {
if t.skip() {
return
}
t.root.End = time.Now()
usage.ExportOTel(usage.Record{OTel: &t.root, RouteID: t.routeID, Time: call.Time, Agent: call.Agent, Model: call.Model, Status: call.Status, Millis: millis})
}
// Called for every routing attempt, including unbilled failures and retries.
// Its timing is the attempt's, not the whole request's ledger duration.
func (t *otelRequest) attempt(call Call, attempt Try, providerID, effort string, held *holdWriter, capture *captureResponseWriter) {
if t.skip() {
return
}
span := &usage.OTelSpan{TraceID: t.root.TraceID, SpanID: otelID(8), ParentID: t.root.SpanID, End: time.Now()}
u := call.Usage.billed()
rec := usage.Record{OTel: span, RouteID: t.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, Reasoning: u.Reasoning,
Millis: time.Since(attempt.Start).Milliseconds(), Status: attempt.Status, TTFT: attempt.TTFT, FirstText: attempt.FirstText, FirstReasoning: attempt.FirstReasoning, ReasoningHidden: attempt.ReasoningHidden}
if usage.OTelBodies() {
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 usage.OTelWhole() {
if !held.passing {
bodies.otelOut = held.held.Bytes()
bodies.otelOutCut = false
} else if capture.otel != nil {
bodies.otelOutCut = capture.otel.cut()
if data, err := capture.otel.read(); err == nil {
bodies.otelOut = data
}
}
}
withBodies(&rec, &bodies)
}
usage.ExportOTel(rec)
}