From 7f961dc18444ecddfe4b1f1784b61fc23c4f23d3 Mon Sep 17 00:00:00 2001 From: CI Test Date: Mon, 30 Nov 2026 20:03:42 +0000 Subject: [PATCH 1/4] Add the operator routing policy store and admin surface - Add migration v69 with a revision-triggered policy store for the discovery exposure mode, per-provider-model enablement, and metadata overrides. - Carry an immutable policy snapshot into each request through routing facts; an unreadable store fails the request closed instead of ignoring a disable. - Exclude disabled provider-model pairs in eligibility and project either consolidated or provider-qualified discovery ids. - Add the /routing/policy admin page and audited /admin/routing mutations with revert-by-delete; keep models.expose_mode parseable but inert. - Update the migration, route, module, and schema censuses, the runtime manifests, the architecture docs, and the changelog. - Verified with fmt, strict clippy, no-default check and clippy, both serial suites, the locked release build, release docs, and the tooling suite. --- AGENTS.md | 10 +- CHANGELOG.md | 12 + architecture/deep-dive-models.md | 3 + architecture/deep-dive-routing.md | 37 ++ architecture/overview.md | 11 +- docs/live-config-rehash.md | 5 +- .../001-policy-store-and-exposure-modes.md | 381 +++++++++++++++++ plans/registry.md | 5 +- plans/subsystems/persistence-roadmap.md | 2 +- .../routing-policy-capacity-roadmap.md | 383 +++++++++++++++++ .../db/migrations/0069_routing_policy.sql | 85 ++++ rust/assets/db/migrations/checksums.json | 3 +- rust/assets/runtime-manifest.json | 4 +- rust/src/coordinator/endpoints.rs | 186 +++++++- rust/src/db/migrations.rs | 4 +- rust/src/db/mod.rs | 1 + rust/src/db/routing_policy.rs | 322 ++++++++++++++ rust/src/lib.rs | 1 + rust/src/routing/eligibility.rs | 18 +- rust/src/routing_policy.rs | 404 ++++++++++++++++++ rust/src/server/dashboard/admin.rs | 245 +++++++++++ rust/src/server/dashboard/mod.rs | 13 +- rust/src/server/dashboard/render/layout.rs | 3 +- rust/src/server/dashboard/render/mod.rs | 2 + .../server/dashboard/render/routing_policy.rs | 198 +++++++++ rust/src/server/health.rs | 8 +- rust/src/server/middleware.rs | 4 +- rust/src/server/mod.rs | 27 +- rust/tests/build_manifest.rs | 4 +- rust/tests/database_compatibility.rs | 18 +- rust/tests/routing_policy.rs | 258 +++++++++++ 31 files changed, 2615 insertions(+), 42 deletions(-) create mode 100644 plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md create mode 100644 plans/subsystems/routing-policy-capacity-roadmap.md create mode 100644 rust/assets/db/migrations/0069_routing_policy.sql create mode 100644 rust/src/db/routing_policy.rs create mode 100644 rust/src/routing_policy.rs create mode 100644 rust/src/server/dashboard/render/routing_policy.rs create mode 100644 rust/tests/routing_policy.rs diff --git a/AGENTS.md b/AGENTS.md index 8bff9193..6b1324ab 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -33,10 +33,10 @@ providers/transport → `deep-dive-providers.md`; reload/restart → `wire/` protocol codecs, `routing/` + `accounts/` + `catalog/` + `quota/` + `health/` selection, `model_router.rs` affinity, `identity.rs` + `web_session.rs` + `user_budget.rs` + `instance_budget.rs` + - `model_policy.rs` + `personal_upstream.rs` on-prem user access, `providers/` transport, + `model_policy.rs` + `routing_policy.rs` + `personal_upstream.rs` on-prem user access, `providers/` transport, `runtime_lifecycle/` generations + `reload.rs` + `task_supervisor.rs` + `security_events.rs`, `operations/` local lifecycle, `db/` + - `rust/assets/db/migrations/` v1–v68 immutable. + `rust/assets/db/migrations/` v1–v69 immutable. - Reusable policy crates: `rust/crates/eggpool-model-routing/` (neutral validation/compilation only; selector execution and affinity cache stay in `rust/src/`), `rust/crates/eggpool-client-config/` (portable Codex/OpenCode projection, profiles, `epc1` tokens, V1/V2 renderers, TOML/JSONC-preserving mutation; EggPool `Config`/catalog/DB/key/endpoint/CLI/file IO stays in `rust/src/operations/integrations.rs`), `rust/crates/eggpool-provider-profile/` (secret-free sans-I/O provider-profile contract plus the canonical bundled asset at `assets/_provider_profiles.toml`; `rust/src/provider_profile.rs` is the only EggPool reader), `rust/crates/eggpool-wire/` (neutral sans-I/O wire kernel; execution stays in `rust/src/`), `rust/crates/eggpool-connect/` (narrow `eggpool-connect` binary: plan/install/verify/backups/restore/remove with byte-exact backups, atomic writes, automatic rollback; no Axum/SQLite/Eggress, no proxy/agent/daemon). - Tooling only (never a runtime fallback): repo-root `pyproject.toml`, `scripts/`, `tests/tooling/`. `scripts/qualification_sbc.py` is the sole physical-SBC runner (loopback-only, aggregate-only, non-CI). Native tests live in `rust/tests/` (serial; there is no `coordinator_c012`; streaming files are `coordinator.rs`, `execution.rs`, `terminal.rs`, `timeout.rs`, `types.rs`, `diagnostics.rs`). - Config resolution: `--config` > `$EGGPOOL_CONFIG` > `~/.config/eggpool/config.toml` > `./config.toml`. Provider/upstream keys come from environment/`.env`, never committed; the server key lives under `[server]` (`api_key` via `eggpool newkey`, or `api_key_env`). Examples: `rust/config.example.toml`, `rust/config.local.example.toml`, `rust/config.sbc.example.toml`. @@ -91,6 +91,12 @@ dir, then `serve` (it daemonizes), curl, `stop`. ## Conventions agents miss +- Operator routing policy lives in SQLite (v69), not configuration: a stored + row overrides, absence inherits the config baseline and then the upstream + fact, and an unreadable snapshot fails closed. `models.expose_mode` stays + parseable but inert; the stored mode drives discovery. Do not add rank, + window, or capacity columns without their milestone. + - `rust/src/config_reload_policy.rs::classify_transition` is the only reload-vs-restart authority. Mutation paths classify before atomic replace; server `rehash` reclassifies before publication. Mixed changes are wholly diff --git a/CHANGELOG.md b/CHANGELOG.md index c55886ce..3460980c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ All notable changes to EggPool are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- **Operator routing policy.** Migration v69 adds a durable policy overlay for + the discovery exposure mode, per-provider-model enablement, and model + metadata overrides, with a revision-triggered immutable request snapshot. + Disables are enforced in eligibility, separate mode advertises + provider-qualified ids, and `/routing/policy` provides audited admin + controls. Reverting an override deletes the row and restores the inherited + value. An installation with no policy rows behaves exactly as before. + ## [0.8.3] - 2026-10-30 ### Changed diff --git a/architecture/deep-dive-models.md b/architecture/deep-dive-models.md index c580a1c7..1993a3cf 100644 --- a/architecture/deep-dive-models.md +++ b/architecture/deep-dive-models.md @@ -23,6 +23,9 @@ tuning (`refresh_interval_s`, `expose_mode`, `startup_refresh`, `stale_after_s`, `allow_stale_catalog`, `ping_retain_days`, `collapse_models`, `catalog_withdrawal_policy`). `RoutingConfig` holds `strategy`, `near_tie_epsilon`, `local_quota_mode`, `fairness_mode`, `fairness_epsilon`, and `fairness_scope`. +`models.expose_mode` stays in `ModelsConfig` for configuration compatibility but +has no runtime consumer; discovery projection is operator policy owned by +`rust/src/routing_policy.rs`. `ModelRouterConfig` declares one virtual model: `selector_model`, `default_model`, `routes: BTreeMap`, `sticky`, `affinity_ttl_s`, diff --git a/architecture/deep-dive-routing.md b/architecture/deep-dive-routing.md index 74e90f21..4d59000a 100644 --- a/architecture/deep-dive-routing.md +++ b/architecture/deep-dive-routing.md @@ -42,6 +42,43 @@ hit and selector repair use the same request snapshot. A policy denial returns 403 before the concrete provider attempt, while provider eligibility, health, quota, and fairness remain owned by this routing module. +## Operator routing policy + +An operator policy overlay sits beside configuration, not inside it. +`rust/src/routing_policy.rs` owns a process-wide `RoutingPolicyService`, and +`rust/src/db/routing_policy.rs` owns the durable rows introduced by migration +v69. A policy row is an explicit override; absence means inherit the +configuration baseline and then the upstream catalog fact, so reverting is a +row delete rather than a sentinel value. + +Precedence is policy row, then configuration, then the upstream catalog entry. +The overlay currently carries the exposure mode, per-provider-model +enablement, and metadata overrides. It deliberately has no rank, window, or +capacity column: those arrive in later milestones. + +Every mutating table carries insert, update, and delete triggers that advance a +singleton revision. Admission calls `RoutingPolicyService::snapshot()`, which +performs one indexed revision read and returns a cached immutable snapshot when +it matches; otherwise it rebuilds the snapshot in one transaction. The request +carries that snapshot as `RoutingRequestFacts::routing_policy`, so selection +reads policy without I/O and an edit can never change decisions already made. +An unreadable store fails the request closed with the typed +`RoutingPolicyUnavailable` outcome instead of silently ignoring a configured +disable. + +`candidate_for_account` checks an explicit provider-model disable immediately +after the credentials and provider gates, before health, quarantine, catalog, +and freshness work, and reports `model_disabled_for_provider`. Discovery +projects the same snapshot: consolidated mode lists canonical ids, separate +mode lists one `model/provider` id per enabled provider-model pair and keeps +virtual aliases unqualified. `models.expose_mode` remains parseable and +classified live, but it has no runtime effect; the stored mode decides. + +The admin surface is `/routing/policy` with admin-scoped, CSRF-protected +`/admin/routing/*` mutations. Each committed mutation writes exactly one +`routing_policy_audit` row in the same transaction; a refused or no-op +mutation writes none. + ## Eligibility gates `eligibility.rs::build_eligible_candidates` is the read-only gate. `EligibilityPolicy::from_config` diff --git a/architecture/overview.md b/architecture/overview.md index c9bbcbd2..904315d1 100644 --- a/architecture/overview.md +++ b/architecture/overview.md @@ -163,8 +163,8 @@ managed-user at `/login`, `/logout`, `/account`, `/account/landing`, `/account/tokens/revoke`, `/usage`, `/api/user-budget`; dashboard pages at `/`, `/accounts`, `/models`, `/models/{*model_id}`, `/latency`, `/events`, `/timeseries`, `/bandwidth`, `/pings`, `/reliability`, `/routing`, -`/traces`, `/runtime`, `/cache`, `/users`, `/profiles`, `/admin/audit`, -`/api/admin/audit/export`; +`/routing/policy`, `/traces`, `/runtime`, `/cache`, `/users`, `/profiles`, +`/admin/audit`, `/api/admin/audit/export`; admin actions at `/admin/users/create`, `/admin/users/state`, `/admin/users/password`, `/admin/users/token`, `/admin/users/revoke-tokens`, `/admin/users/profile`, `/admin/users/override`, @@ -174,7 +174,10 @@ admin actions at `/admin/users/create`, `/admin/users/state`, `/admin/budget/instance`, `/admin/budget/instance/remove`, `/admin/profiles/create`, `/admin/profiles/default`, `/admin/profiles/update`, `/admin/profiles/delete`, `/admin/profiles/rule`, -`/admin/profiles/rule/remove`, `/admin/profiles/prefer`; statics at +`/admin/profiles/rule/remove`, `/admin/profiles/prefer`, +`/admin/routing/mode`, `/admin/routing/model-policy`, +`/admin/routing/model-policy/remove`, `/admin/routing/metadata`, +`/admin/routing/metadata/remove`; statics at `/static/dashboard.css`, `/static/dashboard.js`, `/static/chart.js`, `/static/favicon.svg`, `/static/theme.css`. The per-surface behavior of each family is owned by its deep dive, not by this index. @@ -359,7 +362,7 @@ is the only persistence boundary. `db/` owns only the `backup_to` snapshot primitive; backup orchestration lives in `operations/backup.rs` and crash repair in `runtime_lifecycle/recovery.rs` plus coordinator reconciliation. Migrations (`rust/assets/db/migrations/`, -currently v1–v68 with `checksums.json`) are embedded and immutable; commit or +currently v1–v69 with `checksums.json`) are embedded and immutable; commit or ownership ambiguity fails closed; startup reconciliation repairs only covered states. Repositories accept no unbounded diagnostic content and never store credentials, prompts, raw bodies, or cache keys. diff --git a/docs/live-config-rehash.md b/docs/live-config-rehash.md index c1a0132a..7cdeec5d 100644 --- a/docs/live-config-rehash.md +++ b/docs/live-config-rehash.md @@ -69,7 +69,10 @@ candidate builder already constructs as generation-owned objects: ``collapse_models``, ``refresh_interval_s``, ``stale_after_s``, ``allow_stale_catalog``. Startup-only fields (``startup_refresh``, ``ping_retain_days``, - ``catalog_withdrawal_policy``) remain ``RESTART_REQUIRED``. + ``catalog_withdrawal_policy``) remain ``RESTART_REQUIRED``. The + ``expose_mode`` key remains parseable and live-classified but has no + runtime effect: discovery mode is operator routing policy stored in + SQLite and applied through the per-request policy snapshot. `security.persist_redacted_error_detail` remains parseable for configuration compatibility but has no runtime effect. Its existing reload classification is unchanged and does not imply an active persistence control. diff --git a/plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md b/plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md new file mode 100644 index 00000000..12ea31f6 --- /dev/null +++ b/plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md @@ -0,0 +1,381 @@ +# Routing Policy and Capacity Milestone 001 — Policy store, exposure modes, and per-model controls + +Status: implemented + +Repository baseline: `4a819a6536b17ec2b51d8c2dcaebd72c8511d5b6` + +Source roadmap: + +- `plans/subsystems/routing-policy-capacity-roadmap.md#7-milestones` + +Long-term requirements: + +- `plans/000-long-term-specification.md` — deterministic, load-based selection; generation-owned execution; single SQLite gate +- `plans/001-terminology-and-domain-model.md` — provider, account, and model identity +- `plans/002-long-term-roadmap.md` — sustaining work preserves a working proxy and current compatibility + +Applicable ADRs: + +- None required as scoped. The milestone adds durable policy rows and an admin write surface without changing reload classification, authentication semantics, generation or lease ownership, or a public protocol. +- Stop condition: if review classifies the overlay as a competing configuration authority rather than a documented precedence layer, write the ADR before implementing. + +Primary class: capability + +## 1. Objective + +Give operators a durable routing policy store (migration v69), an immutable +per-request policy snapshot, a consolidated-versus-separate discovery mode, +per-provider-model enablement, and metadata overrides with revert-to-upstream, +all controlled from the admin panel and audited. + +## 2. Why this milestone is ready + +- No hard dependency. The catalog already records per-provider model facts + (`ProviderModelIdentity`), and overrides already resolve provider, then + global, then upstream with per-field source tags + (`ModelCatalogCache::apply_overrides`). +- The revision-trigger, bounded-cache, immutable-snapshot pattern is already + proven by `rust/assets/db/migrations/0058_model_policy.sql` and + `ModelPolicyService::snapshot` in `rust/src/model_policy.rs`. +- The migration inventory and checksum guard already exist in `rust/build.rs`; + v69 is an additive entry, not a new mechanism. +- The admin surface already has admin scoping, CSRF, and an audit page to extend; + this milestone adds routes and rows, not an authentication model. +- Interface dependencies are stable: `RoutingRequestFacts` admission, + `build_eligible_candidates` ordering, and the discovery projection functions. + +## 3. Current implementation evidence + +- Discovery: `ModelCatalogCache::exposed_model_ids` returns model-keyed ids; + `InferenceEndpoints::discovery_model_ids` and + `authorized_discovery_model_ids` add virtual models. `models.expose_mode` is + validated in `rust/src/config.rs` and classified live, but no runtime consumer + reads it. `models.collapse_models` is consumed only by + `rust/src/operations/integrations.rs`. +- Addressing: `ModelCatalogCache::parse_model_provider` splits `provider/model`, + enforced by the `wrong_provider` exclusion. Qualified ids are never listed. +- Eligibility: `rust/src/routing/eligibility.rs` gates enabled, credentials, + provider, surface, protocol, health, quarantine, catalog support, freshness, + thinking capabilities, and quota. There is no per-model enable gate and no + rank or window gate. +- Metadata: `apply_overrides` covers limits, capabilities, and pricing, with + `context_source`, `input_source`, and `output_source` tags. There is no + display-name or policy metadata and no admin surface. +- Store: `rust/src/db/migrations.rs` embeds the manifest generated by + `rust/build.rs`; 68 migrations exist and `checksums.json` is the parity + authority. `user_admin_audit.target_id` allows 128 characters, while model ids + allow 512. +- Admin: `rust/src/server/mod.rs` registers account and model pages as + read-only and admin POST routes for users, profiles, and budgets only. +- Concurrency: no per-account concurrency cap, queue, or wait budget exists in + `rust/src/routing/` or `rust/src/coordinator/`. + +## 4. Invariants that must not regress + +- Selection stays deterministic and load based; policy never introduces price + into ranking. +- The semantic selector still cannot pin an account or bypass health, + quarantine, quota, or (later) capacity. +- `RoutingRouter::selection_lock` remains the atomic synchronous boundary; the + snapshot carries no await and no store access into it. +- One snapshot per request: a mutation during an in-flight request does not + change that request's decisions. +- Policy absence and policy failure stay distinct. Absent rows inherit; an + unreadable snapshot fails closed with a typed unavailable outcome. +- Exclusion reason codes stay bounded, ordered, and secret-free. +- Migrations stay append-only; no prior SQL file or checksum changes. +- Every existing configuration key stays parseable under `deny_unknown_fields`. + +## 5. Scope + +### In scope + +- Migration v69: policy state singleton, per-model policy rows, metadata + overrides, policy audit, revision triggers. +- A typed repository with validation and transactional writes. +- A process-owned `RoutingPolicyService` with a bounded revision cache and an + immutable snapshot. +- Snapshot resolution in inference admission, before selection. +- Per-provider-model enablement with a bounded exclusion reason. +- Consolidated and separate discovery projections. +- Metadata overlay with source tags and revert-by-delete. +- An admin policy page and POST routes, CSRF-protected and audited. +- Documentation of precedence, deprecation, and the new migration range. + +### Explicitly out of scope + +- Per-model ranks and active windows (M002). +- Concurrency caps, queues, and overflow (M003). +- Named timezones and any new dependency. +- Removing `models.expose_mode` or any configuration key. +- Migrating existing TOML `model_overrides` or `model_capabilities` into the + store; they remain the configuration baseline beneath the overlay. +- Changes to quota, health, quarantine, backoff, selector protocol, transport, + wire, or admission fairness. +- Any policy poller task or per-request database write. + +## 6. Required production changes + +- **Migration.** `rust/assets/db/migrations/0069_routing_policy.sql` and its + entry in `rust/assets/db/migrations/checksums.json`. Tables: policy state + singleton, `provider_model_policy`, `model_metadata_override`, + `routing_policy_audit`. Triggers bump the singleton revision on insert, + update, and delete. No existing file changes. +- **Repository.** A new `rust/src/db/` module with typed rows, validated + upsert and delete operations, and transactional audit writes. No secret + columns; model and provider ids validated against the catalog where it is + cheap, and tolerated as orphaned where it is not. +- **Snapshot service.** `rust/src/routing_policy.rs` mirroring + `rust/src/model_policy.rs`: `RoutingPolicyService`, `RoutingPolicySnapshot`, + `snapshot()` revision check, rebuild in one transaction, typed error, ordered + maps, secret-free `Debug`. Constructed once per process. +- **Admission wiring.** `rust/src/coordinator/endpoints.rs` resolves the + snapshot once per request during admission and passes it into routing facts. + The public `FiniteRequest` and `CompactAdmittedRequest` shapes stay source + compatible; any new data is additive and internal. +- **Eligibility.** `rust/src/routing/eligibility.rs` adds + `model_disabled_for_provider` after credentials and provider match, before + catalog freshness. +- **Discovery.** `discovery_model_ids` and `authorized_discovery_model_ids` + project by mode: consolidated lists canonical ids as today; separate lists + `provider/model` for each enabled, fresh provider-model pair. Response shape + is unchanged. +- **Admin.** A policy page and POST routes registered in + `rust/src/server/mod.rs`, rendered under `rust/src/server/dashboard/`, + reusing the existing admin scope and CSRF helpers, with one audit row per + mutation in the same transaction. +- **Docs and assets.** `architecture/deep-dive-routing.md`, + `architecture/deep-dive-models.md`, `docs/live-config-rehash.md`, + `AGENTS.md` (migration range), `CHANGELOG.md`, and the dashboard navigation + description. + +## 7. Ordered work packages + +### Work package A — v69 schema, triggers, and migration inventory + +Intent: land the additive store and make the build fail on inventory drift. + +Required changes: the SQL file, the `checksums.json` entry, and migration +coverage. Constraints: no CHECK on timezone or capability strings beyond +permanent invariants; lengths bounded; singleton enforced; triggers on every +policy table. + +Acceptance evidence: `build_manifest` passes; deleting the checksum entry or +altering the SQL fails the build and the guard is shown failing once; the +migration applies to an empty database and to a v68 database; a trigger test +observes the revision advance on insert, update, and delete for each table. + +### Work package B — Repository, validation, and audit writes + +Intent: one typed write path that cannot produce partial policy. + +Required changes: typed row structs, upsert/delete functions, bounded validation +with typed errors, audit insert in the same transaction. Constraints: no +secret-bearing fields; ids trimmed; enum and range checks isomorphic to the +schema; orphan rows tolerated on read. + +Acceptance evidence: invalid id, enum, and range inputs are rejected without a +write; a failed audit insert rolls the mutation back; each successful mutation +advances the revision exactly once. + +### Work package C — Snapshot service and cache + +Intent: immutable policy per request with revision-based freshness. + +Required changes: service construction in the process runtime; `snapshot()` +revision read, cache comparison, transactional rebuild, `Arc` return; ordered +maps; typed error. Constraints: bounded cache (one entry is sufficient); no +writes; no clock or network. + +Acceptance evidence: a revision change invalidates the cache; repeated calls +return the same `Arc`; a failed read returns the typed error; a concurrent +reader never observes a partially built snapshot; `Debug` output contains no +secret. + +### Work package D — Admission, enablement gate, and discovery projection + +Intent: apply the snapshot once per request and expose the two modes. + +Required changes: snapshot resolution in admission; enablement gate in +eligibility; mode-driven discovery projection; typed unavailable outcome on +snapshot failure. Constraints: no store access inside the selection lock; the +consolidated path is byte-identical to baseline when no rows exist. + +Acceptance evidence: a disabled pair is excluded with +`model_disabled_for_provider`; separate mode lists qualified ids for enabled, +fresh pairs only; consolidated mode is unchanged; snapshot failure returns the +typed outcome instead of proceeding; an invariant test asserts the selection +critical section performs no I/O. + +### Work package E — Admin page, POST routes, and audit + +Intent: let an operator switch modes, toggle a model at a provider, override +metadata, and revert. + +Required changes: page rendering with upstream facts and source tags; forms for +mode, model policy, and metadata; POST routes; CSRF and admin gating; audit rows. +Constraints: no credential display; bounded input lengths; revert is a delete. + +Acceptance evidence: each form round-trips and is visible on the page; a missing +or wrong CSRF token is rejected and writes nothing; a non-admin principal is +denied; each mutation produces exactly one audit row; revert restores the +upstream value and flips the source tag. + +### Work package F — Documentation, deprecation, and migration range + +Intent: make the behaviour and its precedence discoverable. + +Required changes: routing and models deep dives, live-config-rehash note, +`AGENTS.md` v1–v69, changelog entry, dashboard navigation text. Constraints: +state that `models.expose_mode` is parseable but inert, and that policy rows +take precedence over configuration and upstream facts. + +Acceptance evidence: `uv run python scripts/validate_release_docs.py`; +documentation review confirms no stale claim that `expose_mode` controls +discovery. + +## 8. Failure, cancellation, restart, contention semantics + +- Snapshot read or decode failure returns a typed unavailable outcome before + selection. The request does not proceed, so a configured disable can never be + silently bypassed. +- A mutation is one SQLite transaction: rows and audit commit together or not at + all, and the revision advances only on commit. +- Concurrent admin mutations serialize on the single database gate; the revision + is monotonic and last-writer-wins per row. +- An in-flight request keeps the snapshot it admitted with. Revert during that + request changes the next request, not the current one. +- Restart reloads rows from SQLite; the first request rebuilds the snapshot. +- Reload does not transfer policy state: the service is process-owned, and each + request captures its own snapshot. +- A row naming a provider or model absent from configuration or catalog is + ignored for selection and displayed as orphaned; it is never auto-deleted. +- Cancellation during admission releases the generation lease normally; this + milestone adds no queue or waiter to leak. + +## 9. Compatibility and migration + +- v69 is additive and forward-only. There is no downgrade path; restoring a + pre-v69 backup is the documented rollback. +- `models.expose_mode` stays in `Config` with its current validation, is + classified live as today, and is ignored at runtime. The database mode wins, + and documentation records the deprecation. +- `routing.strategy` continues to accept only `quota_fair`; this milestone adds + no strategy value. +- `/v1/models` keeps its response shape; only the id set can differ by mode. +- The CLI and `operations/config_mutation.rs` are unchanged. +- TOML `model_overrides` and `model_capabilities` remain the baseline beneath + the overlay, so existing installations keep their behaviour. + +## 10. Required tests + +- Migration and manifest: `rust/tests/build_manifest.rs`, + `rust/tests/database_compatibility.rs`; empty and v68 upgrade; trigger + revision advances. +- Selection and policy: `rust/tests/routing_domain.rs`, + `rust/tests/routing_fail_closed.rs`, and a focused enablement-gate test. +- Catalog and discovery: `rust/tests/catalog_refresh.rs` plus a projection + test for both modes. +- Admin and audit: `rust/tests/on_prem_admin_ui.rs`, + `rust/tests/gateway_audit.rs`, and the dashboard inline tests for CSRF, + admin gating, and form handling. +- Snapshot: revision invalidation, concurrent readers, typed failure, no-secret + `Debug`. +- Restart: rows persist and the next request observes them. +- No-default parity: the same focused tests under `--no-default-features`. + +All Rust suites run with `--test-threads=1`. + +## 11. Required verification commands + +```bash +cargo fmt --manifest-path rust/Cargo.toml --all -- --check +cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets -- -D warnings +cargo check --manifest-path rust/Cargo.toml --workspace --all-targets --no-default-features +cargo clippy --manifest-path rust/Cargo.toml --workspace --all-targets --no-default-features -- -D warnings +cargo test --manifest-path rust/Cargo.toml --workspace --all-targets -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --workspace --all-targets --no-default-features -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test routing_domain -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test routing_fail_closed -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test catalog_refresh -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test database_compatibility -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test build_manifest -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test on_prem_admin_ui -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test gateway_audit -- --test-threads=1 +cargo build --manifest-path rust/Cargo.toml --locked --release +uv run python scripts/validate_release_docs.py +uv run pytest tests/tooling/ -q --tb=short +``` + +## 12. Documentation updates + +- `architecture/deep-dive-routing.md`: policy precedence, snapshot lifecycle, + enablement gate, and the fail-closed rule. +- `architecture/deep-dive-models.md`: discovery projection modes and the + deprecation of `expose_mode`. +- `docs/live-config-rehash.md`: the key stays classified live and inert. +- `AGENTS.md`: migration range becomes v1–v69. +- `CHANGELOG.md`: operator-facing summary. +- Dashboard navigation and page help text. + +## 13. Acceptance criteria + +- Switching the mode changes the ids returned by `/v1/models` and nothing else + about the response. +- Disabling a model at one provider removes that pair from selection and from + separate-mode discovery, with its own exclusion reason. +- A metadata override is visible with a source tag; deleting it restores the + upstream value. +- Policy changes take effect for the next request without a restart, and + survive a restart. +- A policy store failure produces a typed unavailable outcome, never a silent + fallback. +- Every mutation is audited once; refused mutations write nothing. +- A fresh install and an upgrade from v68 both migrate; no prior migration + changes; the recorded checksums match. +- With no policy rows, routing decisions and discovery output match the + baseline. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- review requires an ADR before the overlay can be treated as authoritative; +- the v69 change cannot remain additive, or an existing migration would need + editing; +- the per-request revision read materially regresses the SQLite gate and folding + it into an existing admission call is not viable; +- the work would need to change selection order beyond the enablement gate, or + would pull rank, windows, or capacity into this milestone; +- a configuration key would have to be removed to proceed; +- catalog or policy facts cannot be represented without storing credentials or + raw request data. + +## 15. Closure evidence required + +- Implementation commits and the exact baseline they landed on. +- Command output for the full matrix above, labelled local or CI truthfully. +- Migration evidence: empty and v68 upgrade, checksum guard shown failing on a + deliberate manifest omission and passing after restoration. +- Restart evidence: policy persists and applies. +- Audit evidence: one row per mutation, none for refusals. +- Discovery evidence for both modes. +- A recorded measurement of the added per-request revision read. +- Documentation and registry updates, including the roadmap status table. + +## 16. Handoff notes + +- Baseline `4a819a6536b17ec2b51d8c2dcaebd72c8511d5b6`; the tree carries four + pre-existing untracked `artifacts/` directories that must stay untracked. +- Rust tests are serial. Strict Clippy and no-default parity are invariants. +- Do not add a policy poller task; freshness is the revision read. +- Do not remove `models.expose_mode`; it stays parseable and inert. +- Keep one `Status:` line in this plan and one in the roadmap; the tooling guard + treats every such line as a declaration. +- Do not touch `plans/` history, closed milestones, or other subsystems' files. +- If the snapshot error path turns out to be reachable on ordinary startup, + report it rather than widening the fail-closed rule. +- Implementation deviation recorded at implementation time: separate-mode + discovery lists enabled catalog pairs, while per-account catalog freshness + remains enforced at selection. Pair-level freshness has no stored fact, so + projecting it into discovery would invent one. diff --git a/plans/registry.md b/plans/registry.md index 77e3a9b9..1896d48d 100644 --- a/plans/registry.md +++ b/plans/registry.md @@ -106,6 +106,7 @@ Security hardening (2026-11-17, baseline `dcbd820e9b978d47bd43d237eded1f488d3449 | Security hardening | active | [security hardening roadmap](subsystems/security-hardening-roadmap.md) | M001–M005, M007, M009 active; M006, M008 blocked | Review baseline `dcbd820e9b`; M006 needs a signature-authority ADR and key custody; M008 needs an Eggress release permitting `russh >=0.65` or an approved vendoring/no-SSH ADR. | | Shared provider profile contract | closed | `plans/subsystems/shared-provider-profile-contract-roadmap.md` | M002 closed — OpenCode Go wire hints for the current first-party endpoint table | M001 and M002 closed; the roadmap re-opened on evidence and closed again on the same evidence. The four placed-but-unhinted models now resolve on their reviewed surfaces — `beam-free`, `minimax-m3.1-flash-free` and `step-5-preview` on Chat Completions, `claude-haiku-5-5` on Anthropic Messages. `gemini-4-argon-contributor` and the five unplaced catalog ids stay unresolved. The six entries the current table no longer places keep their hints with a recorded disposition, and a drift guard compares the wire map, the reviewed record and a dated catalog snapshot, failing closed on an unexplained delta. CodeGG consumption of M001 remains unblocked at immutable revision `9ac6a131`; CodeGG consumption of M002 is pinned to the M002 closure revision. `longcat-2.5-preview-free` stays withdrawn upstream and is not M002's to restore. | | Routing selection | active | `plans/subsystems/routing-selection-roadmap.md` | M009 closed — health effect ownership and terminal-withdrawal producer retirement | Reopened on evidence at baseline `e6822d8f78`: M001–M003 remain closed. M004, M005, and M006 are closed through M007. M008 is closed through `plans/closure/routing-selection/008-status.md`. M009 is closed through `plans/closure/routing-selection/009-status.md`. No further milestone is registered in this subsystem. | +| Routing policy and capacity | active | [routing policy and capacity roadmap](subsystems/routing-policy-capacity-roadmap.md) | M001 implemented — closure pending; M002–M003 blocked | New subsystem: the routing-selection roadmap's non-goals exclude fairness, capacity, priority, and pinning changes, so this policy workstream is separate. M001 landed the additive v69 policy store, exposure modes, per-model enable/disable, and metadata overrides with revert; its local matrix is green and closure evidence remains. M002 and M003 stay blocked on M001. | | Runtime efficiency | closed | `plans/subsystems/runtime-efficiency-roadmap.md` | M004 closed — behavior-identical request-path cost removal; policy revision probe declined | M001–M004 closed. No successor is registered. `eggpool users` can commit a policy revision while `serve` is running, so the per-request revision read stays. Persistence M007 remains rejected; production storage is unchanged. | | Persistence | active | `plans/subsystems/persistence-roadmap.md` | M011 closed — post-M010 roadmap/documentation reconciliation | M009/M010 closures accepted. Documentation/tooling-only corrective; production remains WAL/NORMAL. No technical persistence successor is registered. | | Deployment and packaging | active | `plans/subsystems/deployment-packaging-roadmap.md` | M008–M009 and M012 closed; M010 proposed, M011 blocked | Draft Eggpack/Eggup integration stages release-manifest parity before consumer migration; M011 requires an accepted dependency/ownership ADR and a safe async-restart rollback composition. M012 is closed: RUSTSEC-2026-0620 is resolved by the published `curve25519-dalek 5.1.0`, the exact `eggfetch-core` pin is aligned to `0.4.1` with its profile unchanged, and the stale pin documentation is corrected without an advisory ignore; upstream coordination is [eggfetch#35](https://github.com/eggstack/eggfetch/issues/35) with planning mirror [eggplan#1](https://github.com/eggstack/eggplan/issues/1). | @@ -341,7 +342,7 @@ persistence roadmap. | Subsystem | Milestone | Status | Implementation plan | Handoff note | |---|---|---|---|---| -None. +| Routing policy and capacity | M001 — policy store, exposure modes, and per-model controls | implemented | [M001](implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md) | Implementation and the local matrix are complete. Closure pending: an end-to-end `/v1/models` response check for both modes, process-restart evidence, and the recorded revision-read measurement. | Unblock audit (on-prem member access, 2026-11-10): M001–M005 are closed by their own records. ADR-0010 stays accepted. Searched the member-access roadmap, its implementation plans, and the ready, active, and blocked tables. No successor is registered. Nothing else was waiting on this roadmap, so nothing is promoted. On-prem user access M001–M024 stay closed. @@ -355,6 +356,8 @@ Unblock audit (on-prem member access, 2026-11-10): M001–M005 are closed by the | Provider OAuth | M001 — OAuth credential lifecycle and dispatch integration | Hard: accepted ADR-0012 must specify account/owner eligibility, provider scope, secret custody/backup, refresh coordination, and post-401 behavior; until then OAuth remains excluded. | | Provider OAuth | M002 — Headless device-code login | Hard: M001 closed and the exact provider/device-code profile explicitly approved by ADR-0012. | | Provider OAuth | M003 — Desktop loopback browser login | Hard: M001 closed and the exact provider/authorization-code profile explicitly approved by ADR-0012. | +| Routing policy and capacity | M002 — per-model ranks and active windows | Hard: M001 closed; the store, snapshot, and admin surface it consumes must exist first. | +| Routing policy and capacity | M003 — concurrency caps, bounded queue, and time-based overflow | Hard: M001 closed; operational: loopback evidence that the capacity layer does not meaningfully regress the hot path. | Unblock audit (application boundary, 2026-11-10, baseline `e049025274a397d7799c3ae21ed106947c2a1572`): ADR-0009 supersedes ADR-0007's gateway and hosted-execution decisions. Retrieval R001 is no longer a blocked handoff; R002 is the successor and is documentation only. Tool-integration M003 and M004 stay conditionally closed as historical records, and their open evidence conditions are vacated rather than promoted into new tool-integration work. Nothing else on the blocked table was waiting on R001. M004's missing shared host is an allowed `not measured` closure, not a registry block. The same-day closure audit above records M001–M003 and R002 closed and M004 conditionally closed. Nothing further is promoted. diff --git a/plans/subsystems/persistence-roadmap.md b/plans/subsystems/persistence-roadmap.md index 7bdb5e07..751650b8 100644 --- a/plans/subsystems/persistence-roadmap.md +++ b/plans/subsystems/persistence-roadmap.md @@ -482,7 +482,7 @@ Exit conditions: ## 8. Cross-cutting requirements -Storage and migration: this roadmap authorizes no schema change. WAL/NORMAL and the current schema (migration chain v1–v68) remain authoritative. +Storage and migration: this roadmap authorizes no schema change. WAL/NORMAL and the current schema (migration chain v1–v69) remain authoritative. Protocol and compatibility: no HTTP, wire, CLI, config, or public Rust API change. diff --git a/plans/subsystems/routing-policy-capacity-roadmap.md b/plans/subsystems/routing-policy-capacity-roadmap.md new file mode 100644 index 00000000..a4801ae7 --- /dev/null +++ b/plans/subsystems/routing-policy-capacity-roadmap.md @@ -0,0 +1,383 @@ +# Routing Policy and Capacity Roadmap + +Status: active + +Long-term references: + +- `plans/000-long-term-specification.md` — end-state invariants and ownership boundaries +- `plans/001-terminology-and-domain-model.md` — provider, account, and model identity +- `plans/002-long-term-roadmap.md` — sustaining work preserves a working proxy and current compatibility +- `plans/003-planning-process.md` — evidence-gated milestones and bounded implementation plans + +Related ADRs: + +- None required for M001–M003 as scoped. The milestones add durable policy rows, an admin policy surface, and a capacity layer without changing reload classification, authentication semantics, generation/lease ownership, or a public protocol. +- Stop for architecture review if a milestone treats the policy store as a second configuration authority rather than a documented override layer, introduces a competing ranking authority, or changes lease or queue ownership. + +## 1. Purpose and ownership boundary + +This subsystem owns operator routing policy and the capacity controls that act on +it: + +- `rust/src/routing/` policy consumption: enablement, rank, active windows, and + capacity eligibility, without changing the selection transaction's invariants. +- A process-owned immutable policy snapshot and its durable store. +- Discovery projection: consolidated model names versus provider-qualified names. +- Per-provider, per-model, and per-account policy rows: enablement, rank, + metadata overrides, active windows, concurrency caps, queue bounds, and + overflow budgets. +- The admin policy surface under `rust/src/server/dashboard/`, following the + existing presentation and CSRF conventions of the closed dashboard + subsystem without reopening it. + +It consumes `rust/src/catalog/` provider-model facts, `rust/src/quota/` and +`rust/src/health/` as inputs, and `rust/src/config.rs` as the declarative +baseline. It does not own provider transport, wire adaptation, request +admission, retries, the semantic selector protocol, generation and lease +lifecycle, or generation-owned claim accounting. + +The routing-selection roadmap remains the owner of selection-path performance +and correctness. Its non-goals exclude fairness, capacity, priority, and +pinning changes, which is why this work is a separate workstream that composes +with it rather than extending it. + +## 2. Work classification + +### Invariants + +- Routing stays deterministic and load/quota/health based, never cost based. + A rank expresses operator preference, not price. +- Semantic model selection remains before provider/account selection and still + cannot pin an account or bypass health, quarantine, quota, or capacity. +- The selection lock remains the atomic boundary; no provider, SQLite, + filesystem, or network await enters it. +- One immutable policy snapshot is captured per request and never re-read + inside selection. +- Policy absence and policy failure are distinct: absent rows fall back to + upstream or config defaults, while an unreadable snapshot fails closed. +- Ordered diagnostics stay deterministic; bounded reason codes stay stable and + secret-free. +- Migrations are append-only; prior migration files, checksums, and the + selection transaction's public compatibility surfaces are not rewritten. +- Every existing configuration key remains parseable; deprecation is documented, + not enforced by removal. + +### Capabilities + +- M001: operators switch exposure modes, disable a model at one provider, + override model metadata, and revert to the upstream default from the admin + panel; the policy survives restart. +- M002: operators rank providers per model with ties, and restrict a provider or + a provider's model to UTC active windows. +- M003: operators cap per-account concurrency and queue depth, and set a wait + budget after which requests overflow to another provider or rank. + +### Infrastructure + +- Additive v69 policy tables with revision triggers. +- A process-owned policy snapshot service with a bounded revision cache. +- An admin write path with audit rows. +- A capacity registry with per-key counters, bounded queues, and metrics. + +### Polish + +- Queue depth and wait diagnostics. +- Next-open timestamps for window exclusions. +- Policy revision visibility in status and diagnostics. + +## 3. Non-goals + +- No cost- or price-aware ranking. +- No change to quota formulas, EWMA estimation, health policy, quarantine + semantics, or backoff policy. +- No change to the semantic selector protocol, fingerprint, or affinity cache. +- No removal of `models.expose_mode` or any other parseable configuration key. +- No per-request database write and no policy poller task; freshness comes from + the revision read the snapshot service already performs. +- No new dependency: active windows are UTC-only until a separate decision adds + a timezone database. +- No multi-process or cross-host queue coordination; EggPool remains a single + serving process. +- No dashboard redesign and no reopening of closed subsystem milestones. +- No provider pinning through policy: rank orders candidates, it never forces an + account. + +## 4. Current state + +Repository evidence at baseline `4a819a6536b17ec2b51d8c2dcaebd72c8511d5b6`: + +- Discovery lists canonical model ids only. `ModelCatalogCache::exposed_model_ids` + returns the model-keyed set, and `discovery_model_ids` adds virtual models. + `models.expose_mode` is validated as `union`, `intersection`, or + `healthy_union` and classified live, but no runtime consumer reads it. + `models.collapse_models` is consumed only by client-config projection in + `rust/src/operations/integrations.rs`. +- `provider/model` addressing is parsed by `parse_model_provider` and enforced + by the `wrong_provider` exclusion, but it is never advertised. +- Provider priority is global: `ProviderConfig::routing_priority` becomes the + candidate tier and sorts before load. Fairness rotates only the near-tied top + band. No per-model rank, and no capacity-aware tier selection, exists. +- There is no per-account concurrency cap or request queue. + `NetworkConfig::max_connections` is a transport pool bound, + `routing.inflight_penalty` is a soft score, and + `routing.wire_negotiation.max_concurrent_per_provider` governs negotiation + only. `user_budget.max_concurrent` is per user, not per provider. +- Metadata overrides already follow the required shape: + `ModelCatalogCache::apply_overrides` resolves provider override, then global + override, then the upstream row, and records a source tag per field. It covers + limits, capabilities, and pricing today. +- `rust/assets/db/migrations/0058_model_policy.sql` and + `ModelPolicyService::snapshot` establish the revision-trigger, bounded-cache, + immutable-snapshot pattern this roadmap reuses. `0058` is model + authorization; it is not routing policy. +- The migration inventory holds 68 files. `rust/build.rs` generates the + embedded manifest and fails the build when a SQL file is absent from + `rust/assets/db/migrations/checksums.json` or the counts differ. +- Admin mutation today covers users, profiles, and budgets only. Accounts and + models pages are read-only. `user_admin_audit.target_id` is limited to 128 + characters, while model ids are allowed 512, so policy audit cannot reuse that + table for a `provider/model` key. +- An inference request holds a generation lease from `server/middleware.rs` + admission through completion. Any queue wait therefore delays retirement of + the generation it admitted against. + +## 5. Target architecture + +- **Store.** An additive v69 schema: a singleton policy state row carrying the + exposure mode, strategy, and a monotonic revision; per-model policy rows + (enablement and rank); per-account queue policy rows; active-window rows; + metadata override rows; and a dedicated policy audit table. Every mutating + table carries insert, update, and delete triggers that bump the singleton + revision. +- **Snapshot.** A process-owned `RoutingPolicyService` reads the revision once + per request, returns a cached `Arc` when it matches, and otherwise rebuilds an + immutable snapshot in one transaction. The snapshot is resolved during + admission, before selection, and passed into routing facts. No store access + happens inside the selection lock. +- **Precedence.** Policy row, then configuration baseline, then upstream fact. + Absence of a row means "inherit", which is what makes revert a delete. +- **Eligibility.** The enable, window, and capacity gates extend + `build_eligible_candidates` in a documented order after credentials and + provider match. Rank replaces the provider-priority tier only when a row + exists; one sort key, never two competing authorities. +- **Capacity.** A process-owned registry keyed by provider and account holds an + active counter, a bounded FIFO of waiters, and per-key metrics. Capacity is + acquired synchronously with the claim or not at all; waiting happens in the + coordinator outside the lock and outside any claim, and expiry re-enters the + existing exclusion-and-reselect loop. +- **Operator surface.** One policy page and admin POST routes, CSRF-protected, + admin-scoped, and audited. The page renders upstream facts beside overrides so + an operator can see what they are deviating from. + +## 6. Dependency graph + +- M001 — no hard dependency. Interface dependency on `ProviderModelIdentity` + and `apply_overrides` (catalog facts and the override shape), on + `RoutingRequestFacts` admission, and on the `0058` revision-snapshot pattern. + Soft dependency on the closed dashboard subsystem's presentation conventions. +- M002 — hard dependency on M001 for the store, snapshot, and admin surface. + Interface dependency on the eligibility gate ordering and the fairness scope + key. Soft dependency on M003 only for capacity-aware tier selection. +- M003 — hard dependency on M001. Soft dependency on M002 when rank and + overflow interact. Interface dependency on claim release semantics and the + coordinator's exclusion set. Operational dependency on loopback evidence that + the capacity layer does not meaningfully regress the hot path. + +## 7. Milestones + +### Milestone 1 — Policy store, exposure modes, and per-model controls + +Class: capability + +Objective: Move routing policy into an additive v69 store with an immutable +per-request snapshot, expose a consolidated-versus-separate discovery mode, +allow per-provider-model enablement, allow metadata overrides with +revert-to-upstream, and give operators an admin surface for all of it. + +Dependencies: no hard dependency. Interface on catalog provider-model facts and +the existing override/source-tag shape. Soft on dashboard presentation +conventions. Operational: none. + +Deliverable boundary: the v69 schema and triggers, the policy repository, the +snapshot service and its admission wiring, the enablement gate, the discovery +projection, the metadata overlay, the admin page and audit rows, and the +documentation that records the precedence. Selection order does not otherwise +change; rank, windows, and capacity remain absent. + +User or operator value: switch how models are advertised without editing files, +hide one model at one provider, correct metadata and revert it, and see every +change audited. No-row installs behave exactly as before, and the policy +survives restart. + +Exit conditions: + +- `/v1/models` lists canonical ids in consolidated mode and provider-qualified + ids in separate mode, with the response shape unchanged. +- A disabled provider-model pair is never selected for that model, and the + exclusion carries its own bounded reason code. +- A metadata override is visible with a source tag, and deleting the row + restores the upstream value. +- Policy snapshot failure returns a typed unavailable outcome rather than + silently ignoring a disable. +- Every mutation writes exactly one audit row; non-admin and CSRF failures write + none. +- Restart preserves rows; a fresh database and a v68 upgrade both migrate + cleanly; the checksum guard passes. +- An install with no policy rows produces the same routing decisions and + discovery output as the baseline. + +Deferred work: rank and active windows (M002); concurrency caps, queue, and +overflow (M003); named timezones; removal of the deprecated +`models.expose_mode` key; migrating TOML metadata overrides into the store. + +### Milestone 2 — Per-model ranks and active windows + +Class: capability + +Objective: Let operators rank providers per model with ties, and restrict a +provider or a provider's model to declared UTC active windows, both evaluated +from the immutable request snapshot. + +Dependencies: hard on M001 (store, snapshot, admin surface). Interface on the +eligibility gate ordering and the fairness scope key. Soft on M003 for +capacity-aware tier selection. + +Deliverable boundary: per-model rank policy with a single effective tier and a +documented tie rule; UTC window evaluation with an injected clock; next-open +diagnostics; admin editing for both. Capacity-aware tier selection remains +M003's; M002 rank ordering applies among eligible candidates only. + +User or operator value: preferred providers serve first, equal ranks share +load, and providers that are only available during certain hours stop receiving +requests outside them. + +Exit conditions: + +- A per-model rank overrides the provider-global priority for that model only, + and equal ranks share through the existing near-tie fairness band. +- Windows are evaluated once per request from the snapshot; outside them the + candidate is excluded with a bounded reason and the next opening instant. +- Day masks, midnight wrap, and multiple windows behave as specified; UTC only, + and a named timezone is rejected rather than silently misread. +- Rank and window changes are audited and take effect without a restart. + +Deferred work: capacity-aware tiering (M003); named timezones; per-account +windows; window-aware prewarming or scheduling. + +### Milestone 3 — Concurrency caps, bounded queue, and time-based overflow + +Class: capability + +Objective: Enforce per-provider and per-account concurrency caps with a bounded +queue, and overflow a request to another candidate after a configurable wait +budget, preferring the same rank before descending. + +Dependencies: hard on M001. Soft on M002. Interface on claim release semantics +(`rust/src/routing/claim.rs`) and the coordinator exclusion set +(`rust/src/coordinator/finite.rs`, `rust/src/coordinator/streaming/coordinator.rs`). +Operational on loopback evidence of hot-path cost. + +Deliverable boundary: the capacity registry, bounded per-key queues, the wait +budget and overflow behavior, cancellation on disconnect, queue metrics, and +admin editing. No cross-process coordination and no adaptive cap learning. + +User or operator value: a provider that only tolerates a few concurrent +requests is never overrun; excess requests wait briefly and then spill to backup +providers instead of failing or stalling indefinitely. + +Exit conditions: + +- Concurrent requests never exceed the configured cap for any provider or + account under a sustained loopback load. +- A queued request holds no selection claim and no selection lock, and + cancellation removes it without leaking a permit or a waiter. +- A request that exceeds the wait budget is excluded for that attempt and + re-selected, descending rank only after the same rank has no capacity. +- Queue depth is bounded; a full queue overflows immediately rather than + growing. +- Reload drains waiters under the caps they admitted with, and the + retirement-delay consequence of a long wait is documented and bounded. +- Metrics expose depth, wait distribution, and overflow counts per key; measured + hot-path overhead is recorded in the closure evidence. + +Deferred work: cross-process coordination, admission-level global queueing, +adaptive or learned caps, per-principal queue priorities beyond round robin. + +## 8. Cross-cutting requirements + +- **Storage and migration.** v69 is additive. The SQL file and the + `checksums.json` entry land together; `rust/build.rs` fails otherwise. Prior + migrations and their checksums are never edited. The `AGENTS.md` migration + range is updated when v69 lands. +- **Protocol and compatibility.** No response shape changes: only the id set + differs by mode. Every configuration key stays parseable, including + `models.expose_mode`, which becomes documented-but-inert. `routing.strategy` + keeps accepting only `quota_fair`. No public Rust API break; internal routing + types may gain fields. +- **Security and auth.** All mutations require an admin principal and CSRF, and + are rate-limited by the existing middleware. Policy rows, snapshots, + diagnostics, and audit rows carry no credentials, prompts, or raw bodies. +- **Concurrency and cancellation.** Snapshot capture is per request. Capacity is + acquired synchronously with the claim. Queue waits are cancellable and + observable. Reload swaps generations without transferring queue state. +- **Observability.** The policy revision, exposure mode, and per-key queue state + are exposed through existing status surfaces. New exclusion reasons are + bounded and secret-free. +- **Performance.** M001 adds one indexed revision read per request on the SQLite + gate; M003 adds a synchronous counter path. Both are measured against the + baseline and recorded; no permanent benchmark framework is added. +- **Documentation and ops.** `architecture/deep-dive-routing.md`, + `architecture/deep-dive-models.md`, `docs/live-config-rehash.md`, + `AGENTS.md`, `CHANGELOG.md`, and the dashboard navigation documentation are + updated in the milestone that changes them. + +## 9. Verification strategy + +Focused Rust targets per milestone, then the full serial matrix. The relevant +existing targets are `routing_domain`, `routing_claims`, `routing_fail_closed`, +`catalog_refresh`, `database_compatibility`, `build_manifest`, +`on_prem_admin_ui`, `gateway_audit`, and `dashboard_filters`. M003 adds +contention and cancellation coverage that synchronizes on an observable queue +boundary rather than fixed sleeps. Migration evidence covers an empty database +and a v68 upgrade. Restart evidence covers policy persistence. M003 closure +includes loopback load evidence for the cap and the queue. + +## 10. Risks and decision points + +- **Second authority.** A database overlay beside configuration can confuse + operators. Mitigation: documented precedence, source labels in the admin + surface, and a stop condition requiring an ADR if review classifies the + overlay as a competing configuration authority. +- **Retirement delay.** A queued request holds its generation lease, so a long + wait delays reload retirement. Mitigation: bounded wait budgets, documented + consequence, and a test that a waiter drains on reload. +- **Schema rigidity.** SQLite cannot widen a CHECK constraint without a table + rebuild. Mitigation: constrain only invariants that are certainly permanent; + keep timezone and capability fields loosely typed. +- **Orphan rows.** Removing a provider or model from configuration leaves policy + rows. Mitigation: tolerate and display them as orphaned; prune only through an + explicit operator action. +- **Rank as a pin.** Rank must not become an account pin or bypass health. + Mitigation: rank orders eligible candidates and nothing else; the selector + contract is unchanged. +- **Admin blast radius.** A mistyped cap can strangle traffic. Mitigation: + validation bounds, audit rows, an immediate revert path, and a visible queue + page. +- **SQLite gate pressure.** One extra read per request is measurable. + Mitigation: measure first; fold the revision read into an existing admission + call if it shows up. + +## 11. Completion definition + +M001, M002, and M003 are closed by their own closure records; the admin surface +exposes every control named in the objectives; the capacity layer has loopback +evidence; documentation records precedence, deprecation, and the retirement +consequence; and no invariant listed in section 2 has regressed. + +## 12. Milestone status + +| Milestone | Status | Implementation plan | Closure record | Blockers | +|---|---|---|---|---| +| 1 | implemented — closure evidence pending | [001](../implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md) | — | — | +| 2 | blocked | — | — | Hard: M001 closed | +| 3 | blocked | — | — | Hard: M001 closed | diff --git a/rust/assets/db/migrations/0069_routing_policy.sql b/rust/assets/db/migrations/0069_routing_policy.sql new file mode 100644 index 00000000..8e183117 --- /dev/null +++ b/rust/assets/db/migrations/0069_routing_policy.sql @@ -0,0 +1,85 @@ +-- Routing policy overlay (M001). +-- +-- Operator routing policy lives beside configuration, not inside it. A row is +-- an explicit override; absence means inherit the configuration baseline and +-- then the upstream catalog fact. The singleton revision makes an immutable +-- per-request snapshot cheap to validate: every mutating table bumps it. +-- +-- Deliberately no rank, window, or capacity columns: those milestones add +-- their own additive migrations once their semantics are settled. + +CREATE TABLE routing_policy_state ( + singleton INTEGER PRIMARY KEY CHECK (singleton = 1), + revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0), + exposure_mode TEXT NOT NULL DEFAULT 'consolidated' + CHECK (exposure_mode IN ('consolidated', 'separate')), + updated_by TEXT, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +INSERT INTO routing_policy_state(singleton) VALUES (1); + +CREATE TABLE provider_model_policy ( + provider_id TEXT NOT NULL CHECK (length(provider_id) BETWEEN 1 AND 128), + model_id TEXT NOT NULL CHECK (length(model_id) BETWEEN 1 AND 512), + enabled INTEGER NOT NULL DEFAULT 1 CHECK (enabled IN (0, 1)), + updated_by TEXT, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (provider_id, model_id) +) WITHOUT ROWID; + +CREATE TABLE model_metadata_override ( + id INTEGER PRIMARY KEY, + model_id TEXT NOT NULL CHECK (length(model_id) BETWEEN 1 AND 512), + provider_id TEXT CHECK (provider_id IS NULL OR length(provider_id) BETWEEN 1 AND 128), + display_name TEXT CHECK (display_name IS NULL OR length(display_name) BETWEEN 1 AND 256), + context_tokens INTEGER CHECK (context_tokens IS NULL OR context_tokens > 0), + input_tokens INTEGER CHECK (input_tokens IS NULL OR input_tokens > 0), + output_tokens INTEGER CHECK (output_tokens IS NULL OR output_tokens > 0), + updated_by TEXT, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +-- NULL provider_id is the global overlay; the coalesced key keeps one row per +-- (model, scope) pair without a partial-index special case. +CREATE UNIQUE INDEX model_metadata_override_scope + ON model_metadata_override(model_id, COALESCE(provider_id, '')); + +-- Policy audit is separate from user_admin_audit because a provider/model key +-- can exceed that table's 128-character target bound. +CREATE TABLE routing_policy_audit ( + id INTEGER PRIMARY KEY, + actor_id TEXT NOT NULL, + action TEXT NOT NULL CHECK (length(action) BETWEEN 1 AND 64), + target_kind TEXT NOT NULL CHECK (length(target_kind) BETWEEN 1 AND 32), + target_id TEXT NOT NULL CHECK (length(target_id) BETWEEN 1 AND 512), + detail TEXT, + created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP +); + +CREATE INDEX idx_routing_policy_audit_recent + ON routing_policy_audit(created_at DESC, id DESC); + +CREATE TRIGGER provider_model_policy_revision_insert +AFTER INSERT ON provider_model_policy +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; + +CREATE TRIGGER provider_model_policy_revision_update +AFTER UPDATE ON provider_model_policy +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; + +CREATE TRIGGER provider_model_policy_revision_delete +AFTER DELETE ON provider_model_policy +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; + +CREATE TRIGGER model_metadata_override_revision_insert +AFTER INSERT ON model_metadata_override +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; + +CREATE TRIGGER model_metadata_override_revision_update +AFTER UPDATE ON model_metadata_override +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; + +CREATE TRIGGER model_metadata_override_revision_delete +AFTER DELETE ON model_metadata_override +BEGIN UPDATE routing_policy_state SET revision = revision + 1 WHERE singleton = 1; END; diff --git a/rust/assets/db/migrations/checksums.json b/rust/assets/db/migrations/checksums.json index 6604283d..96ea5678 100644 --- a/rust/assets/db/migrations/checksums.json +++ b/rust/assets/db/migrations/checksums.json @@ -67,6 +67,7 @@ "0065_tool_grants.sql": "757ce7d6e89585bf6f83246b5e4935d29639e037cd0047efcffc0fc160082aff", "0066_personal_upstream.sql": "5f37ccad85c006e3e535322155d52a3bb75cc2fad649af54021c9905db742e4c", "0067_security_events.sql": "a7264a17790a2526655e23461cc075c3248e09e6d10d81d6ca30ba57dee4fe38", - "0068_security_events_legacy_key_rejection.sql": "08f20493e5c9a5c77e2288f5dd0abfdabd442ec40a3bd98c32611717141b726e" + "0068_security_events_legacy_key_rejection.sql": "08f20493e5c9a5c77e2288f5dd0abfdabd442ec40a3bd98c32611717141b726e", + "0069_routing_policy.sql": "7f27c02069225b9fb3e1964e789e1ce0b403f26d015f0ce99076c23ad42747ae" } } diff --git a/rust/assets/runtime-manifest.json b/rust/assets/runtime-manifest.json index f7a07583..7c0cb061 100644 --- a/rust/assets/runtime-manifest.json +++ b/rust/assets/runtime-manifest.json @@ -5,7 +5,7 @@ "path": "db/migrations/checksums.json", "category": "sqlite-migrations", "source": "rust/assets/db/migrations/checksums.json", - "sha256": "64a85a4f3623574ea801cbedae46fc335089af281429eddb70b7ffda2f49aeec", + "sha256": "4c7d88f624410ddc5d9e1cbcc716a1ce758c4699b54e361096082fff2edba2d0", "identity": "exact" }, { @@ -51,7 +51,7 @@ "identity": "exact" } ], - "schema_migration_count": 68, + "schema_migration_count": 69, "schema_change": true, "ownership": "Rust build/runtime embeds these assets; source paths are canonical repository inputs", "rollback": "restore the source tree from Git history" diff --git a/rust/src/coordinator/endpoints.rs b/rust/src/coordinator/endpoints.rs index a163c537..186f34be 100644 --- a/rust/src/coordinator/endpoints.rs +++ b/rust/src/coordinator/endpoints.rs @@ -143,6 +143,8 @@ pub enum EndpointError { Finalization, #[error("Internal effect application failed")] Internal, + #[error("Routing policy is unavailable")] + RoutingPolicyUnavailable, } impl From for EndpointError { @@ -202,7 +204,9 @@ impl EndpointError { Self::PrincipalChanged => StatusCode::UNAUTHORIZED, Self::ModelForbidden => StatusCode::FORBIDDEN, Self::BudgetExceeded | Self::BudgetNotEnforceable => StatusCode::TOO_MANY_REQUESTS, - Self::NoEligibleRoute | Self::Attempt => StatusCode::SERVICE_UNAVAILABLE, + Self::NoEligibleRoute | Self::Attempt | Self::RoutingPolicyUnavailable => { + StatusCode::SERVICE_UNAVAILABLE + } // The endpoint exists and is implemented, but no eligible provider // surface advertises the capability it needs. That is a missing // capability, not a temporarily unavailable route, so it carries @@ -361,6 +365,7 @@ pub struct InferenceState { router: RoutingRouter, catalog_service: Option>, model_policy: Option, + routing_policy: Option, } impl std::fmt::Debug for InferenceState { @@ -448,6 +453,33 @@ impl InferenceState { router, catalog_service, model_policy, + routing_policy: None, + } + } + + /// Attach the process-owned routing policy service. Production generation + /// construction always attaches it; embedded callers that omit it keep the + /// configuration baseline. + pub fn with_routing_policy( + mut self, + service: crate::routing_policy::RoutingPolicyService, + ) -> Self { + self.routing_policy = Some(service); + self + } + + /// Resolve the immutable policy snapshot for one request. + pub async fn routing_policy_snapshot( + &self, + ) -> Result, EndpointError> { + match self.routing_policy.as_ref() { + Some(service) => service + .snapshot() + .await + .map_err(|_| EndpointError::RoutingPolicyUnavailable), + None => Ok(Arc::new( + crate::routing_policy::RoutingPolicySnapshot::default(), + )), } } @@ -542,6 +574,60 @@ impl InferenceState { .collect() } + /// Discovery ids under the requested exposure projection. + /// + /// Consolidated mode keeps the canonical model ids; separate mode + /// advertises one qualified id per enabled provider-model pair plus the + /// virtual aliases, which are not provider-owned. + pub fn discovery_model_ids_with( + &self, + policy: &crate::routing_policy::RoutingPolicySnapshot, + ) -> Vec { + match policy.exposure_mode() { + crate::db::routing_policy::ExposureMode::Consolidated => self.discovery_model_ids(), + crate::db::routing_policy::ExposureMode::Separate => { + let mut models = self.qualified_model_ids(policy, None); + models.extend(self.registry.virtual_model_ids().map(str::to_owned)); + models.sort(); + models.dedup(); + models + } + } + } + + /// Authorized discovery ids under the requested exposure projection. + pub fn authorized_discovery_model_ids_with( + &self, + policy: &crate::routing_policy::RoutingPolicySnapshot, + snapshot: &crate::model_policy::ModelPolicySnapshot, + ) -> Vec { + match policy.exposure_mode() { + crate::db::routing_policy::ExposureMode::Consolidated => { + self.authorized_discovery_model_ids(snapshot) + } + crate::db::routing_policy::ExposureMode::Separate => { + let mut models = self.qualified_model_ids(policy, Some(snapshot)); + models.extend(self.authorized_virtual_model_ids(snapshot)); + models.sort(); + models.dedup(); + models + } + } + } + + fn qualified_model_ids( + &self, + policy: &crate::routing_policy::RoutingPolicySnapshot, + authorization: Option<&crate::model_policy::ModelPolicySnapshot>, + ) -> Vec { + qualified_model_ids( + policy, + &self.known_providers, + &self.router.catalog_snapshot().provider_model_keys, + authorization, + ) + } + pub fn max_body_bytes(&self) -> usize { self.max_body_bytes } @@ -1092,6 +1178,7 @@ pub(crate) async fn execute_embeddings_attributed( // positive output proof, so reserve one harmless token above the exact 0. routing_facts.budget_input_worst_case_tokens = input_bytes; routing_facts.budget_requested_output_tokens = Some(1); + routing_facts.routing_policy = Some(state.routing_policy_snapshot().await?); state .finite .execute_embedding_admitted( @@ -1166,6 +1253,7 @@ pub(crate) async fn execute_endpoint_attributed( } let mut routing_facts = admitted.routing_facts(state.routing_inputs(surface)); routing_facts.provider_id = resolved.provider_id.clone(); + routing_facts.routing_policy = Some(state.routing_policy_snapshot().await?); if stream { let request = StreamRequest::from_admitted( proxy_request_id, @@ -1607,7 +1695,39 @@ pub(crate) async fn build_inference_state_with_shared_and_accounts( Some(crate::model_policy::ModelPolicyService::new( database.clone(), )), - )) + ) + .with_routing_policy(crate::routing_policy::RoutingPolicyService::new( + database.clone(), + ))) +} + +/// Provider-qualified discovery ids. +/// +/// Pure so separate-mode projection is testable without a full generation: +/// unknown providers, disabled pairs, and unauthorized pairs are dropped, and +/// the id is always `model/provider` to match `parse_model_provider`. +fn qualified_model_ids( + policy: &crate::routing_policy::RoutingPolicySnapshot, + known_providers: &BTreeSet, + pairs: &[(String, String)], + authorization: Option<&crate::model_policy::ModelPolicySnapshot>, +) -> Vec { + let mut models = Vec::new(); + for (provider_id, model_id) in pairs { + if !known_providers.contains(provider_id) { + continue; + } + if !policy.model_enabled(provider_id, model_id) { + continue; + } + if let Some(authorization) = authorization + && !authorization.allows(model_id, Some(provider_id)) + { + continue; + } + models.push(format!("{model_id}/{provider_id}")); + } + models } /// Compile all immutable provider wire candidates before allocating the @@ -1729,3 +1849,65 @@ impl AffinityMetrics for crate::model_router::AffinityDecision { 0 } } +#[cfg(test)] +mod routing_policy_projection_tests { + use super::*; + use crate::db::routing_policy::{ExposureMode, ProviderModelPolicy, RoutingPolicyRows}; + use std::collections::BTreeMap; + + fn policy_rows(disabled: &[(&str, &str)]) -> RoutingPolicyRows { + let mut model_policy = BTreeMap::new(); + for (provider, model) in disabled { + model_policy.insert( + ((*provider).to_owned(), (*model).to_owned()), + ProviderModelPolicy { enabled: false }, + ); + } + RoutingPolicyRows { + revision: 7, + exposure_mode: ExposureMode::Separate, + model_policy, + metadata: BTreeMap::new(), + } + } + + #[test] + fn separate_projection_formats_qualified_ids_and_drops_disabled_pairs() { + let policy = crate::routing_policy::RoutingPolicySnapshot::from_rows(policy_rows(&[( + "provider-a", + "model-b", + )])); + let known = BTreeSet::from(["provider-a".to_owned(), "provider-b".to_owned()]); + let pairs = vec![ + ("provider-a".to_owned(), "model-a".to_owned()), + ("provider-a".to_owned(), "model-b".to_owned()), + ("provider-b".to_owned(), "model-a".to_owned()), + ("unknown".to_owned(), "model-a".to_owned()), + ]; + let ids = qualified_model_ids(&policy, &known, &pairs, None); + assert_eq!( + ids, + vec![ + "model-a/provider-a".to_owned(), + "model-a/provider-b".to_owned() + ], + "disabled and unknown-provider pairs are excluded" + ); + } + + #[test] + fn consolidated_rows_do_not_change_the_qualified_projection_helper() { + let policy = crate::routing_policy::RoutingPolicySnapshot::from_rows(RoutingPolicyRows { + revision: 1, + exposure_mode: ExposureMode::Consolidated, + ..RoutingPolicyRows::default() + }); + let known = BTreeSet::from(["provider-a".to_owned()]); + let pairs = vec![("provider-a".to_owned(), "model-a".to_owned())]; + assert_eq!( + qualified_model_ids(&policy, &known, &pairs, None), + vec!["model-a/provider-a".to_owned()], + "the helper is projection-only; mode selection happens in the caller" + ); + } +} diff --git a/rust/src/db/migrations.rs b/rust/src/db/migrations.rs index a53a39d6..61ead727 100644 --- a/rust/src/db/migrations.rs +++ b/rust/src/db/migrations.rs @@ -203,9 +203,9 @@ mod tests { #[test] fn canonical_inventory_is_complete_and_immutable() { MigrationRunner::validate_embedded_checksums().expect("canonical checksums match"); - assert_eq!(MigrationRunner::migrations().len(), 68); + assert_eq!(MigrationRunner::migrations().len(), 69); assert_eq!(MigrationRunner::migrations().first().unwrap().version, 1); - assert_eq!(MigrationRunner::migrations().last().unwrap().version, 68); + assert_eq!(MigrationRunner::migrations().last().unwrap().version, 69); } #[test] diff --git a/rust/src/db/mod.rs b/rust/src/db/mod.rs index 526650ef..09bacd2c 100644 --- a/rust/src/db/mod.rs +++ b/rust/src/db/mod.rs @@ -9,6 +9,7 @@ pub mod migrations; #[cfg(feature = "qualification-db-diagnostics")] mod qualification; pub mod repositories; +pub mod routing_policy; pub use connection::{ Database, DatabaseConfig, DatabaseError, DatabaseStats, DatabaseTransaction, diff --git a/rust/src/db/routing_policy.rs b/rust/src/db/routing_policy.rs new file mode 100644 index 00000000..639efe9c --- /dev/null +++ b/rust/src/db/routing_policy.rs @@ -0,0 +1,322 @@ +//! Durable operator routing policy rows. +//! +//! This module owns SQL only. Validation, snapshot immutability, and cache +//! freshness live in `crate::routing_policy`; the repository stays a thin set +//! of functions over one connection so a caller can compose a write and its +//! audit row in a single transaction. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; +use tokio_rusqlite::rusqlite::{self, params}; + +/// Exposure projection: canonical model names or provider-qualified names. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "snake_case")] +pub enum ExposureMode { + #[default] + Consolidated, + Separate, +} + +impl ExposureMode { + pub fn parse(value: &str) -> Option { + match value { + "consolidated" => Some(Self::Consolidated), + "separate" => Some(Self::Separate), + _ => None, + } + } + + pub const fn as_str(self) -> &'static str { + match self { + Self::Consolidated => "consolidated", + Self::Separate => "separate", + } + } +} + +/// One explicit per-provider-model decision. Absence of a row means inherit. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub struct ProviderModelPolicy { + pub enabled: bool, +} + +/// One metadata overlay. `None` fields inherit the configuration baseline and +/// then the upstream catalog fact. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)] +pub struct MetadataOverride { + pub display_name: Option, + pub context_tokens: Option, + pub input_tokens: Option, + pub output_tokens: Option, +} + +/// The complete durable policy, ordered deterministically. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct RoutingPolicyRows { + pub revision: i64, + pub exposure_mode: ExposureMode, + /// Keyed by (provider_id, model_id). + pub model_policy: BTreeMap<(String, String), ProviderModelPolicy>, + /// Keyed by (model_id, provider_id). A `None` provider is the global scope. + pub metadata: BTreeMap<(String, Option), MetadataOverride>, +} + +/// Read the monotonic policy revision. +pub fn read_revision(connection: &rusqlite::Connection) -> rusqlite::Result { + connection.query_row( + "SELECT revision FROM routing_policy_state WHERE singleton = 1", + [], + |row| row.get(0), + ) +} + +/// Load every policy row. The caller wraps this in one transaction so the +/// revision and the rows it describes cannot disagree. +pub fn load_rows(connection: &rusqlite::Connection) -> rusqlite::Result { + let (revision, mode) = connection.query_row( + "SELECT revision, exposure_mode FROM routing_policy_state WHERE singleton = 1", + [], + |row| Ok((row.get::<_, i64>(0)?, row.get::<_, String>(1)?)), + )?; + let exposure_mode = ExposureMode::parse(&mode).unwrap_or_default(); + let mut model_policy = BTreeMap::new(); + let mut statement = + connection.prepare("SELECT provider_id, model_id, enabled FROM provider_model_policy")?; + let rows = statement.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, String>(1)?, + row.get::<_, i64>(2)?, + )) + })?; + for row in rows { + let (provider_id, model_id, enabled) = row?; + model_policy.insert( + (provider_id, model_id), + ProviderModelPolicy { + enabled: enabled != 0, + }, + ); + } + let mut metadata = BTreeMap::new(); + let mut statement = connection.prepare( + "SELECT model_id, provider_id, display_name, context_tokens, input_tokens, output_tokens \ + FROM model_metadata_override", + )?; + let rows = statement.query_map([], |row| { + Ok(( + row.get::<_, String>(0)?, + row.get::<_, Option>(1)?, + MetadataOverride { + display_name: row.get(2)?, + context_tokens: row.get::<_, Option>(3)?.map(|value| value as u64), + input_tokens: row.get::<_, Option>(4)?.map(|value| value as u64), + output_tokens: row.get::<_, Option>(5)?.map(|value| value as u64), + }, + )) + })?; + for row in rows { + let (model_id, provider_id, override_row) = row?; + metadata.insert((model_id, provider_id), override_row); + } + Ok(RoutingPolicyRows { + revision, + exposure_mode, + model_policy, + metadata, + }) +} + +/// Set the exposure mode and advance the revision in one statement. +pub fn write_mode( + connection: &mut rusqlite::Connection, + mode: ExposureMode, + actor_id: &str, +) -> rusqlite::Result<()> { + connection.execute( + "UPDATE routing_policy_state \ + SET exposure_mode = ?1, revision = revision + 1, \ + updated_by = ?2, updated_at = CURRENT_TIMESTAMP \ + WHERE singleton = 1", + params![mode.as_str(), actor_id], + )?; + Ok(()) +} + +/// Insert or replace one per-provider-model decision. +pub fn upsert_model_policy( + connection: &mut rusqlite::Connection, + provider_id: &str, + model_id: &str, + enabled: bool, + actor_id: &str, +) -> rusqlite::Result { + connection.execute( + "INSERT INTO provider_model_policy(provider_id, model_id, enabled, updated_by) \ + VALUES (?1, ?2, ?3, ?4) \ + ON CONFLICT(provider_id, model_id) DO UPDATE SET \ + enabled = excluded.enabled, \ + updated_by = excluded.updated_by, \ + updated_at = CURRENT_TIMESTAMP", + params![provider_id, model_id, i64::from(enabled), actor_id], + )?; + Ok(true) +} + +/// Delete one decision. Returns whether a row existed. +pub fn delete_model_policy( + connection: &mut rusqlite::Connection, + provider_id: &str, + model_id: &str, +) -> rusqlite::Result { + let removed = connection.execute( + "DELETE FROM provider_model_policy WHERE provider_id = ?1 AND model_id = ?2", + params![provider_id, model_id], + )?; + Ok(removed == 1) +} + +/// Insert or replace one metadata overlay scope. +pub fn upsert_metadata( + connection: &mut rusqlite::Connection, + model_id: &str, + provider_id: Option<&str>, + overlay: &MetadataOverride, + actor_id: &str, +) -> rusqlite::Result<()> { + let updated = connection.execute( + "UPDATE model_metadata_override SET \ + display_name = ?3, context_tokens = ?4, input_tokens = ?5, \ + output_tokens = ?6, updated_by = ?7, updated_at = CURRENT_TIMESTAMP \ + WHERE model_id = ?1 AND provider_id IS ?2", + params![ + model_id, + provider_id, + overlay.display_name, + overlay.context_tokens.map(|value| value as i64), + overlay.input_tokens.map(|value| value as i64), + overlay.output_tokens.map(|value| value as i64), + actor_id, + ], + )?; + if updated == 1 { + return Ok(()); + } + connection.execute( + "INSERT INTO model_metadata_override( \ + model_id, provider_id, display_name, context_tokens, input_tokens, \ + output_tokens, updated_by) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)", + params![ + model_id, + provider_id, + overlay.display_name, + overlay.context_tokens.map(|value| value as i64), + overlay.input_tokens.map(|value| value as i64), + overlay.output_tokens.map(|value| value as i64), + actor_id, + ], + )?; + Ok(()) +} + +/// Delete one metadata scope. Returns whether a row existed. +pub fn delete_metadata( + connection: &mut rusqlite::Connection, + model_id: &str, + provider_id: Option<&str>, +) -> rusqlite::Result { + let removed = connection.execute( + "DELETE FROM model_metadata_override WHERE model_id = ?1 AND provider_id IS ?2", + params![model_id, provider_id], + )?; + Ok(removed == 1) +} + +/// Append one policy audit row. Callers run this in the mutation transaction. +pub fn insert_audit( + connection: &rusqlite::Connection, + actor_id: &str, + action: &str, + target_kind: &str, + target_id: &str, + detail: Option<&str>, +) -> rusqlite::Result<()> { + connection.execute( + "INSERT INTO routing_policy_audit(actor_id, action, target_kind, target_id, detail) \ + VALUES (?1, ?2, ?3, ?4, ?5)", + params![actor_id, action, target_kind, target_id, detail], + )?; + Ok(()) +} + +/// Read the newest policy audit rows for the admin page. +pub fn recent_audit( + connection: &rusqlite::Connection, + limit: i64, +) -> rusqlite::Result> { + let mut statement = connection.prepare( + "SELECT actor_id, action, target_kind, target_id, detail, created_at \ + FROM routing_policy_audit ORDER BY created_at DESC, id DESC LIMIT ?1", + )?; + let rows = statement.query_map([limit.max(0)], |row| { + Ok(RoutingPolicyAuditRow { + actor_id: row.get(0)?, + action: row.get(1)?, + target_kind: row.get(2)?, + target_id: row.get(3)?, + detail: row.get(4)?, + created_at: row.get(5)?, + }) + })?; + rows.collect() +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RoutingPolicyAuditRow { + pub actor_id: String, + pub action: String, + pub target_kind: String, + pub target_id: String, + pub detail: Option, + pub created_at: String, +} + +/// Validate a provider identifier against the schema bounds and emptiness. +pub fn validate_provider_id(value: &str) -> Result<&str, &'static str> { + let value = value.trim(); + if value.is_empty() || value.len() > 128 { + return Err("provider id must be between 1 and 128 bytes"); + } + Ok(value) +} + +/// Validate a model identifier against the schema bounds and emptiness. +pub fn validate_model_id(value: &str) -> Result<&str, &'static str> { + let value = value.trim(); + if value.is_empty() || value.len() > 512 { + return Err("model id must be between 1 and 512 bytes"); + } + Ok(value) +} + +/// Validate a display-name override. +pub fn validate_display_name(value: &str) -> Result<&str, &'static str> { + let value = value.trim(); + if value.is_empty() || value.len() > 256 { + return Err("display name must be between 1 and 256 bytes"); + } + Ok(value) +} + +/// Validate an optional token limit. +pub fn validate_limit(value: Option) -> Result, &'static str> { + match value { + None => Ok(None), + Some(0) => Err("token limits must be greater than zero"), + Some(value) if value > 100_000_000 => Err("token limits are bounded to 100000000"), + Some(value) => Ok(Some(value)), + } +} diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 0d37003c..2c675705 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -26,6 +26,7 @@ pub mod quota; pub mod reload; pub mod request; pub mod routing; +pub mod routing_policy; mod runtime; pub mod runtime_lifecycle; mod secret; diff --git a/rust/src/routing/eligibility.rs b/rust/src/routing/eligibility.rs index 414fc482..7fa96006 100644 --- a/rust/src/routing/eligibility.rs +++ b/rust/src/routing/eligibility.rs @@ -1,6 +1,6 @@ //! Stable, read-only routing eligibility gates. -use std::collections::BTreeMap; +use std::{collections::BTreeMap, sync::Arc}; use serde::Serialize; @@ -35,6 +35,12 @@ pub struct RoutingRequestFacts { /// Authenticated principal. Absent for a legacy shared key, which cannot /// select a personally bound account. pub principal_user_id: Option, + /// Immutable operator routing policy captured for this request. `None` + /// (embedded test callers) means no policy rows, which is the + /// configuration baseline; production admission always captures a + /// snapshot, and an unreadable store fails the request closed. + #[serde(skip)] + pub routing_policy: Option>, } /// The wall clock routing facts are stamped with. @@ -68,6 +74,7 @@ impl RoutingRequestFacts { capability_policy: BTreeMap::new(), now: 0, principal_user_id: None, + routing_policy: None, } } @@ -374,6 +381,15 @@ fn candidate_for_account( }); return None; } + // Operator policy: an explicit disable is checked before the more + // expensive catalog, quarantine, and freshness gates so the reported + // reason names the operator decision rather than a downstream symptom. + if let Some(policy) = facts.routing_policy.as_deref() + && !policy.model_enabled(&identity.provider_id, &facts.canonical_model_id) + { + exclude("model_disabled_for_provider"); + return None; + } if facts.request_surface != "chat_completions" && !identity .supported_request_surfaces diff --git a/rust/src/routing_policy.rs b/rust/src/routing_policy.rs new file mode 100644 index 00000000..492f557c --- /dev/null +++ b/rust/src/routing_policy.rs @@ -0,0 +1,404 @@ +//! Process-owned operator routing policy and its immutable request snapshot. +//! +//! The durable rows live in `crate::db::routing_policy`; this module owns the +//! validation, the snapshot shape routing consumes, and the freshness rule. +//! One service instance is shared across generations. `snapshot()` reads the +//! revision, returns a cached `Arc` when it matches, and otherwise rebuilds +//! the snapshot in one transaction. Nothing here runs inside the selection +//! lock: a request resolves its snapshot during admission and carries it as an +//! immutable value. + +use std::{ + collections::BTreeMap, + sync::{Arc, Mutex}, +}; + +use thiserror::Error; + +use crate::db::{ + Database, DatabaseError, + routing_policy::{self as repository, ExposureMode, MetadataOverride, RoutingPolicyRows}, +}; + +pub use crate::db::routing_policy::{ + MetadataOverride as ModelMetadataOverride, RoutingPolicyAuditRow, +}; + +/// Bounded policy failures. The unavailable variant is the fail-closed signal: +/// a configured disable must never be silently ignored because the store could +/// not be read. +#[derive(Debug, Error)] +pub enum RoutingPolicyError { + #[error("routing policy input is invalid: {0}")] + InvalidInput(&'static str), + #[error("routing policy is unavailable")] + Unavailable(#[from] DatabaseError), +} + +/// Immutable routing policy for one request. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct RoutingPolicySnapshot { + revision: i64, + exposure_mode: ExposureMode, + /// provider_id -> model_id -> enabled. + model_policy: BTreeMap>, + /// provider_id -> model_id -> overlay. + provider_metadata: BTreeMap>, + /// model_id -> overlay for the global scope. + global_metadata: BTreeMap, +} + +impl RoutingPolicySnapshot { + /// Build the immutable snapshot from durable rows. + pub fn from_rows(rows: RoutingPolicyRows) -> Self { + let mut model_policy: BTreeMap> = BTreeMap::new(); + for ((provider_id, model_id), policy) in rows.model_policy { + model_policy + .entry(provider_id) + .or_default() + .insert(model_id, policy.enabled); + } + let mut provider_metadata: BTreeMap> = + BTreeMap::new(); + let mut global_metadata: BTreeMap = BTreeMap::new(); + for ((model_id, provider_id), overlay) in rows.metadata { + match provider_id { + Some(provider_id) => { + provider_metadata + .entry(provider_id) + .or_default() + .insert(model_id, overlay); + } + None => { + global_metadata.insert(model_id, overlay); + } + } + } + Self { + revision: rows.revision, + exposure_mode: rows.exposure_mode, + model_policy, + provider_metadata, + global_metadata, + } + } + + pub fn revision(&self) -> i64 { + self.revision + } + + pub fn exposure_mode(&self) -> ExposureMode { + self.exposure_mode + } + + /// Whether the provider may serve the model. Absence means inherit, which + /// is why this defaults to `true` rather than failing closed. + pub fn model_enabled(&self, provider_id: &str, model_id: &str) -> bool { + self.model_policy + .get(provider_id) + .and_then(|models| models.get(model_id)) + .copied() + .unwrap_or(true) + } + + /// The effective metadata overlay: provider scope first, then global. + pub fn metadata_override( + &self, + model_id: &str, + provider_id: Option<&str>, + ) -> Option<&MetadataOverride> { + provider_id + .and_then(|provider_id| self.provider_metadata.get(provider_id)) + .and_then(|models| models.get(model_id)) + .or_else(|| self.global_metadata.get(model_id)) + } + + /// Every durable policy row, for the admin surface. + pub fn model_policy_rows(&self) -> Vec<(String, String, bool)> { + let mut rows = Vec::new(); + for (provider_id, models) in &self.model_policy { + for (model_id, enabled) in models { + rows.push((provider_id.clone(), model_id.clone(), *enabled)); + } + } + rows + } + + /// Every durable metadata overlay, for the admin surface. + pub fn metadata_rows(&self) -> Vec<(String, Option, MetadataOverride)> { + let mut rows = Vec::new(); + for (model_id, overlay) in &self.global_metadata { + rows.push((model_id.clone(), None, overlay.clone())); + } + for (provider_id, models) in &self.provider_metadata { + for (model_id, overlay) in models { + rows.push((model_id.clone(), Some(provider_id.clone()), overlay.clone())); + } + } + rows.sort_by(|left, right| left.0.cmp(&right.0).then_with(|| left.1.cmp(&right.1))); + rows + } +} + +/// Process-owned handle over the durable policy. +#[derive(Clone)] +pub struct RoutingPolicyService { + database: Database, + cache: Arc>>>, +} + +impl std::fmt::Debug for RoutingPolicyService { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let cached_revision = self + .cache + .lock() + .ok() + .and_then(|cache| cache.as_ref().map(|snapshot| snapshot.revision())); + formatter + .debug_struct("RoutingPolicyService") + .field("cached_revision", &cached_revision) + .finish() + } +} + +impl RoutingPolicyService { + pub fn new(database: Database) -> Self { + Self { + database, + cache: Arc::new(Mutex::new(None)), + } + } + + /// Return the current snapshot. One indexed revision read per call; the + /// rebuild happens only when the revision moved. + pub async fn snapshot(&self) -> Result, RoutingPolicyError> { + let revision = self + .database + .call(|connection| repository::read_revision(connection)) + .await?; + if let Ok(cache) = self.cache.lock() + && let Some(snapshot) = cache.as_ref() + && snapshot.revision() == revision + { + return Ok(Arc::clone(snapshot)); + } + let rows = self + .database + .with_transaction(|connection| repository::load_rows(connection)) + .await?; + let snapshot = Arc::new(RoutingPolicySnapshot::from_rows(rows)); + if let Ok(mut cache) = self.cache.lock() { + *cache = Some(Arc::clone(&snapshot)); + } + Ok(snapshot) + } + + pub async fn set_exposure_mode( + &self, + mode: ExposureMode, + actor_id: &str, + ) -> Result<(), RoutingPolicyError> { + let actor_id = validate_actor(actor_id)?.to_owned(); + self.database + .with_transaction(move |connection| { + repository::write_mode(connection, mode, &actor_id)?; + repository::insert_audit( + connection, + &actor_id, + "set_exposure_mode", + "mode", + "singleton", + Some(mode.as_str()), + )?; + Ok(()) + }) + .await?; + Ok(()) + } + + pub async fn set_model_policy( + &self, + provider_id: &str, + model_id: &str, + enabled: bool, + actor_id: &str, + ) -> Result<(), RoutingPolicyError> { + let provider_id = validate_provider_id(provider_id)?.to_owned(); + let model_id = validate_model_id(model_id)?.to_owned(); + let actor_id = validate_actor(actor_id)?.to_owned(); + self.database + .with_transaction(move |connection| { + repository::upsert_model_policy( + connection, + &provider_id, + &model_id, + enabled, + &actor_id, + )?; + repository::insert_audit( + connection, + &actor_id, + if enabled { + "enable_provider_model" + } else { + "disable_provider_model" + }, + "provider_model", + &model_id, + Some(&provider_id), + )?; + Ok(()) + }) + .await?; + Ok(()) + } + + pub async fn remove_model_policy( + &self, + provider_id: &str, + model_id: &str, + actor_id: &str, + ) -> Result { + let provider_id = validate_provider_id(provider_id)?.to_owned(); + let model_id = validate_model_id(model_id)?.to_owned(); + let actor_id = validate_actor(actor_id)?.to_owned(); + let removed = self + .database + .with_transaction(move |connection| { + let removed = repository::delete_model_policy(connection, &provider_id, &model_id)?; + if removed { + repository::insert_audit( + connection, + &actor_id, + "revert_provider_model", + "provider_model", + &model_id, + Some(&provider_id), + )?; + } + Ok(removed) + }) + .await?; + Ok(removed) + } + + #[allow(clippy::too_many_arguments)] + pub async fn set_metadata( + &self, + model_id: &str, + provider_id: Option<&str>, + overlay: &MetadataOverride, + actor_id: &str, + ) -> Result<(), RoutingPolicyError> { + let model_id = validate_model_id(model_id)?.to_owned(); + let provider_id = provider_id + .map(validate_provider_id) + .transpose()? + .map(str::to_owned); + let overlay = validate_metadata(overlay)?; + let actor_id = validate_actor(actor_id)?.to_owned(); + self.database + .with_transaction(move |connection| { + repository::upsert_metadata( + connection, + &model_id, + provider_id.as_deref(), + &overlay, + &actor_id, + )?; + repository::insert_audit( + connection, + &actor_id, + "set_model_metadata", + "metadata", + &model_id, + provider_id.as_deref(), + )?; + Ok(()) + }) + .await?; + Ok(()) + } + + pub async fn remove_metadata( + &self, + model_id: &str, + provider_id: Option<&str>, + actor_id: &str, + ) -> Result { + let model_id = validate_model_id(model_id)?.to_owned(); + let provider_id = provider_id + .map(validate_provider_id) + .transpose()? + .map(str::to_owned); + let actor_id = validate_actor(actor_id)?.to_owned(); + let removed = self + .database + .with_transaction(move |connection| { + let removed = + repository::delete_metadata(connection, &model_id, provider_id.as_deref())?; + if removed { + repository::insert_audit( + connection, + &actor_id, + "revert_model_metadata", + "metadata", + &model_id, + provider_id.as_deref(), + )?; + } + Ok(removed) + }) + .await?; + Ok(removed) + } + + pub async fn recent_audit( + &self, + limit: i64, + ) -> Result, RoutingPolicyError> { + let rows = self + .database + .call(move |connection| repository::recent_audit(connection, limit)) + .await?; + Ok(rows) + } +} + +fn validate_actor(actor_id: &str) -> Result<&str, RoutingPolicyError> { + let actor_id = actor_id.trim(); + if actor_id.is_empty() || actor_id.len() > 128 { + return Err(RoutingPolicyError::InvalidInput( + "actor id must be between 1 and 128 bytes", + )); + } + Ok(actor_id) +} + +fn validate_provider_id(value: &str) -> Result<&str, RoutingPolicyError> { + repository::validate_provider_id(value).map_err(RoutingPolicyError::InvalidInput) +} + +fn validate_model_id(value: &str) -> Result<&str, RoutingPolicyError> { + repository::validate_model_id(value).map_err(RoutingPolicyError::InvalidInput) +} + +fn validate_metadata(overlay: &MetadataOverride) -> Result { + let display_name = match overlay.display_name.as_deref() { + Some(value) => Some( + repository::validate_display_name(value) + .map_err(RoutingPolicyError::InvalidInput)? + .to_owned(), + ), + None => None, + }; + Ok(MetadataOverride { + display_name, + context_tokens: repository::validate_limit(overlay.context_tokens) + .map_err(RoutingPolicyError::InvalidInput)?, + input_tokens: repository::validate_limit(overlay.input_tokens) + .map_err(RoutingPolicyError::InvalidInput)?, + output_tokens: repository::validate_limit(overlay.output_tokens) + .map_err(RoutingPolicyError::InvalidInput)?, + }) +} diff --git a/rust/src/server/dashboard/admin.rs b/rust/src/server/dashboard/admin.rs index c57e60cc..bdc88faf 100644 --- a/rust/src/server/dashboard/admin.rs +++ b/rust/src/server/dashboard/admin.rs @@ -190,6 +190,45 @@ pub(in crate::server) struct MemberUpstreamRemoveForm { csrf: String, } +#[derive(Deserialize)] +pub(in crate::server) struct RoutingModeForm { + mode: String, + csrf: String, +} + +#[derive(Deserialize)] +pub(in crate::server) struct RoutingModelPolicyForm { + provider: String, + model: String, + enabled: Option, + csrf: String, +} + +#[derive(Deserialize)] +pub(in crate::server) struct RoutingModelPolicyRemoveForm { + provider: String, + model: String, + csrf: String, +} + +#[derive(Deserialize)] +pub(in crate::server) struct RoutingMetadataForm { + model: String, + provider: Option, + display_name: Option, + context_tokens: Option, + input_tokens: Option, + output_tokens: Option, + csrf: String, +} + +#[derive(Deserialize)] +pub(in crate::server) struct RoutingMetadataRemoveForm { + model: String, + provider: Option, + csrf: String, +} + fn csrf_valid( state: &AppState, session: &crate::web_session::Principal, @@ -365,6 +404,212 @@ pub(in crate::server) async fn users_page( ) } +pub(in crate::server) async fn routing_policy_page( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, +) -> Response { + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + let csrf = crate::web_session::csrf_cookie_value(&headers) + .filter(|token| crate::web_session::verify_csrf(&session, token)) + .unwrap_or_default(); + let service = crate::routing_policy::RoutingPolicyService::new(state.database.clone()); + let snapshot = match service.snapshot().await { + Ok(snapshot) => snapshot, + Err(_) => return degraded("routing policy unavailable"), + }; + let audit = match service.recent_audit(50).await { + Ok(audit) => audit, + Err(_) => return degraded("routing policy unavailable"), + }; + let lease = match state.runtime.acquire().await { + Ok(lease) => lease, + Err(_) => return degraded("runtime unavailable"), + }; + let mut catalog_pairs = lease + .generation() + .inference() + .router_handle() + .catalog_snapshot() + .provider_model_keys; + catalog_pairs.sort(); + catalog_pairs.dedup(); + let body = render_routing_policy( + snapshot.exposure_mode(), + &snapshot.model_policy_rows(), + &snapshot.metadata_rows(), + &catalog_pairs, + &audit, + &csrf, + ); + dashboard_page_with_body( + &state.server.dashboard_theme, + "Routing policy", + "routing-policy", + Some("24h".to_owned()), + None, + state.server.dashboard_refresh_interval_s, + body, + "", + ) +} + +pub(in crate::server) async fn set_routing_mode( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + Form(form): Form, +) -> Response { + if !csrf_valid(&state, &session, &headers, &form.csrf) { + return (StatusCode::FORBIDDEN, "Invalid request token.").into_response(); + } + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + let mode = match form.mode.as_str() { + "consolidated" => crate::db::routing_policy::ExposureMode::Consolidated, + "separate" => crate::db::routing_policy::ExposureMode::Separate, + _ => return bad_request("Invalid exposure mode."), + }; + match crate::routing_policy::RoutingPolicyService::new(state.database.clone()) + .set_exposure_mode(mode, &session.user_id) + .await + { + Ok(()) => mutation_redirect("/routing/policy"), + Err(error) => mutation_error(error, "Could not save the exposure mode."), + } +} + +pub(in crate::server) async fn set_routing_model_policy( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + Form(form): Form, +) -> Response { + if !csrf_valid(&state, &session, &headers, &form.csrf) { + return (StatusCode::FORBIDDEN, "Invalid request token.").into_response(); + } + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + let enabled = form.enabled.as_deref() == Some("1"); + match crate::routing_policy::RoutingPolicyService::new(state.database.clone()) + .set_model_policy(&form.provider, &form.model, enabled, &session.user_id) + .await + { + Ok(()) => mutation_redirect("/routing/policy"), + Err(error) => mutation_error(error, "Could not save the model decision."), + } +} + +pub(in crate::server) async fn remove_routing_model_policy( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + Form(form): Form, +) -> Response { + if !csrf_valid(&state, &session, &headers, &form.csrf) { + return (StatusCode::FORBIDDEN, "Invalid request token.").into_response(); + } + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + match crate::routing_policy::RoutingPolicyService::new(state.database.clone()) + .remove_model_policy(&form.provider, &form.model, &session.user_id) + .await + { + Ok(_) => mutation_redirect("/routing/policy"), + Err(error) => mutation_error(error, "Could not revert the model decision."), + } +} + +pub(in crate::server) async fn set_routing_metadata( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + Form(form): Form, +) -> Response { + if !csrf_valid(&state, &session, &headers, &form.csrf) { + return (StatusCode::FORBIDDEN, "Invalid request token.").into_response(); + } + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + let context_tokens = match parse_optional_token_limit(form.context_tokens.as_deref()) { + Ok(value) => value, + Err(message) => return bad_request(message), + }; + let input_tokens = match parse_optional_token_limit(form.input_tokens.as_deref()) { + Ok(value) => value, + Err(message) => return bad_request(message), + }; + let output_tokens = match parse_optional_token_limit(form.output_tokens.as_deref()) { + Ok(value) => value, + Err(message) => return bad_request(message), + }; + let overlay = crate::routing_policy::ModelMetadataOverride { + display_name: form + .display_name + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned), + context_tokens, + input_tokens, + output_tokens, + }; + let provider = form + .provider + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()); + match crate::routing_policy::RoutingPolicyService::new(state.database.clone()) + .set_metadata(&form.model, provider, &overlay, &session.user_id) + .await + { + Ok(()) => mutation_redirect("/routing/policy"), + Err(error) => mutation_error(error, "Could not save the model metadata."), + } +} + +pub(in crate::server) async fn remove_routing_metadata( + State(state): State, + Extension(session): Extension, + headers: HeaderMap, + Form(form): Form, +) -> Response { + if !csrf_valid(&state, &session, &headers, &form.csrf) { + return (StatusCode::FORBIDDEN, "Invalid request token.").into_response(); + } + if !admin_only(&session) { + return (StatusCode::FORBIDDEN, "Administrator access required.").into_response(); + } + let provider = form + .provider + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()); + match crate::routing_policy::RoutingPolicyService::new(state.database.clone()) + .remove_metadata(&form.model, provider, &session.user_id) + .await + { + Ok(_) => mutation_redirect("/routing/policy"), + Err(error) => mutation_error(error, "Could not revert the model metadata."), + } +} + +fn parse_optional_token_limit(value: Option<&str>) -> Result, &'static str> { + match value.map(str::trim).filter(|value| !value.is_empty()) { + None => Ok(None), + Some(value) => value + .parse::() + .map(Some) + .map_err(|_| "Token limits must be positive integers."), + } +} + pub(in crate::server) async fn profiles_page( State(state): State, Extension(session): Extension, diff --git a/rust/src/server/dashboard/mod.rs b/rust/src/server/dashboard/mod.rs index 830fb5f9..049f4925 100644 --- a/rust/src/server/dashboard/mod.rs +++ b/rust/src/server/dashboard/mod.rs @@ -131,7 +131,8 @@ use render::{ DASHBOARD_TABLE_OPEN, USAGE_ROW_CAP, UserAdminFacts, dashboard_page_with_body, dashboard_query_inputs, dashboard_standalone_page, member_standalone_page, render_dashboard_page_body, render_member_upstream, render_model_detail, render_my_usage, - render_overview, render_profiles_admin, render_usage_admin, render_users_admin, summary_json, + render_overview, render_profiles_admin, render_routing_policy, render_usage_admin, + render_users_admin, summary_json, }; #[cfg(test)] use render::{DASHBOARD_TABLE_OPEN_COMPACT, usage_truncation_notice}; @@ -148,10 +149,12 @@ pub(super) use admin::{ add_member_upstream, assign_user_profile, audit_export, audit_page, create_personal_token, create_profile, create_user, delete_profile, issue_admin_token, my_account_page, my_models_page, profiles_page, remove_instance_budget, remove_member_upstream, - remove_profile_rule, remove_upstream_account, remove_user_override, reset_user_password, - revoke_personal_token, revoke_user_tokens, set_default_member_profile, set_instance_budget, - set_profile_preference, set_profile_rule, set_upstream_default, set_upstream_grant, - set_user_budget, set_user_override, set_user_state, update_profile, usage_page, users_page, + remove_profile_rule, remove_routing_metadata, remove_routing_model_policy, + remove_upstream_account, remove_user_override, reset_user_password, revoke_personal_token, + revoke_user_tokens, routing_policy_page, set_default_member_profile, set_instance_budget, + set_profile_preference, set_profile_rule, set_routing_metadata, set_routing_mode, + set_routing_model_policy, set_upstream_default, set_upstream_grant, set_user_budget, + set_user_override, set_user_state, update_profile, usage_page, users_page, }; pub(super) use api::{ grouped_timeseries_api, stats_cache_observability, stats_cache_stability, diff --git a/rust/src/server/dashboard/render/layout.rs b/rust/src/server/dashboard/render/layout.rs index 7f6e0efa..1cfa2c4b 100644 --- a/rust/src/server/dashboard/render/layout.rs +++ b/rust/src/server/dashboard/render/layout.rs @@ -11,10 +11,11 @@ pub(in crate::server::dashboard) const DASHBOARD_TABLE_OPEN_COMPACT: &str = /// The shared navigation destinations. Operator pages render them, so an /// operator always has a route back to the overview. -const DASHBOARD_NAVIGATION: [(&str, &str, &str); 17] = [ +const DASHBOARD_NAVIGATION: [(&str, &str, &str); 18] = [ ("overview", "/", "Overview"), ("reliability", "/reliability", "Reliability"), ("routing", "/routing", "Routing"), + ("routing-policy", "/routing/policy", "Policy"), ("cache", "/cache", "Cache"), ("users", "/users", "Users"), ("profiles", "/profiles", "Profiles"), diff --git a/rust/src/server/dashboard/render/mod.rs b/rust/src/server/dashboard/render/mod.rs index e42ca529..e36d2b95 100644 --- a/rust/src/server/dashboard/render/mod.rs +++ b/rust/src/server/dashboard/render/mod.rs @@ -7,6 +7,7 @@ mod diagnostics; mod layout; mod models; mod overview; +mod routing_policy; mod runtime; mod telemetry; @@ -17,6 +18,7 @@ pub(super) use diagnostics::*; pub(super) use layout::*; pub(super) use models::*; pub(super) use overview::*; +pub(super) use routing_policy::*; pub(super) use runtime::*; pub(super) use telemetry::*; diff --git a/rust/src/server/dashboard/render/routing_policy.rs b/rust/src/server/dashboard/render/routing_policy.rs new file mode 100644 index 00000000..8630b556 --- /dev/null +++ b/rust/src/server/dashboard/render/routing_policy.rs @@ -0,0 +1,198 @@ +use super::*; + +use std::collections::BTreeSet; + +use crate::db::routing_policy::{ExposureMode, MetadataOverride, RoutingPolicyAuditRow}; + +/// Operator routing policy page. +/// +/// The page states the precedence rule once, then shows every stored override +/// beside its revert action. Upstream facts stay on the model and account +/// pages; this surface owns only what the operator explicitly changed. +pub(in crate::server::dashboard) fn render_routing_policy( + mode: ExposureMode, + model_policy: &[(String, String, bool)], + metadata: &[(String, Option, MetadataOverride)], + catalog_pairs: &[(String, String)], + audit: &[RoutingPolicyAuditRow], + csrf: &str, +) -> String { + let csrf = html_escape(csrf); + let selected = |value: ExposureMode| { + if value == mode { " selected" } else { "" } + }; + let mut providers = BTreeSet::new(); + let mut models = BTreeSet::new(); + for (provider_id, model_id) in catalog_pairs { + providers.insert(provider_id.as_str()); + models.insert(model_id.as_str()); + } + let provider_options = providers + .iter() + .map(|provider| format!("", html_escape(provider))) + .collect::(); + let model_options = models + .iter() + .map(|model| format!("", html_escape(model))) + .collect::(); + + let policy_rows = if model_policy.is_empty() { + "No provider-model overrides. Every pair inherits the catalog." + .to_owned() + } else { + model_policy + .iter() + .map(|(provider_id, model_id, enabled)| { + let state = if *enabled { "Enabled" } else { "Disabled" }; + format!( + "{}{}{state}\ +
\ + \ + \ + \ +
", + html_escape(provider_id), + html_escape(model_id), + html_escape(provider_id), + html_escape(model_id), + ) + }) + .collect::() + }; + + let metadata_rows = if metadata.is_empty() { + "No metadata overrides. Every model inherits its upstream facts." + .to_owned() + } else { + metadata + .iter() + .map(|(model_id, provider_id, overlay)| { + let scope = provider_id + .as_deref() + .map(html_escape) + .unwrap_or_else(|| "Global".to_owned()); + let provider_value = provider_id.clone().unwrap_or_default(); + let display = overlay + .display_name + .as_deref() + .map(html_escape) + .unwrap_or_else(|| "—".to_owned()); + let limit = |value: Option| { + value.map_or_else(|| "—".to_owned(), |value| value.to_string()) + }; + format!( + "{}{scope}{display}\ + {}{}\ +
\ + \ + \ + \ +
", + html_escape(model_id), + limit(overlay.context_tokens), + limit(overlay.output_tokens), + html_escape(model_id), + html_escape(&provider_value), + ) + }) + .collect::() + }; + + let audit_rows = if audit.is_empty() { + "No policy changes recorded.".to_owned() + } else { + audit + .iter() + .map(|row| { + format!( + "{}{}{}{}{}", + html_escape(&row.created_at), + html_escape(&row.actor_id), + html_escape(&row.action), + html_escape(&row.target_id), + row.detail.as_deref().map(html_escape).unwrap_or_default(), + ) + }) + .collect::() + }; + + format!( + "

Routing policy

\ +

Configuration remains the baseline and upstream facts remain the default. \ + A saved row is an explicit override; reverting deletes the row and restores what \ + it inherited. Policy changes apply to the next request and never rewrite history.

\ +
\ + \ + \ +
\ +

Provider model policy

\ +

A disabled pair is never selected for that model, whatever the catalog says.

\ +
\ + \ + \ + \ + \ +
\ + {provider_options}\ + {model_options}\ +
\ + {DASHBOARD_TABLE_OPEN}ProviderModelDecisionAction\ + {policy_rows}
\ +

Model metadata

\ +

Leave a field empty to inherit it. The provider scope wins over the global scope.

\ +
\ + \ + \ + \ + \ + \ + \ + \ +
\ +
\ + {DASHBOARD_TABLE_OPEN}ModelScopeDisplay name\ + ContextOutputAction\ + {metadata_rows}
\ +

Recent policy changes

\ +
\ + {DASHBOARD_TABLE_OPEN}UTC timeActorAction\ + TargetScope{audit_rows}
", + c1 = selected(ExposureMode::Consolidated), + c2 = selected(ExposureMode::Separate), + ) +} +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn policy_page_escapes_identifiers_and_offers_revert() { + let body = render_routing_policy( + ExposureMode::Separate, + &[("provider