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..c98ea3b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,30 @@ 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. + +### Fixed + +- **Routing policy now holds on every request path and in separate-mode + discovery.** Separate mode advertised no real provider-model pairs because + the discovery projection read the catalog's pair tuple in the wrong order; + the admin datalists were swapped the same way. The compact endpoint and the + selector's internal dispatch never captured the request snapshot, so a + configured disable did not apply to remote compaction and an unreadable + policy store did not fail them closed. The routing-policy metadata table now + shows the stored input-token override, the effective upstream limit, and its + source tag, and reports a row the catalog does not know as orphaned. + ## [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..31d7e881 100644 --- a/architecture/deep-dive-routing.md +++ b/architecture/deep-dive-routing.md @@ -42,6 +42,50 @@ 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. +Admission resolves the snapshot once per request and shares that `Arc` with the +selector's internal dispatch and the concrete routing facts, so a virtual-model +request cannot observe two different policies; the compact and embeddings +surfaces capture it on the same terms. An unreadable store fails every +inference surface 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. Only a refused mutation, or +a revert of a row that does not exist, writes nothing; saving an unchanged +value is an ordinary committed mutation, so it is audited and advances the +revision. The metadata table shows every stored field beside the effective +upstream value and the source tag that value came from, and reports a row the +catalog does not know as `orphaned` rather than inventing a fact. + ## 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/closure/routing-policy-capacity/001-status.md b/plans/closure/routing-policy-capacity/001-status.md new file mode 100644 index 00000000..59b3052d --- /dev/null +++ b/plans/closure/routing-policy-capacity/001-status.md @@ -0,0 +1,190 @@ +# Routing Policy and Capacity Milestone M001 — Closure Status + +Status: corrective pass required + +Corrective pass: `plans/closure/routing-policy-capacity/004-status.md` — an independent audit at baseline `69247df7` found that separate-mode discovery destructures the catalog pair as `(provider, model)` although the producer emits `(model, provider)`, so it lists no qualified ids; the compact path and the selector dispatch build routing facts without the snapshot; and the metadata page omits a stored input limit. Milestone 4 corrects these and closes the acceptance-evidence gaps named in section 10 and in the audit. Milestone 4 closes it. + +Source implementation plan: + +- `plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md` + +Source subsystem roadmap: + +- `plans/subsystems/routing-policy-capacity-roadmap.md#7-milestones` + +Repository baseline reviewed: `7f961dc1`. + +Implementation commits or pull requests: + +- `7f961dc1` — add the operator routing policy store and admin surface (31 files, local only; not pushed). + +## 1. Executive finding + +The M001 capability is implemented: migration v69 adds a durable operator +policy store, an immutable revision-checked snapshot is carried into every +request, disabled provider-model pairs are enforced in eligibility, discovery +projects a consolidated or provider-qualified mode, and an audited admin +surface can set, revert, and inspect every control. With no policy rows the +runtime behaves exactly as the baseline. + +The milestone is conditionally closed because three pieces of the plan's own +closure evidence were not obtained in this environment: an end-to-end HTTP +response check for the discovery modes, a process stop/start observation, and a +recorded measurement of the added per-request revision read. None is a known +defect; each is an explicit evidence gap with a named future check. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| Mode switch changes `/v1/models` ids and nothing else | `qualified_model_ids` unit tests; consolidated path unchanged by construction | partial | Projection is tested as a pure function; the HTTP response was not exercised end to end. | +| Disabled pair never selected; own reason code | `RoutingPolicySnapshot::model_enabled` tests; `model_disabled_for_provider` gate in `candidate_for_account` | partial | Snapshot behavior is tested; no candidate-level fixture asserts the exclusion reason. | +| Metadata override visible with source scope; revert restores upstream | `metadata_scope_prefers_provider_then_global_and_reverts`; renderer empty/escaping tests | pass | Provider scope wins, global scope is the fallback, delete restores inheritance, a no-op delete writes no audit. | +| Changes apply to the next request; policy survives a later start | `policy_persists_for_a_new_service_over_the_same_database` | partial | A fresh service over the same database observes rows; a process stop/start was not run. | +| Store failure fails closed | Typed `RoutingPolicyUnavailable` path in admission; `EndpointError` status 503 | not run | The error mapping compiles and is reviewed; no test opens an unreadable store. | +| One audit row per committed mutation; none for refusals | `mutations_advance_the_revision_and_are_audited`; no-op delete assertion | pass | CSRF and role refusal paths reuse the existing middleware, covered by the full suite. | +| Fresh database and v68 upgrade migrate; checksums match | `database_compatibility` 13 passed; deliberate checksum removal panic | pass | Guard panic named `canonical migration is absent from checksums.json: 0069_routing_policy.sql`; restored tree compiles. | +| No-row installs match the baseline | `empty_policy_is_the_configuration_baseline`; full suite green | pass | Consolidated mode, every pair enabled, no overrides. | +| Docs and censuses updated | docs validator; tooling suite | pass | Routing, models, rehash, `AGENTS.md`, overview, persistence roadmap, changelog. | + +## 3. Production implementation evidence + +- **Storage.** `rust/assets/db/migrations/0069_routing_policy.sql` adds + `routing_policy_state` (singleton, monotonic revision, exposure mode), + `provider_model_policy`, `model_metadata_override`, and + `routing_policy_audit`, with insert/update/delete triggers on both policy + tables. `checksums.json` and `runtime-manifest.json` were updated. +- **Repository.** `rust/src/db/routing_policy.rs` owns typed rows, load, mode + write, policy and metadata upserts/deletes, audit insert/read, and bounded + identifier/limit validation. +- **Snapshot.** `rust/src/routing_policy.rs` owns the process-wide + `RoutingPolicyService`: one indexed revision read, cached `Arc` on a match, + transactional rebuild otherwise, typed errors, secret-free `Debug`. +- **Request path.** `RoutingRequestFacts::routing_policy` carries the snapshot; + admission resolves it in `execute_endpoint_attributed` for both chat and + embeddings. The eligibility gate runs after credentials and provider match. +- **Discovery.** `discovery_model_ids_with` and + `authorized_discovery_model_ids_with` project the mode; separate mode emits + `model/provider` for enabled catalog pairs and keeps virtual aliases. +- **Operator surface.** `/routing/policy` plus five `/admin/routing/*` + mutations, admin-gated and CSRF-protected, with one audit row per committed + change. The path is registered in the browser-session, navigation, and auth + lists and in the dashboard navigation. +- **Deprecation.** `models.expose_mode` remains parseable and live-classified; + the stored mode decides. + +## 4. Verification executed + +### Commands run + +```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_policy -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --lib -- --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 build --manifest-path rust/Cargo.toml --locked --release +uv run python scripts/validate_release_docs.py +uv run pytest tests/tooling/ -q --tb=short +uv run pytest tests/tooling/test_plan_status_consistency.py -q --tb=short +``` + +### Results + +- Format, strict Clippy, no-default `check`, no-default Clippy: exit 0. +- Default serial suite: 96 targets, 1286 passed, 0 failed. +- No-default serial suite: 96 targets, 1287 passed, 0 failed. +- `routing_policy` target: 6 passed. +- Library tests: 271 passed at the point the projection and renderer tests were added. +- `database_compatibility`: 13 passed, including a fresh database and a v68 upgrade. +- `build_manifest`: 4 passed. +- Locked release build: pass, 47.87 s. +- Release docs validator: pass, 7 documents, published 0.8.3. +- Tooling suite: 267 passed, 1 skipped. +- Plan-status guard: 3 passed. +- Checksum guard: removing the v69 entry made `build.rs` panic with + `canonical migration is absent from checksums.json: 0069_routing_policy.sql`; + restoring the entry compiled clean. + +## 5. Invariant review + +- Deterministic, load-based selection: unchanged; policy ordering is + `BTreeMap`-based and the gate has no score input. +- Selector cannot pin an account: unchanged; enablement only removes candidates. +- No I/O inside the selection lock: the snapshot is resolved during admission + and read as a value inside selection. +- One snapshot per request: the value is captured into routing facts before + submission. +- Absence versus failure: absence inherits; an unreadable store maps to + `RoutingPolicyUnavailable` (503). +- Bounded, secret-free diagnostics: the new reason code is a constant string; + the snapshot `Debug` prints only the cached revision. +- Append-only migrations: prior files and checksums are untouched. +- Parseable configuration: `models.expose_mode` and `routing.strategy` keep + their schemas and validation. + +## 6. Failure and recovery review + +Mutations and their audit rows commit in one SQLite transaction; a failed +insert leaves no partial policy and does not advance the revision. Concurrent +writers serialize on the single database gate and the revision stays monotonic. +A no-op delete returns false and writes no audit row. A request keeps the +snapshot it admitted with, so a concurrent edit cannot change its decision. +The snapshot cache is only replaced after a complete rebuild, so a reader never +observes a partial snapshot. Queueing, cancellation, and generation retirement +are unchanged by this milestone. + +## 7. Migration and compatibility review + +v69 is additive and forward-only. A fresh database and a v68 upgrade both apply +it; rerunning is a no-op. There is no downgrade path; restoring a pre-v69 +backup is the rollback. `/v1/models` keeps its response shape and only the id +set differs by mode. No CLI, config-mutation, wire, or transport behavior moved. +Existing TOML `model_overrides` and `model_capabilities` remain the baseline +beneath the overlay. + +## 8. Security review + +Every mutation requires an admin principal and CSRF; the page is on the +browser-session path list and is refused to members by the existing +administrative gate. The audit table stores actor, action, target, and a +provider scope — no credentials, prompts, bodies, or cache keys. Inputs are +length- and range-bounded in the service and again by SQLite CHECK constraints. +The policy store holds no secret column. + +## 9. Documentation and operations + +Updated: `architecture/deep-dive-routing.md` (precedence, snapshot, gate, +fail-closed, modes), `architecture/deep-dive-models.md` (inert +`expose_mode`), `docs/live-config-rehash.md`, `architecture/overview.md` +(module and route censuses, migration range), `AGENTS.md` (module map, +migration range, policy convention), `plans/subsystems/persistence-roadmap.md` +(schema census), and `CHANGELOG.md`. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | Separate-mode discovery lists enabled catalog pairs; per-account catalog freshness is enforced only at selection | Discovery can advertise a pair whose account freshness would exclude it for a moment | Already recorded as an implementation deviation in the plan; revisit if operators expect freshness-filtered discovery. | +| low | No end-to-end HTTP check of `/v1/models` in either mode | A handler-wiring regression would not be caught by the current tests | Run a live server with one cataloged pair and assert both id sets. | +| low | No process stop/start observation | Restart behavior is inferred from a fresh service over the same database | Start, mutate, stop, start, and re-read the policy. | +| low | No recorded timing for the added revision read | The hot-path cost is unquantified | Measure the snapshot call against the baseline on loopback. | + +## 11. Roadmap disposition + +Conditionally closed with the three named evidence gaps above. M001's +implementation is complete and no corrective plan is required. M002 (ranks and +active windows) and M003 (caps, queue, overflow) remain blocked because their +implementation plans are not written; M001's hard dependency is satisfied. + +## 12. Registry updates + +Applied in the same commit: the subsystem row records M001 conditionally +closed; M001 moves from the active implementation table to recently closed with +this record and implementation `7f961dc1`; the roadmap milestone table links +this closure and keeps M002 and M003 blocked. diff --git a/plans/closure/routing-policy-capacity/004-status.md b/plans/closure/routing-policy-capacity/004-status.md new file mode 100644 index 00000000..b4ae61dd --- /dev/null +++ b/plans/closure/routing-policy-capacity/004-status.md @@ -0,0 +1,260 @@ +# Routing Policy and Capacity Milestone 4 — Closure Status + +Status: closed + +Source implementation plan: + +- `plans/implementation/routing-policy-capacity/004-policy-enforcement-and-projection-correction.md` + +Corrective pass over: + +- `plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md` +- `plans/closure/routing-policy-capacity/001-status.md` + +Source subsystem roadmap: + +- `plans/subsystems/routing-policy-capacity-roadmap.md` (Milestone 4) + +Repository baseline reviewed: `69247df781ca191e3d85e68bf1a832e2ac43b8b4` + +Implementation commits or pull requests: + +- None. The implementation is in the working tree on `main` at the baseline above; no commit was created. + +## 1. Executive finding + +M001's operator policy now holds on every request path and in both discovery +modes. The independent audit at `69247df7` found four defects and a set of +acceptance items that were claimed but never executed; this pass fixed all four +and made each missing item an executable guard. + +The two high-severity defects were: + +- the separate-mode discovery projection destructured the catalog pair as + `(provider_id, model_id)` while the producer emits `(model_id, provider_id)`, + so every real pair was dropped and separate mode returned only virtual + aliases. The admin datalists were swapped the same way; +- the compact endpoint and the selector's internal dispatch built routing facts + with no policy snapshot, so a configured disable did not apply to remote + compaction and an unreadable store did not fail them closed. + +Both are now corrected and guarded by tests that were shown failing on the +pre-correction code. The metadata page renders every stored field beside the +effective upstream value and its source tag, the deep-dive sentence that +overstated no-op audit behavior is corrected, and every acceptance item in the +source plan has a test or a recorded command. + +## 2. Requirement-to-evidence matrix + +| Requirement | Evidence | Result | Notes | +|---|---|---|---| +| A — separate mode lists `model/provider` per enabled pair | `rust/src/coordinator/endpoints.rs` `qualified_model_ids`; `separate_projection_formats_qualified_ids_and_drops_disabled_pairs`; e2e `separate ids: ['demo-model/demo']` | pass | Fixture is fed by `ModelCatalogCache::snapshot().provider_model_keys`, not hand-written | +| A — unknown provider and disabled pair dropped | same test plus `separate_projection_drops_pairs_whose_provider_is_unknown`; e2e `separate ids after disable: []` | pass | | +| A — admin datalists hold the right identifiers | `datalists_hold_provider_ids_and_model_ids_not_the_swapped_order` | pass | Renderer now destructures the producer order | +| A — regression fails on a deliberate swap | swapped destructure made both projection tests fail with `left: []`; restored to pass | pass | Recorded in section 4 | +| B — chat/streaming honour the disable | `chat_refuses_a_disabled_pair_before_submission`, `streaming_refuses_a_disabled_pair_before_submission` | pass | Upstream submission count unchanged | +| B — compact honours the disable | `compact_refuses_a_disabled_pair_before_submission`; e2e `chat status for a disabled pair: 503` | pass | Removing the capture made compact return 200 from the upstream | +| B — embeddings honour the disable | `a_disabled_embedding_pair_is_refused_before_provider_submission` | pass | HTTP surface, 503, no provider submission | +| B — selector refuses a disabled pin | `the_selector_refuses_a_disabled_pin_without_dispatching` | pass | Pre-correction behaviour returns `Selector` and dispatches | +| B — unreadable store fails every surface closed | `an_unreadable_store_fails_every_surface_closed`, embeddings HTTP case, `an_unmigrated_database_reports_unavailable_and_maps_to_503` | pass | 503 typed, no submission | +| B — one snapshot per request shared with the selector | tooling guard `test_admission_resolves_one_snapshot_per_inference_surface`; `with_routing_policy(Arc::clone(routing_policy))` | pass | Three resolutions, three facts assignments | +| C — stored input-token override renders | `metadata_row_renders_every_stored_field_with_its_upstream_source` | pass | Input column added | +| C — effective value and source tag per field | same test: `128000 (upstream_metadata)`, `16000 (static_config)` | pass | Reaches `get_effective_limits` through `RoutingRouter::effective_model_limits` | +| C — orphaned row says so | `orphaned_metadata_row_says_orphaned_instead_of_inventing_a_value` | pass | | +| C — display-only row still shows inherited limits | `display_only_row_still_shows_the_inherited_limits_and_sources` | pass | | +| D — audit documentation matches the code | `architecture/deep-dive-routing.md`; `uv run python scripts/validate_release_docs.py` | pass | Refused mutation or absent-row revert writes nothing; a repeated save is audited and advances the revision | +| E — triggers on insert/update/delete for both tables | `triggers_advance_the_revision_on_insert_update_and_delete` | pass | Includes an unchanged-value update bumping exactly once | +| E — failed audit rolls the mutation back | `a_failed_audit_rolls_back_the_policy_row_and_the_revision` | pass | Oversized action violates the audit CHECK | +| E — repeated snapshot returns the same `Arc` | `repeated_snapshot_without_a_mutation_returns_the_same_arc` | pass | A mutation publishes a new `Arc` | +| E — typed failure and 503 mapping | `an_unmigrated_database_reports_unavailable_and_maps_to_503` | pass | | +| E — secret-free `Debug` | `debug_names_the_cached_revision_and_no_policy_content` | pass | No display name, actor, model, or provider | +| E — concurrent readers see one complete snapshot | `concurrent_readers_observe_one_complete_snapshot` | pass | Two cold readers race a rebuild | +| E — selection-boundary guard | `tests/tooling/test_routing_selection_boundary.py` | pass | Shown failing on a deliberate `RoutingPolicyService` reference | +| E — candidate-level reason code | `an_operator_disable_excludes_the_pair_with_its_own_reason_code` | pass | `model_disabled_for_provider`; absence inherits | +| E — admin refusals for all five mutation classes | `routing_policy_mutations_refuse_a_bad_token_and_a_non_admin_principal` | pass | Forged, missing, and non-admin attempts all 403 with no write | +| F — discovery end to end, both modes | e2e run: `['demo-model']` then `['demo-model/demo']` | pass | Real binary, isolated HOME, audited admin mutations | +| F — restart | e2e: stop, start, `after restart separate ids: []`, chat 503 | pass | Stored policy re-read from SQLite | +| F — revision-read timing | warm singleton read 1.5 us over 2000 reads; `GET /v1/models` p50 0.4 ms / p95 0.5 ms over 200 loopback requests | pass | Method in section 4 | +| Documentation and changelog | `architecture/deep-dive-routing.md`, `CHANGELOG.md` | pass | Docs validator green | + +## 3. Production implementation evidence + +- **Discovery projection.** `qualified_model_ids` destructures `(model_id, + provider_id)` in the producer's order and keeps the known-provider and + enablement filters. `render_routing_policy` reads the same order, so the + provider datalist holds provider ids and the model datalist holds model ids. +- **One snapshot per request.** `execute_endpoint_attributed`, + `execute_compact_finite_attributed`, and `execute_embeddings_attributed` each + resolve the snapshot once, before virtual resolution, and attach that `Arc` + to their routing facts. `resolve_concrete` and `resolve_virtual` take it as a + parameter, and `SemanticSelector::with_routing_policy` carries it into the + internal dispatch, which also sets the same snapshot on its own routing + facts and refuses a provider pin the snapshot disables. +- **Metadata page.** `RoutingRouter::effective_model_limits` is a read-only + accessor over the existing `ModelCatalogCache::get_effective_limits` + projection; the page renders the stored value beside the effective value and + its `context_source`/`input_source`/`output_source` tag, and reports a row + the catalog does not know as `orphaned`. +- **Documentation.** The deep dive states the two-guard enforcement, the + one-snapshot rule, and the corrected audit rule. +- No migration, configuration key, wire codec, or CLI command changed. + +## 4. Verification executed + +### Commands run + +```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_policy -- --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 on_prem_admin_ui -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test gateway_audit -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test routing_policy_enforcement -- --test-threads=1 +cargo test --manifest-path rust/Cargo.toml --test embeddings_api -- --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 +``` + +### Results + +All commands above passed locally on macOS arm64 (darwin 25.6.0). The full +workspace suite produced 194 `test result:` lines with zero failures in the +default and the `--no-default-features` pass; the chained run ended with +`MATRIX_OK`. Focused targets: `routing_policy` 12, `routing_domain` 16, +`routing_fail_closed` 6, `catalog_refresh` 7, `on_prem_admin_ui` 15, +`gateway_audit` 2, `routing_policy_enforcement` 5, `embeddings_api` 4 passed with +1 ignored (the live-Ollama qualification test). Tooling: 270 passed, 1 skipped. +Release docs validator: pass. + +### Deliberate perturbations + +| Guard | Perturbation | Observed | Restored | +|---|---|---|---| +| Pair-order projection | destructure swapped to `(provider_id, model_id)` | both projection tests failed, `left: []` against `right: ["model-a/provider-a", "model-a/provider-b"]` | pass | +| Compact capture | `routing_facts.routing_policy` assignment removed from the compact path | compact returned 200 and the upstream body, so the test failed | pass | +| Selector snapshot | pin refusal and internal facts snapshot both reverted | `left: Selector, right: Default`; the selector dispatched to the disabled pin | pass | +| Selection boundary | `RoutingPolicyService` inserted into `rust/src/routing/eligibility.rs` | guard failed naming the file and the reference | 3 passed | + +### End-to-end discovery and restart + +Real release binary, isolated `HOME` and config, one cataloged pair, audited +admin mutations over the browser session: + +```text +consolidated ids: ['demo-model'] +mode=separate status: 303 +separate ids: ['demo-model/demo'] +disable pair status: 303 +separate ids after disable: [] +chat status for a disabled pair: 503 +after restart separate ids: [] +after restart chat status: 503 +re-enable status: 303 +separate ids after re-enable: ['demo-model/demo'] +mode=consolidated status: 303 +consolidated ids after restore: ['demo-model'] +``` + +### Timing + +Method: `python3 sqlite3` loop against the server's own database for the +singleton revision read, then 200 sequential loopback `GET /v1/models` through +`curl` with p50/p95 from the sorted samples. Local, not CI. + +```text +warm revision read: 1.5 us over 2000 reads (sqlite3, local) +GET /v1/models loopback: p50=0.4 ms p95=0.5 ms over 200 requests (local) +``` + +The revision read is the whole per-request snapshot cost when the revision is +unchanged. Chat, streaming, and embeddings already resolved one snapshot per +request before this pass, so the correction adds a read only to compact, which +previously resolved none. No ranking, wire, or selection-lock work was added. + +## 5. Invariant review + +- **Deterministic, load-based selection.** No scoring, ordering, or fairness + input changed; the disable is an exclusion, not a rank. +- **Selector cannot pin an account.** The selector still emits a concrete model + only; the policy refusal narrows what it may dispatch, never widens it. +- **Selection lock has no I/O.** Unchanged: the snapshot is resolved during + admission and the guard pins the boundary. +- **One immutable snapshot per request.** Enforced by the shared `Arc` and + guarded structurally; a mutation during a request changes the next request. +- **Absence versus failure.** Absent rows inherit; an unreadable store returns + `RoutingPolicyUnavailable` on every surface. +- **Bounded, secret-free reason codes.** `model_disabled_for_provider` is + unchanged and asserted at the candidate level. +- **Migrations append-only.** No migration or checksum changed; v69 remains the + latest. +- **Configuration stays parseable.** `models.expose_mode` remains inert and + `routing.strategy` remains `quota_fair`-only. +- **`/v1/models` shape unchanged.** Only the id set differs by mode, confirmed + by the e2e run. + +## 6. Failure and recovery review + +- A store failure is mapped before selection on chat, streaming, compact, and + embeddings; no surface routes with an empty policy. +- A refused selector pin follows the existing bounded fallback; the parent + request still receives a typed decision. +- Mutations are one transaction: the rollback test proves a failed audit leaves + no policy row and no revision bump. +- Restart re-reads rows from SQLite and rebuilds on the first request; the e2e + run shows a disable surviving stop/start. +- Cancellation, generation retirement, and queue semantics are untouched by + this pass. + +## 7. Migration and compatibility review + +No schema change; v69 SQL, checksum, and manifest entries are untouched. +`RoutingRequestFacts`, `FiniteRequest`, and `CompactAdmittedRequest` keep their +shapes; the snapshot capture is internal. The admin routes, CSRF contract, and +admin gate are unchanged, and the page only gained columns. Rollback is a +revert of the corrective change set. + +## 8. Security review + +- Every mutation class rejects a forged token, a missing token, and a non-admin + principal before any write, with no audit row produced. +- `RoutingPolicyService::Debug` names only the cached revision. +- Failure bodies are the existing typed envelopes and disclose no provider, + account, or credential facts. +- The metadata page escapes every identifier it renders, including the source + tags and the stored display name. + +## 9. Documentation and operations + +`architecture/deep-dive-routing.md` now states the two-guard enforcement, the +one-snapshot-per-request rule, the metadata page's effective-value rendering, +and the actual audit rule. `CHANGELOG.md` carries the operator-facing +correction. `tests/tooling/test_routing_selection_boundary.py` is the durable +guard against selection regaining a policy or database handle. + +## 10. Unresolved findings + +| Severity | Finding | Impact | Required action | +|---|---|---|---| +| low | The selector pin refusal and the facts-level policy are deliberately redundant, so removing only the pin check is not observable from a test | none; both refuse before a provider call, and the combined revert fails the guard | none | +| low | CI has not run this change set; all evidence is local | none for correctness; the repository pipeline is the remaining external check | run CI on the commit | +| low | The live-Ollama embeddings qualification test remains `#[ignore]`d as before this pass | none; it is an optional live qualification | unchanged | + +## 11. Roadmap disposition + +Milestone 4 is closed. M001 is closed through this milestone, and the M002 and +M003 dependencies on it are satisfied; both still need an implementation plan +before they can be dependency-ready. + +## 12. Registry updates + +Applied in the same change set: the subsystem row, the recently-closed table, +and the blocked rows in `plans/registry.md`, plus the roadmap status table and +the pointer in `plans/closure/routing-policy-capacity/001-status.md`. 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/implementation/routing-policy-capacity/004-policy-enforcement-and-projection-correction.md b/plans/implementation/routing-policy-capacity/004-policy-enforcement-and-projection-correction.md new file mode 100644 index 00000000..a1f26a25 --- /dev/null +++ b/plans/implementation/routing-policy-capacity/004-policy-enforcement-and-projection-correction.md @@ -0,0 +1,460 @@ +# Routing Policy and Capacity Milestone 4 — Policy enforcement and discovery projection correction + +Status: implemented + +Repository baseline: `69247df781ca191e3d85e68bf1a832e2ac43b8b4` + +Corrective pass over: + +- `plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md` +- `plans/closure/routing-policy-capacity/001-status.md` + +Source roadmap: + +- `plans/subsystems/routing-policy-capacity-roadmap.md#7-milestones` (Milestone 4) + +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. This pass restores behavior that the M001 plan already specified. It changes no reload classification, authentication semantics, generation or lease ownership, wire behavior, or public protocol. + +Primary class: capability + +## 1. Objective + +Make M001's operator policy actually hold on every request path and in both +discovery modes: correct the catalog pair order that empties separate-mode +discovery, capture one policy snapshot per request on the compact and selector +dispatch paths, complete the metadata page, and land the acceptance evidence +M001 claimed but never executed. + +## 2. Why this milestone is ready + +No hard dependency. M001 landed the v69 store, the revision snapshot, the +enablement gate, the discovery projection, and the audited admin surface; the +corrective edits those surfaces. The interface dependencies are unchanged: +`RoutingRequestFacts`, `ModelCatalogCache::provider_model_key_pairs`, +`RoutingRouter::catalog_snapshot`, and the dashboard CSRF/admin helpers. + +An independent audit at baseline `69247df7` found four defects and a set of +missing acceptance items. This milestone is the corrective pass for that audit; +it adds no policy capability and no schema. + +### Why M001 verification missed these + +- The projection test built its fixture in the order the helper assumed + `(provider_id, model_id)`, while the producer + `ModelCatalogCache::provider_model_key_pairs` emits `(model_id, provider_id)`. + Producer and consumer were never exercised together, so the test asserted the + inversion and passed. +- The snapshot and the eligibility gate were tested separately. No test + enumerated the production sites that construct `RoutingRequestFacts`, so the + compact path and the selector dispatch, which build facts outside the two + edited sites, were invisible to the suite. +- The renderer tests asserted escaping and the empty state, not that every + stored field renders. The closure matrix also reworded the plan's "source + tag" criterion as "source scope", so the missing tag was not visible as a + miss. +- The WP C acceptance items were inferred from reading the implementation + rather than executed, and the conditional closure named only three gaps. + +## 3. Current implementation evidence + +- **Pair order.** `rust/src/catalog/cache.rs:849` builds + `provider_model_keys` as `(model_id, provider_id)`; the pre-existing consumer + `rust/src/operations/status.rs:914-917` destructures that order. + `rust/src/coordinator/endpoints.rs:1716-1728` destructures + `(provider_id, model_id)` and tests `known_providers.contains(provider_id)`, + so every real pair is dropped and separate mode returns only virtual aliases. + `rust/src/server/dashboard/admin.rs:431-436` feeds the same field into + `rust/src/server/dashboard/render/routing_policy.rs:26`, which swaps the + provider and model datalists. The unit test at + `rust/src/coordinator/endpoints.rs:1869-1898` encodes the swapped order. +- **Snapshot capture.** `rust/src/coordinator/endpoints.rs:1387` builds compact + routing facts and sets only `provider_id`; the gate in + `rust/src/routing/eligibility.rs:386-391` applies + `model_disabled_for_provider` only when `routing_policy` is `Some`. + `rust/src/coordinator/semantic.rs:721-729` builds the selector dispatch facts + the same way, and `SemanticSelector::new` at + `rust/src/coordinator/endpoints.rs:954` runs before the concrete facts are + built at `rust/src/coordinator/endpoints.rs:1256`. Chat and streaming already + capture the snapshot; their paths do not need rework. +- **Metadata page.** The form accepts `input_tokens` + (`rust/src/server/dashboard/admin.rs:215-226`), the row stores it, but the + table prints only context and output + (`rust/src/server/dashboard/render/routing_policy.rs:92-93`) under a header + with no Input column (`:158`). The page also shows no upstream fact or + source tag; `ModelCatalogCache::get_effective_limits` + (`rust/src/catalog/cache.rs:970`) already returns per-field + `context_source`, `input_source`, and `output_source` tags but has no + consumer. +- **Documentation.** `architecture/deep-dive-routing.md:79-80` states that a + no-op mutation writes no audit row. `set_exposure_mode` + (`rust/src/routing_policy.rs:196`) and `set_model_policy` (`:219`) audit + every save and advance the revision, including an unchanged value; only a + delete of an absent row writes nothing. +- **Acceptance evidence.** `rust/tests/routing_policy.rs:181-205` observes a + single direct INSERT on `provider_model_policy`. No test observes an UPDATE + or DELETE trigger on either policy table, a failed-audit rollback, a repeated + `snapshot()` returning the same `Arc`, a typed read failure, a concurrent + reader, or a secret-free `Debug`. The original plan's WP D also required an + invariant that the selection critical section performs no I/O; no such guard + exists. + +## 4. Invariants that must not regress + +- Selection stays deterministic and load based; policy never introduces price + into ranking and never becomes a second ranking authority. +- The semantic selector still cannot pin an account or bypass health, + quarantine, quota, or capacity. +- `RoutingRouter::selection_lock` remains the atomic synchronous boundary; the + snapshot carries no await and no store access into it. +- One immutable snapshot per request. A mutation during an in-flight request + does not change that request's decisions, and a request that runs the + selector does not resolve a second, different snapshot for its concrete + dispatch. +- Policy absence and policy failure stay distinct: absent rows inherit, and an + unreadable snapshot fails closed with `RoutingPolicyUnavailable` on every + inference surface. +- Exclusion reason codes stay bounded, ordered, and secret-free. +- Migrations stay append-only. This pass adds no migration and changes no + checksum. +- Every configuration key stays parseable; `models.expose_mode` stays inert. +- The `/v1/models` response shape is unchanged; only the id set differs by + mode. + +## 5. Scope + +### In scope + +- Correct the pair destructure in the discovery projection and the admin + datalists, with a regression test fed by the producer's order. +- Capture one policy snapshot per request and share it between the selector + dispatch and the concrete routing facts; add the compact capture; keep the + fail-closed mapping. +- Render the stored input-token override, and render each stored override + beside the effective upstream value and its source tag. +- Narrow the deep-dive sentence that overstates no-op audit behavior. +- Add the missing acceptance tests and guards named in section 7. +- Record the discovery end-to-end, restart, and revision-read timing evidence + the M001 closure named as outstanding. + +### Explicitly out of scope + +- Per-model ranks and active windows (roadmap Milestone 2). +- Concurrency caps, queue, and overflow (roadmap Milestone 3). +- Projecting per-account catalog freshness into separate-mode discovery. The + M001 plan records this as an implementation deviation; this pass does not + reopen it. +- Filtering consolidated-mode discovery by enablement. The M001 plan specifies + consolidated ids "as today"; this pass does not change that contract. +- Any schema or migration change; v69 is already applied. +- Skipping audit rows for identical-value saves. The deep-dive sentence is + corrected instead; every committed save stays audited once. +- Removing `models.expose_mode` or any configuration key. +- Changing the selector protocol, fingerprint, affinity cache, quota, health, + backoff, transport, or wire behavior. +- A policy poller task or a per-request database write. + +## 6. Required production changes + +- **Discovery projection.** `rust/src/coordinator/endpoints.rs`: destructure + the catalog pair as `(model_id, provider_id)` in `qualified_model_ids` and + keep `known_providers.contains(provider_id)`. Do not introduce a new pair + type; the producer's tuple order is the contract. +- **Admin datalists.** `rust/src/server/dashboard/admin.rs` and + `rust/src/server/dashboard/render/routing_policy.rs`: use the same + `(model_id, provider_id)` order so the provider datalist contains provider + ids and the model datalist contains model ids. +- **Snapshot capture.** `rust/src/coordinator/endpoints.rs`: resolve the + snapshot once per request at the earliest point it is needed, carry that + `Arc` into the selector dispatch, and reuse the same `Arc` in the routing + facts built for the concrete request. Cover + `execute_endpoint_attributed`, `execute_compact_finite_attributed`, and + `execute_embeddings_attributed`. `rust/src/coordinator/semantic.rs`: the + selector dispatch must carry that snapshot and must refuse a provider pin + that the snapshot disables. Do not resolve twice; the internal signature is + the implementer's choice. +- **Admin page.** `rust/src/server/dashboard/render/routing_policy.rs`: add the + Input column and render each stored field beside the effective value and its + source tag. Reach the existing + `ModelCatalogCache::get_effective_limits` projection through a read-only + accessor on `RoutingRouter`; an orphaned row shows "orphaned" rather than an + invented fact. +- **Documentation.** `architecture/deep-dive-routing.md`: replace the no-op + audit sentence with the actual rule — a refused mutation or a revert of an + absent row writes nothing, and a repeated save of an existing value is + audited like any committed mutation. + +No migration, configuration key, wire codec, or CLI command changes. + +## 7. Ordered work packages + +### Work package A — Correct the catalog pair order + +Intent: make separate mode advertise the pairs the catalog actually holds. + +Required changes: the two consumers in section 6 use +`(model_id, provider_id)`. The projection test obtains its pairs from the +producer's order — a `CacheSnapshot` fixture or a helper that takes +`CacheSnapshot` — rather than hand-writing a fixture in the helper's assumed +order. + +Acceptance evidence: with model `m` at providers `a` and `b`, separate mode +returns `m/a` and `m/b`; an unknown provider id and a disabled pair are +dropped; consolidated mode is unchanged. The regression test fails if the +destructure is swapped back — show that failure once during implementation and +record it in the closure. The admin page's provider datalist contains `a`, +`b` and its model datalist contains `m`. + +### Work package B — Capture one snapshot per request on every dispatch + +Intent: a configured disable applies to chat, streaming, compact, embeddings, +and the selector's internal dispatch, and a store failure fails all of them +closed. + +Required changes: resolve the snapshot once per request; pass the same `Arc` +into the selector dispatch and the concrete routing facts. `SemanticSelector` +must refuse to dispatch to a provider-model pin the snapshot disables (falling +back through its existing bounded fallback path rather than issuing the call). +The compact entry point must set the field. Prefer one helper for production +fact construction so a new surface cannot silently omit the capture; the +per-surface tests below are the required guard either way. + +Acceptance evidence: one test per surface (chat/streaming, compact, embeddings, +selector dispatch) shows a disabled pair is excluded or refused with +`model_disabled_for_provider`; an enabled pair still routes. A snapshot +resolution failure maps to `RoutingPolicyUnavailable` (503) on each surface +before submission. A test or a structural check shows the selector and the +concrete request share one snapshot for a virtual-model request. + +### Work package C — Complete the metadata page + +Intent: every stored field is visible, and an operator can see what each +override departs from. + +Required changes: add the Input column; render `input_tokens` with the other +limits; render the effective value and source tag for each stored field using +`get_effective_limits`; show "orphaned" when the catalog has no fact for the +row. Keep escaping and the existing revert actions. + +Acceptance evidence: a renderer test with a row that sets all four fields shows +all four values and the three source tags, and escapes each identifier. An +orphaned row renders "orphaned" and no invented value. A row saved with only a +display name still shows the inherited effective limits and their sources. + +### Work package D — Correct the audit documentation + +Intent: the documented rule matches the code. + +Required changes: the sentence at `architecture/deep-dive-routing.md:79-80` +only. No code change. + +Acceptance evidence: the docs validator passes; the page and the deep dive +agree that a committed save is audited once. + +### Work package E — Restore the missing acceptance evidence + +Intent: the M001 acceptance items that were claimed but not executed become +executable guards. + +Required changes and evidence: + +- **Triggers.** A test observes the revision advance on INSERT, UPDATE, and + DELETE for `provider_model_policy` and `model_metadata_override`, plus the + manual mode bump. A direct UPDATE with an unchanged value still advances the + revision exactly once. +- **Rollback.** A test writes a policy row and then forces an audit insert + failure in the same transaction (an action longer than the CHECK allows); + the transaction returns an error, the policy row is absent, and the revision + is unchanged. The rollback mechanism already exists through + `Database::with_transaction`; the test proves the composition. +- **Snapshot identity and failure.** Two `snapshot()` calls with no mutation + return `Arc::ptr_eq` snapshots. A service over a database that has not + applied v69 returns `RoutingPolicyError::Unavailable`, and + `EndpointError::RoutingPolicyUnavailable` maps to 503. +- **`Debug`.** The service's `Debug` output names the cached revision and + contains no display name, actor id, or metadata content. +- **Concurrent readers.** Two readers racing a rebuild each observe a complete + snapshot with a consistent revision; neither observes a partially built one. +- **Selection boundary guard.** A tooling guard under + `tests/tooling/` fails when `rust/src/routing/` references + `RoutingPolicyService`, `Database`, or `crate::db::`, and asserts + `RoutingRequestFacts::routing_policy` is an `Arc` snapshot rather than a + service handle. This replaces the original plan's unexecutable "selection + performs no I/O" assertion with a guard that reads the repository. +- **Reason code.** A candidate-level test asserts a disabled pair is excluded + with `model_disabled_for_provider` and an enabled pair is not. +- **Admin refusals.** For each mutation class (mode, model-policy set/remove, + metadata set/remove), a wrong or missing CSRF token writes nothing and a + non-admin principal is denied. + +### Work package F — Close the M001 evidence gaps + +Intent: discharge the three gaps the M001 closure named. + +Required changes: none beyond A–E. + +Acceptance evidence: + +- **Discovery end to end.** Start a server with an isolated home and one + cataloged pair; `GET /v1/models` returns the canonical id in consolidated + mode and the qualified id in separate mode, with an unchanged response shape. +- **Restart.** Mutate the mode and a pair; stop the process; start it again; + the next `/v1/models` and the next request observe the stored policy. +- **Revision-read timing.** Record the added per-request snapshot cost against + the baseline on loopback, labelled local, with the measurement method. + +## 8. Failure, cancellation, restart, contention semantics + +- A snapshot read or decode failure returns `RoutingPolicyUnavailable` before + selection on every surface; the request does not proceed. +- One snapshot is resolved per request and reused; a mutation during the + request changes the next request, not the current one. +- The selector dispatch refuses a disabled pin without issuing the internal + call and follows its existing bounded fallback, so the parent request still + receives a typed decision. +- 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. +- Restart reloads rows from SQLite; the first request rebuilds the snapshot. + Reload does not transfer policy state. +- Orphan rows stay tolerated and displayed as orphaned; they are never + auto-deleted. +- This pass adds no queue, waiter, or permit, so cancellation and generation + retirement are unchanged. + +## 9. Compatibility and migration + +- No schema change. v69 remains the latest migration; its SQL, checksum, and + manifest entries are untouched. +- `/v1/models` keeps its response shape; only the id set changes by mode. +- `models.expose_mode` stays parseable and inert; `routing.strategy` stays + `quota_fair`-only. +- `RoutingRequestFacts`, `FiniteRequest`, and `CompactAdmittedRequest` keep + their existing shapes; the snapshot capture is an internal wiring change. +- The admin page gains columns; its routes, CSRF contract, and admin gate are + unchanged. +- Rollback is a revert of the corrective commit. There is no data migration. + +## 10. Required tests + +- `rust/tests/routing_policy.rs`: trigger coverage, rollback, same-`Arc`, + typed failure, `Debug`, concurrent readers, reason code. +- `rust/tests/routing_domain.rs`: the enablement gate and the reason code at + the candidate level. +- `rust/tests/catalog_refresh.rs` or a focused unit: the pair-order projection + from the producer's own order. +- `rust/tests/on_prem_admin_ui.rs` and the dashboard inline tests: CSRF and + role refusals for the five mutation classes; the metadata renderer's + complete-field and source-tag output. +- `rust/tests/gateway_audit.rs`: no audit row for a refused mutation. +- `tests/tooling/`: the selection-boundary guard. +- 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_policy -- --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 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`: the audit rule, the selector-dispatch + capture, and the one-snapshot-per-request statement. +- `architecture/deep-dive-models.md`: only if the metadata projection wording + changes; the discovery mode contract is unchanged. +- `CHANGELOG.md`: an operator-facing line for the separate-mode and + compact/selector enforcement correction. +- `plans/registry.md` and the roadmap status table: this milestone's + registration and, at closure, its disposition. + +## 13. Acceptance criteria + +- Separate mode lists one `model/provider` id per enabled catalog pair and + keeps virtual aliases; the admin datalists hold the right identifiers. +- A disabled pair is never selected or dispatched on chat, streaming, compact, + embeddings, or the selector's internal dispatch, and the exclusion carries + `model_disabled_for_provider`. +- An unreadable policy store fails each inference surface closed with + `RoutingPolicyUnavailable` (503); it never routes with an empty policy. +- One snapshot is resolved per request and shared by the selector and the + concrete request. +- A metadata row shows all four stored fields, the effective upstream value, + and its source tag; deleting the row restores inheritance; an orphaned row + says so. +- The deep dive no longer claims that a repeated save writes no audit row. +- Every acceptance item in section 7 has a test or a recorded command, and each + guard was shown failing on a deliberate perturbation. +- The three M001 evidence gaps are recorded with executed output. + +## 14. Stop conditions + +Stop and report rather than improvise when: + +- the selector fix would require changing the selector protocol, fingerprint, + or affinity cache; +- the one-snapshot requirement cannot be met without changing the public + `FiniteRequest` or `CompactAdmittedRequest` shapes; +- the metadata page would need a new catalog write surface or a schema change; +- a fix expands into freshness projection, consolidated-mode filtering, ranks, + windows, capacity, or any other subsystem; +- an acceptance item cannot be tested without inventing a seam that weakens an + invariant. + +## 15. Closure evidence required + +- Implementation commits and the exact baseline they landed on. +- Command output for the full matrix, labelled local or CI truthfully. +- The pair-order regression shown failing on a deliberate swap and passing + after the fix. +- One test per inference surface proving the disable applies, plus the typed + 503 on an unreadable store. +- The trigger, rollback, same-`Arc`, typed-failure, `Debug`, concurrent-reader, + reason-code, and admin-refusal evidence. +- The selection-boundary tooling guard, shown failing on a deliberate + `RoutingPolicyService` reference under `rust/src/routing/`. +- Discovery end to end for both modes, process stop/start, and the recorded + revision-read timing. +- Documentation and registry updates, including the roadmap status table and + the M001 closure pointer. + +## 16. Handoff notes + +- Baseline `69247df7`; 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. +- The catalog pair order is `(model_id, provider_id)`. Do not add a pair type; + fix the consumers and pin the order with a test fed by the producer. +- Do not resolve the policy snapshot twice for a virtual-model request. +- Do not skip audit rows for identical-value saves; correct the sentence + instead. +- Do not reopen the recorded freshness deviation or consolidated-mode listing. +- No migration, no new configuration key, no wire change. +- Keep one `Status:` line in this plan, one in the roadmap, and one in the + M001 closure record; the tooling guard treats every such line as a + declaration. +- Do not edit `plans/implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md` + or rewrite the M001 closure matrix. diff --git a/plans/registry.md b/plans/registry.md index 77e3a9b9..001f1d9f 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 closed through M004; M002–M003 blocked pending implementation plans | 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. An independent audit at baseline `69247df7` then found that separate-mode discovery reads the catalog pair order backwards, the compact and selector dispatch paths never capture the policy snapshot, the metadata page omits a stored input limit, and several work-package acceptance items were never tested. The M001 closure moved to `corrective pass required` and Milestone 4 corrected the pair order, the compact and selector capture, the metadata page, and restored the missing acceptance evidence; it is now closed through `plans/closure/routing-policy-capacity/004-status.md`. M002 and M003 have no outstanding technical dependency but still need an implementation plan. | | 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). | @@ -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: no outstanding dependency — M001 is closed through Milestone 4, so the store, snapshot, and admin surface it consumes are correct. Blocked on an implementation plan, not on code. | +| Routing policy and capacity | M003 — concurrency caps, bounded queue, and time-based overflow | Hard: no outstanding dependency — M001 is closed through Milestone 4. Blocked on an implementation plan, not on code. 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. @@ -389,6 +392,8 @@ Historical M007 blocker assessment at baseline `7e241ad` (`plans/closure/persist | Subsystem / plan | Disposition | Evidence | |---|---|---| +| Routing policy and capacity M004 — M001 policy enforcement and discovery projection correction | closed — separate mode lists one `model/provider` id per enabled pair, a disabled pair is refused on chat, streaming, compact, embeddings, and the selector dispatch, an unreadable store fails all of them closed with a typed 503, and the metadata page shows every stored field beside its effective upstream value and source | `plans/closure/routing-policy-capacity/004-status.md`; corrective change set at baseline `69247df7` | +| Routing policy and capacity M001 — policy store, exposure modes, and per-model controls | closed through M004 — v69 store, revision snapshot, enablement gate, discovery modes, and audited admin surface; the audit findings at `69247df7` were corrected in Milestone 4 | `plans/closure/routing-policy-capacity/001-status.md`; `plans/closure/routing-policy-capacity/004-status.md`; implementation `7f961dc1` | | On-prem member access M001 — solo sign-in and onboarding credential | closed — a fresh onboard writes no server key; a managed browser GET redirects to `/login`; `/v1` and `/api` stay JSON 401; a legacy database still receives a missing server key | `plans/closure/on-prem-member-access/001-status.md`; implementation `0767576c` | | On-prem member access M002 — usage windows and member limits | closed — current day and current month stay separate totals; remaining is ceiling minus settled minus holds in that window; members receive instance ceilings and not instance usage | `plans/closure/on-prem-member-access/002-status.md`; implementation `0767576c` | | On-prem member access M003 — member navigation and admin roster | closed — member shells link only member destinations; the users roster shows assignment, overrides, USD, and credential labels without secrets; administrative routes stay off the member allow list | `plans/closure/on-prem-member-access/003-status.md`; implementation `0767576c` | 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..29d9ce35 --- /dev/null +++ b/plans/subsystems/routing-policy-capacity-roadmap.md @@ -0,0 +1,436 @@ +# 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. + +### Milestone 4 — M001 policy enforcement and discovery projection correction + +Class: capability + +Objective: make the M001 operator policy hold on every request path and in both +discovery modes after an independent audit at baseline `69247df7` found that +separate-mode discovery destructures the catalog pair in the wrong order, the +compact and selector dispatch paths construct routing facts without the policy +snapshot, and the metadata page omits a stored field. + +Dependencies: no hard dependency. Corrective pass over Milestone 1; interface +on `RoutingRequestFacts`, `ModelCatalogCache::provider_model_key_pairs`, +`RoutingRouter::catalog_snapshot`, and the dashboard CSRF/admin helpers. +Operational: a loopback measurement of the added revision read for the closure +evidence Milestone 1 named. + +Deliverable boundary: the pair-order fix in the discovery projection and the +admin datalists with a regression test fed by the producer's order; one +snapshot per request shared by the selector dispatch and the concrete routing +facts, including the compact path; the metadata page's input column and +effective-value source tags; the corrected audit sentence; and the acceptance +tests and guards Milestone 1 claimed but did not execute. No new policy +capability, no schema change, and no reopen of the recorded freshness +deviation or the consolidated-mode listing. + +User or operator value: separate mode actually advertises provider-qualified +ids, a disabled pair is refused on every surface including remote compaction +and the selector's internal call, an operator can see and preserve every stored +metadata field, and the milestone's evidence is executable rather than +asserted. + +Exit conditions: + +- Separate mode lists one `model/provider` id per enabled catalog pair and + keeps virtual aliases; the admin datalists hold the right identifiers. +- A disabled pair is never selected or dispatched on chat, streaming, compact, + embeddings, or the selector dispatch, with `model_disabled_for_provider`. +- An unreadable store fails each inference surface closed with a typed 503. +- One snapshot is resolved per request and shared by the selector and the + concrete request. +- The metadata page shows all four stored fields, the effective upstream value, + and its source tag; an orphaned row says so. +- The trigger, rollback, same-`Arc`, typed-failure, `Debug`, concurrent-reader, + reason-code, and admin-refusal evidence exists; each guard was shown failing + on a deliberate perturbation. +- Discovery end to end for both modes, process stop/start, and the recorded + revision-read timing are in the closure record. + +Deferred work: rank and active windows (Milestone 2); capacity, queue, and +overflow (Milestone 3); freshness projection into discovery; consolidated-mode +enablement filtering. + +## 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 | closed | [001](../implementation/routing-policy-capacity/001-policy-store-and-exposure-modes.md) | [001](../closure/routing-policy-capacity/001-status.md) | None; closed through Milestone 4. | +| 2 | blocked | — | — | Hard: no outstanding dependency — M001 is closed through Milestone 4; an implementation plan is not written yet, so the milestone is not dependency-ready. | +| 3 | blocked | — | — | Hard: no outstanding dependency — M001 is closed through Milestone 4; an implementation plan is not written yet. Operational: loopback evidence that the capacity layer does not meaningfully regress the hot path. | +| 4 | closed | [004](../implementation/routing-policy-capacity/004-policy-enforcement-and-projection-correction.md) | [004](../closure/routing-policy-capacity/004-status.md) | None. | 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..ece42c91 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 } @@ -737,6 +823,7 @@ fn admit_resolved( /// Returns the concrete body/model plus optional virtual facts. The selector /// runs through the same finite lifecycle with recursion refusal; affinity /// is committed only for validated selections per D007. +#[allow(clippy::too_many_arguments)] // Keeps the one-snapshot-per-request capture explicit. async fn resolve_concrete( state: &InferenceState, surface: ClientSurface, @@ -744,6 +831,7 @@ async fn resolve_concrete( session_header: Option<&str>, proxy_request_id: &str, attribution: Option<&crate::identity::RequestAttribution>, + routing_policy: &Arc, ) -> Result { let model_value = model_field(parsed.object()?)?; let policy = match attribution.and_then(|principal| principal.user_id.as_deref()) { @@ -812,6 +900,7 @@ async fn resolve_concrete( proxy_request_id, attribution, policy.as_deref(), + routing_policy, ) .await } @@ -855,6 +944,7 @@ async fn resolve_virtual( proxy_request_id: &str, attribution: Option<&crate::identity::RequestAttribution>, policy: Option<&crate::model_policy::ModelPolicySnapshot>, + routing_policy: &Arc, ) -> Result { // Build the early canonical view for the semantic prompt and affinity // identity. Admission here is bounded by the same body ceiling. @@ -865,9 +955,13 @@ async fn resolve_virtual( let identity = identity_input.session_identity(); let known = state.known_providers.clone(); let registry_virtual = state.registry.clone(); + // The selector's internal dispatch carries the same snapshot the concrete + // request will use: a disable applies to the selector pin without a second + // revision read, and a virtual request can never resolve two snapshots. let selector = SemanticSelector::new(state.finite.clone(), known) .with_virtual_check(move |model| registry_virtual.is_virtual(model)) - .with_attribution(attribution.map(|principal| principal.selector_child(proxy_request_id))); + .with_attribution(attribution.map(|principal| principal.selector_child(proxy_request_id))) + .with_routing_policy(Arc::clone(routing_policy)); ensure_concrete_model_allowed(policy, &router.selector_model, &state.known_providers)?; if router.sticky && let Some(identity) = identity @@ -1058,6 +1152,7 @@ pub(crate) async fn execute_embeddings_attributed( if state.registry.get(embedding.model.trim()).is_some() { return Err(EndpointError::EmbeddingAliasUnsupported); } + let routing_policy = state.routing_policy_snapshot().await?; let resolved = resolve_concrete( state, ClientSurface::ChatCompletions, @@ -1065,6 +1160,7 @@ pub(crate) async fn execute_embeddings_attributed( None, &proxy_request_id, attribution.as_ref(), + &routing_policy, ) .await?; if resolved.virtual_resolution.is_some() { @@ -1092,6 +1188,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(routing_policy); state .finite .execute_embedding_admitted( @@ -1146,6 +1243,9 @@ pub(crate) async fn execute_endpoint_attributed( _ => EndpointError::Admission, })?; let stream = stream_flag(parsed.object()?)?; + // One snapshot per request: resolved before the selector so the internal + // dispatch and the concrete facts share the same immutable Arc. + let routing_policy = state.routing_policy_snapshot().await?; let resolved = resolve_concrete( state, surface, @@ -1153,6 +1253,7 @@ pub(crate) async fn execute_endpoint_attributed( session_header.as_deref(), &proxy_request_id, attribution.as_ref(), + &routing_policy, ) .await?; let admitted = admit_resolved( @@ -1166,6 +1267,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(routing_policy); if stream { let request = StreamRequest::from_admitted( proxy_request_id, @@ -1272,6 +1374,9 @@ pub(crate) async fn execute_compact_finite_attributed( if stream_flag(payload)? { return Err(EndpointError::Admission); } + // Compact is an inference surface: it must honour the same disable gate + // and fail closed on an unreadable store before anything is submitted. + let routing_policy = state.routing_policy_snapshot().await?; let resolved = resolve_concrete( state, SURFACE, @@ -1279,6 +1384,7 @@ pub(crate) async fn execute_compact_finite_attributed( session_header.as_deref(), &proxy_request_id, attribution.as_ref(), + &routing_policy, ) .await?; let compact = admit_compact_parsed_request( @@ -1298,6 +1404,7 @@ pub(crate) async fn execute_compact_finite_attributed( } let mut routing_facts = compact.routing_facts(state.routing_inputs(SURFACE)); routing_facts.provider_id = resolved.provider_id.clone(); + routing_facts.routing_policy = Some(routing_policy); let execution = state .finite .execute_compact_admitted( @@ -1607,7 +1714,42 @@ 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(); + // The catalog producer emits `(model_id, provider_id)`; see + // `ModelCatalogCache::provider_model_key_pairs`. Do not swap this + // destructure: the pre-existing status aggregation reads the same order. + for (model_id, provider_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 +1871,101 @@ 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(), + } + } + + /// Build pairs exactly the way production builds them: from the catalog + /// producer. Hand-writing this vector in the consumer's assumed order is + /// what let an inverted destructure pass its own test. + fn catalog_pairs(models: &[(&str, &str, &str)]) -> Vec<(String, String)> { + let mut cache = crate::catalog::ModelCatalogCache::default(); + for (account, provider, model) in models { + cache.set_account_provider(*account, *provider); + let mut input = crate::catalog::ModelInput::new(*model); + input.protocol = Some("openai".into()); + input.protocol_source = Some("fixture".into()); + input.resolution_status = crate::catalog::ProtocolResolutionStatus::Resolved; + cache + .seed_from_account(account, provider, std::slice::from_ref(&input)) + .expect("the fixture seeds one provider model"); + } + cache.snapshot().provider_model_keys + } + + #[test] + fn separate_projection_formats_qualified_ids_and_drops_disabled_pairs() { + let pairs = catalog_pairs(&[ + ("account-a", "provider-a", "model-a"), + ("account-b", "provider-b", "model-a"), + ("account-c", "provider-a", "model-b"), + ]); + assert!( + pairs.contains(&("model-a".to_owned(), "provider-a".to_owned())), + "the catalog producer emits (model_id, provider_id), got {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 ids = qualified_model_ids(&policy, &known, &pairs, None); + assert_eq!( + ids, + vec![ + "model-a/provider-a".to_owned(), + "model-a/provider-b".to_owned() + ], + "only the disabled pair is excluded; both providers of model-a survive" + ); + } + + #[test] + fn separate_projection_drops_pairs_whose_provider_is_unknown() { + let pairs = catalog_pairs(&[ + ("account-a", "provider-a", "model-a"), + ("account-b", "provider-b", "model-a"), + ]); + let policy = crate::routing_policy::RoutingPolicySnapshot::from_rows(policy_rows(&[])); + let known = BTreeSet::from(["provider-a".to_owned()]); + assert_eq!( + qualified_model_ids(&policy, &known, &pairs, None), + vec!["model-a/provider-a".to_owned()], + "an unconfigured provider is dropped even though the catalog holds it" + ); + } + + #[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 = catalog_pairs(&[("account-a", "provider-a", "model-a")]); + 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/coordinator/semantic.rs b/rust/src/coordinator/semantic.rs index 7409d52e..4878349f 100644 --- a/rust/src/coordinator/semantic.rs +++ b/rust/src/coordinator/semantic.rs @@ -418,6 +418,9 @@ pub struct SemanticSelector { max_response_bytes: usize, is_virtual: std::sync::Arc bool + Send + Sync>, attribution: Option, + /// The caller's request snapshot. Present in production so the internal + /// dispatch honours the operator disable without a second revision read. + routing_policy: Option>, } impl std::fmt::Debug for SemanticSelector { @@ -427,6 +430,7 @@ impl std::fmt::Debug for SemanticSelector { .field("known_providers", &self.known_providers) .field("max_response_bytes", &self.max_response_bytes) .field("has_attribution", &self.attribution.is_some()) + .field("has_routing_policy", &self.routing_policy.is_some()) .finish() } } @@ -439,9 +443,21 @@ impl SemanticSelector { max_response_bytes: SELECTOR_MAX_RESPONSE_BYTES, is_virtual: std::sync::Arc::new(|_| false), attribution: None, + routing_policy: None, } } + /// Carry the request's immutable policy snapshot into the internal + /// dispatch. The caller resolves it once; the selector never reads the + /// store itself. + pub fn with_routing_policy( + mut self, + snapshot: std::sync::Arc, + ) -> Self { + self.routing_policy = Some(snapshot); + self + } + pub fn with_attribution( mut self, attribution: Option, @@ -687,6 +703,18 @@ impl SemanticSelector { &supplied, &self.known_providers, ); + // An operator disable wins over the compiled selector pin: refuse the + // internal call so the selection follows its bounded fallback instead + // of dispatching to a disabled pair. + // An operator disable wins over the compiled selector pin: refuse the + // internal call so the selection follows its bounded fallback instead + // of dispatching to a disabled pair. + if let (Some(provider_id), Some(policy)) = + (provider_pin.as_deref(), self.routing_policy.as_deref()) + && !policy.model_enabled(provider_id, &dispatch_model) + { + return Err(SelectorDispatchError::PolicyDisabled); + } if dispatch_model != supplied { body_payload.insert("model".into(), Value::String(dispatch_model.clone())); } @@ -736,6 +764,7 @@ impl SemanticSelector { ) .map_err(|error| SelectorDispatchError::Admission(error.to_string()))?; request.routing_facts.provider_id = provider_pin; + request.routing_facts.routing_policy = self.routing_policy.clone(); let execution = match self.attribution.clone() { Some(attribution) => { self.coordinator @@ -845,6 +874,7 @@ impl SemanticSelector { enum SelectorDispatchError { ModelMismatch, Recursive, + PolicyDisabled, Encode(String), Admission(String), Dispatch(String), 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/router.rs b/rust/src/routing/router.rs index 4bda26bc..755d7336 100644 --- a/rust/src/routing/router.rs +++ b/rust/src/routing/router.rs @@ -361,6 +361,21 @@ impl RoutingRouter { .snapshot() } + /// Effective catalog limits for one model, optionally scoped to a + /// provider. Read-only; never performs provider or DB work. The admin + /// policy page uses it to show what a stored override departs from. + pub fn effective_model_limits( + &self, + model_id: &str, + provider_id: Option<&str>, + ) -> Option { + self.state + .catalog + .lock() + .unwrap_or_else(|error| error.into_inner()) + .get_effective_limits(model_id, provider_id) + } + /// Return immutable account identities for the active generation. pub fn account_identities(&self) -> Vec { self.state.registry.enabled_snapshot() 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..ed351d60 100644 --- a/rust/src/server/dashboard/admin.rs +++ b/rust/src/server/dashboard/admin.rs @@ -1,4 +1,6 @@ use super::*; +use std::collections::BTreeMap; + use axum::{ Extension, Form, extract::{Query, State}, @@ -190,6 +192,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 +406,222 @@ 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 router = lease.generation().inference().router_handle(); + let mut catalog_pairs = router.catalog_snapshot().provider_model_keys; + catalog_pairs.sort(); + catalog_pairs.dedup(); + let model_policy_rows = snapshot.model_policy_rows(); + let metadata_rows = snapshot.metadata_rows(); + // Stored rows render beside the effective upstream fact they depart from. + // A row whose pair is not in the catalog has no entry here and renders as + // orphaned rather than as an invented value. + let effective_limits = metadata_rows + .iter() + .filter_map(|(model_id, provider_id, _)| { + router + .effective_model_limits(model_id, provider_id.as_deref()) + .map(|limits| ((model_id.clone(), provider_id.clone()), limits)) + }) + .collect::>(); + let body = render_routing_policy( + snapshot.exposure_mode(), + &model_policy_rows, + &metadata_rows, + &catalog_pairs, + &effective_limits, + &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..57f65662 --- /dev/null +++ b/rust/src/server/dashboard/render/routing_policy.rs @@ -0,0 +1,380 @@ +use super::*; + +use std::collections::{BTreeMap, BTreeSet}; + +use crate::catalog::EffectiveModelLimits; +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)], + effective_limits: &BTreeMap<(String, Option), EffectiveModelLimits>, + 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(); + // `catalog_pairs` follows the catalog producer's `(model_id, provider_id)` + // order; swapping it fills each datalist with the other identifier. + for (model_id, provider_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 effective = effective_limits.get(&(model_id.clone(), provider_id.clone())); + // Each stored field renders beside the value it departs from. + // A row whose provider-model pair is not in the catalog says + // "orphaned" instead of inventing a fact. + let cell = |stored: Option, value: Option, source: &str| { + let stored = stored.map_or_else(|| "—".to_owned(), |value| value.to_string()); + let inherited = match effective { + None => "orphaned".to_owned(), + Some(_) => match value { + Some(value) => format!("{value} ({})", html_escape(source)), + None => "no upstream value".to_owned(), + }, + }; + format!("{stored}
{inherited}") + }; + let source = |field: fn(&EffectiveModelLimits) -> &String| { + effective.map_or("", |limits| field(limits).as_str()) + }; + format!( + "{}{scope}{display}\ + {}{}{}\ +
\ + \ + \ + \ +
", + html_escape(model_id), + cell( + overlay.context_tokens, + effective.and_then(|limits| limits.context_tokens), + source(|limits| &limits.context_source), + ), + cell( + overlay.input_tokens, + effective.and_then(|limits| limits.input_tokens), + source(|limits| &limits.input_source), + ), + cell( + overlay.output_tokens, + effective.and_then(|limits| limits.output_tokens), + source(|limits| &limits.output_source), + ), + 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. \ + The small line under each value is the effective upstream limit and where it came from.

\ +
\ + \ + \ + \ + \ + \ + \ + \ +
\ +
\ + {DASHBOARD_TABLE_OPEN}ModelScopeDisplay name\ + ContextInputOutputAction\ + {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