Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
10 changes: 8 additions & 2 deletions coordinator/api/consumer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions coordinator/api/inference_preprocess_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down
115 changes: 115 additions & 0 deletions coordinator/api/output_token_overflow_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
95 changes: 95 additions & 0 deletions coordinator/api/output_token_validation_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
}
}
44 changes: 37 additions & 7 deletions coordinator/api/request_introspection.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ package api

import (
"encoding/json"
"math"
"net/http"
"strings"

Expand Down Expand Up @@ -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.
Expand Down
9 changes: 8 additions & 1 deletion docs/architecture/routing.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/consumer/quickstart.md
Original file line number Diff line number Diff line change
@@ -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).

Expand Down Expand Up @@ -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)) |
Expand Down
6 changes: 5 additions & 1 deletion docs/developer/build.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading