feature: let a session select its inference server, so concurrent agents can use different backends

未关闭
#1,474 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

还没有人认领这个 Issue。

评估

难度
5/5
预计耗时
一周以上
新手友好度
25/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
活跃
技术栈
go
领域
api, backend, security

调研方向

Start with the inference router configuration at core/plugins/inferencerouter/routerconfig/config.go:36 and request context at core/pipeline/context.go:28; read how session IDs are selected in core/session/idheader.go. Trace how the router maps agents and replaces keys in plugin.go:763, then compare the loopback and authenticated identity paths described in the issue. Done means concurrent sessions can select distinct configured servers while cluster routing derives scope from authenticated identity.

由索引模型根据 Issue 内容生成。

描述

Feature Description

agentop server use <name> --agent <agent> is a machine-wide choice. The
inference-router's config keys routing by agent name and nothing else:

// core/plugins/inferencerouter/routerconfig/config.go:36
Agents map[string]string `json:"agents" description:"Agents to route, by agent name, to a server name. Unlisted agents are not routed."`

So one Claude Code install gets exactly one server at a time. There is no way to run
concurrent sessions of the same agent against different backends.

That is a real setup, not a hypothetical. Today it is done with a per-directory env
block and the router switched off — three internal LiteLLM gateways, each with its own
token and its own model names:

# ~/sandbox/cortex-int
export ANTHROPIC_BASE_URL=https://ete-litellm.ai-models.vpc-int.res.ibm.com
export ANTHROPIC_AUTH_TOKEN=$KLAUDE_AUTH_TOKEN_INT
export ANTHROPIC_MODEL="claude-opus-5[1m]"

# ~/sandbox/cortex-ext
export ANTHROPIC_BASE_URL=https://ete-litellm.ai-models.vpc.res.ibm.com
export ANTHROPIC_AUTH_TOKEN=$KLAUDE_AUTH_TOKEN_EXT
export ANTHROPIC_MODEL="claude-opus-5[1m]"

# ~/sandbox/cortex-cb
export ANTHROPIC_BASE_URL=https://litellm.cb.ete.res.ibm.com
export ANTHROPIC_AUTH_TOKEN=$KLAUDE_AUTH_TOKEN_CB
export ANTHROPIC_MODEL="rits/zai-org/glm-5-3"
export ANTHROPIC_DEFAULT_SONNET_MODEL="rits/nvidia/NVIDIA-Nemotron-3-Ultra-550B-A55B-NVFP4"
export CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000
export CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1

Three terminals, three backends, all at once. Cortex observes and prices all three
correctly today — they are distinct hosts, all on 443, all TLS-bridged. What cannot be
expressed is the router.
agentop server use would force all three onto one server,
so this setup keeps the router off and gives up everything it provides: model
substitution, limit fitting, one key store, central switching, agentop server move.

The documented workaround for simultaneous independent routes is --config PATH, i.e.
a second Cortex instance:

--config PATH points every form at another config, with the stats address read from
it: that is how to try this against a second Cortex without touching the one every
session uses.
— cmd/agentop/README.md

Three installs on three ports is a poor answer for a laptop tool: three proxies, three
CAs, three plugin stores, three cost ledgers, three agentop targets — and the
session, cost and usage views fragment, which is the thing Cortex exists to unify.

Prior art: every comparable gateway solves this, and most do it with the credential

This is a solved problem shape elsewhere, and the convergent answer is worth noting
because it suggests the mechanism rather than just the requirement.

LiteLLM — tag-based routing.
Deployments carry tags; a request's tags narrow the candidate pool. Tags arrive three
ways: a tags array in the body, an x-litellm-tags header, or from the API key via
its team
— create a team with tags: ["teamA"], issue keys bound to that team_id,
and a request with no tags at all sent with that key lands on the teamA deployment.
Key/team-derived tags are tracked as metadata.inherited_tags and treated as
caller-uncontrolled, i.e. deliberately more trusted than a client-sent tag. A
default tag catches untagged traffic; exhausting the pool errors with
no_deployments_with_tag_routing.

Two details are directly relevant here:

  • LiteLLM also ships tag_regex, which matches User-Agent against patterns like
    "^User-Agent: claude-code\\/" — operator-set, for clients that send no tags. Its own
    docs caution that User-Agent is client-settable and so is for "traffic
    classification, not access-control enforcement." That is exactly the caveat that
    applies to Cortex's agent names, which are parsed from User-Agent.
  • tag_routing_prefix exists because plain tags collide with attribution tags. A
    routing directive needs to be distinguishable from a label; worth learning from rather
    than rediscovering.

Portkey resolves the backend
from an x-portkey-provider header, a config naming the provider, or a passthrough
target. Critically, a config can be attached to an API key as its default, so "all
requests made with that key will automatically use the specified config without needing
to include it in each request" — motivated explicitly by integrations that cannot send
custom headers. Request-level config overrides the key's default.

Bifrost makes the
credential the primary routing object outright: "Virtual Keys are the primary governance
entity." A virtual key carries provider_configs (deny-by-default provider gating),
allowed_models/blacklisted_models, weights, and key_ids selecting which upstream
credential to use. It is accepted in x-bf-vk, Authorization, x-api-key,
x-goog-api-key or api-key, so unmodified OpenAI/Anthropic/Gemini SDKs can all carry
one. Different clients present different virtual keys and reach different backends
through one endpoint — which is precisely this issue's requirement.

claude-code-router is the
closest comparable local control plane. It routes on "conditions on headers and bodies"
and mentions "scopes" and "multi-instance workflows", but its README documents no
per-project or per-session provider pinning — its diagram funnels all agents into one
resolution. So the local-proxy category has not clearly solved this either, and there is
room to do it well.

What this prior art suggests. The answer is not a new client feature — it is to read
a signal the client already sends. And in this setup the credential is already
distinct
: $CLAUDE_AUTH_TOKEN in different shells as three different tokens, exported
per directory, already on every request. The user has already expressed the choice; the
router just does not read it.

Multiple users, each with their own backend and keys

The same mechanism generalises from "one user, three workspaces" to "many users, each
with their own gateway and their own credentials" — but the trust model does not, and
the two shapes should not be conflated.

Prior art — every gateway above has a tenant hierarchy, and the credential is the
binding.
LiteLLM's multi-tenancy
doc
nests
Organization → Team → User → Key, where the key "authenticates the request and binds it
to a tenant" and can be scoped to a user, a team, or both. Teams are "the primary tenant
boundary in open source"; Organizations are enterprise. Each level is both an isolation
boundary and a spend-attribution point: a request's cost lands on its key, user, team and
org simultaneously, budgets are "enforced inward" (a team's cannot exceed its org's), and
"a request is blocked once any level along its path is over budget."

Separately, LiteLLM's customers/end-users
model
identifies a downstream user per
request, header-first, first match wins: x-litellm-customer-id, then
x-litellm-end-user-id, then a configured mapping, then the OpenAI user body field,
then litellm_metadata.user, then metadata.user_id. Three findings there are directly
load-bearing for this issue:

  • A validated JWT claim outranks every client-supplied form. With
    end_user_id_jwt_field set, the claim wins and "callers cannot override it with
    x-litellm-end-user-id, metadata.user_id, etc." That is the only form of this that
    is an authorization boundary rather than a label.
  • Customer restrictions are subtractive only — "the customer list only narrows
    access", and key/team restrictions still layer on top. Naming a tenant can never
    grant reach.
  • They hit the Claude Code case specifically. Agent clients send per-session ids —
    "Claude Code puts a JSON blob in metadata.user_id" — so LiteLLM added
    validate_end_user_id_in_db to accept an id only if it matches a known customer, and
    discards JSON-shaped ids. Worth knowing before reading any Claude Code field as a
    tenant name.

Bifrost binds a virtual
key to one team or one customer (mutually exclusive), with key_ids selecting which
upstream provider credential
that key may use — so each tenant's own backend keys stay
in the gateway and are never held by the client. Governance is opt-in by default, and a
request with no key passes through ungoverned until
client.enforce_auth_on_inference: true makes a valid key mandatory.
Portkey attaches a default config
to an API key for the same reason — governance enforcement for clients that cannot send
headers.

Two different shapes, and only one of them is a security boundary.

  • Shape A — many workspaces, one trusted operator (the case in this issue, and
    the laptop case generally). The scope is a convenience selector among servers
    the operator configured. Worth stating plainly that the laptop proxy is already
    single-user by construction: every listener binds loopback
    (listener.bind_loopback_only), and process attribution is uid-scoped by the OS —
    "Only root may read another user's /proc/<pid>/fd, so a socket another uid owns
    cannot be attributed by anyone else" (core/peerproc/linux.go:188), and
    Environ returns ErrNotFound for another user's process. So on a laptop
    "multiple users" really means multiple configurations, and a scope key is the
    right weight of mechanism.
  • Shape B — many real users through one shared Cortex, which is a cluster
    deployment and a genuine isolation requirement. Here a scope must be derived from
    authenticated identity, never from a client-asserted string. Cortex already
    has the pieces and they should be reused rather than paralleled:
    pctx.Identity with Subject(), ClientID() and Scopes()
    (core/pipeline/context.go:28), populated by jwt-validation (JWKS, issuer,
    audience). So the cluster form of this feature is "map an authenticated
    Subject() or a scope/role claim to a server", which is LiteLLM's
    end_user_id_jwt_field rule arrived at from Cortex's own primitives.
  • Do not let Shape A's mechanism silently become Shape B's. The failure mode is
    an env- or header-derived scope being trusted in a cluster, where it is forgeable
    by any caller. Concretely: the scope sources should be per-deployment opt-in,
    the same way session.id_headers already is — core/session/idheader.go notes
    the unnamespaced session headers are read by default "only on a loopback-only
    install", because "in a cluster an agent may send it for its own reasons." Scope
    selection deserves exactly that treatment: environment and credential-fingerprint
    sources on a loopback install, identity-derived only in a cluster, and the two
    never interchangeable.
  • Per-user upstream credentials. Bifrost's key_ids is the shape to copy: the
    tenant's gateway key lives in Cortex's config, and the client never holds it. The
    router already does the hard half — setKey replaces the client's key with the
    server's (plugin.go:763) — so "this user's requests go to this server with this
    key" needs the mapping, not new machinery. For a cluster this likely wants a
    secret reference rather than an inline key; note token-broker and
    token-exchange already exist for acquiring a per-user token, and a chain should
    use one of them or this, not both.
  • Per-user spend, which already half works. Cost is keyed by endpoint host today
    and /v1/usage supports group=endpoint, so per-backend spend is already
    separable. What is missing for Shape B is attribution to a subject — the axis
    LiteLLM gets by landing each request's cost on key, user, team and org at once.
    agentop cost has --endpoint and --agent and no --user. Whether per-user
    budgets belong here or in litellm-budget-track (which already enforces a daily
    cap and reads the settled cost) is an open question, not a given.
Why this is not the existing routing issues
  • #1019 (transparent model and provider switching) switches a session automatically
    on a limit, price or policy boundary. This issue is the opposite: an explicit, static,
    user-declared choice that must never move.
  • #1020 (route by task class) picks a model from the prompt's character.
  • #1400 (alert when a backend degrades) tells you when to switch.

All three assume Cortex decides. Here the user has already decided, per workspace, and
needs a way to say so. It is also far smaller: no provider wire-format abstraction, no
trigger evaluation, no mid-stream switch.

Proposed Solution

Let a scope carried by the client select the server, with agents: as the default
when no scope matches. Sketch:

- name: inference-router
  config:
    servers:
      int: {url: https://ete-litellm.ai-models.vpc-int.res.ibm.com, key: sk-…, main: opus, helper: haiku}
      ext: {url: https://ete-litellm.ai-models.vpc.res.ibm.com,     key: sk-…, main: opus, helper: haiku}
      cb:  {url: https://litellm.cb.ete.res.ibm.com,                key: sk-…, main: glm,  helper: glm}
    agents:
      claude-code: int          # the default, unchanged
    scopes:                     # NEW: checked before `agents`
      int: int
      ext: ext
      cb: cb

A scope naming no server is a startup/reload error, exactly as an agents: value is. An
unset or unmatched scope falls through to agents:, so every existing config behaves
identically
— this is purely additive.

Where the scope comes from

Four candidate sources. The first two need no client cooperation at all, which is
what makes this tractable for Claude Code, whose only configuration surface is an env
block.

  • The client's credential, by fingerprint — the Bifrost/Portkey/LiteLLM-team
    pattern.
    The user's three tokens already differ, and the router already reads
    and replaces the client's key
    : setKey puts the server's key "in the header the
    client authenticated with: X-Api-Key when it sent one, Authorization otherwise"
    (plugin.go:763). So the selector is in hand at exactly the right moment, before
    substitution. Never store the client key in config — map a
    sha256:<prefix> fingerprint to a server name, so the config file holds no
    secret that is not already a server's own. This also inherits the property
    LiteLLM names explicitly: a key-derived route is caller-uncontrolled in a way a
    body tag is not. The weakness is ergonomics — rotating a token means re-pinning a
    fingerprint, and it only works where the user has distinct tokens per backend.
  • The client process's environment. peerproc.Environ(pid) already exists and
    is implemented on both platforms (core/peerproc/linux.go:330 reads
    /proc/<pid>/environ; core/peerproc/darwin.go:276 parses kern.procargs2). The
    forward proxy already resolves the client PID for process attribution, and there
    is a precedent for reading a client's env to make a decision:
    cmd/agentop/opencode.go:125 (var openCodeEnviron = peerproc.Environ). A user
    would then write export CORTEX_SERVER=cb beside the variables already in that
    directory's env block. Caveats the existing code documents and this must honour:
    it is the start-time environment, so a later setenv does not show; an empty
    result means unknown, not absent (a process that rewrote its argument memory —
    Node's process.title — shows nothing, and Claude Code is Node); macOS withholds
    some processes' environments; another user's process returns ErrNotFound. An
    unreadable environment must fall through to agents: and say so in the row,
    never deny.
  • A request header, as LiteLLM's x-litellm-tags and Portkey's
    x-portkey-config do. Cleanest wire signal, agent- and transport-neutral, and the
    obvious choice for any client that can set one. Claude Code has no documented way
    to add an arbitrary header, so this cannot be the only path — but it should
    probably exist for the agents that can.
  • The addressed base URL as a scope key. The user has already distinguished
    these three backends by ANTHROPIC_BASE_URL, and the router already computes the
    addressed host (p.byHost[routerconfig.Key(pctx.Host)], plugin.go:311). Nearly
    free, needs nothing from the client. The limit is that it only expresses "stay
    where you were aimed", so it carries no different key or model word per
    workspace, and servers: already refuses two servers on one host
    (plugin.go:271). Possibly the cheapest useful increment on its own.
Remote Cortex: local agents connecting to a shared proxy

This is the shape that most changes the design, and it is worth treating as a first-class
case rather than a variant of Shape B — because the two strongest signals above stop
working
, and the architecture already says so:

  • Process attribution is local-only by construction. session.process_attribution: auto "means on for this loopback-only install and off in a cluster". The kernel tables
    peerproc reads name a process on this host; across a network the peer is a TCP
    connection from somewhere else. So peerproc.Environ — the most ergonomic source for
    Shape A — is unavailable the moment the proxy is not on the agent's machine, and
    export CORTEX_SERVER=cb cannot be read remotely. A design that leans on it is a
    laptop-only design.
  • TLS bridging is worse, not just absent. The router only acts on "a plain http
    request sent through the proxy, or an https one the TLS bridge decrypts". A remote
    proxy terminating a laptop's agent traffic means minting certificates for
    api.anthropic.com on a shared server and having every client trust that CA — a
    far larger trust concession than the local bridge, where the CA never leaves the
    machine that made it. And the session API is already documented as unauthenticated,
    with the warning that in a pod "the network namespace is the boundary. Never expose it
    through an ingress."
  • The reverse proxy cannot route at all today. core/listener/reverseproxy/support.go
    is explicit: it "forwards inbound requests to the local application, so there is
    nowhere else to send one: it honors no redirect, which is also what keeps a
    WritesDestination plugin off an inbound chain." Since inference-router declares
    WritesDestination: true (plugin.go:249), the inbound listener refuses it by
    design.
    Any remote-Cortex routing story needs this resolved first: either a listener
    that honors a redirect on an inbound chain, or an explicit decision that remote Cortex
    is a gateway rather than a transparent proxy.

So the ideal remote design is a different posture: stop intercepting, become an
endpoint.
The agent points at Cortex as its base URL instead of being proxied into it:

export ANTHROPIC_BASE_URL=https://cortex.corp.example.com
export ANTHROPIC_AUTH_TOKEN=$MY_CORTEX_TOKEN     # a Cortex credential, not a gateway's

That single change resolves every problem above at once, and it is exactly what the
prior art converged on:

  • No CA, no interception. Cortex holds a normal server certificate for its own
    hostname. The TLS bridge, the per-host certificate minting, and the whole
    client-rejected-ca failure class disappear from the remote path.
  • The credential becomes the tenant binding, which is Bifrost's virtual key and
    Portkey's key-default-config verbatim. The scope is no longer inferred from the
    environment or a host — it is the token the client presents, which is the one signal
    that survives a network hop intact.
  • Each user's gateway keys stay server-side. This is Bifrost's key_ids: the user
    holds a Cortex token, Cortex holds the upstream LiteLLM keys, and setKey
    (plugin.go:763) already performs the substitution. The user's three
    KLAUDE_AUTH_TOKEN_* values would move into Cortex and out of their shell.
  • It is already how agentop talks to a remote proxy (--endpoint), so the "point
    at a remote Cortex" idea is not new to the project — only the inference path is.

What this requires that does not exist yet, and should be named honestly:

  • Authenticated inbound inference. Today's remote story is
    session_api_addr: 0.0.0.0:47601 plus agentop observe --endpoint, and #1434
    says of exactly that: "This approach is insecure; anyone can observe the traffic."
    That issue asks for TLS/mTLS on the session API; serving inference remotely needs
    the same thing plus a credential model for agents. #1434 is a prerequisite, not a
    parallel.
  • A Cortex-issued credential distinct from any gateway key, so revoking a user
    does not mean rotating a shared upstream key. This is the object LiteLLM calls a
    virtual key and Bifrost makes "the primary governance entity." Note Bifrost's
    default — governance is opt-in and an unkeyed request passes through ungoverned
    until enforce_auth_on_inference: true. For a remote Cortex the safe default is
    the opposite: refuse an unauthenticated inference request.
  • An inbound path that may redirect. Either lift the reverse proxy's "honors no
    redirect" rule for a listener purpose-built as an inference endpoint, or add one.
    This is the single largest piece of work and the one that decides whether remote
    routing is feasible at all.
  • Keep the laptop case intact. Nothing above should change the local forward-proxy
    design, which works and is the project's centre of gravity. The remote shape is an
    additional deployment mode, and the scopes: interface should be the same in
    both — only the source differs (identity remotely, environment/credential
    locally).

A smaller intermediate worth considering. If full remote inference is too large,
the same user-visible outcome is reachable with a local Cortex per laptop whose
servers: and scopes: come from a shared remote config — central administration of
which backends exist and who may use them, with interception and keys staying local.
That keeps every local guarantee, needs no new listener, and may be the right first step.
It does not give central spend aggregation, which remote Cortex would.

Scaling a remote Cortex: 10s → 1000s → 1M users

Nothing in the issue list addresses horizontal scaling, replicas, load balancing or
statelessness — the laptop is the design centre, and that shows in specific places. This
is a survey of what each order of magnitude actually requires, because the bottlenecks
are not where capacity planning usually looks: the hard ones are statefulness and
buffering, not CPU.

The four pieces of per-request state that currently assume one process. Every one of
these is correct on a laptop and a scaling blocker when shared:

  1. The session store is in memory, capped, and LRU-evicted. session.max_sessions
    defaults to 100, session.max_events is unlimited, "the store is in memory only,
    so a restart clears it regardless", and neither is hot-reloadable. Worse for a shared
    deployment: the docs already note bucket names are unauthenticated, so "anything
    sending unfamiliar ids consumes the same 100 slots and evicts real sessions." At 1000s
    of users that cap is not a tuning value, it is a correctness bug — and raising it
    "trades eviction for memory; it does not remove the issue."
  2. Router pins live in ~/.cortex/plugin-state.json on a local install, "elsewhere
    in the process store, which a restart empties" (pins.go:14). A pin that does not
    survive a restart or reach a sibling replica means a conversation gets re-decided —
    which is exactly the #1340 failure (a running conversation moved to another backend
    mid-task, then refused for context length). Behind a load balancer, every replica
    would re-decide every session it had not seen.
  3. The cost ring is per-process (a 6-hour in-memory ring), with the durable ledger
    as ~/.cortex/cost/YYYY-MM-DD.jsonl — a local file, one writer.
  4. Model-refusal memory, learned limits, and the /v1/models lists are per-process
    caches with hour/30-day TTLs. Cheap to lose, but N replicas means N× the refused
    round trips until each learns independently.

The good news: the abstraction for fixing (1)–(4) already exists. storage.Store
with a scheme registry (core/storage/provider.go:16) already has a Redis/Valkey
driver
(core/storage/redis/) alongside the local filestore, and plugins receive it
via plugins.Deps.Store / storage.StoreConsumer. So "pins in Redis" is a driver
choice, not new architecture. The session store and cost ring are the parts with no
shared-backend path today.

Two hard blockers that are not about state at all:

  • The inbound listener's body cap is 1 MB. core/listener/reverseproxy/server.go:48:
    maxBodySize = 1 << 20 // 1MB — matches Envoy's default per_stream_buffer_limit_bytes,
    against the forward proxy's 32 MiB for requests. A Claude Code opening turn "can pass
    64k tokens" and this issue's own setup sets CLAUDE_CODE_MAX_CONTEXT_TOKENS=1000000.
    A 1M-token conversation is far beyond 1 MB, so remote inference over the inbound
    path would reject real traffic before any scaling question arises. (#1290 already
    raised the forward proxy's cap to 32 MiB for this reason; #1325 pins the divergence
    between shapes deliberately.)
  • Buffering sets the memory ceiling, and it is per in-flight request. Plugins that
    read bodies force the buffered path, and "only buffered mutation is supported" —
    streaming transforms are "a separate project". So concurrency × context size is
    resident memory. At 32 MiB/request that is ~32 GB per 1000 concurrent large requests,
    before any session state. This, not CPU, is what sizes a remote Cortex — and it
    means per-user context limits become a capacity control, not just a cost control.

What each order of magnitude needs:

  • 10s of users — one replica, vertical. Works today in principle, modulo the two
    blockers above. Needs: max_sessions raised far beyond 100 (or sessions moved out
    of memory), the 1 MB inbound cap resolved, authenticated inference (#1434), and
    honest measurement. There is no published benchmark — requests/sec, memory per
    concurrent request, p99 added latency — and nothing can be sized without one. That
    measurement is the first deliverable, not a later one.
  • 1000s — N replicas, which means becoming shared-nothing per request. The work:
    pins and refusal/limit caches on the Redis driver; session store either shared or
    explicitly accepted as per-replica (with the consequence stated — agentop would
    see only one replica's sessions); cost written to a shared sink rather than a local
    file; and a decision on sticky routing. Session affinity by session id would
    sidestep the shared-pin problem entirely and is probably the cheaper first answer,
    but it needs stating as a design choice, since the pin's whole purpose is that a
    conversation never moves. Also: session.* and cost_ledger.* are "refused
    outright" by the reloader (framework-architecture.md:885), so rollout is restarts
    — fine with replicas, a gap without them.
  • 1M users — a different product, and worth saying so plainly. At that scale
    Cortex is a multi-tenant SaaS gateway: per-tenant isolation and noisy-neighbour
    control, a real database rather than JSONL files, sharded/streamed cost
    aggregation, quota enforcement on the hot path, and per-tenant key management
    measured in millions of secrets. Note what the prior art does here: LiteLLM's
    Organizations tier is enterprise, and Bifrost/Portkey both centralise
    credentials in a managed control plane. The honest framing is that 1M users is not
    a scaled-up laptop tool — it is the thing those products are, and the decision is
    whether Cortex intends to be one. Nothing in this issue should assume that
    answer is yes.

Two scaling notes specific to routing, since they are what this issue adds:

  • Scope resolution must not add a per-request network call. An identity-derived
    scope is a JWT claim (already validated in-process by jwt-validation), which is
    free. A credential-fingerprint scope is a hash. But a scope resolved by lookup
    — "which server does this user get?" against a database — puts a round trip on
    every request's critical path. Design it as a cached map reloaded on config change,
    the way servers: already is.
  • Per-scope fairness. One scope's traffic must not exhaust the buffer budget for
    every other. litellm-budget-track already enforces a daily cap and returns 429;
    concurrency and memory are the dimensions it does not cover, and at 1000s of users
    they matter more than spend.
Metrics: combining many laptop Cortexes with remote ones

Routing per user and per workspace only pays off if the spend it produces is answerable
in one place. That is the other half of the remote question, and it has a much cheaper
answer than remote inference — because Cortex already produces a metrics-shaped
artifact on every laptop
.

Note #872 (Enterprise dashboard for Rossoctl / Cortex) already asks for exactly this
and should probably own the work; it names Grafana for both the laptop (a Docker
container with a supplied dashboard) and the enterprise case (Grafana on K8s), and links
Grafana's existing Claude Code dashboards. This section is the routing-shaped half of it:
what a federated view needs per backend and per scope, which is the thing multi-backend
routing adds.

What exists today, per Cortex, and it is more than it first appears:

  • The cost ledger is already a time series on disk. ~/.cortex/cost/YYYY-MM-DD.jsonl,
    "one JSON line per minute per (endpoint, model, agent, provenance)": host, model, the
    calling agent, token counts, dollar figures, a timestamp. Crucially, "No prompt
    content, no completions, no tool arguments — that is a promise a test asserts against
    the serialized bytes, not a convention."
    So the artifact that would be shipped to a
    central store is already content-free by construction, which removes the hardest
    objection to federating it.
  • GET /v1/usage aggregates it with window, group (model, endpoint,
    session, agent, currency, status, plugin, host) and resolution.
  • OTel spans via lineage-telemetry, with an OTLP gRPC endpoint, TLS and a CA file
    — but these are traces, cluster-shaped (they require namespace, a SPIFFE-derived
    self_id), and per-exchange rather than aggregated.

What is missing is the standard scrape surface. There is no /metrics endpoint and
no Prometheus exposition anywhere in core/ or cmd/ — the only matches are
prometheus.* host globs in plugin bypass lists. So today the path to Grafana is
"poll /v1/usage and transform", per machine, by hand.

Proposed shape, cheapest first. These are independent and each is useful alone:

  • A Prometheus /metrics endpoint on the stats listener (:47602 locally,
    :9093 in-cluster, beside /config, /reload/status and /pricing/table).
    Counters and gauges derived from the same settle output the ledger uses, so
    nothing can disagree about what a request cost. The label set is the design
    decision, and routing is what makes it interesting: endpoint (the backend
    actually used), requested_host (where the agent aimed — already recorded when
    they differ), model, requested_model (already kept when substituted), agent,
    provenance, and — once this issue lands — server and scope. That last
    pair is the whole point: "which backend did this team's traffic actually use, and
    under whose scope", answerable in one query.
  • Keep cardinality bounded deliberately. session must not be a label — it is
    unbounded and the session API already answers per-session questions. The existing
    group= list is a good guide to what is safely dimensional, and note that
    /v1/usage already degrades session, host, status and plugin to
    group: "none" on a ledger-backed window, which says which axes the durable store
    actually carries.
  • Federation model: push, not scrape. A laptop is not scrapable — it is NAT'd,
    asleep half the day, and on a different network each morning. Prometheus-style pull
    assumes reachable targets, which is exactly what a fleet of laptops is not. So the
    laptop case wants OTLP metrics push to a collector the organisation runs (the
    project already ships an OTel collector for traces, and #872 proposes adding
    metrics to it), with the /metrics endpoint serving the local-debugging and
    in-cluster-scrape cases where pull does work. Remote and cluster Cortexes are
    scrapable and can be either.
  • One identity per emitter, so totals are attributable and de-duplicable. Each
    Cortex needs a stable instance label plus the scope/user dimension. There is
    precedent for the shape in lineage-telemetry's self_id + namespace pair, and
    a precedent for the care required in #1321, which is researching adoption
    telemetry and states the governing constraint plainly: Cortex "sits in the request
    path and decrypts the user's agent traffic. That earns a level of trust that is
    very easy to spend and very hard to get back." A tool that decrypts your traffic
    must not ship anything you did not ask it to.
  • Therefore: off by default, explicit endpoint, and say exactly what leaves. No
    implicit fleet telemetry. The honest pitch is that the operator configures a
    collector they run, the payload is the ledger's own content-free dimensions, and
    the docs state the field list. This is a different feature from #1321's adoption
    question — opt-in enterprise observability of your own fleet, not vendor
    collection — and the issue should say so to avoid being read as the latter.
  • Double-counting is the correctness trap. If a laptop Cortex routes to a remote
    Cortex which routes to a LiteLLM gateway, both Cortexes see the same request and
    both will settle a cost for it. Summing their metrics overstates spend. Either the
    remote hop must be marked so one side is authoritative, or the dashboards must sum
    over exactly one tier. Cortex already has the vocabulary for this — provenance
    distinguishes authoritative (the gateway's own figure) from bundled/configured
    — and the existing warning that the ring and the ledger "must never be subtracted
    from each other" shows the project already treats this class of error as worth
    documenting rather than hoping about.
  • Mixed currencies must not be summed. unit sits on the endpoint (the shipped
    Bob example bills in Bobcoins), and agentop cost already withholds a combined
    total across units and points at --by currency. A Grafana panel summing a
    cost metric across a fleet with two units would produce a number that is
    "neither" — so the unit belongs in the label set, and the shipped dashboard must
    break down by it rather than total over it.

What a shipped dashboard should answer, which is the test of whether the label set is
right: spend per backend across the fleet; spend per user or team; which scopes are
actually in use; how often a model substitution fired (per server); unpriced-request
count by <endpoint> <model>, since that is the pair a pricing: entry needs; and
per-backend error and refusal rates — which is also the signal #1400 wants for
degradation alerts, so the two should share a definition rather than inventing two.

Semantics to settle
  • The pin still wins, and still never moves a running conversation. A scope
    decides only an unpinned session's server — the same position agents: holds
    today, and the invariant #1340 was filed to protect. A session whose scope changes
    mid-conversation stays where it was pinned; agentop server move remains the one
    thing that moves a live one.
  • Precedence, stated in one place: sessions: entry → pin → scope → agents: →
    not routed. Note Portkey's rule is the mirror of this (request-level beats
    key-level default) and LiteLLM's request-level tags can only add filtering,
    never remove it — both worth comparing against before fixing the order.
  • Record it. The modify/routed row should carry which scope decided, and why
    it fell through when it did (scope_unreadable, scope_unmatched), so a user can
    see in agentop that the variable they exported was actually read. Without this
    the feature is unfalsifiable from outside.
  • Trust. A client-asserted scope is exactly as trusted as the session id headers
    already are — core/session/idheader.go on X-Task-Id: "any client that sends it
    captures a bucket named after its value". A scope selects among servers the
    operator configured
    , so the worst case is using one's own other backend and its
    key. Write that boundary down: a scope must not name a server absent from
    servers:, and the config file stays the only source of keys and URLs. The
    environment and credential sources are both stronger than a header, since neither
    can be forged by a request — the same reasoning behind LiteLLM's
    inherited_tags.
  • Keep it a routing directive, not a label. LiteLLM needed
    tag_routing_prefix after plain tags collided with attribution tags. A distinct
    namespace from the start avoids that.
  • Agent-neutral. Codex, OpenCode, Bob and Pi (#1458) have the same problem; the
    scope must not be Claude-Code-shaped. The env and credential paths are the only
    ones common to all of them.
  • One scope concept, two trust levels. A scope resolved from an authenticated
    pctx.Identity and one read from a client's environment should be the same
    scopes: map with different sources, so the cluster case is not a second
    feature — but the row must record which source decided, and a source must be
    enablable per deployment (see Shape B above). Resolution should prefer the
    strongest source available: identity → credential fingerprint → environment →
    header → addressed host.
Risks and open questions
  • Does this belong in the router, or is it a per-workspace config profile? A
    scopes: map answers only the server part, but the user's real unit is "this
    directory's whole agent setup" — base URL, token, model names, CLAUDE_CODE_* flags.
    Deciding against the broader idea is fine; it should be a decision rather than an
    omission.
  • A scope matched on the client's cwd is tempting and should probably be refused.
    peerproc exposes Exe and not the working directory, and a path glob in router
    config would be a new matching surface. An opaque user-chosen key stays agent- and
    layout-neutral.
  • Credential-fingerprint routing couples routing to rotation. Rotating a gateway
    token silently un-scopes its sessions back to agents:. That must be visible in the
    row rather than inferred from a billing surprise.
  • Cost attribution already works and must not regress. Spend is keyed by endpoint
    host today (agentop cost --endpoint <host>, /v1/usage?group=endpoint), which is
    what makes the current three-backend setup legible. Routing more traffic through the
    router must keep each backend's spend separable.
  • agentop server output needs a scope column, or the listing silently stops
    describing what the proxy does — the same gap the SERVER column closed for agents.
  • Is the multi-user half in scope for this issue at all? Shape A is small and
    laptop-only; Shape B touches identity, secret handling and per-subject spend, and
    plausibly belongs in its own issue so the cheap case is not blocked behind it. The
    argument for designing them together is only that the scopes: key should not have to
    be redesigned later to admit an authenticated source — splitting the work while
    fixing that one interface now may be the right answer.
  • Per-user keys raise a question Cortex has not had to answer on a laptop: today
    every server's key sits in ~/.cortex/config.yaml, which is fine for one owner. A
    shared deployment holding many users' gateway credentials wants secret references and
    a redaction story beyond the existing /config and /v1/pipeline redaction.
  • The remote case may be a different product decision, not a bigger version of this
    one.
    Local Cortex is a transparent proxy that intercepts; remote Cortex is most
    naturally an endpoint that agents address. Those have different threat models,
    different credential stories and different listeners. Deciding deliberately which
    Cortex wants to be — and whether both — matters more than the scopes: schema.
  • Scale changes what "a session never moves" costs to guarantee. On one process a pin
    is a map lookup. Across replicas it is either shared state on the hot path or sticky
    routing at the load balancer — and the invariant #1340 established is strong enough
    that neither can be chosen casually. If the answer is sticky routing, say so early:
    it shapes the deployment topology, not just the code.
  • There is no performance baseline, and capacity claims are unfalsifiable without
    one.
    No benchmark exists in the repo or the issue list for requests/sec, memory per
    concurrent buffered request, or added p99 latency. Given that buffering makes memory a
    function of context size × concurrency, this is the measurement everything else
    depends on — and the answer may well be that the current shape serves 10s of users
    comfortably and needs real work for 1000s. Better to learn that from a benchmark than
    from a deployment.
  • Three scope sources, three localities, one risk: a design that works locally
    (environment), remotely (identity) and in a cluster (identity) must not let the
    weakest source be accepted where a stronger one is expected. The per-deployment
    opt-in modelled on session.id_headers is the mitigation, and it should be designed
    in from the start rather than retrofitted.
  • The metrics half may be better owned by #872, which already proposes Grafana for
    both laptop and enterprise. The only part this issue genuinely adds is the server
    and scope dimensions — without them a fleet dashboard cannot answer "which backend
    did this team use", which is the question multi-backend routing creates. Worth a
    cross-link and a decision about which issue carries the label-set design rather than
    both specifying it.
  • Fleet metrics is adjacent to #1321's trust boundary and must not be confused with
    it.
    One is opt-in observability of an organisation's own fleet into a collector it
    runs; the other is telemetry reaching the project. Shipping the first without stating
    the distinction loudly risks being read as the second, which #1321 is explicitly
    careful about. The safe defaults — off, explicit endpoint, documented field list,
    content-free payload — should be stated as part of the feature, not as reassurance
    added afterwards.
Additional Context

Verified against main and the full issue list (600 issues, open and closed, via the
public API). No existing issue covers per-session or per-scope server selection: #1330,
#1355, #1336 and #1435 all build the current agent-keyed model, and #1019/#1020/#1400
are automatic switching. Relevant to the #962 v0.9.0 epic's "one Cortex, invisible to
everything else" goal: three installs on three ports is the current answer and
contradicts it.

#1434 (Support mTLS for Session API) is a prerequisite for the remote shape, not a
duplicate of it — it secures observation of a remote proxy; this would need the same
transport security plus a credential model for inference. Nothing in the issue list
proposes serving inference from a remote Cortex, so that part is new ground and may
warrant its own issue once the local case is settled.

Suggested split, if the whole is too large for one issue: (1) scope selection on a
local Cortex (Shape A — small, self-contained, unblocks the three-workspace case);
(2) identity-derived scopes for shared/cluster Cortex (Shape B); (3) remote
Cortex as an authenticated inference endpoint, which depends on #1434 and on an inbound
listener that may redirect; (4) fleet metrics, which is #872's existing scope
plus the server/scope labels this work adds; (5) a performance baseline and the
shared-state work behind horizontal scaling, which (3) needs before it serves more than
a handful of users. Only the scopes: interface needs to be agreed across all five now
— (1) is the only one with no prerequisites, and (5) starts with a measurement rather
than a design.

No existing issue covers scaling, replicas, statelessness or load balancing, so (5) is
new ground. The two concrete blockers found while writing this — the reverse proxy's
1 MB body cap against a 1M-token context, and per-request buffering as the memory
ceiling — are each small enough to file on their own and are worth doing regardless of
whether remote Cortex is pursued.

Related: #872 (enterprise Grafana dashboard — owns the metrics surface), #1434
(mTLS for the session API — prerequisite for anything remote), #1400 (backend
degradation alerts — should share an error/latency definition with the metrics labels),
#1321 (adoption telemetry research — adjacent trust boundary, deliberately distinct),
#951 (latency metrics: TTFT and percentiles, which a dashboard would want and
SessionEvent cannot yet supply).

Prior art reviewed: LiteLLM tag routing,
LiteLLM key/team router settings,
LiteLLM multi-tenant architecture,
LiteLLM customers / end-users,
Portkey configs,
Bifrost virtual keys,
claude-code-router.

主要语言
Go
星标
31
派生
49
平均合并
9 小时 43 分钟
30 天内合并 PR
367

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

rossoctl/cortex 的其他 Issue

查看 rossoctl/cortex 的全部 Issue

相似的 Issue

更多 Go Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。