Repository navigation
feat(coordinator): safely fetch and inline remote media URLs #530
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
1a391d7
393f115
c4eda1a
d3d74f3
c503404
3bfd39b
5aa0cea
f2ebfd5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 { | ||
|
|
@@ -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. | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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
runInferenceAdmissionperforms 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 👍 / 👎.
There was a problem hiding this comment.
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-049rather than changed in code.Fleet eligibility is checked before any fetch:
visionToolsFailFastcallsHasVisionProviderForModel(inference_preprocess.go:220) andHasToolCapableProviderForModel, and it runs atconsumer.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)
runInferenceAdmissionneeds the POST-inline traits —MinPrefixCacheProtocolis derived from body size, and deriving it from the pre-inline URL body is exactly the bug fixed inc503404— 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-049with that reasoning, so it is visible to the next reviewer rather than implicit.