Commit Graph
368 Commits
Author SHA1 Message Date
lukaszraczylo c3adbfe073 fix(mcp): keep the target query when it does not parse
mergeQueryStrings now forwards a configured query that ParseQuery
rejects, next to the client query, instead of dropping it.
2026-11-29 00:24:56 +00:00
lukaszraczylo eb3846e317 fix(discovery): bound the number and length of discovered model ids
A provider keeps at most 10000 discovered ids of at most 256 bytes.
The registry drops empty ids, ids with control characters, longer ids
and the overflow, and logs the count once per 10 minutes.
2026-11-29 00:24:53 +00:00
lukaszraczylo 916070e16d test(passthrough): rename the client reset reader helper
Two packages each declared failingReader in the same test package. The passthrough gate test now uses clientResetReader.
2026-11-29 00:24:16 +00:00
lukaszraczylo 4e87b61932 fix(proxy): do not relay a redirect that carries a configured target query
proxyUpstream answers 502 when an upstream replies with a 3xx Location
and the upstream URL holds a query the client did not send. Targets
without a configured query still relay redirects.
2026-11-29 00:23:11 +00:00
lukaszraczylo 7d43366324 fix(admin): scrub the re-serialised base URL from provider errors
sanitizeProviderErr now also replaces the URL as net/url writes it.
A provider baseUrl with userinfo, a query or a fragment logs one
construction warning. The config still loads.
2026-11-29 00:23:11 +00:00
lukaszraczylo d01e287ea2 fix(passthrough): bill Responses API and Gemini streaming usage shapes
Read input_tokens/output_tokens and input_tokens_details.cached_tokens
for OpenAI Responses JSON, and response.usage from response.completed
SSE events. Decode the Gemini streamGenerateContent JSON array and read
usageMetadata from Gemini SSE data events, last one wins.

Field names follow the OpenAI Responses API and Gemini
GenerateContentResponse references. A truncated array yields no usage.
2026-11-29 00:23:11 +00:00
lukaszraczylo 47f885343f docs: state that /v1/messages responses are cached
The Caching section named chat and embeddings only. It now names
/v1/messages, the beta set in the key, and that entries are shared
across users and groups.
2026-11-29 00:23:10 +00:00
lukaszraczylo 365fe88819 fix(cache): key /v1/messages entries on the forwarded anthropic-beta set
Two callers that sent different anthropic-beta values shared one cache
entry, although the gateway forwards that header upstream. The key now
includes the normalised beta set when the header is present. Requests
without the header keep their existing key.
2026-11-29 00:23:10 +00:00
lukaszraczylo 932b459257 fix(billing): estimate completion when a stream ends before its usage
A streaming unified request that failed after output reached the client
recorded zero completion tokens. The gateway now estimates them from the
forwarded output bytes and marks the usage as estimated. Streams that
report usage, and streams that end cleanly, are unchanged.
2026-11-29 00:23:10 +00:00
lukaszraczylo a11e640230 fix(passthrough): gate and bill passthrough requests by cost budget
Refusal text stays under 128 bytes, and only models the provider serves get a per-model counter. When the first 64 KiB does not settle the model, the gate reads the body up to the smaller of maxRequestBytes and the passthrough cap, inside a body-admission slot. It refuses with 402 if the model is missing, repeated, or in a malformed or unterminated object, with 413 if the object does not close within the bound, and with 400 if the body read fails. A priced model after 64 KiB passes and the body reaches the upstream unchanged. A 2xx event stream with no completion usage bills one estimated token per data event.
2026-11-29 00:23:09 +00:00
lukaszraczylo 250d83de2a fix(webui): show provider upstream errors
The dashboard ignored upstreamErrors from the admin overview. A provider
with a failing modelBaseUrls upstream looked healthy. The provider panel
now lists each upstream error, and the breaker rows mark such a provider
as degraded.
2026-11-29 00:23:09 +00:00
lukaszraczylo b796fd5df1 fix(discovery): keep context lengths when one upstream fails metadata
A failing modelBaseUrls upstream dropped its models from the metadata map.
The registry replaced the discovered contexts, so those models lost their
context length. The failure was also not visible. The adapter now keeps the
last good metadata per upstream and reports metadata failures through
upstreamErrors.
2026-11-29 00:23:09 +00:00
lukaszraczylo e9fce98bab fix(admin): list the anonymous user in snapshot views
The auth snapshot built users from the key digest map only. The keyless
principal never appeared in usage, catalog, metrics or fleet views, and
its rejection counter was pruned on a users-file reload. The snapshot now
adds the anonymous principal once, with source anonymous.
2026-11-29 00:23:08 +00:00
lukaszraczyloandGitHub f1633666ff fix(discovery): isolate each modelBaseUrls upstream's timeout (#24)
Discovery and metadata polled the upstreams one after another on one
shared context. A hanging modelBaseUrls upstream used up the deadline,
and the whole provider failed again.

Query all upstreams concurrently. Give each modelBaseUrls upstream its
own context with 3/4 of the remaining time, or 30s without a deadline.
A child timeout is recorded in upstreamErrors and skipped. Only a
baseUrl failure, or a cancelled or expired parent context, fails the
listing. The result order stays baseUrl first, then the sorted upstreams.
2026-11-28 02:26:16 +00:00
lukaszraczyloandGitHub bfdffc2ab0 fix(admin): show aliases, guard the provider filter, tolerate failing upstreams (#23)
* fix(admin): attach model aliases to the model their target resolves to

The catalog grouped aliases by the raw target string and looked them up by
canonical provider/model id. A bare target never matched, so no model card
listed its aliases. Each alias now keys on the canonical id that the
registry resolves its target to. The alias view gains an additive
resolvedTarget field.

Model-id cells in the overview, usage and panels now show an alias badge
with the target, using the catalog alias list.

* fix(webui): omit the provider filter select until providers load

* fix(discovery): tolerate failing modelBaseUrls upstreams

A modelBaseUrls upstream that fails /v1/models must not fail the provider.
Discovery now fails only when baseUrl fails. The explicit models of the
failing upstream stay listed, and the other upstreams still merge.

The admin overview reports each failed upstream in the additive
upstreamErrors field. The registry logs it at most once per 10 minutes
per provider. The README states the new semantics.

* chore(webui): regenerate admin assets

Rebuilt with make admin-ui for the alias badge and the provider filter changes.

* style(auth): order authStore fields for fieldalignment

golangci-lint's fieldalignment check reported 240 leading pointer bytes on authStore where 232 is optimal. The bool anonymousAnyKey moves next to the mutexes. No behaviour change.
2026-11-28 02:13:22 +00:00
lukaszraczyloandGitHub 7fade3cdee feat(models): advertise max_context_length and query every modelBaseUrls upstream (#22)
GET /v1/models now emits max_context_length next to the other context
fields, so a downstream gateway can read it through metadataPath. The
field is omitted when the context window is unknown.

Discovery and metadataPath now query baseUrl and each distinct
modelBaseUrls upstream. The gateway keeps an id only from the upstream
that serves it. Discovery fails when any upstream fails and keeps the
last-known set. Metadata keeps the ids of the upstreams that answered.
2026-11-28 01:19:54 +00:00
lukaszraczyloandGitHub 1c9ce1c2ad feat(providers): turn thinking off for small output caps on opted-in providers (#21)
A thinking model spends a small max_tokens on reasoning and returns empty
content with finish_reason length. TensorFold on the d1 DeepSeek server
warns about this and suggests chat_template_kwargs enable_thinking false.

providers.<name>.thinking.offBelowMaxTokens (openai type, default off)
adds chat_template_kwargs: {"enable_thinking": false} to the upstream
body when a chat request caps its output under the value. It also does
this when /v1/messages translates a request for that provider. A request
with no cap, a cap at or above the value, or its own thinking choice
(reasoning_effort, reasoning, thinking, enable_thinking, or
chat_template_kwargs.enable_thinking or .thinking) is not changed. Other
client chat_template_kwargs keys are kept, and the client's map is not
modified. The response cache still keys on the client body.
2026-11-27 16:31:36 +00:00
lukaszraczyloandGitHub c89df4bc6a fix(openai): treat a stream cut before its finish as an upstream failure (#20)
An OpenAI-compatible stream that ended with neither a finish_reason nor
[DONE] counted as a finished answer. When the d1 model server died
mid-reply, the gateway sent the client an empty stream with no
finish_reason, and the smart router did not try its next tier.

forwardStream now returns errStreamTruncated for such a stream, wrapped
in errUpstream. Before any output reaches the client, the request fails
over or escalates to the next tier. After output, the client gets an
error event and no [DONE]. A stream with [DONE] but no finish_reason
keeps its old behaviour.
2026-11-27 11:55:52 +00:00
lukaszraczyloandGitHub af1a64aaa3 fix(passthrough): send event-stream headers before the first event (#19)
The passthrough proxy wrote the status line but flushed only on the first
body write. An MCP server-to-client stream (GET with text/event-stream)
can stay silent for a long time, so the client did not get the response
headers. Traefik in front of the standalone gateway waited for its 20m
responseHeaderTimeout and then returned 504.

The proxy now flushes the headers at once when the upstream answers with
text/event-stream.
2026-11-27 10:46:22 +00:00
lukaszraczyloandGitHub 9f2690b9bf feat(auth): add users.anonymousAcceptAnyKey for clients that need a key (#16)
The OpenAI SDKs refuse to start without an API key, so keyless callers
set a placeholder key. With users.anonymousGroup alone, that placeholder
gets 401.

Set users.anonymousAcceptAnyKey to true to serve a key that matches no
user as "anonymous". A configured user's key still resolves to that
user. A placeholder key does not count toward the auth-failure
throttle. The admin API and the metrics key fallback still use
identifyKeyed, so they still need a valid key. The option is false by
default, and it needs users.anonymousGroup.
2026-11-27 10:44:03 +00:00
lukaszraczyloandGitHub 335ffb5a96 test: make the pacing cap and cache-hit parse tests deterministic (#18)
TestPacing_ConcurrentPacedRequestsCappedPerUser counted every paced
request, but the gate caps only the requests that wait at the same time.
The delays were 4 to 44 ms, so with one CPU early requests finished and
freed their slots, and a fifth request was paced correctly. The test now
gives each request a delay of at least 3 s, waits until the gate holds
maxConcurrentPaced requests, and checks that two more requests return at
once without the paced header.

TestCacheHit_BodyParseSkippedWhenStatsAdminOff compared the CPU time of
a cache hit with admin on and off. The parse is a small part of a hit,
so the ratio fell below the 1.33 threshold on every run without -race.
A nil-by-default Gateway field now lets the test count the parses: a hit
with admin on parses the body, and a hit with admin off does not.
2026-11-27 10:26:37 +00:00
lukaszraczyloandGitHub 9e886aef89 feat(messages): stream /v1/messages responses (#17)
A request with "stream": true on POST /v1/messages now gets the
Anthropic Messages event stream instead of a 400. Claude Code streams
every call, so the route must stream before it can front an
OpenAI-compatible cluster.

For openai and gemini providers, the gateway asks the upstream for a
stream with include_usage and translates each chunk as it arrives. It
emits message_start, one content block group per text or tool_use
block, then message_delta and message_stop. Tool call arguments arrive
as input_json_delta. The stop reason uses the non-streaming mapping.

For anthropic providers, the gateway relays each upstream event and
rewrites only message.model in message_start. An upstream error event
reaches the client once, as sent.

Billing uses the stream usage. An error before the stream starts gets
the normal JSON error. An error after the start ends the stream with an
error event. Streams are never cached. yaegi-check now drives a
streamed request under the interpreter.
2026-11-27 01:49:52 +00:00
lukaszraczyloandGitHub df1ca8cde2 feat(auth): add opt-in anonymous access with users.anonymousGroup (#15)
Set users.anonymousGroup to a configured group to serve requests that
carry no credential as the reserved user "anonymous" in that group. The
group grant applies, and the group memberLimits are the per-user limits
that all keyless callers share.

A request that sends an Authorization or x-api-key header must carry a
valid key, so a wrong or malformed credential still gets 401. The admin
API and the metrics key fallback use identifyKeyed and never admit the
anonymous user. The name "anonymous" is reserved while the option is
set. The option is empty by default, and then every route needs a key as
before.

The .traefik.yml testData now enables anonymous access, and yaegi-check
exercises it under the interpreter.
2026-11-26 23:54:17 +00:00
lukaszraczyloandGitHub 04600a7bc9 fix(mcp): stop the progress watchdog cutting idle MCP event streams (#14)
MCP GET event streams (the server-to-client channel) now run without the progress watchdog and are ended by the client, the upstream or Gateway.DrainIdleStreams.
The standalone binary drains them on shutdown and when a config reload retires a gateway, so they do not hold either open.
2026-11-26 20:20:43 +00:00
lukaszraczyloandGitHub e667b6ec69 docs(examples): add a standalone Kubernetes deployment (#13)
examples/standalone is a kustomization for the compiled gateway with restart draining, a configMapGenerator config, placeholder Secrets and an optional Traefik route.
TestHandleChat_RequestLimitExceeded_BodyNeverRead now pins the limiter clock and uses an unreachable local upstream, so it no longer flakes at a minute boundary or calls api.openai.com.
2026-11-26 19:42:48 +00:00
lukaszraczyloandGitHub 66ca8a5633 feat: standalone gateway image and config reload (#12)
The standalone binary reloads its config file on change and on SIGHUP, and keeps the old gateway for running requests.
GoReleaser publishes the standalone binaries and a signed multi-arch image to ghcr.io/lukaszraczylo/traefik-llmgateway.
The plugin form does not change.
2026-11-26 16:33:39 +00:00
lukaszraczyloandGitHub 979d903c19 feat: admin redesign, decision assist, prompt caching and shared state (#11)
This change adds the redesigned admin panel and the smart router decision model assist.
It adds opt-in prompt-prefix caching per provider and cached-token pricing and metrics.
With Redis, the metrics route reports fleet-wide values. The redis.sharedState switch shares six coordination states across replicas.
PR CI grants actions read, which the shared go-pr workflow needs.
The pull request description has the full list and the verification.
2026-11-26 15:50:11 +00:00
lukaszraczyloandGitHub 4c61d19a72 feat(router): smart routers and per-member rate limits (#9)
Add smart routers: virtual models that score each request and route it to admin-defined model tiers. A retryable failure moves the request to a higher tier. The classifier v2 extracts prose, finds the original ask in long tool loops, adds an uncertainty margin and reads tool-output failures. Sessions, outcome signals, bounded calibration, adaptive selection within a tier, gated saturation downgrade, a first-byte timeout and an opt-in timeout fallback are included. Every new feature is off by default.

Add per-member group limits, a tokensPerMinute window that counts uncached input and output, rate-limit headers in three dialects, soft pacing before the hard limit, and a limitExemptKinds list so embedding and reranking traffic never counts toward or hits a limit.

Fix yaegi named-result state that made smartContentSize grow between calls.
2026-11-25 00:40:30 +00:00
lukaszraczylo 6fb048b599 fix(admin): show kinds and endpoints in the providers panel
The provider accordion reads the overview response, not the catalog, so
the earlier change never reached it. Add kinds and endpoints to the
overview provider view and group the accordion rows by kind. Endpoint ids
now read gx10/v1/decide, without a doubled slash.
2026-11-10 12:38:33 +00:00
lukaszraczylo 085292143c feat(admin): group catalog models by kind
Add a display-only kinds map to the provider config. Each pathBaseUrls key
now appears in the admin catalog as an endpoint row. The Models page splits
a provider into one sub-section per kind.
2026-11-10 12:24:34 +00:00
lukaszraczyloandGitHub a4fda5f9cb feat(provider): per-model and per-path upstreams (#8)
Add modelBaseUrls and pathBaseUrls to openai-type providers.
2026-11-08 07:26:14 +00:00
lukaszraczylo aa9a925d49 fix(admin-ui): distinct percent ticks and a type-clean build
The error-rate axis rounded half-percent ticks up, so labels repeated (4%, 4%, 3%, 3%). Ticks now show one decimal where needed. The CSS layer test imported node:fs, which broke npm run build under vue-tsc, so it is removed.
2026-11-08 02:38:50 +00:00
lukaszraczylo 3e1750ddb9 fix(admin-ui): cap user detail cache, gate breakdown on ranking, restore single chevron
The per-user detail cache grew without limit and now keeps the 20 most recently fetched users. Spend refresh built the breakdown from a stale ranking after the ranking failed or was superseded, and now skips that step. The FontAwesome stylesheet overrode Tailwind hidden and showed two accordion chevrons, so it now loads in a low cascade layer.
2026-11-08 02:35:06 +00:00
lukaszraczylo 8c5e4fbcda fix(admin-ui): clear data on key change and show empty Spend chart
A new API key kept the previous key's data on screen until each store refreshed. All data stores now reset when the key changes. The Spend breakdown chart showed a column of identical zero ticks for an empty range, so it now shows an empty message. A stray quote in the Reliability page markup is removed.
2026-11-08 02:32:09 +00:00
lukaszraczylo 0a05dfc035 fix(admin-ui): keep sign and precision in CSV, YAML and context labels
CSV export prefixed negative numbers with an apostrophe, which corrupted the data. YAML emitted NaN and Infinity as plain strings. Context windows such as 1500 read as 2k. Numbers now skip the CSV formula guard, non-finite values use YAML float forms, and counts below 10k keep one decimal.
2026-11-08 02:29:28 +00:00
lukaszraczylo e985fded45 feat(admin-ui): hide runaway budget line and link form errors to inputs
The burn-down chart drew the budget line even when it was more than ten times the spend, which flattened the spend curve. The line now hides with a note. Limits, pricing, model metadata and grant forms mark invalid inputs with aria-invalid and aria-describedby.
2026-11-08 02:28:27 +00:00
lukaszraczylo 1ec8aacee7 feat(admin-ui): fit the Models catalog table without horizontal scroll
The table had 11 columns and scrolled at 1280px, hiding p50, p95 and error rate. It now shows compact price, one token column and a short error header. Context window stays in the model chip hover, and the :free flag moves into the price cell.
2026-11-08 02:27:10 +00:00
lukaszraczylo 429edb873d fix(admin-ui): ship FontAwesome CSS in bundle to satisfy style-src 'self'
FontAwesome injected a style element at runtime. The admin CSP blocks that and logged a console error on every load. The UI now imports the stylesheet and disables auto injection.
2026-11-08 02:24:47 +00:00
lukaszraczylo 758d7c7020 feat(admin-ui): alias labels, active-provider legends, denser tables and readable money
Label configured model aliases with an alias badge wherever a model id shows.
List only providers with traffic in the window in provider chart legends.
Page long tables, show a scroll shadow on wide ones and drop the duplicate model link.
Show costs with thousands separators and magnitude-scaled decimals on cards and chart axes.
Use whole-number ticks for count charts and replace all-zero charts with a message.
Back off polling after failures.
Keep the CSV status region from widening the page on phones.
Regenerate admin_assets_gen.go.
2026-11-08 02:22:22 +00:00
lukaszraczylo 05a7c114f5 fix(admin-ui): page-level loading, stale and form fixes
Fetch the consumers list on the user detail page so admin and grant data show on a deep link.
Gate Recent errors, the Spend total and the forecast card on load state instead of showing zeros.
Show a stale notice on top lists when a refresh fails.
Clear the target name when the target kind changes.
Ignore out-of-order config responses.
Wrap long group names and event messages, and announce projected budget overruns to screen readers.
Regenerate admin_assets_gen.go.
2026-11-08 02:04:23 +00:00
lukaszraczylo fcfb298077 fix(admin-ui): stale-data notice, request timeout and dedupe, hash and format edge cases
Show a persistent notice when a refresh fails while old data is on screen.
Add retry to the Targets and Access Matrix error states.
Give tables names, skeletons a status role and CSV export a live region.
Abort admin requests after 15 seconds and share concurrent identical GETs.
Show a reload prompt when a lazy page chunk fails to load.
Ignore prototype keys in the location hash.
Stop formatContextWindow emitting 1000k, round latency before the 1s cutoff,
and treat NaN as not enough data in the month projection.
Regenerate admin_assets_gen.go.
2026-11-08 01:59:34 +00:00
lukaszraczylo 5f5efa5a8d docs: state the concurrent budget overshoot bound
The README claimed an at-most-one-request overshoot. Requests in flight
together all pass the pre-check, so the bound is concurrency times the
largest request cost.
2026-11-03 01:05:27 +00:00
lukaszraczylo d9ec84ebc0 fix(retry): stop the backoff timer when the wait ends early
time.After keeps its timer alive until it fires on go 1.22 semantics,
so each cancelled retry wait pinned a timer for up to 2s. A stoppable
timer releases it at once.
2026-11-03 00:51:15 +00:00
lukaszraczylo a96ecb2dc9 test(admin): guard that every Config string key is redaction-classified
A secret field added under a new JSON key would pass through the config
endpoint unredacted because the redactor matches keys by name. The test
fails until each string key is redacted or declared non-secret.
2026-11-03 00:29:20 +00:00
lukaszraczylo 8998d70654 fix(translate): cap the gemini image count at 10
A client could send a huge n and the translator forwarded it as the Imagen sampleCount. The translator now refuses n above 10 with a request error.
2026-11-03 00:27:13 +00:00
lukaszraczylo 138ced884e fix(translate): saturate out-of-range integer fields
Go leaves a float to int64 conversion implementation-defined when the value is out of range, so a huge max_tokens could become a negative number on some architectures. The conversion now saturates to the int64 range and refuses NaN.
2026-11-03 00:27:11 +00:00
lukaszraczylo 1236aa4901 fix(resp): size a bulk reply buffer by bytes received
The parser allocated the full declared bulk length before any payload arrived, so a stalled peer could pin 64 MiB per connection. The buffer now starts at 64 KiB and doubles only after the previous capacity has fully arrived. A test measures the allocation.
2026-11-03 00:25:38 +00:00
lukaszraczylo 1a2cea3417 fix(users): cap the users file read at 16 MiB
The loader read the whole users file into memory on the request path, whatever its size. The loader now reads at most the cap plus one byte and refuses a larger file. The last good user set stays active.
2026-11-03 00:23:01 +00:00
lukaszraczylo f9418cc860 fix(passthrough): release the tee budget when the copy panics
A panic inside the response copy skipped the caller's release, so the tee kept its reserved bytes in the shared budget for good. The proxy now releases the tee and keeps unwinding. A test reproduces the leak.
2026-11-03 00:22:16 +00:00
lukaszraczylo 15e0415164 fix(registry): keep known models on an empty discovery answer
A successful but empty discovery answer replaced the known model set with nothing, so a flapping upstream made every discovered model return 404 until the next refresh. The registry now treats that answer as a failure. It keeps the previous set and counts the failure toward the discovery breaker.
2026-11-03 00:21:01 +00:00