From 12ce5dadaeb3b0a616939a2fb48e396812a8601c Mon Sep 17 00:00:00 2001 From: kaiser-data <61822885+kaiser-data@users.noreply.github.com> Date: Tue, 1 Dec 2026 15:25:31 +0100 Subject: [PATCH 1/3] feat(fallback): first_token_timeout fails over a stalled stream early A provider that accepts a streaming request but never sends a token used to hold the request for the full provider timeout before failover. fallback.first_token_timeout arms a second timer for streaming calls that is reset by content or reasoning chunks; when it fires, the router moves to the next provider. Off by default in code; the example config sets 10s. - peekStream gains a progress hook; reasoning-only chunks keep the timer alive - timeout errors name which timer fired - FAILOVER_BENCH_FIRST_TOKEN knob for make bench-failover - docs/first-token-timeout.md with tradeoffs and a real-board test plan Measured (Mac, 2s provider timeout, 500ms first-token): stalled-provider cold p50 2028 -> 528 ms; healthy and 429 rows unchanged; buffered chat benchmark stays at 151 allocs/op. Co-Authored-By: Claude Opus 5.5 --- Makefile | 2 +- README.md | 4 +- configs/config.example.yaml | 6 ++ docs/first-token-timeout.md | 154 ++++++++++++++++++++++++++++++ pkg/config/config.go | 5 + pkg/proxy/failover_bench_test.go | 23 +++-- pkg/proxy/fallback.go | 60 +++++++++--- pkg/proxy/first_token_test.go | 113 ++++++++++++++++++++++ pkg/proxy/upstream_stream.go | 29 +++++- pkg/proxy/upstream_stream_test.go | 6 +- 10 files changed, 374 insertions(+), 28 deletions(-) create mode 100644 docs/first-token-timeout.md create mode 100644 pkg/proxy/first_token_test.go diff --git a/Makefile b/Makefile index e6c0be4..6a23d09 100644 --- a/Makefile +++ b/Makefile @@ -35,7 +35,7 @@ test-verbose: ## Run unit tests with verbose output test-integration: ## Run integration tests (requires API keys) $(GOCMD) test -tags=integration ./... -count=1 -bench-failover: ## End-to-end failover benchmark: TTFT when the first provider 429s or stalls (FAILOVER_BENCH_N, _CONC, _TIMEOUT, _OUT) +bench-failover: ## End-to-end failover benchmark: TTFT when the first provider 429s or stalls (FAILOVER_BENCH_N, _CONC, _TIMEOUT, _FIRST_TOKEN, _OUT) FAILOVER_BENCH=1 $(GOCMD) test ./pkg/proxy -run '^TestFailoverBenchmark$$' -count=1 -v vet: ## Run go vet diff --git a/README.md b/README.md index c4b6768..6f2d0ac 100644 --- a/README.md +++ b/README.md @@ -161,7 +161,7 @@ How long a client waits for its first token when the first provider fails. Two l | returns 429 | 100% | 27.1 ms | 28.0 ms | 31.1 ms | | stalls before its first token | 100% | 2028 ms | 2032 ms | 2036 ms | -Each request starts with no health history here, so every one of them pays the fallback. In a running proxy the first failures put the provider on cooldown: after a 429, 11 of 400 requests still reached it; after a stall, 16 did (one per client in flight), and p95 fell back to 33 ms. A 429 costs about half a millisecond. A stall costs the provider's `timeout`, because the proxy cannot tell a slow first token from none. Keep `timeout` short on providers you route latency-sensitive work to. Reproduce with `make bench-failover` (knobs: `FAILOVER_BENCH_N`, `_CONC`, `_TIMEOUT`, `_UPSTREAM_TTFT`). +Each request starts with no health history here, so every one of them pays the fallback. In a running proxy the first failures put the provider on cooldown: after a 429, 11 of 400 requests still reached it; after a stall, 16 did (one per client in flight), and p95 fell back to 33 ms. A 429 costs about half a millisecond. A stall costs the provider's `timeout`, because the proxy cannot tell a slow first token from none, unless `fallback.first_token_timeout` is set (10 s in the example config): then a stream with no content token for that long moves on, and every reasoning chunk restarts the clock so a thinking model is not cut off. With `first_token_timeout: 500ms` in the same run, a stall cost 528 ms at p50 instead of 2028 ms; the healthy and 429 rows did not change. How to pick a value and what it costs: [docs/first-token-timeout.md](docs/first-token-timeout.md). Reproduce with `make bench-failover` (knobs: `FAILOVER_BENCH_N`, `_CONC`, `_TIMEOUT`, `_UPSTREAM_TTFT`, `_FIRST_TOKEN`). The [install script](#install) picks the right archive on the board itself. For `mipsle`, `loong64` or other targets, cross-compile from any machine with Go and copy the result over: @@ -363,7 +363,7 @@ configs/ bundled config and the free-model catalog - **Free tiers are small, and they change.** The proxy makes the most of them. It does not create capacity, and it is not a fit for production traffic with an SLA. - **A stream that breaks after its first token cannot fall back.** The client already has part of the answer, so the stream ends with an SSE error event (`stream_interrupted`), never with a clean end that would look like a complete answer. That includes a provider that closes its connection cleanly before sending `[DONE]` or a `finish_reason`. Gemini is still buffered (its thought blocks are stripped from the full answer) and re-emitted as SSE. - **The catalog can lag a provider's change by up to a week.** Models that vanish are cooled down on the first 404 and skipped. -- **A provider that stalls before its first token costs its full `timeout`** before the fallback starts (15–30 s in the example config). After that the provider is cooled down and skipped. See [What failover costs you](#what-failover-costs-you). +- **A provider that stalls before its first token costs `fallback.first_token_timeout`** (10 s in the example config) before the fallback starts, or its full `timeout` (15–30 s) when that is off and for non-streaming requests, which have no first token to watch. After that the model is cooled down and skipped. A free model that is merely queued longer than `first_token_timeout` is dropped the same way; raise it if that costs you answers. See [First-token timeout](docs/first-token-timeout.md). - **Local quota tracking is best-effort.** The proxy honours the providers' rate-limit headers, but under heavy concurrency a provider may still send the occasional 429, which simply triggers the fallback. ## Development diff --git a/configs/config.example.yaml b/configs/config.example.yaml index 4009434..b68abb5 100644 --- a/configs/config.example.yaml +++ b/configs/config.example.yaml @@ -132,6 +132,12 @@ fallback: # Upper bound for one request across all providers it tries. When it passes # the proxy returns 503 + Retry-After instead of waiting on. 0 = no limit. request_timeout: 90s + # Streaming only: if a provider sends no content token for this long, the + # chain moves on (and cools that model for 5 minutes) instead of waiting + # out the provider's own timeout. Each reasoning chunk restarts it, so a + # model that is thinking is not cut off. 0 or unset = off. + # Tradeoffs and how to pick a value: docs/first-token-timeout.md + first_token_timeout: 10s refresh: model: "groq/openai/gpt-oss-120b" diff --git a/docs/first-token-timeout.md b/docs/first-token-timeout.md new file mode 100644 index 0000000..b3a4728 --- /dev/null +++ b/docs/first-token-timeout.md @@ -0,0 +1,154 @@ +# First-token timeout + +`fallback.first_token_timeout` decides how long a streaming request waits for a provider's first content token before the proxy gives up on that provider and tries the next free model. + +Without it, a provider that accepts the request and then goes silent costs its full `timeout` (15–30 s in the example config) before the fallback starts. With it, the same stall costs `first_token_timeout`. + +## Use it + +```yaml +fallback: + request_timeout: 90s + first_token_timeout: 10s # 0 or unset = off +``` + +- **Default:** off in code, so a config without the line behaves as before. [`configs/config.example.yaml`](../configs/config.example.yaml) sets `10s`, and a fresh install without its own `config.yaml` uses that file. +- **Scope:** one value for all providers. A per-provider override does not exist yet. +- **Hot reload:** the value is read per call, so a config change applies to the next request without a restart. + +## How it decides + +``` +request ──► provider accepts (HTTP 200, text/event-stream) + │ + │ role chunk {"delta":{"role":"assistant"}} ← does NOT count + │ reasoning chunk {"delta":{"reasoning_content":"…"}} ← restarts the clock + │ … + │ first content / tool-call chunk ← committed: the timer stops for good + ▼ + tokens flow to the client; only request_timeout bounds the rest +``` + +1. The timer starts when the upstream call starts, so connecting, TLS and the provider's queue count against it. +2. Only **content**, a **tool call** or a **function call** ends the wait. These are the same chunks that commit the stream, so once the client sees a byte the timer is gone. +3. A chunk carrying **reasoning** (`reasoning_content`, as DeepSeek and most OpenAI-compatible hosts send it, or `reasoning`, as OpenRouter does) restarts the timer. A model that is visibly thinking is not stalled. +4. A role-only chunk, a keep-alive comment or an empty delta does **not** restart it. "Headers plus role chunk, then nothing" is the most common real stall, and the benchmark reproduces exactly that. +5. The provider's own `timeout` still caps the whole wait before the first token. A model that streams reasoning forever is still dropped at `timeout`. +6. When the timer fires, the call is cancelled and treated like any transport failure: the model is paused for 5 minutes (`transportModelCooldown`), the provider's reliability score records a failure, and the walk continues with the next candidate. The log line names the cause: + + ``` + fallback: openrouter/some-model:free transport error — model cooldown 5m0s, walking on (no first token within 10s) + ``` + + With the setting off, the same line ends in `(provider timeout 30s)`. + +## When it does not apply + +| Case | Why | What bounds the wait instead | +|---|---|---| +| Non-streaming requests (`stream` absent or `false`) | The whole answer arrives at once, so there is no first token to watch. | provider `timeout` | +| Gemini | The proxy always calls Gemini buffered (to strip thought blocks) and re-emits SSE. | provider `timeout` | +| `first_token_timeout` ≥ provider `timeout` | The provider timeout would fire first anyway, so no second timer is started. | provider `timeout` | +| After the first content token | The stream is committed to that provider and cannot fall back. A later break ends with a `stream_interrupted` event. | `request_timeout` | + +## Tradeoffs + +**What you gain** +- A silent provider costs seconds, not half a minute. Measured below: 528 ms instead of 2028 ms with a 500 ms setting. +- The stalled model is then paused, so later requests skip it entirely (the warm rows below). +- The cost when nothing goes wrong is close to zero. A request that uses the setting starts one extra timer and checks one more field in the chunks it already parses before the first token. Non-streaming requests allocate nothing extra (151 allocations per request, same as before). + +**What you risk** +- **A slow but working model gets dropped.** Free tiers queue: an OpenRouter `:free` model under load or a busy NVIDIA NIM model can take longer than 10 s to say anything. With the timer on, that model is abandoned *and* paused for 5 minutes, even though it would have answered. If the next candidate is worse, you have traded latency for answer quality. +- **Models that think silently look like stalls.** The reasoning reset only works for models that *stream* their reasoning. A model that reasons internally and sends nothing until its answer (hidden-reasoning models, some hosted "thinking" endpoints) gets cut off after `first_token_timeout`. If you route long reasoning work to such a model, raise the value or leave it off. +- **Long prompts take longer to start.** Time to first token grows with prompt length (prefill). A 100k-token prompt can legitimately need more than 10 s before the first token, even on a healthy provider. +- **More memory per in-flight request on small boards.** Because thinking models are no longer cut off at their first pause, more requests can sit in the "thinking, not yet committed" state. Each one buffers up to 1 MB (`maxStreamPrefix`) until content arrives. Ten parallel thinkers can hold about 10 MB, which matters on a 512 MB board. +- **One bad window costs every model it hits.** If your network briefly stalls (Wi-Fi drop, cellular handover), every model tried during that window is paused for 5 minutes. A setting far below your link's worst-case round trip makes this more likely. + +## Choosing a value + +| Situation | Suggested | Reason | +|---|---|---| +| Interactive chat, coding agents, PicoClaw | `5s`–`10s` | Users notice anything above a few seconds, and there are many free models to fall back to. | +| Mixed traffic, default | `10s` | Catches dead providers, leaves room for typical free-tier queueing. | +| Long prompts (RAG, `long-context` strategy) or silent-reasoning models | `20s`–`30s`, or off | Prefill and hidden thinking need the time. | +| Flaky uplink (cellular, satellite, busy Wi-Fi) | at least 3× the link's worst round trip | Avoids pausing healthy models during a network hiccup. | +| Batch jobs where latency does not matter | off | Every answer counts, waiting is free. | + +Rule of thumb: set it above the **p99 time to first token you see from healthy providers** for your typical prompt size, and below the provider `timeout`. `grep "no first token" proxy.log | wc -l` over a day shows how often it fires. A high count against providers that otherwise work means the value is too tight. + +## Measuring it + +### On your machine (loopback, no API keys) + +```bash +make bench-failover # setting off +FAILOVER_BENCH=1 FAILOVER_BENCH_FIRST_TOKEN=500ms \ + go test ./pkg/proxy -run '^TestFailoverBenchmark$' -count=1 -v +``` + +Two local upstreams: "alpha" is tried first and fails as each row says, "beta" always answers. The "stalls before first token" row sends headers and a role chunk, then nothing. + +Measured 1 Dec 2026 on an 8-core Apple Silicon Mac, 200 streaming requests per row, 16 concurrent clients, provider `timeout` 2 s, healthy upstream first token after 25 ms: + +| mode | scenario | off: p50 / p95 | `500ms`: p50 / p95 | +|---|---|---|---| +| cold | healthy first provider | 26.8 / 27.3 ms | 26.9 / 29.5 ms | +| cold | first provider 429 | 27.2 / 28.0 ms | 27.2 / 28.8 ms | +| cold | first provider stalls | **2028 / 2032 ms** | **528 / 533 ms** | +| warm | first provider stalls | 26.7 / **2032 ms** | 26.5 / **528 ms** | + +"Cold" means a fresh proxy per request, so every request pays the fallback. "Warm" means one running proxy: after the first stalls (one per concurrent client), the model is paused and later requests skip it, which is why warm p50 matches the healthy case. + +The unit tests in [`pkg/proxy/first_token_test.go`](../pkg/proxy/first_token_test.go) pin the behaviour: a stall falls back early, the setting off keeps the old wait, a model that keeps thinking past the limit still answers, and a slow non-streaming answer is unaffected. + +### On real small boards (planned) + +The loopback numbers above come from a fast machine. The claims that matter for this project are about $10 boards, so these runs are still to do. + +**Boards** + +| Board | GOARCH | Notes | +|---|---|---| +| Jetson Orin Nano (6× A78AE) | `arm64` | Available for testing. Much faster than the boards below, so say so when quoting it. Use single-core numbers (`-test.cpu 1`): it runs other jobs. | +| Raspberry Pi Zero 2 W (4× A53, 512 MB) | `arm` `GOARM=7` / `arm64` | The main PicoClaw target. | +| Raspberry Pi Zero W (1× ARM11, 512 MB) | `arm` `GOARM=6` | Worst case for CPU. | +| RISC-V board (e.g. LicheeRV / Milk-V Duo) | `riscv64` | The smallest-memory target. | + +**Build and run (no API keys, no internet needed on the board)** + +```bash +GOOS=linux GOARCH=arm64 go test -c -o flpr-failover ./pkg/proxy # adjust GOARCH/GOARM per board +scp flpr-failover user@board:/tmp/ +ssh user@board 'cd /tmp && \ + FAILOVER_BENCH=1 FAILOVER_BENCH_N=100 FAILOVER_BENCH_CONC=4 \ + ./flpr-failover -test.run "^TestFailoverBenchmark$" -test.v -test.count=1; \ + FAILOVER_BENCH=1 FAILOVER_BENCH_N=100 FAILOVER_BENCH_CONC=4 FAILOVER_BENCH_FIRST_TOKEN=500ms \ + ./flpr-failover -test.run "^TestFailoverBenchmark$" -test.v -test.count=1; \ + rm -f flpr-failover' +``` + +Lower `_N` and `_CONC` on single-core boards, so the client load itself does not dominate. + +**What to record** + +1. **Overshoot:** stall-row p95 minus `first_token_timeout`. Below 50 ms on the Mac. On a Pi Zero, timer wake-up and goroutine scheduling under load may add more. If it is large, a fixed value means something different per board. +2. **Overhead when nothing fails:** healthy-row p50/p95 with the setting on vs off. It should be within noise. A difference here would come from the extra reasoning-field check on pre-first-token chunks. +3. **Memory under stalls:** peak RSS of the proxy (`/usr/bin/time -v`, or `ps -o rss` in a loop) with 16 concurrent stalls, on vs off. Expect fewer stalled connections held at the same time with the setting on. +4. **Memory under thinking:** the same with an upstream that streams reasoning chunks for 10 s, to confirm the 1 MB-per-request prefix bound holds on a 512 MB board. +5. **Real network (needs API keys, ask before bulk runs):** on the board's actual uplink, the p99 time to first token from 3–5 healthy free providers over ~50 short prompts. This is the number to compare `first_token_timeout` against. Then count how many `no first token` lines `10s` produces over a day of normal use. + +**Results** (fill in per run: date, board, Go version, `_N`/`_CONC`, provider `timeout`) + +| Board | stall p50/p95, off | stall p50/p95, 500ms | healthy p95 off / on | peak RSS, 16 stalls off / on | +|---|---|---|---|---| +| Jetson Orin Nano (1 core) | | | | | +| Pi Zero 2 W | | | | | +| Pi Zero W | | | | | +| RISC-V | | | | | + +## Ideas not built yet + +- **Per-provider override** (`providers[].first_token_timeout`), for example a longer value for a provider that hosts silent-reasoning models. +- **A shorter pause for this kind of stall.** Today it shares the 5-minute pause with other transport errors. A slow-queue model might deserve less. +- **An adaptive value** from each provider's observed time-to-first-token percentiles, so the limit follows the provider instead of a global guess. diff --git a/pkg/config/config.go b/pkg/config/config.go index ba000de..8aee5aa 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -123,6 +123,11 @@ type FallbackConfig struct { // RequestTimeout bounds one client request across every provider it // tries. When it passes, the proxy answers 503 + Retry-After. 0 = no limit. RequestTimeout time.Duration `mapstructure:"request_timeout"` + // FirstTokenTimeout bounds how long a streaming call may go without its + // first content token before the chain moves on. Each reasoning chunk + // restarts it; the provider timeout still caps the whole wait. Buffered + // (non-streaming) calls are not affected. 0 = off. + FirstTokenTimeout time.Duration `mapstructure:"first_token_timeout"` } // mu guards the current config pointer for concurrent hot-reload. diff --git a/pkg/proxy/failover_bench_test.go b/pkg/proxy/failover_bench_test.go index 4d848da..0d7e04d 100644 --- a/pkg/proxy/failover_bench_test.go +++ b/pkg/proxy/failover_bench_test.go @@ -9,7 +9,8 @@ package proxy // Knobs (env): FAILOVER_BENCH_N requests per row (default 400), // FAILOVER_BENCH_CONC concurrent clients (16), FAILOVER_BENCH_TIMEOUT the // first provider's timeout (2s), FAILOVER_BENCH_UPSTREAM_TTFT the healthy -// upstream's delay before its first token (25ms), FAILOVER_BENCH_OUT a file +// upstream's delay before its first token (25ms), FAILOVER_BENCH_FIRST_TOKEN +// fallback.first_token_timeout (off), FAILOVER_BENCH_OUT a file // to write the markdown table to (relative paths resolve in pkg/proxy). // // Two upstreams on loopback: "alpha" is tried first and fails as the @@ -131,13 +132,13 @@ func benchEnvDur(t *testing.T, key string, def time.Duration) time.Duration { } // failoverProxy is a proxy over alpha (ranked first) and beta. -func failoverProxy(t *testing.T, alphaURL, betaURL string, timeout time.Duration) *Server { +func failoverProxy(t *testing.T, alphaURL, betaURL string, timeout, firstToken time.Duration) *Server { cfg := &config.Config{ Providers: []config.ProviderConfig{ {ID: "alpha", BaseURL: alphaURL, Enabled: true, Timeout: timeout.String()}, {ID: "beta", BaseURL: betaURL, Enabled: true, Timeout: timeout.String()}, }, - Fallback: config.FallbackConfig{MaxAttempts: 5, RequestTimeout: 30 * time.Second}, + Fallback: config.FallbackConfig{MaxAttempts: 5, RequestTimeout: 30 * time.Second, FirstTokenTimeout: firstToken}, } cfg.Proxy.Strategy = "adaptive" cat := &catalog.Catalog{Entries: []catalog.CatalogEntry{ @@ -253,6 +254,7 @@ func TestFailoverBenchmark(t *testing.T) { conc := benchEnvInt(t, "FAILOVER_BENCH_CONC", 16) timeout := benchEnvDur(t, "FAILOVER_BENCH_TIMEOUT", 2*time.Second) upTTFT := benchEnvDur(t, "FAILOVER_BENCH_UPSTREAM_TTFT", 25*time.Millisecond) + firstToken := benchEnvDur(t, "FAILOVER_BENCH_FIRST_TOKEN", 0) // Every fallback logs a line; at hundreds of requests that is noise and // measurable work on the hot path a quiet deployment (log_level: warn) @@ -278,10 +280,10 @@ func TestFailoverBenchmark(t *testing.T) { var h http.HandlerFunc if mode == "warm" { - h = failoverProxy(t, alpha.URL, beta.URL, timeout).handleChatCompletions + h = failoverProxy(t, alpha.URL, beta.URL, timeout, firstToken).handleChatCompletions } else { h = func(w http.ResponseWriter, r *http.Request) { - failoverProxy(t, alpha.URL, beta.URL, timeout).handleChatCompletions(w, r) + failoverProxy(t, alpha.URL, beta.URL, timeout, firstToken).handleChatCompletions(w, r) } } proxy := httptest.NewServer(h) @@ -299,8 +301,8 @@ func TestFailoverBenchmark(t *testing.T) { } var out strings.Builder - fmt.Fprintf(&out, "Failover benchmark: %d streaming requests per row, %d concurrent clients, first-provider timeout %s, healthy upstream TTFT %s, %s.\n\n", - n, conc, timeout, upTTFT, goEnv()) + fmt.Fprintf(&out, "Failover benchmark: %d streaming requests per row, %d concurrent clients, first-provider timeout %s, first_token_timeout %s, healthy upstream TTFT %s, %s.\n\n", + n, conc, timeout, offIfZero(firstToken), upTTFT, goEnv()) out.WriteString("| mode | scenario | completed | hit failing provider | p50 TTFT | p95 TTFT | p99 TTFT | max TTFT |\n") out.WriteString("|---|---|---|---|---|---|---|---|\n") for _, r := range rows { @@ -335,3 +337,10 @@ func fmtMs(d time.Duration) string { func goEnv() string { return fmt.Sprintf("%s/%s, %d CPUs, %s", runtime.GOOS, runtime.GOARCH, runtime.NumCPU(), runtime.Version()) } + +func offIfZero(d time.Duration) string { + if d <= 0 { + return "off" + } + return d.String() +} diff --git a/pkg/proxy/fallback.go b/pkg/proxy/fallback.go index a4d00c5..af93b72 100644 --- a/pkg/proxy/fallback.go +++ b/pkg/proxy/fallback.go @@ -546,18 +546,56 @@ func (fc *FallbackChain) callProvider(ctx context.Context, cfg config.ProviderCo // The provider timeout bounds a buffered answer, and a stream only up to // its first content chunk: once tokens flow, a long answer from a slow // model may take longer, and the request deadline bounds it instead. + parent := ctx ctx, cancelCall := context.WithCancel(ctx) stopTimer := func() bool { return true } - if d, err := time.ParseDuration(cfg.Timeout); err == nil && d > 0 { - stopTimer = time.AfterFunc(d, cancelCall).Stop + providerTimeout, _ := time.ParseDuration(cfg.Timeout) + if providerTimeout > 0 { + stopTimer = time.AfterFunc(providerTimeout, cancelCall).Stop + } + // fallback.first_token_timeout: a shorter bound on a stream's wait for + // its first content chunk, restarted by every reasoning chunk (a model + // that thinks is not stalled). Only for streams, since a buffered answer + // has no first token to watch, and only if shorter than the provider + // timeout, which bounds the same wait. No closure escapes unless it is on. + var firstToken *time.Timer + var progress func() + ft := fc.Cfg.Fallback.FirstTokenTimeout + if ft > 0 && body["stream"] == true && (providerTimeout <= 0 || ft < providerTimeout) { + firstToken = time.AfterFunc(ft, cancelCall) + progress = func() { firstToken.Reset(ft) } + } + // firstTokenFired is known once the timer has been stopped (or failed to). + firstTokenFired := func() bool { return firstToken != nil && !firstToken.Stop() } + stopTimers := func() bool { + if firstTokenFired() { + stopTimer() + return false + } + firstToken = nil // stopped in time; a later stop must not read as fired + return stopTimer() } committed := false defer func() { if !committed { - stopTimer() + stopTimers() cancelCall() } }() + // A transport error caused by one of our timers says which one fired + // (the bare error is just "context canceled"). Error path only. + withCause := func(err error) error { + if err == nil || ctx.Err() == nil || parent.Err() != nil { + return err + } + if firstTokenFired() { + return fmt.Errorf("no first token within %s", ft) + } + if providerTimeout > 0 { + return fmt.Errorf("provider timeout %s", providerTimeout) + } + return err + } endpoint := strings.TrimRight(cfg.BaseURL, "/") + "/chat/completions" data, err := json.Marshal(body) @@ -585,7 +623,7 @@ func (fc *FallbackChain) callProvider(ctx context.Context, cfg config.ProviderCo resp, err := fc.HTTPClient.Do(req) if err != nil { - return nil, err + return nil, withCause(err) } defer func() { if !committed { @@ -593,15 +631,15 @@ func (fc *FallbackChain) callProvider(ctx context.Context, cfg config.ProviderCo } }() if resp.StatusCode == http.StatusOK && strings.HasPrefix(resp.Header.Get("Content-Type"), "text/event-stream") { - out, err := peekStream(resp.StatusCode, resp.Header, resp.Body) + out, err := peekStream(resp.StatusCode, resp.Header, resp.Body, progress) if err != nil || out.stream == nil { - return out, err + return out, withCause(err) } - // Committed: the stream owns the connection; the provider timeout ends. - if !stopTimer() { - // The provider timeout fired just as the first chunk came in: - // the call's context is already cancelled. - return nil, context.DeadlineExceeded + // Committed: the stream owns the connection; the timeouts end. + if !stopTimers() { + // A timeout fired just as the first chunk came in: the call's + // context is already cancelled. + return nil, withCause(context.DeadlineExceeded) } committed = true out.stream.onClose(func() { resp.Body.Close() }) diff --git a/pkg/proxy/first_token_test.go b/pkg/proxy/first_token_test.go new file mode 100644 index 0000000..25bc99d --- /dev/null +++ b/pkg/proxy/first_token_test.go @@ -0,0 +1,113 @@ +package proxy + +import ( + "bytes" + "io" + "log" + "net/http" + "net/http/httptest" + "strings" + "sync/atomic" + "testing" + "time" +) + +const sseThink = `data: {"model":"m","choices":[{"delta":{"reasoning_content":"hmm"}}]}` + "\n\n" + +// stallAfterRole sends headers and the role chunk, then nothing. +func stallAfterRole(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sseRole) + w.(http.Flusher).Flush() + <-r.Context().Done() +} + +func firstTokenRun(t *testing.T, alphaH http.HandlerFunc, timeout, firstToken time.Duration, body string) (rec *httptest.ResponseRecorder, alphaHits int64, logs string, took time.Duration) { + t.Helper() + var hits atomic.Int64 + alpha := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + alphaH(w, r) + })) + defer alpha.Close() + beta := httptest.NewServer(healthyUpstream(0)) + defer beta.Close() + + var buf bytes.Buffer + prev := log.Writer() + log.SetOutput(&buf) + defer log.SetOutput(prev) + + s := failoverProxy(t, alpha.URL, beta.URL, timeout, firstToken) + rec = httptest.NewRecorder() + start := time.Now() + s.handleChatCompletions(rec, httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(body))) + return rec, hits.Load(), buf.String(), time.Since(start) +} + +// A provider that sends its role chunk and then stalls is abandoned after +// first_token_timeout, not after its much longer provider timeout. +func TestFirstTokenTimeout_StallFallsBackEarly(t *testing.T) { + rec, hits, logs, took := firstTokenRun(t, stallAfterRole, 5*time.Second, 150*time.Millisecond, streamBody) + if hits != 1 { + t.Fatalf("alpha hits = %d, want 1 (alpha must be tried first)", hits) + } + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"hello"`) { + t.Fatalf("want beta's answer, got %d %q", rec.Code, rec.Body.String()) + } + if took > 2*time.Second { + t.Fatalf("took %s: the provider timeout (5s) bounded the stall, not first_token_timeout", took) + } + if !strings.Contains(logs, "no first token within 150ms") { + t.Fatalf("log does not name the first-token timeout:\n%s", logs) + } +} + +// Without first_token_timeout the stall still costs the provider timeout. +func TestFirstTokenTimeout_OffKeepsProviderTimeout(t *testing.T) { + _, _, logs, took := firstTokenRun(t, stallAfterRole, 400*time.Millisecond, 0, streamBody) + if took < 400*time.Millisecond { + t.Fatalf("took %s, want at least the 400ms provider timeout", took) + } + if !strings.Contains(logs, "provider timeout 400ms") { + t.Fatalf("log does not name the provider timeout:\n%s", logs) + } +} + +// A reasoning model that keeps thinking is not a stall: each reasoning chunk +// restarts the timer, so its answer still arrives even though the first +// content comes long after first_token_timeout. +func TestFirstTokenTimeout_ReasoningKeepsAlive(t *testing.T) { + thinker := func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sseRole) + w.(http.Flusher).Flush() + for range 8 { // 8 × 50ms = 400ms of thinking, ft = 150ms + time.Sleep(50 * time.Millisecond) + io.WriteString(w, sseThink) + w.(http.Flusher).Flush() + } + io.WriteString(w, sseHello+sseWorld+sseDone) + } + rec, hits, _, _ := firstTokenRun(t, thinker, 5*time.Second, 150*time.Millisecond, streamBody) + if hits != 1 || rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "hmm") { + t.Fatalf("want alpha's streamed answer incl. its reasoning, got hits=%d %d %q", hits, rec.Code, rec.Body.String()) + } +} + +// A buffered request cannot see a first token, so the timer does not apply. +func TestFirstTokenTimeout_BufferedUnaffected(t *testing.T) { + slow := func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + time.Sleep(400 * time.Millisecond) + w.Header().Set("Content-Type", "application/json") + io.WriteString(w, `{"model":"m","choices":[{"message":{"role":"assistant","content":"slow but fine"},"finish_reason":"stop"}]}`) + } + rec, hits, _, _ := firstTokenRun(t, slow, 5*time.Second, 100*time.Millisecond, + `{"model":"auto","messages":[{"role":"user","content":"hi"}]}`) + if hits != 1 || rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "slow but fine") { + t.Fatalf("want alpha's buffered answer, got hits=%d %d %q", hits, rec.Code, rec.Body.String()) + } +} diff --git a/pkg/proxy/upstream_stream.go b/pkg/proxy/upstream_stream.go index 454213b..a174dbf 100644 --- a/pkg/proxy/upstream_stream.go +++ b/pkg/proxy/upstream_stream.go @@ -55,10 +55,14 @@ const streamReadBuffer = 32 << 10 // so it is classified like the same error sent as a plain HTTP response; // - err — the connection broke before any content. // +// progress, when non-nil, is called for each event that carries reasoning +// but no content yet: the model is thinking, not stalled, so the caller can +// restart its first-token timer. +// // Events follow the SSE spec: "data:" lines are joined until a blank line. // Memory stays bounded by maxStreamPrefix whatever the provider sends: past // it the stream is committed and piped as is. -func peekStream(status int, header http.Header, body io.Reader) (*Response, error) { +func peekStream(status int, header http.Header, body io.Reader, progress func()) (*Response, error) { br := bufio.NewReaderSize(body, streamReadBuffer) var prefix, line, data bytes.Buffer usedModel := "" @@ -93,6 +97,9 @@ func peekStream(status int, header http.Header, body io.Reader) (*Response, erro if chunk.hasContent() { return commit() } + if progress != nil && chunk.hasReasoning() { + progress() + } return nil } for { @@ -157,9 +164,11 @@ type streamChunk struct { Error any `json:"error"` Choices []struct { Delta struct { - Content any `json:"content"` - ToolCalls []any `json:"tool_calls"` - FunctionCall any `json:"function_call"` + Content any `json:"content"` + ToolCalls []any `json:"tool_calls"` + FunctionCall any `json:"function_call"` + ReasoningContent any `json:"reasoning_content"` + Reasoning any `json:"reasoning"` } `json:"delta"` Text string `json:"text"` } `json:"choices"` @@ -181,6 +190,18 @@ func (c streamChunk) hasContent() bool { return false } +// hasReasoning reports whether the chunk carries reasoning text +// (reasoning_content as DeepSeek and most OpenAI-compatible hosts send it, +// reasoning as OpenRouter does). +func (c streamChunk) hasReasoning() bool { + for _, ch := range c.Choices { + if hasContent(ch.Delta.ReasoningContent) || hasContent(ch.Delta.Reasoning) { + return true + } + } + return false +} + // writeUpstreamStream pipes a committed provider stream to the client, // flushing as bytes arrive. Once the first byte is written the status is // final; an upstream failure after that can only end the stream. diff --git a/pkg/proxy/upstream_stream_test.go b/pkg/proxy/upstream_stream_test.go index d2bace9..156bc68 100644 --- a/pkg/proxy/upstream_stream_test.go +++ b/pkg/proxy/upstream_stream_test.go @@ -399,7 +399,7 @@ func TestPeekStream_PrefixIsBounded(t *testing.T) { } in.WriteString(sseHello + sseDone) want := in.String() - resp, err := peekStream(200, http.Header{}, &in) + resp, err := peekStream(200, http.Header{}, &in, nil) if err != nil || resp.stream == nil { t.Fatalf("resp=%v err=%v", resp, err) } @@ -427,7 +427,7 @@ func FuzzPeekStream(f *testing.F) { f.Add([]byte(seed)) } f.Fuzz(func(t *testing.T, in []byte) { - resp, err := peekStream(200, http.Header{}, bytes.NewReader(in)) + resp, err := peekStream(200, http.Header{}, bytes.NewReader(in), nil) if err != nil || resp.stream == nil { return } @@ -479,7 +479,7 @@ func TestStream_EOFWithoutContentIsEmptyNotTransportError(t *testing.T) { // A single line without a newline cannot grow memory without bound. func TestPeekStream_HugeLineIsBounded(t *testing.T) { in := "data: " + strings.Repeat("x", 3*maxStreamPrefix) - resp, err := peekStream(200, http.Header{}, strings.NewReader(in)) + resp, err := peekStream(200, http.Header{}, strings.NewReader(in), nil) if err != nil || resp.stream == nil { t.Fatalf("resp=%v err=%v", resp, err) } From ad4fc3e7bb6cb3474c077f01702b176b3c989282 Mon Sep 17 00:00:00 2001 From: kaiser-data <61822885+kaiser-data@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:30:41 +0100 Subject: [PATCH 2/3] docs(first-token): add Jetson Orin Nano results Co-Authored-By: Claude Opus 5.5 --- docs/first-token-timeout.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/docs/first-token-timeout.md b/docs/first-token-timeout.md index b3a4728..323a9bd 100644 --- a/docs/first-token-timeout.md +++ b/docs/first-token-timeout.md @@ -102,7 +102,7 @@ Measured 1 Dec 2026 on an 8-core Apple Silicon Mac, 200 streaming requests per r The unit tests in [`pkg/proxy/first_token_test.go`](../pkg/proxy/first_token_test.go) pin the behaviour: a stall falls back early, the setting off keeps the old wait, a model that keeps thinking past the limit still answers, and a slow non-streaming answer is unaffected. -### On real small boards (planned) +### On real small boards The loopback numbers above come from a fast machine. The claims that matter for this project are about $10 boards, so these runs are still to do. @@ -142,11 +142,15 @@ Lower `_N` and `_CONC` on single-core boards, so the client load itself does not | Board | stall p50/p95, off | stall p50/p95, 500ms | healthy p95 off / on | peak RSS, 16 stalls off / on | |---|---|---|---|---| -| Jetson Orin Nano (1 core) | | | | | +| Jetson Orin Nano (1 core) | 2031 / 2033 ms | 529 / 532 ms | 30.8 / 30.1 ms | 14.8 / 14.3 MB¹ | | Pi Zero 2 W | | | | | | Pi Zero W | | | | | | RISC-V | | | | | +Jetson run: 1 Dec 2026, Go 1.26.1, `-test.cpu 1`, `_N=100`, `_CONC=4`, provider `timeout` 2 s, cold rows. Overshoot past the 500 ms limit is ~32 ms at p95, close to the Mac. Healthy and 429 rows are within noise. The Orin is far faster than a Pi Zero, so these numbers are not Pi Zero numbers. + +¹ Peak RSS (`VmHWM`) of the whole test process, which includes the fake upstreams and the client, at 4 concurrent stalls, not 16. It shows the setting adds no memory. It is not the proxy's own footprint. + ## Ideas not built yet - **Per-provider override** (`providers[].first_token_timeout`), for example a longer value for a provider that hosts silent-reasoning models. From 863d1eeef3ae3f86005df2fa71797b1dc3d214d2 Mon Sep 17 00:00:00 2001 From: kaiser-data <61822885+kaiser-data@users.noreply.github.com> Date: Tue, 1 Dec 2026 17:30:58 +0100 Subject: [PATCH 3/3] docs(first-token): note which board runs remain Co-Authored-By: Claude Opus 5.5 --- docs/first-token-timeout.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/first-token-timeout.md b/docs/first-token-timeout.md index 323a9bd..f13ee78 100644 --- a/docs/first-token-timeout.md +++ b/docs/first-token-timeout.md @@ -104,7 +104,7 @@ The unit tests in [`pkg/proxy/first_token_test.go`](../pkg/proxy/first_token_tes ### On real small boards -The loopback numbers above come from a fast machine. The claims that matter for this project are about $10 boards, so these runs are still to do. +The loopback numbers above come from a fast machine. The claims that matter for this project are about $10 boards, so these runs matter more. The Jetson is done; the Pi Zero and RISC-V runs are still to do. **Boards**