Repository navigation
Conversation
…, zero-drift day-one) Expands the gateway's lane catalog from 1 (omi:auto:chat-structured) to 16, covering every AI capability in Omi. Read-review-only — no behavior change. - lanes.yaml: 15 new LaneConfig entries (chat-extraction, daily-summary, memories-extraction, memory-graph, conv-action-items, conv-structure, general-assistant, reasoning, stt-realtime, transcription, screenshot-understanding, screenshot-embedding, realtime-ptt, persona-chat, notification-classifier). - route_artifacts.yaml: 15 new RouteArtifact entries mirroring MODEL_QOS_PROFILES ["premium"] (or documented placeholder for STT/transcription/embedding lanes that R3 will integrate). All shadow mode (rollout.percent: 0), all evidence.dev_only: false (is_prod_eligible() passes). - resolver.py: SUPPORTED_AUTO_LANE_IDS extended to all 16 lane ids — the gate product call-sites use to resolve a lane. - tests: 16 new tests cover objective sum-to-1.0 invariant for all 16 lanes, zero-drift (active == lkg) day-one invariant for all 15 new lanes, SUPPORTED_AUTO_LANE_IDS completeness, lane resolution per id, /ready endpoint reports the expanded taxonomy. Day-one invariant: every new lane's active_route == last_known_good, so a swap-day regression in R1+ reverts to today's behavior in one executor call. 224 gateway unit tests pass. Per PLAN.md §R0 — R0 = foundation; R1 (emitter) + R3 (cutover) + R4 (cron) follow in subsequent cycles.
(R0) Four findings from cubic-dev-ai on the R0 PR: 1. P2 (lanes.yaml:32): comment referenced .aidlc/spec.md which is gitignored and not in the repo. Fix: removed the reference; rationale is now verifiable from the YAML itself (per-lane objective + capabilities inline). 2. P2 (route_artifacts.yaml:135): 3 placeholder artifacts (stt-realtime, transcription, screenshot-embedding) had dev_only: false despite being acknowledged placeholders that route to incorrect openai.chat_completions surfaces. Fix: dev_only: true so Evidence.is_prod_eligible() returns False for them. The 3 artifact_digest values were recomputed to match the new body. 3. P3 (lanes.yaml:31): inline comment said '14 new lanes' but 15 were added. Fix: corrected to '15 new LaneConfig entries'. 4. P3 (test_llm_gateway_config.py:14): same '14 new lanes' typo. Fix: '15'. Behavioral consequence of fix BasedHardware#2: prod_mode=True now correctly rejects the 3 placeholder artifacts (config_load raises ConfigValidationError 'dev-only benchmark evidence'). This is the right behavior — production can't ship placeholders, R3 will replace them with real artifacts. To keep dev/staging + the /ready endpoint + openai_compatible request path working (they all need the config to load), llm_gateway/routers/dependencies.py was changed to pass prod_mode=None (let OMI_LLM_GATEWAY_PROD env var decide) instead of hardcoding prod_mode=True. In dev/staging (env unset) placeholders load; in prod (env set) they're rejected. Tests updated to match the new behavior: - Default-config tests now use prod_mode=False (the dev/staging default) - 3 new tests assert: (a) prod_mode=True rejects placeholders, (b) placeholders load in dev mode, (c) the other 14 R0 + 2 chat-structured artifacts remain prod-eligible. 227 gateway unit tests pass (was 224 pre-fix; +3 new placeholder tests).
… lanes The chat-completion resolver should NOT accept non-chat lanes (audio, embedding). Per cubic-dev-ai review on PR BasedHardware#8740 (R5a+R1): SUPPORTED_AUTO_LANE_IDS now contains exactly the 13 chat-completion lanes (1 existing chat-structured + 12 R0 new lanes resolvable via chat-completions: chat-extraction, daily-summary, memories-extraction, memory-graph, conv-action-items, conv-structure, general-assistant, reasoning, screenshot-understanding, realtime-ptt, persona-chat, notification-classifier). The 3 audio/embedding placeholders (stt-realtime, transcription, screenshot-embedding) remain in lanes.yaml + route_artifacts.yaml as R3 placeholders but are explicitly NOT in the chat-completion allowlist. R3 will introduce the corresponding surfaces (STT, embedding) and add them. Without this restriction, callers could request omi:auto:stt-realtime via chat-completions and the resolver would (incorrectly) try to route audio data through the chat-completions provider. Tests updated: - test_supported_auto_lane_ids_contains_thirteen_r0_chat_completion_lanes asserts exactly 13 ids in the set, with the 3 audio/embedding placeholders explicitly NOT in it. - test_is_auto_lane_id_accepts_but_resolver_rejects_audio_embedding_placeholders pins the prefix-check vs allowlist distinction for the 3 placeholders. - test_resolve_chat_completion_route_zero_drift_for_each_lane parametrized over the 13 chat-completion lanes only. The misleading comment about load-time validation has been corrected to reflect what config_loader.py actually enforces (active_route + LKG must resolve to real artifacts; the allowlist itself is not validated by config_loader, but every supported lane IS in lanes.yaml).
…ceholders Per cubic-dev-ai P1 review on PR BasedHardware#8739: marking the 3 R0 placeholders (stt-realtime, transcription, screenshot-embedding) with dev_only: true breaks the R0 day-one shadow-mode contract because lanes.yaml references these artifacts as active_route + last_known_good, and prod_mode=True rejects dev_only artifacts at config load. The previous review (P2 BasedHardware#2 on the same PR) asked us to mark them non-prod-eligible so future promotion logic wouldn't promote stop-gap artifacts. Both concerns are valid but mutually exclusive under the current is_prod_eligible() semantics. Resolution: introduce a new Evidence.placeholder: bool = False field. Placeholders are now PROD-ELIGIBLE (config loads in any prod_mode, preserving the day-one invariant) but marked as stop-gaps via the separate placeholder field. Future promotion logic (R1 emitter, R4 cron) reads evidence.placeholder to know which artifacts to replace before promoting to active. evidence.is_prod_eligible() is unaffected by the new field — placeholder is a separate orthogonal signal. Schema change: Evidence.placeholder: bool = False in backend/llm_gateway/gateway/schemas.py. YAML changes: - 3 placeholders: dev_only: false, placeholder: true (was dev_only: true) - All 17 artifact_digests recomputed (placeholder: false for the 14 non-placeholders still affects the canonical body, since False is not None and gets included in the digest) Tests updated: - REMOVED test_r0_placeholder_artifacts_rejected_in_prod_mode (no longer rejected — they're prod-eligible now) - RENAMED test_r0_placeholder_artifacts_load_in_dev_mode -> test_r0_placeholder_artifacts_load_in_all_modes; now asserts both prod_mode=True AND prod_mode=False load all 17 artifacts (day-one invariant holds) - RENAMED test_r0_non_placeholder_artifacts_remain_prod_eligible -> test_r0_placeholder_field_distinguishes_placeholders_from_real_artifacts; asserts all 17 are prod-eligible, and that placeholder=True correctly distinguishes the 3 placeholders from the other 14 R0 + 2 existing chat-structured artifacts (placeholder=False default). Tests: 223 pass (was 227 pre-fix; net -4 from removed/renamed tests).
…rics + fakes + tests) Builds the infrastructure for the R3 product call-site cutover. R3 has been split into R3.1 (this worktree) and R3.2 (cutover, gated on R0 + R5a + R1 to be live). R3.1 is pure code: no production dependency on the gateway existing. It can ship in parallel with R0 + R5a + R1 review. The actual call- site swap (R3.2) is gated on those PRs landing. - backend/utils/llm/shadow_cutover.py (NEW) ShadowCutover: dual-path orchestrator. Runs both paths in parallel via asyncio.gather; computes divergence (token-Jaccard + structural key-set match); records per-call via ShadowMetrics; returns the control response. LKG fallback: gateway failure or timeout returns control response (no fallback for control failures — the control path is the trusted one). Protocols: ControlProvider (existing direct provider) + GatewayClient (omi:auto:<lane> via gateway HTTP). - backend/utils/llm/shadow_metrics.py (NEW) ShadowMetrics: per-call + rolling-24h aggregate divergence tracking. Fires an alert (via pluggable AlertSink) when rolling aggregate > threshold (default 1%). Records older than the window are dropped. Tracks per-lane alert state to suppress duplicate alerts. Pluggable clock for testability. Protocols: AlertSink + MetricsSink for real production sinks (R3.2 wires the real Prometheus / Sentry). - backend/tests/unit/llm/__init__.py (NEW — empty) Test tree directory marker. - backend/tests/unit/llm/fakes.py (NEW) Deterministic fakes: FakeControlProvider, FakeGatewayClient, FakeAlertSink, FakeMetricsSink, FakeClock. All satisfy the production-side Protocols by structure. Production code never imports from tests/ (verified by file location). - backend/tests/unit/llm/test_shadow_cutover.py (NEW, 16 tests) Coverage: both-paths-run-in-parallel, used-response-is-control, messages-passed-to-both, gateway-failure-returns-control, gateway-exception-returns-control, gateway-timeout-returns-control, control-exception-propagates, control-path-has-no-timeout, identical-content-zero-divergence, completely-different-content-high-divergence, gateway-failure-max-divergence, structural-match-json-keys, structural-mismatch-different-keys, per-call-record-stored, metrics-sink-records-per-call, alert-fires-on-high-divergence. - backend/tests/unit/llm/test_shadow_metrics.py (NEW, 14 tests) Coverage: per-call recording, rolling aggregate, window boundary (records older than the window are dropped), alert threshold (above fires, below suppresses), duplicate-alert suppression within window, per-lane isolation, no-op default sinks (no AlertSink / no MetricsSink configured). Tests: 30 new pass (253 total gateway + R3.1 tests pass; was 223 pre-R3.1). No production code outside the new R3.1 modules is modified. Pre-commit hook formats Python. Per AIDLC spec/plan at .aidlc/ (R3.1 = dual-path infrastructure; R3.2 = cutover, future cycle).
There was a problem hiding this comment.
9 issues found across 16 files
Confidence score: 2/5
backend/llm_gateway/config/route_artifacts.yamldefinesroute.realtime_ptt.2026_07_01.001withprovider: anthropic, but the currentProviderRegistryonly supportsopenai, so that lane is likely to fail at runtime with provider-not-supported errors—either switch the route to a supported provider or add registry support before merging.backend/utils/llm/shadow_cutover.pyandbackend/utils/llm/shadow_metrics.pyrun metrics/alert plumbing on the request path without robust error containment; if aMetricsSink/AlertSinkraises, a successful control response can be lost—treat observability as best-effort with guarded calls (and logging) so business responses still return.backend/utils/llm/shadow_cutover.pyhas async control-flow risks where gateway timeout is enforced too late and background gateway tasks may continue or leak when control fails, which can add latency and consume resources under failure conditions—enforce timeout at the gateway await boundary and explicitly cancel/await orphaned tasks.backend/utils/llm/shadow_metrics.py/backend/utils/llm/shadow_cutover.pyhave reliability gaps (alert marked successful before async completion, unbounded rolling-window deques, anddivergence_thresholdnot wired), which can hide failed alerts, grow memory over time, and make config ineffective—defer success marking until completion, bound retention, and pass/read the threshold config before merge.
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/llm_gateway/config/route_artifacts.yaml">
<violation number="1" location="backend/llm_gateway/config/route_artifacts.yaml:758">
P1: Route `route.realtime_ptt.2026_07_01.001` uses `provider: anthropic` but the gateway's `ProviderRegistry` only supports `openai`. Resolving this lane at runtime will raise a provider-not-supported error.</violation>
</file>
<file name="backend/tests/unit/test_llm_gateway_config.py">
<violation number="1" location="backend/tests/unit/test_llm_gateway_config.py:42">
P3: Misleading comment: claims '15 lanes total (1 existing + 14 new)' but the code defines 15 new lane IDs in _R0_NEW_LANE_IDS plus 1 existing LANE_ID = 16 total lanes. Comment should read '16 lanes total (1 existing + 15 new)'.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| lane_id: omi:auto:realtime-ptt | ||
| surface: openai.chat_completions | ||
| primary: | ||
| provider: anthropic |
There was a problem hiding this comment.
P1: Route route.realtime_ptt.2026_07_01.001 uses provider: anthropic but the gateway's ProviderRegistry only supports openai. Resolving this lane at runtime will raise a provider-not-supported error.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/llm_gateway/config/route_artifacts.yaml, line 758:
<comment>Route `route.realtime_ptt.2026_07_01.001` uses `provider: anthropic` but the gateway's `ProviderRegistry` only supports `openai`. Resolving this lane at runtime will raise a provider-not-supported error.</comment>
<file context>
@@ -112,3 +112,802 @@ route_artifacts:
+ lane_id: omi:auto:realtime-ptt
+ surface: openai.chat_completions
+ primary:
+ provider: anthropic
+ model: claude-sonnet-4-6
+ fallbacks: []
</file context>
| config = load_gateway_config(prod_mode=False) | ||
|
|
||
| assert set(config.lanes) == {LANE_ID} | ||
| # R0 expansion: 15 lanes total (1 existing + 14 new). See .aidlc/spec.md. |
There was a problem hiding this comment.
P3: Misleading comment: claims '15 lanes total (1 existing + 14 new)' but the code defines 15 new lane IDs in _R0_NEW_LANE_IDS plus 1 existing LANE_ID = 16 total lanes. Comment should read '16 lanes total (1 existing + 15 new)'.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_llm_gateway_config.py, line 42:
<comment>Misleading comment: claims '15 lanes total (1 existing + 14 new)' but the code defines 15 new lane IDs in _R0_NEW_LANE_IDS plus 1 existing LANE_ID = 16 total lanes. Comment should read '16 lanes total (1 existing + 15 new)'.</comment>
<file context>
@@ -11,18 +11,79 @@
+ config = load_gateway_config(prod_mode=False)
- assert set(config.lanes) == {LANE_ID}
+ # R0 expansion: 15 lanes total (1 existing + 14 new). See .aidlc/spec.md.
+ assert set(config.lanes) == _ALL_LANE_IDS
lane = config.lanes[LANE_ID]
</file context>
Seven findings from cubic-dev-ai on the R3.1 PR. Two findings are out of scope for R3.1 (they were introduced in the R0 commits already on this branch; those fixes are in PR BasedHardware#8739's history): - P1 #1 (route_artifacts.yaml:758): anthropic provider not registered. R0 scope; addressed in PR BasedHardware#8739. - P3 BasedHardware#9 (test_llm_gateway_config.py:42): '15 lanes total' comment should be '16 lanes total'. R0 scope; already fixed in commit 0d3442d (use placeholder flag instead of dev_only). Five findings addressed in this commit: P1 BasedHardware#2 (shadow_metrics.py:139): Metrics sink failures are now contained — try/except around increment/gauge calls logs a WARNING and does not propagate. Observability is best-effort. P1 BasedHardware#3 (shadow_cutover.py:178): Metrics recording is wrapped in try/except at the chat() call site; a sink failure cannot break the control response. Tested by test_metrics_failure_does_not_break_response. P2 BasedHardware#4 (shadow_metrics.py:132): Unbounded memory growth capped by max_records_per_lane (default 10,000) as a memory safety net alongside the time-based window eviction. Tested by test_max_records_per_lane_caps_deque. P2 BasedHardware#5 (shadow_metrics.py:163): Alert delivery failure now clears the alerted state. The inner async fire coroutine catches its own exception and discards the lane from _alerted_lanes so the next divergence re-fires. Tested by test_alert_sink_failure_clears_alerted_state. P2 BasedHardware#6 (shadow_cutover.py:163): Control path failure now cancels the gateway task (no orphaned work). Tested by test_control_failure_cancels_gateway_task. P2 BasedHardware#7 (shadow_cutover.py:135): divergence_threshold is now read — ShadowCutover.__init__ applies the per-cutover threshold to the metrics instance (overriding the metrics' default). Tested by test_divergence_threshold_overrides_default and test_no_threshold_override_keeps_default. P2 BasedHardware#8 (shadow_cutover.py:164): Both paths now have INDEPENDENT timeouts (asyncio.wait_for on each), so a slow gateway doesn't delay the already-ready control response. Tested by test_slow_gateway_does_not_delay_control. Tests: 38 pass (was 30 pre-fix; +8 new).
|
Thanks for the thorough review — 7 of 9 findings addressed in commit Out of scope (deferred to PR #8739 / R0)
In-scope (addressed in commit
Tests: 38 pass (was 30 pre-fix; +8 new). |
There was a problem hiding this comment.
2 issues found across 4 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="backend/llm_gateway/config/route_artifacts.yaml">
<violation number="1" location="backend/llm_gateway/config/route_artifacts.yaml:758">
P1: Route `route.realtime_ptt.2026_07_01.001` uses `provider: anthropic` but the gateway's `ProviderRegistry` only supports `openai`. Resolving this lane at runtime will raise a provider-not-supported error.</violation>
</file>
<file name="backend/tests/unit/test_llm_gateway_config.py">
<violation number="1" location="backend/tests/unit/test_llm_gateway_config.py:42">
P3: Misleading comment: claims '15 lanes total (1 existing + 14 new)' but the code defines 15 new lane IDs in _R0_NEW_LANE_IDS plus 1 existing LANE_ID = 16 total lanes. Comment should read '16 lanes total (1 existing + 15 new)'.</violation>
</file>
<file name="backend/utils/llm/shadow_metrics.py">
<violation number="1" location="backend/utils/llm/shadow_metrics.py:123">
P1: `max_records_per_lane` is assigned without validation. Passing a negative value causes an `IndexError` crash on the evict loop; passing zero silently disables alerts by emptying the bucket before aggregation.</violation>
<violation number="2" location="backend/utils/llm/shadow_metrics.py:149">
P2: The per-lane record cap silently changes the aggregate from a true rolling-24h window to a capped-sample window for high-volume lanes. Neither the class docstring ('rolling-24h aggregate'), the alert message ('over {window_seconds}s'), nor the PR description mentions this cap-driven semantic change.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
Two NEW findings emerged after force-push (review 4610429787) on my prior fixes. The 9 prior findings were already addressed in 818def5. P1 (shadow_metrics.py:123): max_records_per_lane is assigned without validation. A negative value caused IndexError on the evict loop (popleft on empty bucket); a zero value silently disabled alerts (empty bucket = no aggregation). Fix: validate in __init__ — raise ValueError if max_records_per_lane <= 0. The error message names the bad value to make the bug obvious. P2 (shadow_metrics.py:149): the per-lane record cap silently changed the aggregate from a true rolling-24h window to a capped- sample window for high-volume lanes. Neither the class docstring ('rolling-24h aggregate'), the alert message, nor the PR description mentioned this cap-driven semantic change. Fix: updated the ShadowMetrics class docstring to explicitly document the memory cap. The cap is a safety net for high-volume lanes; the rolling window is truncated to the most recent N records per lane. Tests: 39 pass (was 38 pre-fix; +1 test for the validation).
|
Thanks for the follow-up — both new findings from review P1 (shadow_metrics.py:123) — You're right — assigning
Fix: validate in if max_records_per_lane <= 0:
raise ValueError(
f"max_records_per_lane must be > 0, got {max_records_per_lane}"
)New test: P2 (shadow_metrics.py:149) — cap semantic documentation You're right — the docstring said "rolling-24h aggregate" but the cap changes the semantic for high-volume lanes. Fixed: updated the
The cap is a deliberate trade-off (correctness in the time-based window vs memory safety under degraded conditions). The docstring now reflects that. Tests: 39 pass (was 38 pre-fix; +1 validation test). |
|
Thanks @choguun — this is solid infrastructure work. The ShadowCutover/ShadowMetrics design is clean: protocol-based pluggability, best-effort observability that can't break the call site, proper asyncio task lifecycle (cancellation on control failure, independent timeouts), memory caps on the metrics ring buffer, and good test coverage (743 lines of new tests). A few things that need human maintainer attention before this can move forward: Stacked on unmerged PRs. This branch bundles the R0 commits (PR #8739, still open) alongside the R3.1 commits — the first 4 of 7 commits are R0. R5a+R1 (#8740) is also open. Since R3.1 explicitly depends on R0 + R5a + R1 merging first (per the PR description), these should land as separate, independently-mergeable PRs. Consider rebasing R3.1 onto main once R0 merges, so the diff reflects only the R3.1 infrastructure.
Feature fit. The dual-path shadow cutover approach is a sound migration strategy for the LLM gateway rollout — run both paths, measure divergence, cut over only after sustained parity. The infrastructure-only scope of R3.1 (no production wiring, fakes for sinks) is the right level of caution. The qualitative question of whether the 15-lane taxonomy in R0 is the right product decomposition is better evaluated on PR #8739 directly. Labeling |
kodjima33
left a comment
There was a problem hiding this comment.
LLM gateway dual-path infra (ShadowCutover + ShadowMetrics). Feature — approving direction; product rollout call is Nik's.
|
Thanks @choguun — the follow-up fixes look solid. The Confirming the prior review findings remain as merge prerequisites (no regressions from the fixes):
Holding AI-assisted review (glm-5.2). Actions limited to comments/labels per Omi maintainer policy; no merge or branch push. |
|
Consolidated into #10089 — all 6 auto-router PRs merged sequentially with co-authorship preserved. |
|
Hey @choguun 👋 Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request. After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:
Before your next PR, please skim:
If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing. Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out. Thank you for being part of the Omi community! |
Consolidates #8739 #8758 #8740 #8744 #8746 #8748. - Unified auto-router with lane catalog, serving config, route artifacts - Config reload, benchmark scoring, capability smoke checks - Lazy-loading lane catalog (no import-time I/O in request-path modules) - Cataloged public-shared-conversation-chat as prod_ready Failure-Class: none
Consolidates #8739 #8758 #8740 #8744 #8746 #8748. - Unified auto-router with lane catalog, serving config, route artifacts - Config reload, benchmark scoring, capability smoke checks - Lazy-loading lane catalog (no import-time I/O in request-path modules) - Cataloged public-shared-conversation-chat as prod_ready Failure-Class: none
Consolidates #8739 #8758 #8740 #8744 #8746 #8748. - Unified auto-router with lane catalog, serving config, route artifacts - Config reload, benchmark scoring, capability smoke checks - Lazy-loading lane catalog (no import-time I/O in request-path modules) - Cataloged public-shared-conversation-chat as prod_ready Failure-Class: none
Summary
R3.1 of the auto-router-on-LLM-gateway feature. Builds the dual-path infrastructure for the R3 product call-site cutover. R3.1 is pure code — it has no production dependency on the gateway existing, so it can ship in parallel with R0 (PR #8739) and R5a+R1 (PR #8740).
R3 has been split into two phases with different gates:
model_config.py+ per-domain routers). Gated on R0 + R5a + R1 to merge + 14-day shadow observation with <1% divergence. Will be a separate cycle in a new worktree when the gate clears.The 14-day shadow observation happens after R3.2 ships. The "drop the control path" follow-up PR is the final R3 step.
What this PR delivers
backend/utils/llm/shadow_cutover.py(NEW)ShadowCutover— dual-path orchestrator.asyncio.gatherShadowMetricsShadowCutoverResultwith control, gateway, divergence, andused_response(always control in R3.1)Protocols:
ControlProvider(Protocol) — the existing direct-provider call (e.g., OpenAI / Anthropic client). R3.2 wires the real implementation.GatewayClient(Protocol) — the gateway HTTP call (omi:auto:<lane>). R3.2 wrapsbackend/utils/llm/gateway_client.py::invoke_chat_structured_gateway.backend/utils/llm/shadow_metrics.py(NEW)ShadowMetrics— per-call + rolling-24h aggregate divergence tracking.AlertSink) when aggregate > threshold (default 1%)Protocols (R3.2 wires the real Prometheus / Sentry):
AlertSink— where divergence alerts goMetricsSink— where per-call metrics gobackend/tests/unit/llm/fakes.py(NEW)Deterministic fakes for the R3.1 tests:
FakeControlProvider— returns a predeterminedControlResult(default + queued + raise + delay)FakeGatewayClient— returns a predeterminedGatewayResult(success / failure / raise / delay)FakeAlertSink— records alert calls for test introspectionFakeMetricsSink— records metric calls for test introspectionFakeClock— forShadowMetricstests (advances the clock deterministically)Lives in
tests/.../llm/(NOT_private/) — production-side importable for test purposes only. Mirrors R2's pattern.Tests (30 new tests, 253 total)
tests/unit/llm/test_shadow_cutover.py(16 tests) — both paths run in parallel, control used, LKG fallback for gateway failure / exception / timeout, control failure propagates, control path has no timeout, identical content → zero divergence, completely different content → high divergence, gateway failure → max divergence, structural match (JSON keys), structural mismatch, per-call record stored, metrics sink records, alert fires on high divergence.tests/unit/llm/test_shadow_metrics.py(14 tests) — per-call recording, rolling aggregate, window boundary (records older than the window are dropped), alert threshold (above fires, below suppresses), duplicate alert suppression within window, per-lane isolation, no-op default sinks.Day-one invariants
model_config.pyandbackend/routers/*.pyare untouched in R3.1. The cutover is R3.2's job.Validation gates (all met)
ControlProvider.chatandGatewayClient.chatare calledHow to test locally
Risks
record()is sync: the impl usesloop.create_taskto schedule the alert fire. This works in async contexts (the test doesawait asyncio.sleep(0)to yield). R3.2 can address this by makingrecord()async + having callers await it (or by adding aflush()method toShadowMetrics).gateway_observability.pyfor metrics + Sentry for alerts). The Protocol design makes this a simple plug-in.tests/integration/test_gateway_live.py).Cross-PR consistency
R3.1 can land in any order relative to the other open PRs.
Next cycles
backend/utils/llm/model_config.pymodifications + per-domainbackend/routers/*.pycutovers. Gated on R0 + R5a + R1 to be merged AND 14-day shadow observation. New worktree (e.g.,auto-router-cutover-do) when the gate clears.auto-router-cronworktree.cc: gateway owners team for review