Skip to content

fix(sandbox): move the model gateway to Bifrost v2.2.4 - #3961

Merged
yannickmonney merged 7 commits into
mainfrom
fix/gateway-bifrost-v2
Sep 30, 2026
Merged

yannickmonney merged 7 commits into
mainfrom
fix/gateway-bifrost-v2

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Why

The pinned gateway (Bifrost v1.6.11) never noticed a caller leaving a whole answer. It served, and billed, an abandoned request to its end, and the same went for a prefill that a stream was still waiting on. On a model that serves one request at a time, every resent request queued behind its own ghost (vatplus run r0014). Bifrost v2.2 cancels the vendor call as soon as the caller hangs up.

What changes

  • Gateway image (services/sandbox-llm-gateway): pinned to maximhq/bifrost:v2.2.4.
    • v2.2 creates its first admin account only for a caller that presents the setup token it started with. A new docker-entrypoint.sh always sets BIFROST_SETUP_TOKEN to SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD, which is the token the platform presents, then runs the upstream entrypoint unchanged. An explicit BIFROST_SETUP_TOKEN on the container is replaced, and a log notice names it without printing either value.
    • Every deployment path already gives the gateway that variable (tale deploy via env_file: .env, compose.yml, and the documented Kubernetes envFrom: tale-env), so there is no new secret and no manifest change. compose.dev.yml gives the gateway its dev default.
    • The container smoke test now waits for the gateway, gives it a different explicit BIFROST_SETUP_TOKEN, and checks that the running process holds the password.
  • Platform bootstrap (llm_gateway_admin.ts):
    • The first PUT /api/config carries auth_config.setup_token, which is the admin password.
    • Every management call also sends X-Bifrost-Setup-Token. Upstream's open fix(auth): require the setup token on the management API until an admin exists maximhq/bifrost#7595 moves the management API to requiring that header until an admin exists; a gateway that already has an admin ignores it.
    • Three fields the gateway ignores are dropped: enforce_governance_header, disable_auth_on_inference and allow_all_keys. Enforcement was re-checked live on both versions without them.
    • The wire facts are restated as verified against v2.2.4.
  • Metering (model_api): a whole answer the caller abandoned is now cancelled at the vendor. It is booked like a cut stream, at least its prompt plus the relayed output at the catalog price, and settled a few seconds after it ends instead of after the 10+ minute request timeout. Only a request the watchdog closes as stale still waits, because a hung process may keep its connection open. A call the caller leaves before it is sent (while the guardrails judge it, or its hold or key is being made) is not sent and books nothing of its own.
  • Docs (EN/DE/FR):
    • Environment reference, own Compose and Kubernetes: the gateway reads the admin password as its setup token. The environment reference adds that the image always uses it and replaces BIFROST_SETUP_TOKEN.
    • A new upgrade-guide section covers the in-place store migration, how to back up and restore llm-gateway-data, and rollback. It is keyed to the Bifrost 1.6 → 2.2 move, which comes in a release after 0.5.64 whose notes list it; no release number is guessed.
    • The model-endpoint billing sentence is updated.
  • Contracts: .agents/repo.md narrows the debt entry to what is still missing (usage of a cancelled call). There is a new manual box, GOV-F47, and the automation row is updated.

Verified live

Test rig: an isolated gateway container and a scriptable mock upstream. The platform's own llm_gateway_admin.ts drove every call.

This table is the author's report. Its rig, fixtures and raw results are not attached to this PR; see Review corrections below for what was independently re-run.

Check v1.6.11 v2.2.4
Fresh bootstrap by the platform ok (no token) ok with the token; 403 without or with a wrong one
v1.6.11 store opened by v2.2.4 in place — migrations clean; spend (5¢), admin, provider keys, pricing and old virtual keys kept
Whole answer, caller hangs up at 3 s ran 20 s to the end, billed 104¢ upstream aborted 0.5 s later, billed 0
Stream with headers withheld (prefill), hang-up upstream ran the full 30 s prefill aborted 0.5 s later
Stream, hang-up cancelled after 2 s cancelled after 0.5 s
Real Claude Code 2.1.285, tool loop on a DeepSeek-style reasoning upstream — reasoning_content replayed, turn completes
Anthropic record with thinking signatures; Codex Responses → chat-only upstream ok ok (identical)
Allowlist 403, cross-org 403, revoked key 401, spent budget 402, current_usage kept across a cap change ok ok
Rollback: v1.6.11 on a migrated store serves Tale, but logs no such column: oauth_configs.token_id —

The documented backup and restore commands were run against a real store volume.

Review corrections (after 2af85d2)

These answer the review of 2af85d28c (three P2 findings). Commits 2d3249aec, 37b2ae8ca and 610bc9e4d were pushed as a fast-forward on top of it.

  1. A call its caller left before it was sent was booked at its prompt.
    • The relay now checks the caller right before the gateway call. It books a floor only for a call that may have left the process (dispatched && !neverConnected).
    • With the real Node fetch against an inert loopback gateway, a synthetic 1M-token prompt at 30¢/M:
      • Before the fix, a pre-aborted whole answer, a pre-aborted stream, and a hang-up during 50 ms of pre-relay work each sent 0 requests but booked a 30¢ floor.
      • After the fix they send 0 and book no floor.
      • Unchanged controls: a caller who stays gets 1 request and completes; a hang-up after the gateway received the request keeps its 30¢ floor.
    • New tests cover this in relay.test.ts (real fetch), metering.test.ts, and v1-model-api.test.ts (hang-up during the guardrails and during the key mint). Four of them fail against the unfixed relay.
  2. A distinct explicit BIFROST_SETUP_TOKEN kept a fresh gateway from its admin.
    • Policy: the setup token is always the admin password. The entrypoint replaces an explicit token and reads the password the way the platform does. The platform keeps sending only the password.
    • gateway_setup_token.test.ts runs the real entrypoint and gives its token to a management plane that decides as upstream transports/v2.2.4 (ed8371a) does. The platform's own applyGatewayConfig then bootstraps it. Cases: password only; distinct explicit token; explicit token equal to the password; the pre-rename name; no password (403, fail closed); installed admin with any token or none. Four cases fail against the old entrypoint.
    • Live, against the real maximhq/bifrost:v2.2.4 linux/amd64 binary (index sha256:5f8215163cea…, layers sha256-verified), run as the image's entrypoint chain on loopback without Docker:
      • The old entrypoint with a distinct token answered 403. The gateway stayed unclaimed, and anonymous GET /api/config answered 200.
      • The new entrypoint bootstraps it: the admin is created and anonymous access answers 401.
      • Installed admins ignore any token or none.
      • The only deviation from production: config.json points the pricing datasheets at local files, because this sandbox resolves no public DNS.
  3. The upgrade guide named the wrong release. v0.5.64 (ebf4546) still pins Bifrost 1.6.11. The EN/DE/FR section is now keyed to the Bifrost 1.6 → 2.2 move ("a release after 0.5.64", whose notes list it).

What this does not prove:

  • The matrix above (providers, isolation, the SQLite migration, backup and restore) is still the author's report. No raw rig, fixture or result for it was found in this PR, its CI artifacts, the repair workspace or the organization knowledge base, and none was re-run here.
  • The live check above covers the setup-token handshake only.

Known, not changed here

  • Cut calls are still not billed by the gateway. v2.2.4 books nothing for a cut OpenAI-wire call; an Anthropic stream keeps its input tokens. So the floor stays, and the debt entry keeps this.
  • New v2 heartbeat rule. An OpenAI-wire stream ends on two keepalive comments after finish_reason, so an upstream that sends them before its usage frame is billed 0. The mock reproduced this. It is recorded in the debt entry; I have no evidence that a real upstream does this.
  • Pre-existing SQLite lock contention. Under concurrent key churn and right after boot, the gateway answers some management writes with 500 "database is locked" (64 lifecycles at 8-way concurrency: 16 revoke failures on v1.6.11, 9 on v2.2.4). The platform's sweeps retry revokes, but an image admission can be refused. A follow-up PR retries idempotent management writes.
  • Unchanged in both versions:
    • INFERENCE-16: a role-less first tool-call chunk still gets no message_start.
    • count_tokens on custom records still answers 400.
    • Stale-connection replay (R14-16) is now limited to failures before the status line on a pooled socket, so it is reduced but not gone.

The gateway now creates its first admin account only for a request that
carries the setup token it started with. The platform sends its admin
password as that token in the bootstrap body, and on every management call
in the header a gateway that closes its whole management plane until an
admin exists reads. It also stops sending three fields the gateway ignores
(enforce_governance_header, disable_auth_on_inference, allow_all_keys) and
states the wire facts as verified against Bifrost v2.2.4.
Bifrost 1.6 kept serving, and billing, an abandoned whole answer to its
end, and a prefill a stream was waiting on, so every resent request queued
behind its own ghost on a model that serves one request at a time. v2.2
cancels the vendor call within half a second of the caller hanging up.

v2.2 creates its first admin account only for a caller presenting its setup
token. The gateway image derives BIFROST_SETUP_TOKEN from
SANDBOX_LLM_GATEWAY_ADMIN_PASSWORD, which every Tale deployment already
passes it, so no new secret exists; the dockerized dev overlay now gives
the gateway its dev default, and the container smoke test checks the
running gateway holds the token.

The store migrates in place on first start. The upgrade guide says how to
copy the gateway volume first, since an older gateway on a migrated store
serves Tale but logs errors, and what changes for operators.
The gateway now cancels the vendor call when a caller hangs up, so a whole
answer the caller abandoned no longer generates, and bills, to its end
while its settlement waits out the request timeout. It is booked like a
stream that ended early: at least its prompt and the output that reached
the caller, at the catalog price, settled a few seconds after it ends.
Only a request the watchdog closes as stale still waits out a whole
answer's lifetime, since its process may hold its connection open.

The debt entry keeps what the gateway still does not do: book the usage a
cancelled call had reached.
An answer that ended early is booked at its prompt floor because the
vendor may have read the prompt. A call whose connection to the gateway
was never made (refused while a deploy replaces the gateway, a name that
does not resolve, a connect timeout) left this process, so it books only
the gateway's own figure. The old deferred read booked such a whole answer
at 0; streams had booked the floor.
@yannickmonney

Copy link
Copy Markdown
Contributor Author

Holding this PR at 2af85d28c7b9bfeab3a9e6443d700ed94f64ef9b for three corrections found in independent local review:

  1. P2 — a request cancelled before dispatch can still charge its prompt. In model_api/relay.ts:673,707, an already-aborted signal reaches fetch and the resulting AbortError is assigned countedOutputTokens: 0. Actual spendFactsOf then books the prompt floor. Using real Node fetch against a synthetic loopback server: 0 requests received, but a synthetic 1M-token prompt produced 30¢ of floor spend. The healthy control received one request and completed. Handle cancellation before dispatch as never sent; preserve accounting when transmission may already have occurred. Cover cancellation during the asynchronous pre-relay guardrail/provisioning work and retain whole/stream controls.

  2. P2 — a distinct explicit setup token breaks initial bootstrap. The gateway wrapper preserves BIFROST_SETUP_TOKEN and its README promises that override, but llm_gateway_admin.ts:176,1488 always sends the admin password in the setup header/body. Actual applyGatewayConfig against a scripted boundary implementing the tagged upstream comparison passes for token=password and fails 403 for a distinct token. Choose one consistent policy for both containers: derive unconditionally and document it, or have the platform send the same explicit setup token while keeping the admin password for admin authentication. Add the distinct-token regression. This reproduction is source-coupled client proof, not a live Bifrost process.

  3. P2 — fix the EN/DE/FR upgrade boundary. The upgrade guide calls the Bifrost 1.6→2.2 migration the first release after 0.5.63. Immutable v0.5.64 points at ebf4546fb1455a236c1046f3d73ef78c2e1d0109, which still pins Bifrost v1.6.11 and does not contain this PR. Describe the actual Bifrost transition, or use the real containing release once allocated; do not guess the next version.

Fresh affected local suites: 161 passed. Four independent probes: 2 healthy controls passed, 2 finding expectations failed. Exact-head hosted Build/Checks/E2E attempt 1 passed; affected unit tasks show actual cache misses and gateway smoke executed 29/29. Those successes do not cover the two counterexamples. No production probing, Docker execution, or product changes were made during this independent review.

Please also link the raw fixture/results for the PR's live provider/isolation and SQLite migration/backup/restore matrix, with source/image identity, so a reviewer can distinguish verified artifacts from prose claims. The current matrix remains author-reported.

Upstream comparison: https://github.com/maximhq/bifrost/blob/ed8371a9779bfbc8aa689d4d77964cf8ce9308bf/transports/bifrost-http/handlers/config.go#L932 . Root retains the final independent review and normal merge gate.

A caller that hung up while its request was still being governed (the
input guardrails judging it, its budget hold being taken, its gateway key
being minted) reached the relay with an aborted signal. Node's fetch then
failed at once without sending a byte, yet the relay reported the call as
an answer that ended early, and the settlement booked its whole prompt at
the catalog price: 30 cents for a 1M-token prompt at 30 cents per million,
against a gateway that received nothing.

The relay now checks the caller right before it makes the gateway call and
books a floor only for a call that may have left the process. A request the
caller left first is closed as cancelled with nothing of its own to book, so
only the gateway's figure for its unused key counts. Every hang-up after the
call was made keeps its accounting: a whole answer at least its prompt, a
stream its prompt and the output relayed.

The endpoint docs say that a call broken off during its checks is neither
sent nor booked.
The gateway image kept a BIFROST_SETUP_TOKEN set on the container, while the
platform always presents the admin password as the setup token. A fresh
gateway given any other token refused the platform's bootstrap with 403, so
it never got its admin account, and Bifrost 2.2 leaves the management API of
an unclaimed gateway open to anyone who can reach it.

The token is now the admin password, always. The entrypoint replaces an
explicit BIFROST_SETUP_TOKEN, says so in the log without printing either
value, and reads the password the way the platform does. One secret claims
the gateway and manages it, so nothing has to stay in step between two
containers. A gateway that already has its admin ignores the token either
way.

A new platform suite runs the real entrypoint and hands its token to a
management plane that decides as Bifrost 2.2.4 does, bootstrapped by the
platform's own client. The container smoke test now gives the gateway a
different explicit token and checks that the running process holds the
password.
The upgrade guide said the first release after 0.5.63 moves the model
gateway from Bifrost 1.6 to 2.2. That release is 0.5.64, which still pins
Bifrost 1.6.11 and does not carry the move. The section now keys on the move
itself, in English, German and French: a release after 0.5.64 makes it, and
its release notes list it. The rollback paragraph names a release before the
move rather than an older one.
@yannickmonney

yannickmonney commented Sep 30, 2026 •

Copy link
Copy Markdown
Contributor Author

All three findings from the review of 2af85d28c are fixed at head 610bc9e4d8c7ec75f1a4f6d20d2f9c4e3b906a97. The three commits are a fast-forward on top of the reviewed head; nothing was rewritten.

1. A call cancelled before dispatch charged its prompt (2d3249aec)

  • The relay checks the caller right before the gateway call (signal.throwIfAborted()) and books a floor only for a call that was actually dispatched and got a connection.

  • Reproduced with the real Node fetch against an inert loopback gateway, a synthetic 1M-token prompt and the real spendFactsOf:

    Case Before: requests / floor After: requests / floor
    Whole answer, pre-aborted 0 / 30¢ 0 / none
    Stream, pre-aborted 0 / 30¢ 0 / none
    Hang-up during 50 ms of pre-relay work 0 / 30¢ 0 / none
    Caller stays (control) 1, completed 1, completed
    Hang-up after the gateway received the request (control) 1 / 30¢ 1 / 30¢
  • New tests:

    • relay.test.ts uses the real fetch (whole answer, stream, the governed-delay case, plus both controls).
    • v1-model-api.test.ts covers a caller who hangs up during the guardrails or during the key mint: no gateway call, the lease closes {status: 'cancelled'}, and the real spendFactsOf returns a null floor. It has a control where the caller stays.
    • metering.test.ts has the contract case.
  • Four of these fail against the unfixed relay.

  • The billing sentence in the EN/DE/FR docs now says that a call broken off during its checks is neither sent nor booked.

2. An explicit setup token broke the first bootstrap (37b2ae8ca)

  • Policy: the setup token is always the admin password. The entrypoint sets BIFROST_SETUP_TOKEN from the password the way the platform reads it (current name if set, else the pre-rename one). It replaces an explicit token, with a stderr notice that prints neither value. The platform still sends only the password, so no second secret has to stay in step between two containers.
  • The policy is documented in the gateway README and the EN/DE/FR environment reference.
  • gateway_setup_token.test.ts runs the real entrypoint under /bin/sh (only its exec swapped) and gives its token to a management plane that follows upstream transports/v2.2.4 (ed8371a): trimmed token, empty means none, constant-time compare, token ignored once an admin exists. The platform's own applyGatewayConfig then bootstraps it. Cases:
    • password only
    • a distinct explicit token
    • an explicit token equal to the password
    • the legacy password name
    • no password (403, fail closed)
    • an installed admin restarted with a distinct token, or with none
  • Four of these fail against the old entrypoint, including the distinct-token 403.
  • Live check, on the real maximhq/bifrost:v2.2.4 linux/amd64 static binary:
    • Pulled by digest (index sha256:5f8215163cea…, manifest sha256:74826952fd6f…, layers sha256-verified) and run through the image's own entrypoint chain on loopback. There is no Docker on the review host, and only the absolute exec paths were swapped.
    • The one deviation: config.json points the pricing datasheets at local files, because that host resolves no public DNS.
    • With the reviewed entrypoint and a distinct token, the platform's applyGatewayConfig got a live 403. The gateway stayed unclaimed, and anonymous GET /api/config answered 200.
    • With the fix, the same case bootstraps: the admin is created and anonymous access gets 401.
    • An installed admin ignores any token, or none.
  • The CI smoke test now gives the gateway a distinct explicit token through .env.test, and checks that PID 1 holds the password.

3. Upgrade boundary (610bc9e4d)
The EN/DE/FR section is now "Bifrost 1.6 → 2.2": the move comes in a release after 0.5.64, whose notes list it. No release number is guessed. For reference, the tags pin Bifrost 1.5.13 up to v0.5.18 and 1.6.11 from v0.5.19 through v0.5.64.

Raw evidence for the live matrix: I could not find any raw rig, fixture or result for the author's provider/isolation and SQLite migration/backup/restore matrix. I looked in the PR body and comments, the PR's files, the CI artifacts of 2af85d28c (build SBOMs and caches only), the local workspace and the knowledge base. That table stays author-reported, and I did not re-run it. The only live receipt of the reviewed head is the hosted smoke job (29/29, image pr-3961-sha-180965c9…), which checks gateway health and PID 1's token but never bootstraps the gateway.

Local gates on 610bc9e4d:

  • vitest: 15 files, 355 tests pass (model_api, v1-model-api, llm_gateway_admin, gateway_provisioning, gateway_setup_token, spend-settlement, turbo-inputs guard).
  • Docs suite: 36 files, 200 tests pass.
  • lint:manual passes; oxlint (type-aware) and a scoped tsc are clean on the changed files.
  • The turbo guard fails when the new entrypoint input is removed, so it really checks it.

CI on 610bc9e4d: green.

  • 74 check runs: 60 success, 13 skipped, and Trivy neutral, as it was on 2af85d28c. All 7 workflows succeeded on the first attempt.
  • turbo ran @tale/platform:test, @tale/docs:test and @tale/cli:test as cache misses, not replays. The new counts show in the Unit log: relay 31, metering 30, v1-model-api 17, turbo guard 29, gateway_setup_token 12.
  • The hosted smoke test pulled the corrected gateway image by digest sha256:f1b0329a… and passed 29/29. That includes "Gateway takes its setup token from the admin password, not BIFROST_SETUP_TOKEN", with a distinct explicit token in the container's environment.

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