# Conditional target routing

**Last updated:** 2026-11-13T07:33:34-03:00 (UTC-3)

Use `targets[].when` to restrict which upstream connections may serve an alias for an authenticated key, its team and admitted usage tags. Conditions narrow destinations; they never grant model access, route scopes, team rights or budget.

## Enable and configure

`conditional_routing` defaults to **false** and can be managed through YAML, the feature API and **Settings & sources**. The example assumes existing provider connections `openai-primary` and `alternate`, plus permitted usage tags:

```yaml
features:
  conditional_routing: true
  usage_tags: true
usage_tags:
  allowed_values:
    region: [eu, us]
models:
  - id: chat-conditional
    capabilities: [chat]
    targets:
      - provider: openai-primary
        model: gpt-4o-mini
        when:
          team_ids: [team_platform]
          key_ids: [service_chat]
          tags:
            region: [eu]
      - provider: alternate
        model: alternate-model
        when:
          tags:
            region: [us]
```

The first target needs **both** the exact authenticated team and key IDs, and an admitted `region=eu` tag. Each key/team list accepts any one of its entries. Each tag value list accepts any one of its entries; every configured tag name must match. IDs are IDs, not display names, and are case-sensitive. A client cannot set its identity with `metadata`, a team header or a body field. Tags can be client-selected within the operator's taxonomy, so do not use a tag as proof of identity.

Team/key-only conditions do not need usage tags. Conditions with tags use the same bounded header, taxonomy and optional team defaults as [usage tags](/docs/features/usage-tags/). Missing or unpermitted inputs never become an unrestricted match.

## Defaults and limits

| Field | Default | Contract |
| --- | --- | --- |
| `targets[].when` | Absent: unconditional | When present, nonempty object containing only the three fields below; explicit null is invalid |
| `when.key_ids` | No key restriction | 1–32 unique exact IDs when present |
| `when.team_ids` | No team restriction | 1–32 unique exact IDs when present |
| Each ID | None | 1–256 UTF-8 bytes; nonblank, no surrounding whitespace or controls; historical dots/slashes remain literal |
| `when.tags` | No tag restriction | 1–8 names, each with 1–32 unique string values |
| Tag names/values | None | Existing usage-tag ASCII tokens, 1–64 bytes |
| Complete condition | None | At most 16,384 canonical JSON bytes, in addition to the existing model/configuration request bounds |
| `features.conditional_routing` | `false` | Runtime operator control; does not grant permission |

Lists, objects and strings cannot be empty or null. Unknown, duplicated or case-aliased fields, malformed types, expressions, regex and wildcards are rejected. The combined condition byte limit applies even when each individual list fits its limit. The full model-write JSON envelope also retains its 400 KiB (409600-byte) bound: combining maximum-size Codex instructions and several conditions can exceed that envelope even when every individual field validates. Keep the whole encoded request within that cap; the per-condition limit does not raise it. The API and console use the same typed definition; this definition was introduced in **V19** (107 definitions); the current console uses **V21** (109 definitions), preserving the same condition profile. Older catalog selectors and the omitted V1 response stay unchanged.

## Selection, weights and fallback

A target without `when` is eligible for everyone who is otherwise authorized for the alias. A matching condition makes its target eligible; a nonmatching condition excludes it. There is **no implicit conditional-first priority**. Existing [weights and capacity](/docs/features/routing-and-admission/) and [strategies](/docs/features/routing-strategies/) choose among the eligible set, and fallback/retry cannot reintroduce an excluded target. Existing `target.tags` restrictions also apply.

An unconditional fallback remains eligible and can be chosen by the configured strategy. To enforce a restricted destination, do not add an unrestricted target that contradicts that restriction.

| Situation | Result |
| --- | --- |
| Alias has conditions but `conditional_routing` is off | 503 `conditional_routing_disabled`, before cache/provider |
| No target meets the conditions | 403 `no_target_for_conditions`, without reflecting rule or identity values |
| Required tag capture cannot be used | Refusal before provider; never ignore the tag dimension |
| Alias has no conditions | Existing routing behavior |
| Budget/profile cannot safely protect the resulting operation | Existing quota refusal; conditions do not bypass financial proof |

Selection precedes pricing, durable send and provider attribution. A genuinely single eligible destination may use an existing single-destination financial profile. The feature does not add a new retry/accounting protocol or authorize an uncertain paid replay.

## Cache and helper calls

Exact-cache identity includes the eligible target set, for both memory and remote storage. The stored key uses a private hash, not raw IDs or tags. Changing a condition/tag that changes the eligible pool cannot return an answer from another pool. Unchanged unconditional cache profiles keep their existing behavior.

Semantic answer caching is bypassed when either the answer alias or its embedding alias declares conditions. This preserves routing correctness; it does not claim conditional semantic-cache hits. Auto-router example indexes use a private contextual namespace for conditional embedding aliases and retain their existing bounded lifecycle.

Internal embeddings, classifiers and other alias-based helpers evaluate their own alias using the trusted in-process caller and their own admitted/default tags. They do not silently inherit a parent header that was not forwarded by the existing helper. A denied final destination may still follow earlier, visible and accounted helper work; do not treat every denied outer request as a guarantee of zero helper cost.

Identity follows the accepted authentication snapshot, including any explicitly enabled [managed-key cache window](/docs/features/managed-key-cache/). This feature does not promise a stronger identity freshness boundary than authentication provides.

## Stateful work and realtime

New resource creation and realtime connection establishment apply current eligibility. A new inference that uses a pinned conversation/response provider must also fit the currently eligible pool; it is refused rather than moved to another provider.

Existing signed resources remain bound to their owner and provider. Reading, deleting, polling or settling an already admitted resource does not reroute it because a condition changed. Realtime pins its provider at connection establishment; configuration changes affect new requests/connections, not the destination of an admitted socket. Existing live credential, ownership and quota checks remain applicable.

## API and console edits

Use **Model catalog → Edit routing**. Each target has typed conditions, with explicit key/team ID lists and tag/value lists. The editor preserves conditions on unrelated edits and derives its bounds from exact V19 metadata. Missing metadata or `target_condition_access.write` makes conditional editing unavailable; flag state and write permission are separate, so an authorized operator can stage a model while routing is disabled.

The existing `PUT /api/v1/admin/models/{id}` accepts the full model and reviewed global version. For example, with an existing administrative session cookie and CSRF token:

```bash
BASE_URL=http://localhost:8080
# COOKIE_JAR and CSRF_TOKEN come from the existing administrative login.
VERSION=$(curl --fail-with-body -sS -b "$COOKIE_JAR" \
  "$BASE_URL/api/v1/admin/config?parameter_catalog_version=19" | jq -r '.version')
jq -n --argjson version "$VERSION" '{
  version: $version,
  model: {
    id: "chat-conditional", capabilities: ["chat"],
    targets: [{
      provider: "openai-primary", model: "gpt-4o-mini",
      when: {team_ids: ["team_platform"], tags: {region: ["eu"]}}
    }]
  }
}' | curl --fail-with-body -sS -X PUT -b "$COOKIE_JAR" \
  -H "X-CSRF-Token: $CSRF_TOKEN" -H 'Content-Type: application/json' \
  --data-binary @- "$BASE_URL/api/v1/admin/models/chat-conditional"
```

PUT is a **complete replacement**: omitting `when` removes it; explicit null is rejected. An older full-spec client can therefore remove a rule it does not preserve. Use the current editor or retain every target field when automating. `DELETE` reverts the model override to the reviewed YAML base, including its conditions, rather than patching an individual target.

Current identity/role, CSRF, captured version, whole-candidate validation and before/after feature-license checks apply to additions, edits, removals, disabled models and YAML restoration. Stale writes fail409. Read-only inspection does not make Save available; a late response cannot restore lost authority. The fixed publication-only unpublish action remains a recovery action when it leaves conditions identical.

Rule IDs and raw predicates are private administration data. Team/public/hub projections do not expose them, and telemetry never records predicate arrays or raw condition values. Use normal request/trace IDs and existing routing/usage records to follow an admitted attempt.

## Upgrade and rollout

No new database engine or schema migration is required for the target JSON. Replace or quiesce all older gateway replicas and administrative writers **before persisting conditions**. An older binary may ignore a field in stored JSON or continue serving its last older snapshot, so a normal mixed-version rollout does not prove these destination restrictions. Route traffic only to the upgraded pool, then stage/activate conditions through the versioned API. Preserve the existing configuration/database/key backup and new-binary recovery procedure; do not use an old binary to manage conditional models.
