Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 94 additions & 14 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1548,9 +1548,14 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
input != nil && len(messages) == 0, policy, allowedProviderSerials) {
return
}
// Reject remote/non-data: media URLs pre-dispatch (the provider VLM path is
// data:-only): one clean 400 instead of dispatching and 400ing across the fleet.
if s.rejectRemoteMediaURLs(w, r, parsed, model, publicModel, requiresVision, hasTools) {
// Remote media URL gate (phase 1, pre-billing). With the media resolver
// enabled (default), remote http(s) image_url/video_url links are fetched
// and inlined as data: URIs AFTER the balance reservation (resolveRemoteMedia
// below); here we fail fast only the cases that must never fetch: sealed
// requests, remote refs in shapes the resolver doesn't handle, and the
// resolver-disabled fallback (the legacy one-clean-400, the provider VLM
// path being data:-only).
if s.gateRemoteMediaPreDispatch(w, r, parsed, model, publicModel, requiresVision, hasTools) {
return
}

Expand Down Expand Up @@ -1724,17 +1729,49 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
return
}

// Shared routing/capacity admission preflight (self-route / prefer / public
// capacity+TTFT gate — see runInferenceAdmission). On the chat path an alias
// fallback must refresh the threaded rawBody: re-lowering Responses input→chat
// when applicable, which can itself fail with a 400. Thread that as the
// onModelFallback callback; resolvedModel uses the new build to match the
// pre-extraction behavior.
onModelFallback := func(newModel string) bool {
rawBody, _ = marshalForwardBody(parsed)
// Resolve remote http(s) image_url/video_url links into inline base64 data:
// URIs (phase 2 — see media_resolve.go) — AFTER token admission, the balance
// reservation, and the catalog check, so network I/O is gated behind the
// cost gates: an authenticated but unfunded/over-quota request (or one for a
// nonexistent model) can never drive coordinator-side fetches. The token &
// routing estimates above count media parts flatly (300/1500 per part), so
// they don't need the inlined bytes. The billing reservation is refunded on
// any failure, and topped up below on success — it was taken while the media
// was still a ~100-byte URL. parsed is mutated in place, so every view
// derived from the pre-inline body is refreshed via refreshForwardBody.
var mediaInlined bool
rawBody, mediaInlined, ok = s.resolveRemoteMedia(w, r, rawBody, parsed, timing, mediaResolveMeta{

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Move public availability admission ahead of media fetching

For an ordinary paid-fleet request whose catalog model currently has no eligible vision provider or capacity, this call downloads and inlines up to the configured media limits before runInferenceAdmission performs the capacity/eligibility rejection at line 1846. The initial balance hold is then refunded by that rejection, so a funded account can repeatedly consume coordinator egress while only receiving 429/503 responses rather than incurring inference cost. Fresh evidence beyond the earlier self-route comment is that the same ordering remains on the public route despite its refundable reservation; perform an availability preflight before fetching and retain the later check for races.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Half of this is already gated, and the other half is a deliberate tradeoff — documented in T-049 rather than changed in code.

Fleet eligibility is checked before any fetch: visionToolsFailFast calls HasVisionProviderForModel (inference_preprocess.go:220) and HasToolCapableProviderForModel, and it runs at consumer.go:1545 — ~200 lines ahead of the media gate. A model with no eligible vision provider gets a 503 with zero egress today.

What remains is transient capacity: providers exist and are eligible but are momentarily full. Two reasons not to duplicate the preflight: (1) runInferenceAdmission needs the POST-inline traits — MinPrefixCacheProtocol is derived from body size, and deriving it from the pre-inline URL body is exactly the bug fixed in c503404 — so an earlier copy would answer from the wrong body or need permanent syncing with the real gate, and would still race; (2) token-rate admission is charged before the fetch and is never refunded, so repeat probing burns the caller's ITPM quota even though the monetary hold comes back.

Recorded as an accepted residual in T-049 with that reasoning, so it is visible to the next reviewer rather than implicit.

model: model,
publicModel: publicModel,
stream: stream,
estimatedPromptTokens: estimatedPromptTokens,
requestedMaxTokens: requestedMaxTokens,
hasTools: hasTools,
requiresVision: requiresVision,
selfRoute: policy.enabled,
ownerAccountID: policy.ownerAccountID,
traits: routingTraits,
})
if !ok {
refundReservation()
// Token-rate admission is intentionally NOT refunded: this matches every
// other post-admission validation failure and makes blocked/invalid URL
// probes consume the caller's input/output token quota.
return
}

// refreshForwardBody re-derives every view of the provider-bound request from
// a freshly marshaled `parsed`: the threaded rawBody, the body actually
// forwarded to the provider (re-lowered input→chat on the Responses surface,
// which can itself fail with a 400), and the routing traits computed from it.
// Any in-place mutation of `parsed` MUST go through it — an alias fallback
// rewriting the model, or remote media being inlined as data: URIs. Returns
// false after writing a terminal response.
refreshForwardBody := func(body []byte, forModel string) bool {
rawBody = body
if !isResponsesAPI {
providerBody = rawBody
routingTraits = routingTraitsForModel(newModel)
routingTraits = routingTraitsForModel(forModel)
return true
}
var err error
Expand All @@ -1749,7 +1786,7 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
keyID: keyIDFromContext(r.Context()),
consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())),
requestedModel: publicModel,
resolvedModel: newModel,
resolvedModel: forModel,
stream: stream,
estimatedPromptTokens: estimatedPromptTokens,
requestedMaxTokens: requestedMaxTokens,
Expand All @@ -1760,9 +1797,52 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", err.Error()))
return false
}
routingTraits = routingTraitsForModel(newModel)
routingTraits = routingTraitsForModel(forModel)
return true
}

// Remote media was fetched and inlined into `parsed` above, so `providerBody`
// (captured before the resolve) and the routing traits derived from it now
// describe a body that no longer exists. Without this refresh the coordinator
// pays for the fetch and then seals and dispatches the ORIGINAL body still
// carrying the http(s) URL, which the provider's data:-only guard rejects.
if mediaInlined {
if !refreshForwardBody(rawBody, model) {
return
}
// The reservation was taken against a body where the image was a short
// URL, so estimateBillingPromptTokens — the guaranteed len(bytes) >= tokens
// upper bound the settlement path relies on — was computed over ~100 bytes
// of URL instead of the inlined media. Re-reserve against the real body
// before dispatch; otherwise settlement's 2x-reservation overage clamp
// silently absorbs the difference and underpays the provider.
var topUpHandled bool
reservedMicroUSD, topUpHandled = s.topUpReservationForInlinedMedia(w, r, parsed, balanceReservationParams{
model: model,
publicModel: publicModel,
billingPromptTokens: estimateBillingPromptTokens(parsed),
estimatedPromptTokens: estimatedPromptTokens,
requestedMaxTokens: requestedMaxTokens,
stream: stream,
requiresVision: requiresVision,
hasTools: hasTools,
policy: policy,
}, reservedMicroUSD)
if topUpHandled {
refundReservation()
return
}
}

// Shared routing/capacity admission preflight (self-route / prefer / public
// capacity+TTFT gate — see runInferenceAdmission). On the chat path an alias
// fallback must refresh the threaded rawBody; thread that as the
// onModelFallback callback. resolvedModel uses the new build to match the
// pre-extraction behavior.
onModelFallback := func(newModel string) bool {
body, _ := marshalForwardBody(parsed)
return refreshForwardBody(body, newModel)
}
var preflightHandled bool
model, preflightHandled = s.runInferenceAdmission(w, r, parsed, inferenceAdmissionParams{
model: model,
Expand Down
73 changes: 60 additions & 13 deletions coordinator/api/consumer_media_url_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package api

import "testing"
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"unicode/utf8"
)

// C4: media parts carrying a remote/non-data: URL must be detected so the
// coordinator can reject them pre-dispatch (the provider VLM path is data:-only).
Expand Down Expand Up @@ -64,20 +70,61 @@ func TestValidateMediaParts_RejectsRemote(t *testing.T) {
}
}

func TestVisionRejectRemoteEnabled_KillSwitch(t *testing.T) {
if !visionRejectRemoteEnabled() {
t.Error("default (unset) must be ON")
// TestRejectRemoteMediaURLsIsUnconditional pins the gate as unconditional on
// every surface. The generic (completions + Anthropic) surface never fetches,
// so forwarding a remote URL there can only end in a provider-side 400 — the
// retired DARKBLOOM_VISION_REJECT_REMOTE_URLS switch must never re-enable it.
func TestRejectRemoteMediaURLsIsUnconditional(t *testing.T) {
s := &Server{logger: quietLogger()}
remotePart := map[string]any{"type": "image_url", "image_url": map[string]any{"url": "https://example.com/x.png"}}
remote := map[string]any{"messages": []any{msg([]any{remotePart})}}

// The retired flag is read nowhere: no value of it may disable the gate.
for _, flag := range []string{"", "false", "0", "true"} {
t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", flag)
w := httptest.NewRecorder()
if !s.rejectRemoteMediaURLs(w, plainReq(), remote, "test", "test", true, false) {
t.Fatalf("flag=%q: a remote media URL must always be rejected pre-dispatch", flag)
}
if w.Code != http.StatusBadRequest {
t.Errorf("flag=%q: status = %d, want 400", flag, w.Code)
}
}
t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "false")
if visionRejectRemoteEnabled() {
t.Error("=false must disable")

// Unconditional on the flag, still conditional on the request: non-vision
// bodies and inline data: URIs pass untouched.
if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), remote, "test", "test", false, false) {
t.Error("non-vision requests must never be gated")
}
t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "0")
if visionRejectRemoteEnabled() {
t.Error("=0 must disable")
inline := map[string]any{"messages": []any{msg([]any{
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,AAAA"}},
})}}
if s.rejectRemoteMediaURLs(httptest.NewRecorder(), plainReq(), inline, "test", "test", true, false) {
t.Error("inline data: URI must pass")
}
t.Setenv("DARKBLOOM_VISION_REJECT_REMOTE_URLS", "true")
if !visionRejectRemoteEnabled() {
t.Error("=true must enable")
}

func TestTruncateMediaRef(t *testing.T) {
// "é" is 2 bytes; placed at offset 199 it straddles the 200-byte cut, so a
// naive ref[:200] ends on a partial rune that encoding/json renders U+FFFD.
straddling := strings.Repeat("a", 199) + "é" + strings.Repeat("b", 50)
cases := []struct {
name string
ref string
want string
}{
{"short ref verbatim", "https://example.com/a.png", "https://example.com/a.png"},
{"exactly at the cap verbatim", strings.Repeat("a", 200), strings.Repeat("a", 200)},
{"ascii over the cap", strings.Repeat("a", 201), strings.Repeat("a", 200) + "…"},
{"multibyte rune straddling the cut is dropped", straddling, strings.Repeat("a", 199) + "…"},
}
for _, c := range cases {
got := truncateMediaRef(c.ref)
if got != c.want {
t.Errorf("%s: truncateMediaRef() = %q, want %q", c.name, got, c.want)
}
if !utf8.ValidString(got) {
t.Errorf("%s: truncateMediaRef() emitted invalid UTF-8: %q", c.name, got)
}
}
}
39 changes: 29 additions & 10 deletions coordinator/api/dispatch.go
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,15 @@ func applyTimingDecomposition(out *store.InferenceRouteOutcome, t *registry.Requ
}
out.ParseMs = timingMsBetween(t.ReceivedAt, t.ParsedAt)
out.ReserveMs = timingMsBetween(t.ParsedAt, t.ReservedAt)
out.RouteMs = timingMsBetween(t.ReservedAt, t.RoutedAt)
// Remote-media fetch (when it happened) sits between ReservedAt and
// RoutedAt; anchor the route segment past it so a multi-second download
// doesn't masquerade as routing latency. The fetch duration itself is
// reported via the X-Timing header and DD histogram (no outcome column).
routeAnchor := t.ReservedAt
if !t.MediaFetchedAt.IsZero() {
routeAnchor = t.MediaFetchedAt
}
out.RouteMs = timingMsBetween(routeAnchor, t.RoutedAt)
out.EncryptMs = timingMsBetween(t.RoutedAt, t.EncryptedAt)
out.QueueWaitMs = timingMsBetween(t.QueuedAt, t.DispatchedAt)
out.DispatchMs = timingMsBetween(t.DispatchedAt, firstChunk)
Expand Down Expand Up @@ -2882,13 +2890,17 @@ func (d *dispatchState) writeCommittedResponse() {
// Latency decomposition header for observability.
if timing := pr.Timing; timing != nil {
type timingJSON struct {
ParseUs int64 `json:"parse_us"`
ReserveUs int64 `json:"reserve_us"`
RouteUs int64 `json:"route_us"`
QueueUs int64 `json:"queue_us"`
EncryptUs int64 `json:"encrypt_us"`
DispatchUs int64 `json:"dispatch_us"`
ProviderUs int64 `json:"provider_us"`
ParseUs int64 `json:"parse_us"`
ReserveUs int64 `json:"reserve_us"`
// MediaFetchUs covers the post-reservation remote media download +
// inline step (media_resolve.go); omitted for the (typical) request
// that fetched nothing.
MediaFetchUs int64 `json:"media_fetch_us,omitempty"`
RouteUs int64 `json:"route_us"`
QueueUs int64 `json:"queue_us"`
EncryptUs int64 `json:"encrypt_us"`
DispatchUs int64 `json:"dispatch_us"`
ProviderUs int64 `json:"provider_us"`
}
tj := timingJSON{}
if !timing.ParsedAt.IsZero() {
Expand All @@ -2897,8 +2909,15 @@ func (d *dispatchState) writeCommittedResponse() {
if !timing.ReservedAt.IsZero() && !timing.ParsedAt.IsZero() {
tj.ReserveUs = timing.ReservedAt.Sub(timing.ParsedAt).Microseconds()
}
if !timing.RoutedAt.IsZero() && !timing.ReservedAt.IsZero() {
tj.RouteUs = timing.RoutedAt.Sub(timing.ReservedAt).Microseconds()
// Media fetch (when present) sits between reserve and route; anchor the
// route segment past it so a download never inflates route_us.
routeAnchor := timing.ReservedAt
if !timing.MediaFetchedAt.IsZero() && !timing.ReservedAt.IsZero() {
tj.MediaFetchUs = timing.MediaFetchedAt.Sub(timing.ReservedAt).Microseconds()
routeAnchor = timing.MediaFetchedAt
}
if !timing.RoutedAt.IsZero() && !routeAnchor.IsZero() {
tj.RouteUs = timing.RoutedAt.Sub(routeAnchor).Microseconds()
}
if !timing.QueuedAt.IsZero() && !timing.DispatchedAt.IsZero() {
tj.QueueUs = timing.DispatchedAt.Sub(timing.QueuedAt).Microseconds()
Expand Down
80 changes: 79 additions & 1 deletion coordinator/api/inference_admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,13 @@ func (s *Server) reserveInferenceBalance(w http.ResponseWriter, r *http.Request,
return 0, false, false
}
consumerKey := consumerKeyFromContext(r.Context())
reservedMicroUSD = s.reservationCost(p.model, p.billingPromptTokens, p.requestedMaxTokens)
// Normally the byte-count billing bound dominates the routing estimate. A
// remote media URL is the exception: its short URL is rewritten after this
// gate into hundreds/thousands of vision soft tokens. Reserve against the
// larger bound so a low-balance caller cannot trigger coordinator egress and
// only then fail the platform-price balance check.
reservationPromptTokens := max(p.billingPromptTokens, p.estimatedPromptTokens)
Comment on lines +61 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] 🔒 Potential integer overflow in reservation cost calculation

💡 Suggestion: Add bounds checking before max() operation to prevent overflow when estimatedPromptTokens is extremely large

📊 Score: 3×4 = 12 · Category: missing-input-validation

Comment on lines +61 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ max() function call on every request creates unnecessary allocation overhead

💡 Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path

📊 Score: 3×4 = 12 · Category: unbounded_allocations

Comment on lines +61 to +66

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 [MEDIUM] ⚡ max() function call on every request creates unnecessary allocation overhead

💡 Suggestion: Pre-compute the maximum value or use a simple conditional to avoid function call overhead on the hot path

📊 Score: 3×4 = 12 · Category: unbounded_allocations

reservedMicroUSD = s.reservationCost(p.model, reservationPromptTokens, p.requestedMaxTokens)
// Per-key spend cap (phase 1) — checked before the reservation so a capped
// key never debits the account ledger.
if msg, ok := s.checkKeySpendCap(r.Context(), reservedMicroUSD); !ok {
Expand Down Expand Up @@ -112,6 +118,78 @@ func (s *Server) reserveInferenceBalance(w http.ResponseWriter, r *http.Request,
return reservedMicroUSD, serviceReservation, false
}

// topUpReservationForInlinedMedia re-reserves after remote media has been
// fetched and inlined into parsed.
//
// reserveInferenceBalance runs BEFORE the fetch (deliberately — network I/O must
// stay behind the cost gates), so for a remote media URL it reserves against a
// body where the image is ~100 bytes of URL text. That breaks the invariant the
// rest of the money path depends on: estimateBillingPromptTokens is documented
// as a guaranteed upper bound (len(bytes) >= tokens for any BPE tokenizer), and
// for an inline data: URI it is. The flat routing floor (300 image / 1500 video
// soft tokens) is NOT an upper bound — a provider samples up to 32 video frames
// at ~282 soft tokens each — and settlement clamps any overage at 2x the
// reservation as a fraud circuit-breaker, so the shortfall is silently written
// off AND the provider payout is recomputed from the clamped total. Recomputing
// the byte bound over the inlined body restores the guarantee.
//
// p.billingPromptTokens must already be recomputed from the mutated parsed.
// Returns the reservation now held (unchanged when no top-up was needed or when
// the top-up failed) and handled=true after writing a terminal response, in
// which case the caller must refund and return.
func (s *Server) topUpReservationForInlinedMedia(w http.ResponseWriter, r *http.Request, parsed map[string]any, p balanceReservationParams, currentMicroUSD int64) (reservedMicroUSD int64, handled bool) {
// Same skips as reserveInferenceBalance: self-route is free and a nil billing
// backend never reserved anything to top up.
if s.billing == nil || p.policy.enabled || currentMicroUSD <= 0 {
return currentMicroUSD, false
}
want := s.reservationCost(p.model, max(p.billingPromptTokens, p.estimatedPromptTokens), p.requestedMaxTokens)
if want <= currentMicroUSD {
return currentMicroUSD, false
}
reject := func(reasonCode, code, msg string) {
s.recordRejection(rejectionInfo{
r: r,
stage: "balance",
reasonCode: reasonCode,
httpStatus: http.StatusPaymentRequired,
keyID: keyIDFromContext(r.Context()),
consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())),
requestedModel: p.publicModel,
resolvedModel: p.model,
stream: p.stream,
estimatedPromptTokens: p.estimatedPromptTokens,
requestedMaxTokens: p.requestedMaxTokens,
requiresVision: p.requiresVision,
hasTools: p.hasTools,
params: rejectionSamplingParams(parsed),
})
s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:rejected"})
writeJSON(w, http.StatusPaymentRequired, errorResponse(code, msg, withCode("insufficient_quota")))
}
// Cap check against the new TOTAL, matching reserveAdditionalForProvider.
if msg, ok := s.checkKeySpendCap(r.Context(), want); !ok {
reject("insufficient_quota", "insufficient_quota", msg)
return currentMicroUSD, true
}
consumerKey := consumerKeyFromContext(r.Context())
// Charge only the delta; reserveInitialBalance re-derives the same
// service-vs-ledger mode for this account, so the hold stays consistent.
if _, err := s.reserveInitialBalance(consumerKey, p.model, want-currentMicroUSD); err != nil {
if errors.Is(err, store.ErrInsufficientBalance) {
reject("insufficient_funds", "insufficient_funds",
"your balance is too low for this request once the linked media is included — add funds at /billing, use smaller media, or lower max_tokens")
} else {
s.logger.Error("media reservation top-up failed (DB error)", "consumer_key", consumerKey, "error", err)
s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:error"})
Comment on lines +182 to +184
s.writeServiceUnavailable(w, p.model)
}
return currentMicroUSD, true
}
s.ddIncr("billing.media_reservation_topup", []string{"model:" + p.model, "outcome:reserved"})
return want, false
}

// inferenceAdmissionParams bundles the per-request inputs the shared routing
// preflight needs. model is the resolved build id; the preflight may swap it to
// a Previous build via an alias fallback and returns the final value.
Expand Down
Loading
Loading