Skip to content

feat(backend): route Pro and Flash overflow to gemini-3.1-flash-lite - #11823

Merged
Git-on-my-level merged 1 commit into
mainfrom
feat/vertex-pt-3.1-flash-lite-migration
Aug 18, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
feat/vertex-pt-3.1-flash-lite-migration

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Aug 18, 2026 •

Copy link
Copy Markdown
Member

What this does

Routes the two Gemini paths we pay on-demand for onto gemini-3.1-flash-lite, and makes the pending Provisioned Throughput migration cut over by itself.

Path Billed today After
Server-paid gemini-2.5-pro on-demand $10.00/1M out gemini-3.1-flash-lite, $1.50/1M out
gemini-2.5-flash spillover on-demand $2.50/1M out gemini-3.1-flash-lite, $1.50/1M out
gemini-2.5-flash dedicated prepaid, flat ~$290.32/day unchanged until the new reservation is observed live

Prices (Vertex list, captured 2026-08-18)

Model Input $/1M Output $/1M
gemini-2.5-flash-lite 0.10 0.40
gemini-3.1-flash-lite 0.25 1.50
gemini-2.5-flash 0.30 2.50
gemini-2.5-pro 1.25 10.00

gemini-3.1-flash-lite is not the same price class as gemini-2.5-flash-lite — it is 2.5x input and 3.75x output. It is cheaper than what it replaces on both paths above, but that makes the client-pinned Lite lanes a trap: promoting ModelQoS.lightweight (macOS) or the Windows memory/goals/insight pins onto it would raise their output cost 3.75x. Those pins are deliberately untouched and test_client_pinned_flash_lite_is_never_promoted holds the boundary.

Spillover was not previously controllable

The proxy sent no capacity header, so Vertex silently spilled over-cap requests onto pay-as-you-go. This adds X-Vertex-AI-LLM-Request-Type: dedicated for the reservation, which turns an over-cap request into a 429 Exceeded the Provisioned Throughput that the proxy can route deliberately. Everything else is pinned shared so it can never draw down the reservation.

Generic per-project 429s are explicitly not treated as overflow — buying on-demand capacity to work around backpressure would be a cost bug. test_generic_rate_limiting_is_not_converted_into_extra_spend.

The migration needs no deploy, flag, or date

When the gemini-3.1-flash-lite PT order provisions (~10 business days), the first overflow attempt asks it for dedicated capacity. That single request is the detection: if the order exists it succeeds and the proxy latches the promotion permanently; if not it 429s and falls through to the same on-demand call it would have made anyway. Detection therefore costs no extra request and only happens when the old reservation is already full.

test_a_successful_dedicated_probe_promotes_the_reservation covers the whole mechanism.

Why dedicated traffic is gated rather than moved now

Moving gemini-2.5-flash onto an on-demand model before the replacement order is live would pay the flat ~$290.32/day for idle capacity and full on-demand for ~597M tokens/day — strictly worse than either alone. test_flash_stays_on_the_current_reservation_until_target_capacity_exists.

Operator follow-up: promotion is the code-side cutover only. The 5 GSU gemini-2.5-flash order bills until ~2027-05-28 regardless, so converting or cancelling it in Cloud Console is a separate commercial action — until that happens, both are billed.

Failure class

FC-degraded-fallback-consumes-protected-budget (PR #10686) applies with a new edge: once gemini-3.1-flash-lite is the reservation, pinning overflow to it would dump degraded traffic onto the protected budget. resolve_overflow_model() is therefore a ladder resolved against the live reservation and structurally cannot return it, for this migration or any future one. test_overflow_never_targets_the_live_reservation asserts both states.

Gemini 3.x changed the thinking contract

2.5 takes thinkingConfig.thinkingBudget; 3.x takes thinkingConfig.thinkingLevel and cannot disable thinking (floor minimal). Thinking tokens bill as output, and thinkingBudget stays schema-valid on 3.x — so a stale budget is accepted and then ignored, uncapping reasoning at $1.50/1M. thinking_config_for() selects by family prefix (same approach as _CACHE_KEY_MODEL_PREFIXES), and _retarget_thinking() rewrites the body when overflow crosses families.

Unverified: whether 3.x hard-errors on thinkingBudget or silently ignores it could not be settled — aiplatform.endpoints.predict is denied to the read-only service account and no human ADC was live. The code is correct under either behaviour, but the real token counts are still worth capturing. backend/scripts/probe_gemini_thinking_contract.py reports thoughtsTokenCount per configuration; run it with credentials that can call generateContent.

Overrides

Read per request, so a bad promotion is correctable without shipping code.

Env Effect
OMI_VERTEX_PT_MODEL Pins the reservation model, beating auto-detection both ways
OMI_GEMINI_OVERFLOW_MODEL Pins overflow; rejected if it equals the reservation
OMI_GEMINI_OVERFLOW_ENABLED false disables overflow; a full reservation then 429s to the client

Testing

  • 18 new policy tests (test_vertex_pt_routing.py) and 18 new proxy tests
  • test_desktop_proxy.py + test_vertex_pt_routing.py: 77 passed
  • Streaming ladder asserts every refused attempt is closed and its provider slot released (test_streaming_overflow_falls_back_and_leaks_no_provider_slot) — a leak there would drain the concurrency pool whenever the reservation saturated
  • test_a_new_instance_probes_immediately_regardless_of_uptime covers a bug CI caught that a dev machine cannot: time.monotonic() has an arbitrary origin, so seeding the last-probe time with 0.0 suppressed the first capacity probe for the first 10 minutes of process uptime. That is invisible on a laptop with days of uptime and would have applied to every new Cloud Run instance, which is most of an instance's life. The last-probe time is now an explicit None sentinel meaning "never probed".
  • Unrelated pre-existing failures, reproduced on base d3b26f003f without this change: test_byok_security.py fails only when run after other files (39F/4E; passes alone), and test_prompt_caching.py cannot import (langchain_core.prompts missing from the venv)

Server-paid gemini-2.5-pro ($10.00/1M out) and gemini-2.5-flash spillover
($2.50/1M out) both move to gemini-3.1-flash-lite ($1.50/1M out). Dedicated
Flash traffic stays on the current reservation until a gemini-3.1-flash-lite
PT order is observed live, because moving it early would pay the flat
~$290.32/day for idle capacity AND full on-demand for the same tokens.

Spillover was not previously controllable: the proxy sent no capacity header,
so Vertex silently spilled over-cap requests onto pay-as-you-go. Requesting
`dedicated` for the reservation converts that into a 429 the proxy routes
deliberately, and pins everything else to `shared` so it can never draw the
reservation down. Generic per-project 429s are not treated as overflow.

The migration needs no deploy: the first overflow attempt asks the target for
dedicated capacity, which succeeds only once the order exists and then latches
the promotion. Detection rides an existing overflow request, so it costs no
extra call and only runs when the reservation is already full.

Overflow is a ladder resolved against the live reservation, never a pin, so
once gemini-3.1-flash-lite holds prepaid capacity overflow steps past it to
gemini-2.5-flash-lite instead of dumping degraded traffic onto the protected
budget.

gemini-3.1-flash-lite is NOT the same price class as gemini-2.5-flash-lite
(2.5x in / 3.75x out), so the client-pinned Lite lanes are deliberately left
alone; promoting them would be a large cost regression.

Gemini 3.x replaced thinkingBudget with thinkingLevel and cannot disable
thinking. thinkingBudget stays schema-valid on 3.x, so a stale budget is
accepted and ignored, uncapping reasoning tokens that bill as output. Thinking
config is now selected by family prefix and rewritten when overflow crosses
families.

Failure-Class: FC-degraded-fallback-consumes-protected-budget

Co-Authored-By: Claude Opus 5 <[email protected]>
@Git-on-my-level
Git-on-my-level force-pushed the feat/vertex-pt-3.1-flash-lite-migration branch from 822aafb to 7b85d2a Compare August 18, 2026 18:34
@Git-on-my-level
Git-on-my-level merged commit bc7f765 into main Aug 18, 2026
39 of 42 checks passed
@Git-on-my-level
Git-on-my-level deleted the feat/vertex-pt-3.1-flash-lite-migration branch August 18, 2026 19:16
Git-on-my-level added a commit that referenced this pull request Aug 18, 2026
… model a fallback chain (#11826)

## The defect

`gemini-3.1-flash-lite` returns **404** for `based-hardware`. #11823
routes server-paid Pro and Flash overflow onto it, so that routing could
not work.

**The first diagnosis in this PR was wrong, and is corrected here.** The
original claim was "no Gemini 3.x model is callable by this project". It
is not an access gap:

> **Gemini 3.x has no regional endpoint.** It is served on plain
`aiplatform.googleapis.com` with a multi-region `locations/{loc}` path
segment. `_vertex_url()` built a regional URL for every model, and a
regional URL can never work for a 3.x model.

Measured 2026-08-18 on `based-hardware` with credentials that can invoke
inference:

| Endpoint | `gemini-3.1-flash-lite` |
| --- | --- |
| `aiplatform.googleapis.com` + `locations/us` | **200** ON_DEMAND |
| `aiplatform.googleapis.com` + `locations/global` | **200** ON_DEMAND |
| `aiplatform.googleapis.com` + `locations/us` + `dedicated` header |
**429** provisioned throughput |
| `us-central1` / `us-east5` / `us-west1` / `europe-west4` /
`asia-northeast1` | **404** |
| `eu-aiplatform.googleapis.com` + `locations/eu` | **404** |

The host is always plain `aiplatform.googleapis.com`;
`us-aiplatform.googleapis.com` is not a valid host (400 `Invalid
hostname`). Only the `locations/{loc}` segment changes.

The `dedicated` 429 is the "no PT order for this model" answer, expected
while we own no 3.1 order. It also proves the capacity header is honored
multi-region, so the existing auto-detect probe works there. Note it
reads lowercase `provisioned throughput` where the regional endpoint
uses title case — the matcher casefolds, and a regression test now pins
that.

**How it got through:** availability was checked with `GET
/publishers/google/models` — the *global* catalog, no project in the
path. That enumerates models that exist in Vertex; it says nothing about
whether the URL you are about to build will reach one. Only a real
`generateContent` attempt answers that.

## Blast radius had it deployed

`bc7f7657c9` is merged but prod still serves `c5b0b5d14b`, so this never
reached production traffic.

- **Server-paid Pro** — every request 404s. `is_model_unavailable` is
not `_overflow_triggered`, so there was no retry: hard failure to the
client.
- **Flash spillover at peak** — requests that previously spilled and
*succeeded* would 429 on the reservation, fall to a 404 target, and
fail. A working degraded path converted into an outage under exactly the
load that triggers it.

## Failure class

Failure-Class: FC-platform-grant-record-as-live-capability

Same contract, new subsystem: a platform *record* was treated as proof
the running process can exercise the capability it names. There it was
`CGPreflightScreenCaptureAccess()` reading `true` while ScreenCaptureKit
refused the same process; here it is the global publisher catalog
listing a model while the request the proxy actually builds 404s.
Correcting the root cause from "access gap" to "wrong endpoint" does not
move the class — the defect is still that a catalog entry was accepted
in place of an invocation. The class's canonical prevention prescribes
the shape used here: resolve the capability from the refusal reported by
the subsystem that actually performs the work, and latch that in memory
rather than persisting it, because it is a fact about this process and
this deployment rather than a durable truth.

## Fix 1 — address each model at its real endpoint

`ptr.vertex_endpoint()` resolves `(host, location)` **per model, by
family**, in the pure policy module:

| Model | Host | Location |
| --- | --- | --- |
| `gemini-3.*` | `aiplatform.googleapis.com` | `us`
(`OMI_VERTEX_GLOBAL_LOCATION`) |
| everything else | `{loc}-aiplatform.googleapis.com` | `GCP_LOCATION`,
default `us-central1` |

**Why `us` and not `global`.** Both answer. `global` may serve a request
from anywhere in the world; `us` is the US multi-region. This path
carries users' personal conversations, transcripts and memories, and
every other server-paid Gemini call in this service runs in
`us-central1`, so `us` preserves the existing residency posture.
Widening it is a deliberate operator decision, not a side effect of a
routing change — hence a named default and an env flip rather than a
literal in a URL builder.

**Why the rule is by family and not "whatever answers".**
`gemini-2.5-flash` *also* returns 200 on `locations/us` and
`locations/global`. Sending it there would bypass the 5 GSU
**us-central1** Provisioned Throughput order and bill on-demand while
the reservation kept charging ~$290/day — paying twice for the same
tokens, which is the 2026-08-04 double-pay incident.
`test_the_reservation_model_is_never_routed_off_its_region` exists
specifically to stop that "simplification", and cites the incident in
its docstring.

Location being per-model also means nothing assumes the reservation and
the model absorbing its overflow share a location. **Unresolved and not
encoded anywhere:** whether a PT order for a 3.x model is purchased
multi-region, and how that interacts with the existing regional order.

## Fix 2 — every routable model gets a declared fallback chain

Generalized from the single migration target in the first revision of
this PR. Now defense in depth rather than the headline fix: a model that
404s degrades instead of erroring, whatever the reason.

`MODEL_FALLBACKS` in the policy module is one reviewable data table:

| Model | Falls back to |
| --- | --- |
| `gemini-2.5-pro` | `gemini-3.1-flash-lite`, `gemini-2.5-flash-lite` |
| `gemini-2.5-flash` | `gemini-3.1-flash-lite`, `gemini-2.5-flash-lite`
|
| `gemini-3.1-flash-lite` | `gemini-2.5-flash-lite` |
| `gemini-2.5-flash-lite` | *(terminal)* |
| `gemini-embedding-001` | *(terminal)* |

**`gemini-2.5-pro` is not a route in normal use.** It appears in the
table because it stays proxy-allowlisted and BYOK users pay for it on
their own key, but no server-paid request is dispatched as Pro:
`_serving_model()` remaps it to `gemini-3.1-flash-lite` before dispatch,
and over the daily soft limit the metering path demotes it to
`gemini-2.5-flash-lite` first.
`test_server_paid_traffic_never_dispatches_gemini_2_5_pro` asserts this
across both reservation states and both reachability states — 4
parametrised cases — and a companion test asserts BYOK Pro is still
honoured.

Three invariants, each enforced by a test rather than by convention:

- **Never onto the reservation.** The live PT model is filtered out of
every chain at resolution time, asserted at both PT states across every
model (FC-degraded-fallback-consumes-protected-budget).
- **Never upward in price.** Each chain is non-increasing in
`PRICE_PER_MTOK_OUT`, so a degraded request cannot cost more than the
one it replaces. This is also why `gemini-2.5-flash-lite` is terminal —
it is the floor of the ladder *and* the model the desktop clients pin
directly (`ModelQoS.lightweight`, Windows `memory`/`goals`/`insight`).
`test_client_pinned_flash_lite_is_never_promoted` still holds.
- **Never onto itself.** A chain never contains its own head, so a dead
model cannot retry itself.

## Fix 3 — reachability is learned, per model, from traffic only

- **No startup probe.** The metadata endpoint `GET
.../publishers/google/models/{m}` is not an oracle: it 404s for
`gemini-2.5-flash-lite`, which works fine. The only honest signal is a
real `generateContent` attempt, and burning one per model per instance
is unaffordable on Cloud Run, which churns instances constantly.
- **Per model**, so one dead model cannot take the ladder down with it.
- **Absence of an entry — never `0.0` — means "never observed".**
`time.monotonic()` has an arbitrary origin, so a zero-seeded observation
would mark every model dead for the first 10 minutes of each new
instance's life. Regression test included, alongside the existing one
for the probe timestamp.
- **BYOK never teaches the table.** BYOK goes to AI Studio on the user's
own key, so its answers say nothing about what this project reaches on
Vertex; one user's key must not latch a model dead for the fleet. (This
also closes a narrower version of the same hole in the previous
revision.)
- Entries expire on the capacity TTL, so a routing fix or a serving
change recovers with no deploy.
- A generic 429 (`Quota exceeded for requests per minute`) is still
backpressure and never triggers fallback. Only a PT-exhaustion 429 or a
model-unavailable 404 does.

Both the streaming and non-streaming paths get all of this;
`test_streaming_unreachable_model_falls_back_and_leaks_no_provider_slot`
asserts every refused attempt is closed and its provider slot released,
matching the existing overflow-ladder guarantee.

## The thinking contract: measured, and it deleted a branch

The 3.x half of the table was unmeasurable before, because those models
were unreachable. With the endpoint fixed:

| Model | Config | thoughts | output |
| --- | --- | ---: | ---: |
| `gemini-2.5-flash-lite` | `thinkingBudget: 0` | 0 | 225 |
| `gemini-2.5-flash-lite` | `thinkingBudget: 1024` | 863 | 300 |
| `gemini-2.5-flash-lite` | `thinkingLevel: minimal` | **HTTP 400 — not
supported** | |
| `gemini-2.5-flash` | no config | 516 | 213 |
| `gemini-3.1-flash-lite` | `thinkingBudget: 0` | 0 | 64 |
| `gemini-3.1-flash-lite` | `thinkingBudget: 1024` | 278 | 77 |
| `gemini-3.1-flash-lite` | `thinkingLevel: minimal` | 0 | 75 |
| `gemini-3.1-flash-lite` | `thinkingLevel: high` | 603 | 76 |
| `gemini-3.1-flash-lite` | no config | 0 | 64 |

**This reverses the earlier conclusion.** #11823 split `thinkingConfig`
by family on the documented claim that 3.x ignores `thinkingBudget` and
cannot disable thinking. Measured, `gemini-3.1-flash-lite` **honors**
`thinkingBudget` — 0 really is 0 thoughts, 1024 spends 278 — while 2.5
models **reject** `thinkingLevel` with HTTP 400. So `thinkingBudget` is
the one option both families accept and `thinkingLevel` is the one that
works on neither universally.

The split is therefore **deleted rather than inverted**:
`ptr.thinking_config_for()` is a single path and `_retarget_thinking()`
is gone, so a fallback that crosses families rewrites nothing. Net
removal of a branch and a body-rewriting function.

It still justifies injecting a budget at all: `gemini-2.5-flash` with no
thinking config spent 516 thinking tokens on a trivial prompt, all
billed as output.

## Testing

```
backend $ .venv/bin/python -m pytest tests/unit/test_desktop_proxy.py \
      tests/unit/test_vertex_pt_routing.py -q
128 passed

$ .venv/bin/python -m pyright backend/routers/desktop_proxy.py \
      backend/utils/llm/vertex_pt_routing.py
0 errors, 0 warnings, 0 informations
```

Behavioral coverage added for each claim above:

- `test_gemini_3_x_is_routed_to_the_us_multi_region_endpoint` — the
actual production defect
- `test_the_reservation_model_is_never_routed_off_its_region` — the
2026-08-04 double-pay guard
- `test_the_multi_region_residency_pin_is_us_and_is_operator_flippable`
— residency default and its escape hatch
- `test_a_fallback_across_families_also_crosses_endpoints` — per-model
location, end to end through `_upstream`
- `test_no_fallback_chain_ever_routes_onto_the_reservation` /
`test_no_recovery_plan_ever_routes_onto_the_reservation` — parametrized
over every model at both PT states
- `test_every_chain_is_non_increasing_in_output_price`,
`test_the_cheapest_text_model_is_terminal` — the cost invariants
- `test_reachability_is_learned_per_model_not_globally`,
`test_byok_traffic_never_teaches_the_reachability_table`
-
`test_a_new_instance_believes_every_model_reachable_regardless_of_uptime`
— the `monotonic()` origin trap
- `test_a_404_on_any_model_falls_back_and_latches_it`,
`test_streaming_unreachable_model_falls_back_and_leaks_no_provider_slot`
- `test_thinking_budget_is_the_one_option_both_families_accept` — cites
the measurement above, per the rule that a test rewritten alongside its
code must cite an external source

`backend/docs/vertex-pt-flash.md` carries the corrected endpoint
finding, the residency reasoning, the fallback table, and the full
measured thinking contract; `test_migration_contract_is_documented` now
asserts every declared model and both endpoint constants appear there.

## Operator note

The earlier note here said enabling Gemini 3.x access for
`based-hardware` was a prerequisite for any of this. **That was wrong —
there is nothing to enable.** 3.x is reachable today at the multi-region
endpoint, so the routing and the PT migration are unblocked. What
remains genuinely open is whether a 3.x PT order is purchased
multi-region and how it interacts with the existing regional
`gemini-2.5-flash` order; no code here assumes an answer.
mikejsmith1985 pushed a commit to mikejsmith1985/omi that referenced this pull request Aug 18, 2026
No gemini-3.x model is callable by based-hardware: every one 404s on the
project-scoped endpoint while appearing in the global publisher catalog, on
both v1 and v1beta1 and in both us-central1 and global. BasedHardware#11823 routes
server-paid Pro and Flash overflow to gemini-3.1-flash-lite, so Pro would have
404'd outright and peak spillover would have turned a working degraded path
into a hard failure under exactly the load that triggers it.

The availability check that missed this listed the global catalog, which
enumerates models that exist in Vertex rather than models a project may call.
Only the project-scoped path answers that, and it needs credentials that can
invoke inference.

Availability is now a routing state rather than an error. A 404 from the target
latches the observation, re-serves the in-flight request on a model that works,
and clears the prepaid-capacity flag, because a model the project cannot call
cannot be holding a reservation. Overflow resolves to a ladder instead of a
single pin so a dead rung is skipped and a reachable rung always remains, still
never returning the reservation itself. The latch is re-checked on the same TTL
as capacity, so enabling 3.x access later restores the intended routing with no
deploy.

Also records the measured thinking contract: 2.5 models honor thinkingBudget
and reject thinkingLevel with a 400, so the family split is required in both
directions rather than defensive.

Failure-Class: FC-platform-grant-record-as-live-capability
Co-Authored-By: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant