Skip to content

feat(llm): R3.1 — dual-path infrastructure (ShadowCutover + ShadowMetrics) (v.0.5) - #8748

Closed
choguun wants to merge 7 commits into
BasedHardware:mainfrom
choguun:feat/auto-router-cutover
Closed

choguun wants to merge 7 commits into
BasedHardware:mainfrom
choguun:feat/auto-router-cutover

Conversation

@choguun

@choguun choguun commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

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:

  • R3.1 (THIS PR): infrastructure (ShadowCutover + ShadowMetrics + fakes + tests). No production dependency. Can ship now.
  • R3.2 (FOLLOW-UP): actual call-site swap (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.

  • Runs both paths in parallel via asyncio.gather
  • Computes divergence (token-Jaccard + structural-key-set match) on every call
  • Records per-call + per-lane aggregate via ShadowMetrics
  • LKG fallback: if the gateway path fails or times out, returns the control response
  • Control failure propagates (no fallback for control failures — the control path is the trusted one)
  • Returns ShadowCutoverResult with control, gateway, divergence, and used_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 wraps backend/utils/llm/gateway_client.py::invoke_chat_structured_gateway.

backend/utils/llm/shadow_metrics.py (NEW)

ShadowMetrics — per-call + rolling-24h aggregate divergence tracking.

  • Records per-call: lane id, timestamps, latencies, divergence score
  • Computes rolling-24h aggregate per lane
  • Fires an alert (via pluggable AlertSink) when aggregate > threshold (default 1%)
  • Records older than the window are dropped
  • Tracks per-lane alert state to suppress duplicate alerts within the window
  • Pluggable clock for testability

Protocols (R3.2 wires the real Prometheus / Sentry):

  • AlertSink — where divergence alerts go
  • MetricsSink — where per-call metrics go

backend/tests/unit/llm/fakes.py (NEW)

Deterministic fakes for the R3.1 tests:

  • FakeControlProvider — returns a predetermined ControlResult (default + queued + raise + delay)
  • FakeGatewayClient — returns a predetermined GatewayResult (success / failure / raise / delay)
  • FakeAlertSink — records alert calls for test introspection
  • FakeMetricsSink — records metric calls for test introspection
  • FakeClock — for ShadowMetrics tests (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

  1. Dual-path is non-negotiable — every call runs both paths. R3.1 always returns the control response; the gateway is observed but not used.
  2. LKG fallback — if the gateway path fails or times out, the control response is returned. The gateway failure doesn't take down the call site.
  3. No real HTTP in tests — fakes are deterministic. CI is fast + free.
  4. No call-site changes — model_config.py and backend/routers/*.py are untouched in R3.1. The cutover is R3.2's job.

Validation gates (all met)

Gate What it proves Status
Both paths run in parallel asyncio.gather; both ControlProvider.chat and GatewayClient.chat are called ✅
LKG fallback Gateway failure / exception / timeout → control returned ✅
Control failure propagates No fallback for control — the cutover trusts control ✅
Divergence computation Token-Jaccard + structural match; 0.0–1.0 score ✅
Rolling aggregate 24h window; records dropped after window ✅
Alert threshold Above 1% fires; below suppresses ✅
No-op default sinks Missing AlertSink / MetricsSink doesn't raise ✅
30 R3.1 tests pass + 223 pre-existing gateway tests pass No regression ✅ 253 total

How to test locally

cd backend
python -m pytest tests/unit/llm/ -v
# → 30 passed

# Demo: dual-path with fakes (no real HTTP calls)
python -c "
import asyncio
from utils.llm.shadow_cutover import ShadowCutover, ShadowCutoverConfig, ControlResult
from utils.llm.shadow_metrics import ShadowMetrics
from tests.unit.llm.fakes import FakeControlProvider, FakeGatewayClient, FakeClock

async def main():
    control = FakeControlProvider()
    gateway = FakeGatewayClient()
    metrics = ShadowMetrics(clock=FakeClock())
    cutover = ShadowCutover(ShadowCutoverConfig(
        lane_id='omi:auto:chat-extraction',
        control_provider=control,
        gateway_client=gateway,
        metrics=metrics,
    ))
    result = await cutover.chat(messages=[{'role': 'user', 'content': 'hi'}])
    print(f'control: {result.control.content}')
    print(f'gateway: {result.gateway.content}')
    print(f'divergence: {result.divergence.score}')
    print(f'used: {result.used_response.content}')

asyncio.run(main())
"

Risks

  • AlertSink.fire is async but record() is sync: the impl uses loop.create_task to schedule the alert fire. This works in async contexts (the test does await asyncio.sleep(0) to yield). R3.2 can address this by making record() async + having callers await it (or by adding a flush() method to ShadowMetrics).
  • No default Prometheus / Sentry sink: R3.1 ships no defaults — tests use fakes. R3.2 wires the real sinks (existing gateway_observability.py for metrics + Sentry for alerts). The Protocol design makes this a simple plug-in.
  • No integration test against a real gateway: R3.1 is unit-tested only (with fakes). R3.2 should add an integration test that runs against a real local gateway on shadow mode (per the plan's tests/integration/test_gateway_live.py).

Cross-PR consistency

R3.1 can land in any order relative to the other open PRs.

Next cycles

  1. R3.2 — Call-site swap: backend/utils/llm/model_config.py modifications + per-domain backend/routers/*.py cutovers. 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.
  2. R4 — Nightly rotation cron: doubly-gated on R3 ship + R3 ≥30 days live. Plan-only in auto-router-cron worktree.

cc: gateway owners team for review

Review in cubic

choguun added 5 commits July 1, 2026 17:22
…, 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).
@choguun choguun changed the title feat(llm): R3.1 — dual-path infrastructure (ShadowCutover + ShadowMetrics) feat(llm): R3.1 — dual-path infrastructure (ShadowCutover + ShadowMetrics) (v.0.5) Jul 1, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

9 issues found across 16 files

Confidence score: 2/5

  • backend/llm_gateway/config/route_artifacts.yaml defines route.realtime_ptt.2026_07_01.001 with provider: anthropic, but the current ProviderRegistry only supports openai, 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.py and backend/utils/llm/shadow_metrics.py run metrics/alert plumbing on the request path without robust error containment; if a MetricsSink/AlertSink raises, 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.py has 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.py have reliability gaps (alert marked successful before async completion, unbounded rolling-window deques, and divergence_threshold not 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>

Comment thread backend/utils/llm/shadow_metrics.py Resolved
Comment thread backend/utils/llm/shadow_cutover.py Resolved
Comment thread backend/utils/llm/shadow_metrics.py Resolved
Comment thread backend/utils/llm/shadow_metrics.py Resolved
Comment thread backend/utils/llm/shadow_cutover.py Resolved
Comment thread backend/utils/llm/shadow_cutover.py Resolved
Comment thread backend/utils/llm/shadow_cutover.py Resolved
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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).
@choguun

choguun commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review — 7 of 9 findings addressed in commit 818def53d (rebased onto the original commit). Two findings are out of scope for R3.1 (they originated in the R0 commits that are stacked on this branch, and were addressed in PR #8739's history).

Out of scope (deferred to PR #8739 / R0)

  • P1 Client #1 (route_artifacts.yaml:758): realtime_ptt uses provider=anthropic but the gateway's ProviderRegistry only supports openai. This is a real concern, but it's a property of the R0 artifact, not R3.1. The TODO(R3) comment on the artifact in route_artifacts.yaml already documents this. R3 (the product cutover) will register the Anthropic provider. Tracked in the R0 lane definition.
  • P3 feat: Implement double tap start recording #9 (test_llm_gateway_config.py:42): The "15 lanes total" comment is from R0's pre-fix state. Already corrected to "16 lanes total" in commit 0d3442de2 (the R0 placeholder fix). The fix is on this branch — the test on main may still show the old comment, but the new comment is in the diff that will land when PR feat(llm_gateway): R0 — 15 new lanes + initial artifacts (shadow mode, zero-drift day-one) (v.0.1) #8739 merges.

In-scope (addressed in commit 818def53d)

  • P1 colors to the LED board #2 (shadow_metrics.py:139) — Metrics sink failure containment: Wrapped MetricsSink.increment() and gauge() calls in try/except. A sink exception is logged at WARNING level and does not propagate. New test: test_metrics_sink_failure_does_not_break_record.
  • P1 Add printing BLE device address to serial monitor #3 (shadow_cutover.py:178) — Metrics recording on critical path: Wrapped self._config.metrics.record(record) in try/except at the chat() call site. A sink exception is logged at WARNING level; the control response is always returned. New test: test_metrics_failure_does_not_break_response.
  • P2 About Firebase #4 (shadow_metrics.py:132) — Unbounded memory growth: Added max_records_per_lane (default 10,000) as a memory safety net alongside the time-based window eviction. Even if the clock is stuck, the deque is capped. New test: test_max_records_per_lane_caps_deque.
  • P2 Making setup process better #5 (shadow_metrics.py:163) — Alert state on failure: The inner async fire coroutine now catches its own exception and discards the lane from _alerted_lanes. The next divergence re-fires correctly. New test: test_alert_sink_failure_clears_alerted_state.
  • P2 Fixes boot #6 (shadow_cutover.py:163) — Gateway task cancellation on control failure: When control raises, the gateway task is explicitly cancelled (no orphaned work). New test: test_control_failure_cancels_gateway_task.
  • P2 chore: Update .gitignore to remove build artifacts #7 (shadow_cutover.py:135) — divergence_threshold not read: ShadowCutover.__init__ now applies the per-cutover threshold to the metrics instance, overriding the metrics' default. Changed divergence_threshold type to Optional[float] (default None = use metrics' default). New tests: test_divergence_threshold_overrides_default, test_no_threshold_override_keeps_default.
  • P2 Update README.md #8 (shadow_cutover.py:164) — Parallel timeouts: Both paths now have INDEPENDENT timeouts (asyncio.wait_for on each). A slow gateway doesn't delay the already-ready control response. New test: test_slow_gateway_does_not_delay_control.

Tests: 38 pass (was 30 pre-fix; +8 new).

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread backend/utils/llm/shadow_metrics.py Resolved
Comment thread backend/utils/llm/shadow_metrics.py Resolved
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).
@choguun

choguun commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the follow-up — both new findings from review 4610429787 addressed in commit 41d095f0a. (The 9 prior findings were already addressed in 818def53d; the line numbers in this review re-fired after my force-push but the underlying issues were addressed.)

P1 (shadow_metrics.py:123) — max_records_per_lane validation

You're right — assigning max_records_per_lane without validation is a footgun. Fixed:

  • A negative value caused IndexError on the evict loop (popleft on empty bucket)
  • A zero value silently disabled alerts (empty bucket = no aggregation = aggregate always 0)

Fix: validate in __init__ — raise ValueError with the bad value if max_records_per_lane <= 0. The error message names the bad value to make the bug obvious.

if max_records_per_lane <= 0:
    raise ValueError(
        f"max_records_per_lane must be > 0, got {max_records_per_lane}"
    )

New test: test_max_records_per_lane_must_be_positive asserts ValueError for 0 and -1.

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 ShadowMetrics class docstring to explicitly document the memory cap:

Memory cap: as a safety net, each lane is also capped at max_records_per_lane records (default 10,000). For high-volume lanes, this becomes the effective limit — the rolling window is truncated to the most recent N records per lane. The cap prevents unbounded memory growth if the clock is stuck or the time-based window eviction doesn't trigger for any reason.

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).

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge needs-scope-reduction PR scope should be reduced or split labels Jul 1, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

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.

prod_mode change in dependencies.py. On main, get_gateway_config() hardcodes prod_mode=True, which rejects dev_only artifacts at config load. This PR changes it to prod_mode=None (env-driven via OMI_LLM_GATEWAY_PROD). That env var is set in the llm-gateway Helm charts but does not appear to be set in the main backend deployment config. If it's unset in production, prod_mode resolves to False, relaxing the guard. All new R0 artifacts have dev_only: false, so the practical impact may be nil today — but this weakens a hard-coded production safety invariant and warrants explicit maintainer sign-off on the deployment story.

realtime-ptt uses provider: anthropic. The ProviderRegistry only registers openai. This lane is in SUPPORTED_AUTO_LANE_IDS and would fail at the executor if called. It's in shadow mode (percent: 0) so it won't receive traffic yet, but it's a latent issue worth tracking — either add an Anthropic provider or exclude the lane until it's supported.

Evidence.placeholder field added to schema. This is a reasonable design (distinct from dev_only), but note that adding the field changes content_digest for all existing artifacts (since placeholder=false is included in the canonical JSON via exclude_none=True). The PR correctly updates the artifact_digest values to match. Worth confirming the digest recomputation is intentional and documented.

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 needs-maintainer-review and needs-scope-reduction (stacking). Not approving — this is a large architectural PR in a stacked sequence touching model/provider routing.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LLM gateway dual-path infra (ShadowCutover + ShadowMetrics). Feature — approving direction; product rollout call is Nik's.

@Git-on-my-level

Copy link
Copy Markdown
Member

Thanks @choguun — the follow-up fixes look solid. The max_records_per_lane validation, alert-state-clear-on-sink-failure, and independent-timeout improvements are well-implemented with good test coverage (39 tests across ShadowCutover + ShadowMetrics).

Confirming the prior review findings remain as merge prerequisites (no regressions from the fixes):

  1. Stacked sequence — this branch bundles R0 commits (PR feat(llm_gateway): R0 — 15 new lanes + initial artifacts (shadow mode, zero-drift day-one) (v.0.1) #8739, still open) alongside the R3.1 commits. Please rebase onto main once R0 + R5a + R1 land, so the diff reflects only the R3.1 infrastructure.
  2. prod_mode weakening — the dependencies.py change from prod_mode=True to prod_mode=None (env-driven via OMI_LLM_GATEWAY_PROD) relaxes a hard-coded production guard. This needs explicit maintainer sign-off on the deployment story (confirming the env var is set in the production backend deployment).
  3. realtime-ptt provider mismatch — references provider: anthropic but the ProviderRegistry only registers openai. Latent in shadow mode (percent=0) but should be tracked or excluded until supported.

Holding needs-maintainer-review and needs-scope-reduction. Not approving — this is a large architectural PR in a stacked sequence touching model/provider routing infrastructure.

AI-assisted review (glm-5.2). Actions limited to comments/labels per Omi maintainer policy; no merge or branch push.

@undivisible

Copy link
Copy Markdown
Collaborator

Consolidated into #10089 — all 6 auto-router PRs merged sequentially with co-authorship preserved.

@github-actions

Copy link
Copy Markdown
Contributor

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:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

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!

undivisible added a commit that referenced this pull request Jul 29, 2026
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
undivisible added a commit that referenced this pull request Jul 31, 2026
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
undivisible added a commit that referenced this pull request Jul 31, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

needs-maintainer-review Needs a human maintainer to sign off before merge needs-scope-reduction PR scope should be reduced or split

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants