diff --git a/CHANGELOG.md b/CHANGELOG.md index c413b6aaa6..34a178ed16 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## Unreleased — output token estimate bounds + +- Reject generic inference requests with 400 when `n` times the per-choice output token limit exceeds the supported integer range, before token quotas, billing reservations or routing. Ordinary requests retain their existing output limits and admission policy. + ## Release candidate v0.9.2 — Gemma QAT caching, adaptive MTP and Nemotron Lightning (not shipped; 2026-09-10) Source changes since `v0.9.1`. Provider changes require a new signed bundle. diff --git a/coordinator/api/consumer.go b/coordinator/api/consumer.go index da16c39956..8542939f02 100644 --- a/coordinator/api/consumer.go +++ b/coordinator/api/consumer.go @@ -2022,7 +2022,10 @@ func (s *Server) handleChatCompletions(w http.ResponseWriter, r *http.Request) { stream, _ := parsed["stream"].(bool) estimatedPromptTokens := shape.routingPromptTokens(parsed) billingPromptTokens := shape.billingPromptTokens(parsed) - requestedMaxTokens := estimateRequestedMaxTokens(parsed) + requestedMaxTokens, ok := s.validateRequestedMaxTokens(w, r, parsed, model, publicModel) + if !ok { + return + } deadline := s.FirstContentDeadline(model, estimatedPromptTokens) timing.ParsedAt = time.Now() rp.Mark(registry.StampReqParsed) @@ -2786,7 +2789,10 @@ func (s *Server) handleGenericInference(w http.ResponseWriter, r *http.Request, stream, _ := parsed["stream"].(bool) estimatedPromptTokens := estimatePromptTokens(parsed) billingPromptTokens := estimateBillingPromptTokens(parsed) - requestedMaxTokens := estimateRequestedMaxTokens(parsed) + requestedMaxTokens, ok := s.validateRequestedMaxTokens(w, r, parsed, model, publicModel) + if !ok { + return + } genericDeadline := s.FirstContentDeadline(model, estimatedPromptTokens) timing.ParsedAt = time.Now() rp.Mark(registry.StampReqParsed) diff --git a/coordinator/api/inference_preprocess_bench_test.go b/coordinator/api/inference_preprocess_bench_test.go index 3d66750fac..48f0323111 100644 --- a/coordinator/api/inference_preprocess_bench_test.go +++ b/coordinator/api/inference_preprocess_bench_test.go @@ -257,8 +257,8 @@ func benchPreprocess(b *testing.B, srv *Server, body []byte) { } estimatedPromptTokens := shape.routingPromptTokens(parsed) billingPromptTokens := shape.billingPromptTokens(parsed) - requestedMaxTokens := estimateRequestedMaxTokens(parsed) - if estimatedPromptTokens <= 0 || billingPromptTokens <= 0 || requestedMaxTokens <= 0 { + requestedMaxTokens, valid := estimateRequestedMaxTokens(parsed) + if !valid || estimatedPromptTokens <= 0 || billingPromptTokens <= 0 || requestedMaxTokens <= 0 { b.Fatal("estimates must be positive") } diff --git a/coordinator/api/output_token_overflow_test.go b/coordinator/api/output_token_overflow_test.go new file mode 100644 index 0000000000..808552dbd6 --- /dev/null +++ b/coordinator/api/output_token_overflow_test.go @@ -0,0 +1,115 @@ +package api + +import ( + "bytes" + "encoding/json" + "io" + "math" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/ratelimit" + "github.com/eigeninference/d-inference/coordinator/registry" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestGenericOutputTokenOverflowCannotBypassKeyQuota(t *testing.T) { + for _, endpoint := range []string{"/v1/completions", "/v1/messages"} { + t.Run(endpoint, func(t *testing.T) { + st := store.NewMemory(store.Config{}) + seedActiveModel(t, st, "test-model", "test-model") + limit := int64(100) + rawKey, _, err := st.CreateAPIKey("test-account", store.APIKeyCreate{OTPMLimit: &limit}) + if err != nil { + t.Fatal(err) + } + logger := quietLogger() + srv := NewServer(registry.New(logger), st, ServerConfig{}, logger) + t.Cleanup(srv.Close) + srv.SetKeyLimiters(nil, ratelimit.NewKeyTokenLimiter()) + srv.SyncModelCatalog() + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + client := ts.Client() + client.Timeout = 5 * time.Second + body := map[string]any{"model": "test-model"} + if endpoint == "/v1/completions" { + body["prompt"] = "Hello" + } else { + body["messages"] = []any{map[string]any{"role": "user", "content": "Hello"}} + } + for _, tc := range []struct { + name string + copies, maxTokens int + status int + quotaRejected bool + }{ + // The limiter admits at most one burst per request, even when + // its estimate is larger. Spend half a burst first so a normal + // oversized estimate is refused while a wrapped value fits. + {"spend_half_burst", 1, 50, http.StatusTooManyRequests, false}, + {"ordinary_over_quota", 1, 101, http.StatusTooManyRequests, true}, + {"negative_wrap", math.MaxInt, 2, http.StatusBadRequest, false}, + {"positive_wrap", math.MaxInt/2 + 2, 4, http.StatusBadRequest, false}, + } { + t.Run(tc.name, func(t *testing.T) { + body["n"], body["max_tokens"] = tc.copies, tc.maxTokens + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequest(http.MethodPost, ts.URL+endpoint, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+rawKey) + req.Header.Set("Content-Type", "application/json") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + response, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + quotaRejected := strings.Contains(string(response), "output_tokens") + if resp.StatusCode != tc.status || quotaRejected != tc.quotaRejected { + t.Fatalf("quotaRejected=%v, want %v: status=%d body=%s", quotaRejected, tc.quotaRejected, resp.StatusCode, response) + } + }) + } + }) + } +} + +func TestRequestedOutputTokenEstimateRejectsOverflow(t *testing.T) { + for _, field := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} { + t.Run(field, func(t *testing.T) { + for _, tc := range []struct { + maxTokens, copies, want int + valid bool + }{ + {7, 3, 21, true}, + {math.MaxInt / 2, 2, math.MaxInt - 1, true}, + {math.MaxInt/2 + 1, 2, 0, false}, + {4, math.MaxInt/2 + 2, 0, false}, + {math.MaxInt, 1, math.MaxInt, true}, + } { + parsed := map[string]any{field: tc.maxTokens, "n": tc.copies} + if got, valid := estimateRequestedMaxTokens(parsed); got != tc.want || valid != tc.valid { + t.Errorf("%d tokens across %d choices = (%d, %t), want (%d, %t)", tc.maxTokens, tc.copies, got, valid, tc.want, tc.valid) + } + } + }) + } + if got, valid := estimateRequestedMaxTokens(map[string]any{"n": math.MaxInt}); valid || got != 0 { + t.Errorf("default-token overflow = (%d, %t), want (0, false)", got, valid) + } + if got, valid := estimateRequestedMaxTokens(nil); !valid || got != 256 { + t.Errorf("default-token estimate = (%d, %t), want (256, true)", got, valid) + } +} diff --git a/coordinator/api/output_token_validation_test.go b/coordinator/api/output_token_validation_test.go new file mode 100644 index 0000000000..ec8616f3d9 --- /dev/null +++ b/coordinator/api/output_token_validation_test.go @@ -0,0 +1,95 @@ +package api + +import ( + "bytes" + "encoding/json" + "io" + "math" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/eigeninference/d-inference/coordinator/ratelimit" + "github.com/eigeninference/d-inference/coordinator/store" +) + +func TestGenericOutputTokenOverflowRejectedBeforeAdmission(t *testing.T) { + for _, endpoint := range []string{"/v1/completions", "/v1/messages"} { + for _, quota := range []string{"full", "unlimited"} { + for _, tc := range []struct { + name string + copies, maxTokens int + }{ + {"negative_wrap", math.MaxInt, 2}, + {"positive_wrap", math.MaxInt/2 + 2, 4}, + {"default_limit", math.MaxInt, 0}, + } { + t.Run(endpoint+"/"+quota+"/"+tc.name, func(t *testing.T) { + srv, st := testBillingServer(t) + t.Cleanup(srv.Close) + seedActiveModel(t, st, "test-model", "test-model") + limit := int64(100) + if quota == "unlimited" { + limit = 0 + } + rawKey, _, err := st.CreateAPIKey("test-account", store.APIKeyCreate{OTPMLimit: &limit}) + if err != nil { + t.Fatal(err) + } + if err := st.Credit("test-account", 1_000_000, store.LedgerDeposit, "fixture"); err != nil { + t.Fatal(err) + } + srv.SetKeyLimiters(nil, ratelimit.NewKeyTokenLimiter()) + srv.SyncModelCatalog() + ts := httptest.NewServer(srv.Handler()) + t.Cleanup(ts.Close) + client := ts.Client() + client.Timeout = 5 * time.Second + body := map[string]any{"model": "test-model", "n": tc.copies} + if endpoint == "/v1/completions" { + body["prompt"] = "Hello" + } else { + body["messages"] = []any{map[string]any{"role": "user", "content": "Hello"}} + } + if tc.maxTokens > 0 { + body["max_tokens"] = tc.maxTokens + } + data, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req, err := http.NewRequest(http.MethodPost, ts.URL+endpoint, bytes.NewReader(data)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+rawKey) + req.Header.Set("Content-Type", "application/json") + resp, err := client.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + response, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatal(err) + } + var payload struct { + Error struct{ Type, Param string } + } + if err := json.Unmarshal(response, &payload); err != nil { + t.Fatal(err) + } + if resp.StatusCode != http.StatusBadRequest || payload.Error.Type != "invalid_request_error" || payload.Error.Param != "n" { + t.Errorf("overflow must fail before admission: status=%d body=%s", resp.StatusCode, response) + } + // A refunded reservation still appends ledger records. Require + // no billing mutation at all, even with a full quota bucket. + if entries := st.LedgerHistory("test-account"); len(entries) != 1 || entries[0].Type != store.LedgerDeposit { + t.Errorf("overflow reached billing: ledger=%+v", entries) + } + }) + } + } + } +} diff --git a/coordinator/api/request_introspection.go b/coordinator/api/request_introspection.go index c23014c1db..a89323c093 100644 --- a/coordinator/api/request_introspection.go +++ b/coordinator/api/request_introspection.go @@ -26,6 +26,7 @@ package api import ( "encoding/json" + "math" "net/http" "strings" @@ -539,19 +540,48 @@ func requestHasTools(parsed map[string]any) bool { return ok && len(tools) > 0 } -func estimateRequestedMaxTokens(parsed map[string]any) int { +// estimateRequestedMaxTokens reports whether the selected output bound times +// the choice count fits in an int. Overflow is invalid input, not a token value +// that can safely continue into quota, price or capacity arithmetic. +func estimateRequestedMaxTokens(parsed map[string]any) (int, bool) { + maxTokens := 256 for _, key := range []string{"max_tokens", "max_completion_tokens", "max_output_tokens"} { if n, ok := intFromRequestValue(parsed[key]); ok && n > 0 { - if copies, ok := intFromRequestValue(parsed["n"]); ok && copies > 1 { - return n * copies - } - return n + maxTokens = n + break } } if copies, ok := intFromRequestValue(parsed["n"]); ok && copies > 1 { - return 256 * copies + if maxTokens > math.MaxInt/copies { + return 0, false + } + return maxTokens * copies, true + } + return maxTokens, true +} + +func (s *Server) validateRequestedMaxTokens(w http.ResponseWriter, r *http.Request, parsed map[string]any, model, publicModel string) (int, bool) { + if tokens, ok := estimateRequestedMaxTokens(parsed); ok { + return tokens, true } - return 256 + copies, _ := intFromRequestValue(parsed["n"]) + stream, _ := parsed["stream"].(bool) + s.recordRejection(rejectionInfo{ + r: r, + stage: "validation", + reasonCode: "bad_param", + httpStatus: http.StatusBadRequest, + keyID: keyIDFromContext(r.Context()), + consumerKeyHash: store.HashKey(consumerKeyFromContext(r.Context())), + requestedModel: publicModel, + resolvedModel: model, + stream: stream, + n: copies, + params: rejectionSamplingParams(parsed), + }) + writeJSON(w, http.StatusBadRequest, errorResponse("invalid_request_error", + "n times the requested output token limit exceeds the supported integer range", withParam("n"))) + return 0, false } // stripProviderRoutingFields drops the retired consumer-side serial allowlist. diff --git a/docs/architecture/routing.md b/docs/architecture/routing.md index 7984b859a8..64c2f65305 100644 --- a/docs/architecture/routing.md +++ b/docs/architecture/routing.md @@ -1,6 +1,6 @@ # Routing: how a request becomes a provider choice -> Last updated: 2026-09-08 · commit `0c162cdae` +> Last updated: 2026-09-12 · commit `932037b7c` Routing is the part of the coordinator that, given one inference request and the live fleet, picks the provider that should run it. It filters the fleet @@ -44,6 +44,13 @@ content beyond that. See [`data-flow.md`](data-flow.md) and ### Entry points +Before token quotas, balance reservation or routing, the API validates that the +selected per-choice output bound times `n` fits in its integer estimate +(`validateRequestedMaxTokens`, `coordinator/api/request_introspection.go`). +An overflowing product returns 400 `invalid_request_error`; it never enters +downstream cost or capacity calculations as a saturated token count. See the +[request limits](../reference/api-contracts.md#limits-and-validation). + `ReserveProviderWithPlan` (`coordinator/registry/scheduler.go`) is the dispatch-time entry point. It scans the fleet (`scanCandidatesLocked`), gates each provider diff --git a/docs/consumer/quickstart.md b/docs/consumer/quickstart.md index 5e4b4e3b6b..bea913cc69 100644 --- a/docs/consumer/quickstart.md +++ b/docs/consumer/quickstart.md @@ -1,6 +1,6 @@ # Quickstart: first request in five steps -> Last updated: 2026-09-04 · commit `7ae06021f` +> Last updated: 2026-09-12 · commit `932037b7c` Get an API key from the console, list the models your key can use, and make your first chat completion against `https://api.darkbloom.dev` — first with `curl`, then from the OpenAI and Anthropic SDKs. For developers integrating the API; each step is one action. Route details for everything used here are in [`../reference/api-contracts.md`](../reference/api-contracts.md). @@ -124,6 +124,7 @@ defines refresh intervals, maximum cached staleness, and window aliases. | Response | Cause | Fix | |---|---|---| +| 400 `invalid_request_error` with `param: "n"` | Chat/Responses received `n > 1`, or a generic endpoint's choice count times output limit exceeds the supported integer range | Use `n: 1` or lower the output limit; this rejection occurs before token or balance reservation ([request limits](../reference/api-contracts.md#limits-and-validation)) | | 401 `authentication_error` | `Authorization: Bearer` header missing, or the key is unknown, disabled, expired or revoked | Re-export the key; create or rotate one in the console ([`authentication.md`](authentication.md)) | | 402 | Balance or key budget cannot cover the worst-case reservation ([payment-required taxonomy](../architecture/billing.md#payment-required-responses)) | Deposit, or lower `max_tokens` ([`billing.md`](billing.md)) | | 403 `model_not_allowed` | The key was created with an `allowed_models` list that excludes this model | Pick an id from the list, or `PATCH` the key ([`authentication.md`](authentication.md)) | diff --git a/docs/developer/build.md b/docs/developer/build.md index 2f6e4d4065..69a2dd8d78 100644 --- a/docs/developer/build.md +++ b/docs/developer/build.md @@ -1,6 +1,6 @@ # Build -> Last updated: 2026-09-10 · commit `4f29957d2` +> Last updated: 2026-09-12 · commit `932037b7c` How to build every component of Darkbloom from a fresh clone: the Go coordinator, the Rust prompt-contract sidecar, the Swift provider CLI (with its @@ -77,6 +77,10 @@ understand what `make` runs. ### 3. Coordinator (Go) +Output-bound validation builds with the normal coordinator target. Its +[HTTP and billing regressions](test.md#2-coordinator-go) run in process and +require no provider binary or external service. + The owned two-host Go fixture embeds `e2e/testbed/provider_host.py`; rebuild its test binary after helper or lifecycle changes. The CPU-only `TestPrepareConnectedInputBindings` check uses the actual fixture input/report diff --git a/docs/developer/test.md b/docs/developer/test.md index 34e02254db..0cb3660046 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1,6 +1,6 @@ # Test -> Last updated: 2026-09-11 · commit `d22ad0cf3` +> Last updated: 2026-09-12 · commit `932037b7c` How to run the unit tests for each component, the end-to-end suite that boots a real coordinator + Swift provider against ephemeral Postgres, and the docs @@ -66,6 +66,14 @@ make test # coordinator-test prompt-sidecar-test provider-test ui-test benchma ### 2. Coordinator (Go) +`TestGenericOutputTokenOverflowRejectedBeforeAdmission` exercises both generic +HTTP routes with full and unlimited output quotas and real in-process billing. +It requires a 400 for overflowing output estimates and no charge/refund ledger +entries. `TestGenericOutputTokenOverflowCannotBypassKeyQuota` keeps the partially +spent quota controls, and `TestRequestedOutputTokenEstimateRejectsOverflow` +checks fitting and overflowing products (`coordinator/api/output_token_validation_test.go`, +`coordinator/api/output_token_overflow_test.go`). + Run prediction telemetry checks from the repository root: ```bash diff --git a/docs/reference/api-contracts.md b/docs/reference/api-contracts.md index 8f67cb25aa..58150c721a 100644 --- a/docs/reference/api-contracts.md +++ b/docs/reference/api-contracts.md @@ -1,6 +1,6 @@ # HTTP API contracts -> Last updated: 2026-09-09 · commit `884d97862` +> Last updated: 2026-09-12 · commit `932037b7c` The complete public HTTP surface of the coordinator, derived from the 108 `HandleFunc` registrations in `routes()` (`coordinator/api/server.go`), including the `/v1/` catch-all. Every route is listed once below with its handler symbol, authentication requirement, and rate-limit bucket; the second half of the page gives the wire shapes, headers, error table, SSE framing, limits, timeouts, and version-gate semantics that those routes share. For *why* the pipeline is built this way see [`../architecture/components/consumer.md`](../architecture/components/consumer.md); for the crypto model behind sealed transport see [`../architecture/security/encryption.md`](../architecture/security/encryption.md). @@ -466,7 +466,7 @@ Built by `handleStreamingResponseWithFirstChunkAndError` (`coordinator/api/consu | Inference body | 16 MiB (`maxInferenceBodyBytes`) → 413 `invalid_request_error`; sealed bodies are read with the same cap (400 `invalid_request_error` when exceeded) | `parseInferencePrelude` (`coordinator/api/inference_preprocess.go`), `sealedTransport` (`coordinator/api/sender_encryption.go`) | | Control-plane bodies | 64 KiB (`maxControlPlaneBodyBytes`) for enroll, device token, admin auth | `coordinator/api/server.go` | | MDM webhook body | 1 MiB (`maxMDMWebhookBodyBytes`) | `HandleMDMWebhook` (`coordinator/api/server.go`) | -| `n` | Must be 1 | `handleChatCompletions` | +| `n` | Chat/Responses reject integer values greater than 1. Generic endpoints return 400 `invalid_request_error` with `param: "n"` when the positive per-choice output bound times `n` exceeds the supported integer range. | `handleChatCompletions`; `validateRequestedMaxTokens`, `estimateRequestedMaxTokens` (`coordinator/api/request_introspection.go`) | | `max_tokens` | `max_completion_tokens` → `max_tokens`; an explicit value is not clamped, a missing one is filled from the [output bound](pricing-model.md#formulas) | `ensureMaxTokensBound` | | Prompt size at admission | 413 `payload_too_large` when the estimated prompt exceeds what the model's providers can accept | `runInferenceAdmission` (`coordinator/api/inference_admission.go`) | | Catalog membership | Model resolved but absent from the routable catalog → 404 `model_not_found`, after the balance reservation is released | `handleChatCompletions` | @@ -479,6 +479,12 @@ Built by `handleStreamingResponseWithFirstChunkAndError` (`coordinator/api/consu | Token rate limits | Per-account input and output tokens per minute → 429 with `Retry-After` | `applyTokenRateLimitWithAdmission`, `writeTokenRateLimited` | | Model shedding | A model currently rejecting → 429 with `Retry-After` from `estimateRetryAfter` | `shedIfModelRejected` | +Output-estimate overflow is rejected before token admission, balance reservation +or capacity routing, including when token quotas are full or unlimited. The +coordinator never substitutes a maximum-integer token count for this invalid +product. Representable estimates retain the existing one-burst admission policy +and provider-bound output limits. + ## Timeouts and constants | Constant | Value | Where | Effect |