Commit Graph
319 Commits
Author SHA1 Message Date
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
lukaszraczylo 9f13cb719a Merge branch 'fix/l4' 2026-11-03 00:12:09 +00:00
lukaszraczylo 3c91046433 fix(passthrough): reserve tee budget with compare-and-swap
The reserve step added first and checked after. Concurrent reservations saw a transient overshoot and were denied while room remained. The step now claims bytes only when they fit, so used never exceeds the limit.
2026-11-03 00:04:54 +00:00
lukaszraczylo c851e237eb fix(sse): count retained line cost in the event size cap
An upstream could send millions of empty data lines in one event. The cap counted one byte per line, but each line kept a 16-byte string header in memory. The cap now counts the header too, so retained memory stays within the cap.
2026-11-03 00:04:52 +00:00
lukaszraczylo cbffcb4061 fix(concurrency): clamp learned limit below the ceiling
An overload seen with many requests in flight set the learned limit above the ceiling. The learner now clamps the value to one below the ceiling.
2026-11-02 23:57:07 +00:00
lukaszraczylo 36ad65c96e fix(retry): reject non-positive backoff
A zero or negative backoff passed validation and made retries fire with no pause. The config loader now rejects it. The wait ladder compares the backoff to the cap before it multiplies, so a very large backoff cannot overflow.
2026-11-02 23:57:05 +00:00
lukaszraczylo 53a7fa74c1 fix(providers): do not follow upstream redirects
The adapter client re-sent provider API key headers to any redirect target. The client now returns the 3xx response to the caller. A test pins this behaviour.
2026-11-02 23:57:01 +00:00
lukaszraczylo 6d3c8bf9b7 fix(cache): skip embeddings in the response cache
Embeddings responses are large and rarely repeat. Each one was stored
for the cache TTL in the shared Redis. A burst of them raised memory
on the shared Dragonfly to its limit.

The cache now skips /v1/embeddings unless cache.cacheEmbeddings is
true. The default is false. Chat caching does not change.
2026-10-28 20:34:48 +00:00
lukaszraczylo 52b5e60719 test(yaegi): assert RateLimit-Policy header under the interpreter 2026-10-18 13:44:08 +01:00
lukaszraczylo 644b8115c8 feat(config): advertise concurrency via RateLimit-Policy with autodetect
The gateway now sends the concurrency limit as a RateLimit-Policy
field from draft-ietf-httpapi-ratelimit-headers. The value is
"concurrency";q=<n>;qu="concurrent-requests". The invented
X-Concurrency-Limit header is gone.

The new concurrencyAutodetect option is off by default. When on,
the gateway learns a limit for each configured provider. A 429, 503,
504 or upstream timeout sets the limit to half the in-flight
requests, with a minimum of 1. Four consecutive successes add 1.
At 64 the limit counts as unknown again.

Responses served via a provider advertise the smaller of
maxConcurrency and the learned value. An explicit maxConcurrency
always wins. Routing, retry and failover do not change.
2026-10-18 13:44:08 +01:00
lukaszraczylo 3e3517eb62 feat(config): advertise a concurrency limit to clients
Self-hosted upstreams serve few requests at once. A client that opens
many requests overloads them.

The new maxConcurrency option sends X-Concurrency-Limit on every
response. Clients that honour the header cap their own in-flight
requests. The default of 0 sends no header, so behaviour does not
change.
2026-10-18 13:44:08 +01:00
lukaszraczyloandGitHub 62c66f2907 Merge pull request #7 from lukaszraczylo/feat/max-request-bytes
feat(config): add maxRequestBytes for the unified body cap
2026-10-16 00:36:12 +01:00
lukaszraczylo a328a8687e feat(config): add maxRequestBytes for the unified body cap
The unified chat and embeddings routes reject bodies above 4 MiB. Long
agent sessions exceed this limit and receive a 413.

Add Config.maxRequestBytes. Zero or a negative value keeps the 4 MiB
default. A positive value raises the cap, clamped to 64 MiB.

An adversarial body decodes to about 12x live heap. An operator who raises
the cap must also set maxInFlightBodyRequests and the pod memory limit.
2026-10-16 00:34:14 +01:00
lukaszraczyloandGitHub 4ecfa10532 Merge pull request #6 from lukaszraczylo/security/fixes-oct-2026
fix(security): harden accounting, fan-out and relayed text
2026-10-15 22:28:41 +01:00
lukaszraczylo 11b3b77662 style: reorder Config and modelRegistry fields for alignment 2026-10-15 22:21:33 +01:00
lukaszraczylo d0d29b8c52 fix(security): bound fan-out and method surface and scrub relayed text
- Add a process-wide gate on MCP tools/list backend connections. The
  per-request limit alone let N callers open N times as many.
- Reject CONNECT and TRACE on native passthrough and on MCP and A2A
  targets with 405.
- Scrub URL query strings and the target URL from a backend JSON-RPC
  error message before it reaches the caller.
- Replace the value of redis.address in GET /admin/api/config. The
  users file path stays visible by design.
- Escape line breaks in every log line so an upstream string cannot
  forge log entries.
- Add stripClientAnthropicBeta. When true, POST /v1/messages does not
  forward the client anthropic-beta header. The default stays false.
2026-10-15 22:20:07 +01:00
lukaszraczylo 8c4bd16a22 fix(accounting): bound upstream-controlled usage and counter keys
Passthrough accounting read the model id, the usage figures and the
response size from the upstream response without limits.

- Mint a model counter scope only for ids the provider serves. An
  upstream that echoed new ids created unbounded counter keys.
- Drop a reported token or cost figure above a fixed ceiling. One huge
  figure locked a user out of every budget for the whole window.
- Bill an echoed unpriced model at the price of the model that passed
  the cost-budget gate.
- Cap a body-size prompt estimate at one million tokens.
- Bound the total bytes that concurrent passthrough accounting tees
  hold. A tee that cannot reserve room falls back to the estimate.
- Add cache.accountHits. When true, a cache hit charges the cached usage
  to the user. The default stays false.
2026-10-15 22:19:57 +01:00
lukaszraczyloandGitHub e5fe48a9a6 Merge pull request #5 from lukaszraczylo/perf/stream-translation
Perf/stream translation
2026-10-15 22:17:05 +01:00
lukaszraczylo 77d5d1f9d0 test(translate): compare invalid UTF-8 JSON by value
Go 1.25 json.Marshal escapes invalid UTF-8 as \ufffd. Go 1.26 writes the
raw replacement rune. The streaming encoder writes the raw rune. The tests
now compare these inputs as decoded values and keep byte comparison for
valid input.
2026-10-15 21:59:16 +01:00
lukaszraczylo 06769904f4 ci: build with Go 1.26
staticcheck and govulncheck at latest require Go 1.26.0 or newer.
The runner used Go 1.25, so both tools failed to install.
2026-10-15 21:59:15 +01:00
lukaszraczylo 6226860917 feat(registry): add requireModelPrefix to disable bare model ids
When the flag is true, a model resolves only as provider/model or as a
modelAliases id. A bare id returns 404 unknown model. GET /v1/models
lists every model in provider/model form and lists no bare ids.

The flag defaults to false, so existing deployments keep the sorted-first
bare-id collision winner.
2026-10-15 21:48:18 +01:00
lukaszraczylo 6be3f09032 chore(pricing): keep claude-sonnet-4-5-20250929 in the builtin table 2026-09-29 13:58:22 +01:00
lukaszraczylo d4322e914c feat(pricing-sync): make the age cutoff and keep list configurable
Add the -max-age-months and -keep flags, with PRICING_MAX_AGE_MONTHS and
PRICING_KEEP make variables. A built-in list keeps ids that are still served.
2026-09-29 13:58:20 +01:00
lukaszraczylo 4edf9be804 chore(pricing): regenerate the builtin table with the age filter
Keeps 171 entries, down from 211. Drops mostly dated snapshot ids.
2026-09-29 13:49:15 +01:00
lukaszraczylo 4681596281 feat(pricing-sync): drop entries older than 12 months
An entry is dropped when its deprecation date has passed, or when a full date
in its id is over 12 months old. Ids with no date signal stay.
2026-09-29 13:49:13 +01:00
lukaszraczylo 0a9522dfa7 chore(pricing): resync the builtin table from LiteLLM
Adds 39 models, including Claude 5.5, GPT-6, Grok 4.20 variants and Qwen 3.8.
Drops 65 models that LiteLLM no longer lists, for example Grok 2 and 3, old
Kimi and Claude 3 ids. Updates 6 prices.
2026-09-29 13:23:06 +01:00
lukaszraczylo b8772d3d73 perf(sse): reuse the data-line buffer across events in readSSE 2026-09-29 12:35:05 +01:00
lukaszraczylo e12cec8bf9 style(stream): reorder stream state fields for fieldalignment 2026-09-29 12:31:07 +01:00
lukaszraczylo c25c6e38e1 perf(sse): skip line splitting for single-line data events 2026-09-29 12:31:04 +01:00
lukaszraczylo 2cd686a669 perf(stream): append text deltas as JSON without an intermediate Marshal 2026-09-29 12:26:15 +01:00
lukaszraczylo baabd5d3bb perf(gemini): share text-delta chunk builder with the anthropic stream 2026-09-29 12:21:50 +01:00
lukaszraczylo f94fe1dad5 perf(anthropic): build text-delta stream chunks without envelope maps 2026-09-29 12:16:20 +01:00
lukaszraczylo f5482317d7 test(bench): add benchmarks for translators, SSE and unified route 2026-09-29 12:10:27 +01:00
lukaszraczylo 2608e01c50 refactor(webui): extract repeated dashboard elements into shared components
Markup and helpers that were copied between pages now live in one
place:
- ChartCard, StatDisabledAlert, StatItem, DetailField, BudgetRatioBars,
  LabeledSelect, TargetPicker and LoadStateView components
- lib/scope.ts, lib/columns.ts and lib/chart-palette.ts
- messageOf, isAuthRejection, and the USD to micro-USD conversion
  helpers
- one monthly cost projection, one date formatter, and the
  useCopyFeedback composable

Behaviour is unchanged. Before and after screenshots of every page
match at 390 and 1440 px. Empty-state text now comes from the shared
EmptyState component, and the user run-out date uses the short date
format. admin_assets_gen.go is regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-24 06:04:46 +01:00
lukaszraczylo ce39b8eb37 fix(registry): retry failed startup discovery once in the background
A provider whose discovery failed during the warm fill at pod start
went without discovered models for a full discovery interval, which is
1 hour by default. It also stayed that way until a request arrived
after the interval. Production logs showed this for openai-audio and
anthropic when outbound calls were slow at startup.

A provider that fails the warm fill now gets one background retry
after 10s. The retry has its own timeout and uses the same refresh
bookkeeping. It is skipped when a refresh is already in flight or has
finished since the warm fill, and it is not scheduled when the parent
context was canceled. A recovery logs one INFO line. If the retry also
fails, the existing breaker behaviour applies unchanged.

The retry delay and the warm-fill timeout can be set per registry for
tests. yaegi-check probes the retry under the interpreter.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-24 06:04:43 +01:00
lukaszraczylo 8807f4d27d fix(test): pin the limiter clock in TestModelSpanTotalsSumsBuckets
The test wrote counters for a fixed date, 2026-09-23, but never pinned
the limiter's clock. modelTotals therefore read the real time. The test
passed only on the date it was written and fails on every later day.
It now sets l.nowFn to the fixed time, as the other span tests do. This
is a test-only fix; production code is unchanged.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-24 06:04:40 +01:00
lukaszraczylo cf308624af feat(webui): make the dashboard responsive and add loading and empty states
Every tab row scrolls sideways instead of being clipped by its card.
On phones this hid tabs, such as the Config change helper's last forms
at 360-390px. The login button has a larger touch target, and long
names are truncated with a tooltip.

Loading and empty states:
- Skeletons show only while a selection has no data yet, never over
  data already on screen during a refresh.
- Empty states name the next step to take.
- Error states offer a Retry button that shows progress, and each card
  keeps its own error.
- Toasts confirm copies and key generation, and report background
  failures once per streak through polite and assertive live regions.

Other changes:
- The access matrix switches between Models, MCP servers and Agents,
  and says "none configured" only once its data has loaded.
- Home ranks the top 5 users by cost, requests or tokens. It requests
  only the needed metrics and warns before a range exceeds the
  server's key cap.
- MCP and agent deep links accept a bare target name.

admin_assets_gen.go is regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 23:02:22 +01:00
lukaszraczylo 95a3a0e235 docs: document admin statistics, new endpoints and the redesigned dashboard
The README covers the admin.stats switches and the Redis cost per
request with and without them. It lists the always-on counters, key
names and TTLs, and every new or changed admin endpoint with its limits
and config redaction rules. It describes the seven dashboard pages, the
filter bar and the hash schema. It notes that a failed failover
candidate no longer counts toward a model's requests.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 16:41:04 +01:00
lukaszraczylo ee49467e64 feat(webui): redesign the admin dashboard around admin tasks
A sidebar replaces the flat tabs with seven pages, and one filter bar
sets the time range, comparison period and scope for all of them.

- Home: spend against budget, forecast, request rate, error rate,
  open breakers, top users and models, recent events and warnings.
- Spend: spend over time with comparison, budget burn-down, an
  attribution drill-down from group to user to model, pricing health
  and cost avoided by free models.
- Consumers: a directory with last seen and limit bars, an access
  matrix, and a detail page per user.
- Models: the catalog with billing prices, fleet latency and error
  rates, and provider health.
- Reliability: error, timeout, failover, 429 and 402 trends, events,
  and latency per provider.
- Config: the redacted config and a change helper that emits YAML or
  users.json snippets to paste into git.
- MCP & Agents: callers per target.

Page state lives in the URL hash, and old tab links map to the new
pages. The replaced views are removed. admin_assets_gen.go is
regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 16:41:01 +01:00
lukaszraczylo e8abb91dc8 test(admin): probe the statistics endpoints under Yaegi and across replicas
yaegi-check adds probes for these, run under the interpreter against a
fake Redis:
- the last-seen SET reply
- usage/series and usage/totals
- performance with latency on
- catalog price source
- config redaction
- consumers key source
- cache-hit counters

The integration suite adds three checks against two replicas: last seen
is visible across replicas, latency counts match on both, and target
caller totals appear after an MCP call.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 16:40:59 +01:00
lukaszraczylo 65b2f121c4 feat(admin): add fleet statistics and admin read endpoints
Counters (always on when admin is enabled):
- last seen per user and group, written asynchronously after
  admission, throttled to one write per scope per minute per replica
- hourly provider and model attempts, failures and timeouts
- failovers per provider, rejections per hour, and unpriced (402)
  refusals
- cache hits, misses and cost saved
- request counts per target and caller

Opt-in counters under admin.stats (both default off):
- userModel: usage per user and model
- latency: latency histograms per provider and model

All counters ride the existing Redis batches. A test measures three
round trips per request with defaults and with every statistic on. A
cache hit takes two. A model request is no longer counted for failed
failover candidates.

New admin endpoints:
- usage/series and usage/totals
- performance, with percentiles from the histograms
- catalog, with the price billing actually uses and its source
- consumers, with key source, grants and model access
- config, with secrets redacted

The overview gains features and a pricing summary. Usage gains
lastSeen. usage/models gains offset and more detail fields. Reads are
chunked at 1600 keys per round trip and capped at 64000 keys per
request.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 16:40:45 +01:00
lukaszraczylo 8ac20d8d5e fix(provider): list models in one page for Anthropic and Gemini
Model discovery used each API's default page size: 20 for Anthropic and
50 for Gemini. A full catalog needed several sequential requests, and at
pod start that overran the 5s warm-fill budget. One replica then
logged "initial discovery ... context deadline exceeded" and went
without that provider's models until the next probe. Every page now
asks for the documented maximum of 1000: Anthropic limit and Gemini
pageSize. Gemini gets pageSize on each page, because it requires the
same parameters across one listing.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:46:11 +01:00
lukaszraczylo 28722d983f docs: document per-model detail and media model counters
The README describes the detail parameter on GET /admin/api/usage/models
and the fields it adds. It also notes that the media routes write
per-model request counters on success.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:40:10 +01:00
lukaszraczylo 782ea43b02 feat(webui): list every model with full usage on the Models tab
The Models tab ranks by requests by default and asks the server for
per-model detail. A table under the chart lists requests, tokens in,
tokens out and cost for each model. A model with no recorded cost that
is marked free shows a "free" badge instead of $0. The CSV export
includes every column and the free flag. admin_assets_gen.go is
regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:40:08 +01:00
lukaszraczylo 3e05a79c0b feat(admin): report per-model detail, including free models
GET /admin/api/usage/models accepts detail=1. Each entry then carries
requests, tokensIn, tokensOut, costMicroUsd and a free flag. A model is
listed when any of those four totals is non-zero, so a free model with
traffic appears with value 0 even when ranked by cost. The free flag is
true when modelMeta marks the model free, or its resolved price is zero.
Without detail the response is unchanged.

The image and audio routes now write the per-model request counter after
a successful upstream call, so media models show up in the ranking. They
still record no tokens or cost.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:40:05 +01:00
lukaszraczylo b8f240caac docs: document the events feed and the new dashboard features
The README now covers GET /admin/api/events: its limit, response shape,
kinds and routes. It explains the Redis list and throttle, the replica
fallback, and the replica id caveat under hostNetwork. It also covers
the new overview fields, rejectionsPerDay, and the span and prefix
parameters on the models ranking.

The dashboard section describes the limit bars, cost forecast, CSV
export, click-through links, Events tab, polling pause, URL hash state
and configuration warnings banner.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:10:04 +01:00
lukaszraczylo 4261efc41b feat(webui): add limit bars, forecasts, events, exports and URL state
The Usage tab shows a bar for each configured limit. It turns amber at
80% and red at 100%. The tab also shows rejected requests per day, a
projected month-end cost with budget headroom, and CSV export for users
and groups. Names link to Charts with the matching scope.

The Charts tab ranks models over the full 24h, 30d or 12mo window. A
provider filter is applied on the server, and the ranking can be
exported as CSV. A new Events tab lists recent failures, filtered by
kind and user. The selected tab, filters and scope live in the URL
hash. Polling stops while the page is hidden. Views show which replica
answered, and a banner lists configuration warnings.

CSV cells that start with a formula character are neutralised. Links
sit outside the accordion buttons, so both controls keep their
accessible names. admin_assets_gen.go is regenerated.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:09:57 +01:00
lukaszraczylo 25e6a7779e test(admin): probe the new admin routes under Yaegi and across replicas
yaegi-check now calls the new routes under the interpreter. It checks
the overview replica and warnings, a 429 followed by a rate_limit
event, the kind and status of upstream and timeout events, span=24 on
the models ranking, and rejectionsPerDay in usage. A new integration
test with two replicas triggers a 429 on one replica and reads the
event from the other through Redis. It checks that the two replicas
report different ids and the same total rejectionsPerDay.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:09:53 +01:00
lukaszraczylo 6776981675 feat(admin): add events feed, fleet-wide rejections and span rankings
GET /admin/api/events returns recent failures, newest first. It covers
rate limits, budget and unpriced-model refusals, upstream errors,
timeouts and capacity rejections. Events go into an in-process ring of
200 entries and are copied to a Redis list (llmgw:events, LPUSH plus
LTRIM to 200). The copy happens only on the error path, is throttled to
50 per second per replica, and never blocks a request. When Redis is
absent or down, the feed falls back to this replica's ring. Messages
are fixed strings or scrubbed provider errors. Fields are assigned one
at a time, because Yaegi drops values from a multi-value assignment
that contains a call.

Rejections per day are counted per scope and in total, in the same
store call that already rolls back a rejected request. /admin/api/usage
returns them as rejectionsPerDay. /admin/api/usage/models accepts span,
which sums that many buckets, and prefix, which filters model ids
before the limit applies. The overview reports the replica id, the
instance name and the warnings logged while the middleware was built.
The failover and retry fan-out warning is now logged at WARN.

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 13:09:38 +01:00
lukaszraczylo 41bff22cb5 docs: document the standalone binary and match the README to the code
The README now describes deployment mode B (the standalone binary and
its container image). It documents these keys: allowUnpricedWithCostBudget,
redis.poolSize and redis.tls.

It corrects these statements:
- the multi-group user model
- reserved provider names, now including admin
- users.json reload on mtime only
- the authorization function names
- the breaker re-probe cadence
- the order of pricing resolution and validation
- passthrough stream accounting and the 413 response
- latency metric names and metrics.path rules
- the MCP fan-out budget, handshake and pagination
- the A2A card and query rules
- response header stripping
- API key lookup by digest

Claude-Session: https://claude.ai/code/session_01V5jYJNxpDFdJkyyExpADrv
2026-09-23 09:44:33 +01:00