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
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions configs/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
158 changes: 158 additions & 0 deletions docs/first-token-timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
# 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

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**

| 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) | 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.
- **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.
5 changes: 5 additions & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading