Skip to content

feat(llm_gateway): R5b — mtime-watched config hot-reload (v.0.3) - #8744

Closed
choguun wants to merge 9 commits into
BasedHardware:mainfrom
choguun:feat/auto-router-hot-reload
Closed

choguun wants to merge 9 commits into
BasedHardware:mainfrom
choguun:feat/auto-router-hot-reload

Conversation

@choguun

@choguun choguun commented Jul 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

R5b of the auto-router-on-LLM-gateway feature. Replaces the @lru_cache(maxsize=1) pattern on get_gateway_config with an mtime-watched config reloader. The gateway now picks up YAML changes on the next request after merge — no pod restart required. : "the cache invalidation path is what makes 'nightly rotation' mean 'the next request after merge sees the new artifact' instead of 'restart the pod.'"

This branch is independent of R5a+R1 (PR #8740, in review) and can land in parallel. Rebased onto the latest R0 fixes from PR #8739.

What this PR delivers

backend/llm_gateway/gateway/daily_refresh.py (NEW, 159 LOC)

Verbatim cherry-pick of v3's backend/utils/auto_router/daily_refresh.py (sha256 6e6897f5f0490417dd06924b32a79b0b6d2cd44b14079a20fdb37c75baf84d74 verified). Provides DailyRefreshCache[T] — a generic TTL + asyncio.Lock + stale-fallback primitive.

Public module (lives at gateway/daily_refresh.py, NOT _private/). The request path uses it via config_reload.py, so it must be public. A lint test enforces this constraint — see TestPublicNamespace.test_daily_refresh_NOT_in_private_namespace. This differs from R5a's scoring.py which IS in _private/ (only emitter uses it).

backend/llm_gateway/gateway/config_reload.py (NEW)

GatewayConfigReloader — wraps DailyRefreshCache with mtime polling:

  • async get() — checks max mtime across lanes.yaml + route_artifacts.yaml + feature_bundles.yaml; on change, invalidates the cache + reloads; otherwise returns the cached instance (same identity, no reload)
  • Stale fallback on ConfigValidationError — serves the last good config (DailyRefreshCache handles this)
  • invalidate() — admin/test helper
  • last_loaded_config — diagnostic accessor
  • TTL default: 60s (only an upper bound; mtime check is the primary trigger)

backend/llm_gateway/routers/dependencies.py (MODIFY)

Replaced @lru_cache(maxsize=1) with the module-level _config_reloader singleton pointing at DEFAULT_CONFIG_DIR. get_gateway_config() is now async; awaits _config_reloader.get(). prod_mode=None (env-driven: OMI_LLM_GATEWAY_PROD env var decides) — preserves R0's day-one invariant.

backend/llm_gateway/routers/health.py (MODIFY)

get_ready() is now async; awaits get_gateway_config(). Returns 200 with sorted lane list + artifact count, 503 on ConfigValidationError (unchanged behavior).

backend/llm_gateway/gateway/config_loader.py (MODIFY — small hardening)

Wrap yaml.safe_load in try/except yaml.YAMLError and re-raise as ConfigValidationError. The gateway's error contract is now: any YAML load failure raises ConfigValidationError. Previously malformed YAML leaked yaml.parser.ParserError to callers — which broke the reloader's stale-fallback semantics (it can't fallback on an exception type it doesn't know about).

Tests (24 new tests, 248 total)

  • backend/tests/unit/llm_gateway/test_daily_refresh.py (11 tests) — parity tests mirroring v3's test_auto_router_daily_refresh.py (focused subset): TTL refresh, lock contention (double-checked locking), stale fallback on loader error, invalidate(), TTL validation, public-namespace lint.
  • backend/tests/unit/llm_gateway/test_config_reload.py (14 tests) — behavior tests: _max_mtime() helper, first-call load, cached on unchanged mtime, reload on mtime change (any of 3 files), stale fallback, first-call error propagation, recovery, concurrency, invalidate(), end-to-end against real config.

Day-one invariants

  1. Byte-equivalence with v3: daily_refresh.py sha256 matches v3's exactly. Drift would be silent breakage; future re-cherry-picks must update both file and parity tests.
  2. Public/private namespace: daily_refresh.py is at gateway/daily_refresh.py (public), scoring.py is at gateway/_private/scoring.py (private to emitter). The boundary is enforced by a lint test.
  3. No request-path scoring: reloader only does file I/O + Pydantic validation. The R5a isolation test still passes — daily_refresh doesn't transitively pull in _private/scoring.py.
  4. Per-request cost is bounded: 3 os.stat() calls (microseconds); only on mtime change does it reload (~10-50ms cold). On hot path, returns the same GatewayConfig instance (verified by assert cfg1 is cfg2).
  5. Stale fallback: on ConfigValidationError, serves the last good config. Operations team sees a WARNING log; gateway stays up.

Validation gates (all met)

Gate What it proves Status
Cherry-pick parity daily_refresh.py byte-equivalent to v3 (sha256 verified) ✅
Scoring isolation (regression) R5a's _private/ invariant still holds ✅ existing tests pass
First-call load reloader reads from disk on first get() ✅
Cache behavior same mtime → same instance (no reload) ✅
Reload trigger mtime change on any of 3 files → reload ✅
Stale fallback ConfigValidationError post-success → serve last good ✅
First-call error ConfigValidationError first call → propagate ✅
Concurrency 5 concurrent get() → 1 loader invocation ✅
/ready endpoint 200 with correct lane/artifact counts ✅ existing readiness tests pass
224 pre-existing tests No regression ✅ 248 total (224 + 24 new)

How to test locally

cd backend
python -m pytest tests/unit/test_llm_gateway_*.py tests/unit/llm_gateway/ -v
# → 248 passed

# Demo: reloader behavior (in-process)
python -c "
import asyncio
from pathlib import Path
from llm_gateway.gateway.config_reload import GatewayConfigReloader

async def demo():
    reloader = GatewayConfigReloader(Path('llm_gateway/config'))
    cfg = await reloader.get()
    print(f'Loaded {len(cfg.lanes)} lanes, {len(cfg.route_artifacts)} artifacts')
    cfg2 = await reloader.get()
    print(f'Second call returns same object: {cfg is cfg2}')

asyncio.run(demo())
"

Risks

  • Mtime resolution ~1s: filesystem mtime granularity is ~1s on most systems. A config change + read within the same second could miss the change. Acceptable for the rotation-cron use case (PRs merge at human timescale).
  • config_loader.py modification: I wrapped yaml.safe_load to convert yaml.YAMLError to ConfigValidationError. This is a behavior change beyond R5b's strict scope but necessary for the reloader to surface YAML errors uniformly (otherwise the reloader can't do stale-fallback on YAML parse errors — they'd be uncaught). The change is small and adds clarity to the gateway's error contract.
  • get_ready async cascading: making get_gateway_config async required get_ready to also be async. TestClient (Starlette) handles async-from-sync bridging transparently — no test client changes needed.

Next PRs after this merges

  1. R2 — capability smoke gate (PR for the smoke script; independent of R5b, can land in parallel)
  2. R3 — product call-site cutover (gated on R0+R1+shadow stability; ≥14 days of <1% divergence)
  3. R4 — nightly rotation cron (gated on R3 ≥30 days live)

cc: gateway owners team for review

Review in cubic

choguun added 7 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).
…tale-fallback)

Cherry-picks v3's DailyRefreshCache primitive verbatim into the gateway
as a public module on the request path:

- backend/llm_gateway/gateway/daily_refresh.py (159 LOC, sha256
  6e6897f5f0490417dd06924b32a79b0b6d2cd44b14079a20fdb37c75baf84d74)
  Verbatim copy of v3's backend/utils/auto_router/daily_refresh.py.
  Stdlib imports only (asyncio, logging, time, datetime, typing).
  Same as R5a's scoring.py cherry-pick discipline (byte-equivalent,
  verified).

- backend/llm_gateway/gateway/config_loader.py
  Wrap yaml.safe_load in try/except yaml.YAMLError; raise
  ConfigValidationError. The gateway's contract is now: any YAML load
  failure raises ConfigValidationError. Previously a malformed YAML
  leaked yaml.parser.ParserError to callers.

- backend/tests/unit/llm_gateway/test_daily_refresh.py (11 tests)
  Parity tests mirroring v3's test_auto_router_daily_refresh.py (focused
  subset): TTL refresh, lock contention (double-checked locking),
  stale fallback on loader error, invalidate(), TTL validation, and
  a public-namespace lint check confirming daily_refresh.py is at
  gateway/ (NOT _private/) since the request path uses it.

Public location: daily_refresh.py lives at gateway/daily_refresh.py
(not _private/) because the R5b config_reload.py uses it on the
request path. This differs from R5a's scoring.py which is in _private/
(emitter-only).

Per PLAN.md §R5b + §Sequencing: this is the foundation for the hot-
reload cache; T-003 (config_reload.py + dependencies.py wiring) lands
in the next commit.
Wraps DailyRefreshCache with mtime polling so the gateway picks up
YAML changes on the next request after merge — no pod restart required.

- backend/llm_gateway/gateway/config_reload.py
  GatewayConfigReloader class:
  - get() (async): check max mtime across the 3 config files; on
    change, invalidate DailyRefreshCache + reload. Otherwise return
    the cached GatewayConfig instance (same identity, no reload).
  - _load(): called by DailyRefreshCache.get_or_refresh under the
    cache lock. Reads from config_dir + sets self._cached on success.
    On ConfigValidationError, raises — DailyRefreshCache does the
    stale-fallback (returns last good value if cached, propagates if
    first-call).
  - invalidate(): test helper + admin path; clears mtime + cached +
    cache.
  - last_loaded_config property: diagnostic accessor.

- _max_mtime() helper: returns max st_mtime across lanes.yaml +
  route_artifacts.yaml + feature_bundles.yaml (0.0 if none exist).

- backend/tests/unit/llm_gateway/test_config_reload.py (14 tests):
  - _max_mtime() helper: zero on empty dir, max of existing files,
    ignores unrelated files
  - First-call load: 16 lanes + 17 artifacts (R0 placeholder fix)
  - Cached on unchanged mtime: same object identity
  - Reload on mtime change: bumps mtime, gets new instance
  - Reload on any of 3 files' mtime change
  - Stale fallback on ConfigValidationError (post-success)
  - First-call error propagation (no cached value)
  - Recovery after first-call error
  - Concurrency: 5 concurrent get() calls produce 1 loader invocation
  - invalidate() forces reload + clears last_loaded_config
  - End-to-end: reloader works against the real default config

Per PLAN.md §R5b: 'the cache invalidation path is what makes nightly
rotation mean the next request after merge sees the new artifact
instead of restart the pod.'

T-003 (dependencies.py + route handlers) lands in the next commit.
…ready

Replaces the @lru_cache(maxsize=1) pattern on get_gateway_config with
the mtime-watched GatewayConfigReloader. The gateway now picks up YAML
changes on the next request after merge — no pod restart.

- backend/llm_gateway/routers/dependencies.py
  - Module-level singleton _config_reloader pointing at DEFAULT_CONFIG_DIR.
  - get_gateway_config() is now ASYNC; awaits _config_reloader.get().
  - prod_mode=None (env-driven): dev/staging loads all configs;
    prod rejects dev_only artifacts. R0 day-one invariant preserved.
  - reset_gateway_config_reloader() helper for tests + admin paths.

- backend/llm_gateway/routers/health.py
  - get_ready() is now ASYNC; awaits get_gateway_config(). The /ready
    endpoint still returns 200 with sorted lane list + artifact count.
  - 503 on ConfigValidationError (unchanged behavior).

TestClient transparently handles async handlers (Starlette's TestClient
calls async endpoints via asyncio.run internally), so the readiness +
openai_compatible tests pass without TestClient changes.

Tests: 248 pass (was 224 pre-R5b; +24 new: 11 daily_refresh parity +
13 config_reload behavior).

Per PLAN.md §R5b: this completes the R5b hot-reload cycle. R2
(capability smoke) and R3/R4 (gated) are next.
@choguun choguun changed the title feat(llm_gateway): R5b — mtime-watched config hot-reload feat(llm_gateway): R5b — mtime-watched config hot-reload (v.0.3) 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.

5 issues found across 16 files

Confidence score: 2/5

  • In backend/llm_gateway/gateway/schemas.py, adding a default for evidence.placeholder can change artifact content digests for existing configs that omitted the field, which can trigger artifact_digest mismatches during config load and break route startup behavior — preserve backward-compatible digest inputs (or version/migrate digest computation) before merging.
  • In backend/llm_gateway/gateway/daily_refresh.py (DailyRefreshCache[T]), using None as the empty-cache sentinel means real None payloads are treated as missing/stale, causing incorrect freshness checks and fallback behavior at runtime; the last_loaded_at docstring formula is also misleading and could cause incorrect maintenance assumptions — switch to a dedicated sentinel object and align the docstring/tests with the actual time semantics before merging.
  • In backend/llm_gateway/gateway/resolver.py, expanding SUPPORTED_AUTO_LANE_IDS without validating those IDs against lanes.yaml risks referencing lanes that do not exist, leading to misrouting or failed auto-lane resolution when configs drift — add load-time validation that every supported ID is present (and fail fast with a clear error) before merging.
  • In backend/llm_gateway/gateway/config_reload.py, synchronous config loading inside async _load() can block the event loop during reloads, which may increase latency or stall concurrent async work under load — move blocking I/O/CPU work off the loop (e.g., thread executor) or make the loader fully async before merging.
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/gateway/resolver.py">

<violation number="1" location="backend/llm_gateway/gateway/resolver.py:33">
P2: The hardcoded `SUPPORTED_AUTO_LANE_IDS` frozenset was expanded from 1 to 13 lane IDs, but `load_gateway_config` does not validate that all entries are actually present in `lanes.yaml`. The comment in `resolver.py` misleadingly claims `load_gateway_config` enforces this invariant, but the loader only validates `lane -> route artifact` resolution for lanes present in YAML, not that all `SUPPORTED_AUTO_LANE_IDS` members exist in YAML. If a lane is added to the frozenset but omitted from `lanes.yaml`, config loading succeeds and the failure is deferred to runtime. Add cross-file validation in `load_gateway_config` (or a parity test) to ensure every lane in `SUPPORTED_AUTO_LANE_IDS` has a corresponding config entry and valid route artifacts.</violation>
</file>

<file name="backend/llm_gateway/gateway/schemas.py">

<violation number="1" location="backend/llm_gateway/gateway/schemas.py:117">
P1: New default `evidence.placeholder` will silently change route artifact content digests for existing artifacts that omit the field, causing `artifact_digest` mismatches at config load time.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

# Distinct from `dev_only` (which excludes the artifact from production
# loading entirely). A placeholder is fully servable — it just shouldn't
# be the long-term primary. See R0 spec + PR #8739 review (cubic P1).
placeholder: bool = False

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: New default evidence.placeholder will silently change route artifact content digests for existing artifacts that omit the field, causing artifact_digest mismatches at config load time.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/llm_gateway/gateway/schemas.py, line 117:

<comment>New default `evidence.placeholder` will silently change route artifact content digests for existing artifacts that omit the field, causing `artifact_digest` mismatches at config load time.</comment>

<file context>
@@ -109,8 +109,18 @@ class Evidence(StrictBaseModel):
+    # Distinct from `dev_only` (which excludes the artifact from production
+    # loading entirely). A placeholder is fully servable — it just shouldn't
+    # be the long-term primary. See R0 spec + PR #8739 review (cubic P1).
+    placeholder: bool = False
 
     def is_prod_eligible(self) -> bool:
</file context>

# (it validates active_route + last_known_good resolve to real artifacts).
# Adding a lane here that is missing from config is a hard error at config
# load.
SUPPORTED_AUTO_LANE_IDS = frozenset(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2: The hardcoded SUPPORTED_AUTO_LANE_IDS frozenset was expanded from 1 to 13 lane IDs, but load_gateway_config does not validate that all entries are actually present in lanes.yaml. The comment in resolver.py misleadingly claims load_gateway_config enforces this invariant, but the loader only validates lane -> route artifact resolution for lanes present in YAML, not that all SUPPORTED_AUTO_LANE_IDS members exist in YAML. If a lane is added to the frozenset but omitted from lanes.yaml, config loading succeeds and the failure is deferred to runtime. Add cross-file validation in load_gateway_config (or a parity test) to ensure every lane in SUPPORTED_AUTO_LANE_IDS has a corresponding config entry and valid route artifacts.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/llm_gateway/gateway/resolver.py, line 33:

<comment>The hardcoded `SUPPORTED_AUTO_LANE_IDS` frozenset was expanded from 1 to 13 lane IDs, but `load_gateway_config` does not validate that all entries are actually present in `lanes.yaml`. The comment in `resolver.py` misleadingly claims `load_gateway_config` enforces this invariant, but the loader only validates `lane -> route artifact` resolution for lanes present in YAML, not that all `SUPPORTED_AUTO_LANE_IDS` members exist in YAML. If a lane is added to the frozenset but omitted from `lanes.yaml`, config loading succeeds and the failure is deferred to runtime. Add cross-file validation in `load_gateway_config` (or a parity test) to ensure every lane in `SUPPORTED_AUTO_LANE_IDS` has a corresponding config entry and valid route artifacts.</comment>

<file context>
@@ -15,7 +15,46 @@
+# (it validates active_route + last_known_good resolve to real artifacts).
+# Adding a lane here that is missing from config is a hard error at config
+# load.
+SUPPORTED_AUTO_LANE_IDS = frozenset(
+    {
+        'omi:auto:chat-structured',  # existing — pilot lane
</file context>

 (R5b)

Four findings from cubic-dev-ai on the R5b PR. P1 #1 was a false positive
(digests already correct after the R0 placeholder fix in 7c82adf). The
remaining 4 (P1 BasedHardware#2 + P2 BasedHardware#3/4/5) are addressed as follows:

P2 BasedHardware#3 (resolver.py:33) — Add cross-validation that every lane in
SUPPORTED_AUTO_LANE_IDS exists in lanes.yaml. Fix:

- backend/llm_gateway/gateway/config_loader.py:
  load_gateway_config() now accepts an optional required_lane_ids
  parameter. When provided, missing lane ids raise ConfigValidationError
  at load time (no longer deferred to runtime).
- backend/llm_gateway/gateway/config_reload.py: passes
  SUPPORTED_AUTO_LANE_IDS to load_gateway_config so the cross-check
  fires on every reload (startup AND mtime-driven reloads).
- backend/llm_gateway/routers/dependencies.py: imports
  SUPPORTED_AUTO_LANE_IDS (no circular import — resolver imports
  config_loader but not dependencies).
- 3 new tests: missing-id raises, satisfied-id succeeds,
  default-None skips cross-validation.

P2 BasedHardware#4 (config_reload.py:88) — Sync config loading blocks the event loop.
Fix:

- backend/llm_gateway/gateway/config_reload.py: _load() now wraps the
  sync load_gateway_config() call in asyncio.to_thread() so the
  ~10-50ms yaml.safe_load + Pydantic validation runs in a threadpool
  instead of blocking the event loop.

P1 BasedHardware#2 (daily_refresh.py:59) + P2 BasedHardware#5 (daily_refresh.py:77) — Both
findings are inside the cherry-picked daily_refresh.py file. Per
PLAN.md §R5a discipline, the cherry-pick is byte-equivalent to v3
(sha256 6e6897f5f0490417dd06924b32a79b0b6d2cd44b14079a20fdb37c75baf84d74
verified). Modifying it to fix the bugs would break byte-equivalence
and conflict with future re-cherry-picks.

DEFERRED to v3 (documented as advisory in .aidlc/review.md):

- P1 BasedHardware#2: None sentinel — DailyRefreshCache uses 'None' as the
  cache-empty sentinel, so legitimate None payloads can't be cached
  (loader is re-invoked on every call; stale fallback never triggers).
  Real v3 bug. Our usage (DailyRefreshCache[GatewayConfig]) never
  has None values, so the bug doesn't manifest in our path.
- P2 BasedHardware#5: docstring math is wrong — last_loaded_at + (monotonic_now()
  - last_loaded_at) simplifies to monotonic_now(). Just misleading
  docstring; doesn't affect behavior.

P1 #1 (schemas.py:117) — false positive. The reviewer is concerned
that adding the Evidence.placeholder field (default False) will
silently change route artifact content digests for existing
artifacts that omit the field. This was already addressed in commit
7c82adf ('fix: use placeholder flag instead of dev_only for R0
placeholders') which recomputed all 17 artifact_digests after adding
the field. Verified post-rebase: all 17 digests in
route_artifacts.yaml match the canonical body computed via
RouteArtifact.model_validate(...).content_digest.

Tests: 251 pass (was 248 pre-fix; +3 new cross-validation tests).
@choguun

choguun commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review — 4 of 5 findings addressed in commit f883fc286. P1 #1 was a false positive.

P1 #1 (schemas.py:117) — False positive. The reviewer is concerned that adding evidence.placeholder: bool = False will silently change content digests for existing artifacts that omit the field. This was already addressed in commit 7c82adf6f (the R0 placeholder fix) — all 17 artifact_digest values in route_artifacts.yaml were recomputed against the new canonical body. Verified post-rebase on this branch: every entry["artifact_digest"] matches RouteArtifact.model_validate(entry).content_digest. No fix needed.

P1 #2 (daily_refresh.py:59) — Deferred to v3. The None sentinel bug is real — legitimate None payloads can't be cached. Fix would require modifying the cherry-picked file, which breaks byte-equivalence with v3 (sha256 6e6897f5… no longer holds). Our usage is DailyRefreshCache[GatewayConfig], where GatewayConfig is a Pydantic model that can never be None — the bug doesn't manifest in our path. The proper fix is in v3 first (then re-cherry-pick on this branch). Deferred; documented as advisory in .aidlc/review.md.

P2 #3 (resolver.py:33) — Fixed. Added a required_lane_ids parameter to load_gateway_config. When provided, missing lane ids raise ConfigValidationError at load time (no longer deferred to runtime). dependencies.py:get_gateway_config now passes SUPPORTED_AUTO_LANE_IDS so the cross-check fires on every reload (startup AND mtime-driven). 3 new tests:

  • test_required_lane_ids_missing_raises
  • test_required_lane_ids_satisfied_succeeds
  • test_required_lane_ids_default_none_skips_cross_validation

P2 #4 (config_reload.py:88) — Fixed. Sync config loading inside async _load() now wraps the call in asyncio.to_thread(). The ~10-50ms YAML parse + Pydantic validation runs in a threadpool instead of blocking the event loop. Existing behavior preserved (same return value, same exception types).

P2 #5 (daily_refresh.py:77) — Deferred to v3. The docstring math is wrong (last_loaded_at + (monotonic_now() - last_loaded_at) simplifies to monotonic_now()). Docstring only — no behavior impact. Same byte-equivalence reason as P1 #2.

Cherry-pick discipline

The plan's R5a/R5b discipline keeps cherry-picked files byte-equivalent to v3. Two of cubic's findings (P1 #2 + P2 #5) are inside daily_refresh.py and would require modifying it. Trade-off:

  1. Defer real v3 bugs to v3 (where they belong per "improvements go to v3 first" rule)
  2. Preserve byte-equivalence so future re-cherry-picks from v3 are conflict-free
  3. Document this trade-off so it's visible

If v3 fixes P1 #2 / P2 #5 upstream, this branch's cherry-pick will diverge and need to be re-applied. The sha256 verification at cherry-pick time catches drift; this branch's test_daily_refresh.py parity tests pin the API contract.

Tests

251 pass (was 248 pre-fix; +3 cross-validation tests).

choguun added a commit to choguun/omi that referenced this pull request Jul 1, 2026
…ring

Per cubic-dev-ai review on PR BasedHardware#8744 (the same bug exists on v3):

1. None-sentinel bug (P1): DailyRefreshCache used None as the empty-
   cache sentinel, so legitimate None payloads couldn't be cached (loader
   was re-invoked on every call, stale fallback never triggered).
   Fix: introduce a private _MISSING = object() sentinel; update
   has_value, _is_fresh, the loader's success path, and the stale-
   fallback check to use `is _MISSING` / `is not _MISSING`.

2. Docstring math (P2): last_loaded_at property had a misleading
   formula 'last_loaded_at + (monotonic_now() - last_loaded_at)' which
   simplifies to `monotonic_now()` — still monotonic, not wall-clock.
   Fix: rewrite the docstring to honestly describe the limitation
   (use last_loaded_wall_time() for approximation, or have the loader
   record time.time() for exact wall-clock).

Tests: 18 pass (was 15; +3 regression tests for None-payload caching,
stale fallback with None, and the empty-cache sentinel).

Note: the cherry-pick on feat/auto-router-hot-reload (PR BasedHardware#8744) will
need a re-cherry-pick or the same fix applied to keep parity. v3 is
the source of truth; auto-router-hot-reload was previously a verbatim
copy (sha256 6e6897f5) and will diverge with this fix.
…bic fixes

Propagates the cubic-dev-ai P1 BasedHardware#2 + P2 BasedHardware#5 fixes from v3 (commit
`84e690464`) into the R5b cherry-pick. The cherry-pick is no longer
byte-equivalent to v3's pre-fix state — it's now sourced from v3's
post-fix state (sha256 `f9fed285e7d446224c19b9393f137f40591381726642e8eb084f164c204c06c1`).

What's in the fix:

- backend/llm_gateway/gateway/daily_refresh.py (now 168 LOC, was 159):
  - P1: `None` sentinel bug — introduce private `_MISSING = object()`
    sentinel. `has_value`, `_is_fresh`, the loader's success path, and
    the stale-fallback check now use `is _MISSING` / `is not _MISSING`
    instead of `is None` / `is not None`. Legitimate None payloads can
    now be cached; stale fallback correctly fires when a previously-
    cached None value is preserved across a failed refresh.
  - P2: `last_loaded_at` docstring math — the misleading formula
    'last_loaded_at + (monotonic_now() - last_loaded_at) = monotonic_now()'
    is replaced with an honest description: monotonic clock has no
    wall-clock meaning; use `last_loaded_wall_time()` for approximation
    or have the loader record `time.time()` for exact wall-clock.

- backend/tests/unit/llm_gateway/test_daily_refresh.py:
  - +3 regression tests for None-payload caching
    (TestNonePayloadCaching class): cache a None, stale-fallback a
    None, and the empty-cache sentinel. These tests would have failed
    against the pre-fix code.
  - Updated module docstring: documents the new sha256 + the fact
    that a previous verbatim copy (sha256 6e6897f5) predates this
    fix.

Tests: 254 pass (was 251 pre-fix; +3 None-payload regressions).

Cross-branch consistency: v3 source-of-truth now matches the
cherry-pick. Future re-cherry-picks from v3 will be conflict-free.

Per cubic-dev-ai review on PR BasedHardware#8744 (R5b).
@choguun

choguun commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

Update on the P1 #2 + P2 #5 fixes — both landed (in v3 and re-cherry-picked into this PR).

P1 #2 (None sentinel bug) — Fixed.

  • v3 commit 84e690464: fix(auto_router): use sentinel for cache-empty + fix misleading docstring — introduces private _MISSING = object() sentinel; updates has_value, _is_fresh, the loader's success path, and the stale-fallback check to use is _MISSING / is not _MISSING. Legitimate None payloads can now be cached; stale fallback correctly fires when a previously-cached None value is preserved across a failed refresh.
  • This PR commit ae613bb63: re-cherry-picked v3's updated daily_refresh.py into gateway/daily_refresh.py so the cherry-pick matches v3's current state. New sha256 f9fed285e7d446224c19b9393f137f40591381726642e8eb084f164c204c06c1 (was 6e6897f5… for the pre-fix verbatim copy).
  • +3 regression tests in TestNonePayloadCaching: cache a None, stale-fallback a None, empty-cache sentinel.

P2 #5 (docstring math) — Fixed.

  • v3 commit 84e690464: replaced the misleading formula 'last_loaded_at + (monotonic_now() - last_loaded_at) = monotonic_now()' with an honest description of the monotonic vs wall-clock distinction. Use last_loaded_wall_time() for approximation; have the loader record time.time() for exact wall-clock.
  • Re-cherry-picked into this PR as part of ae613bb63.

Cross-branch consistency

Both v3 and this branch now contain the same fix. Future re-cherry-picks from v3 are conflict-free.

Tests

  • v3: 18 pass (was 15; +3 None-payload regressions)
  • This branch: 254 pass (was 251; +3 None-payload regressions in test_daily_refresh.py)

Cherry-pick discipline (revised)

The plan's R5a/R5b discipline is to keep cherry-picked files byte-equivalent to v3. With the v3 source-of-truth fix, the cherry-pick on this branch is now in sync (both at sha256 f9fed285e7d446224c19b9393f137f40591381726642e8eb084f164c204c06c1). The module docstring in test_daily_refresh.py documents the sha256 transition for future maintainers.

All 5 findings on PR #8744 are now resolved.

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

backend feature: llm_gateway R5b config hot-reload — approve only

@Git-on-my-level Git-on-my-level added needs-maintainer-review Needs a human maintainer to sign off before merge feature-fit-review Needs review of product/feature direction with Omi mission/vision backend Backend Task (python) labels Jul 1, 2026
@Git-on-my-level

Copy link
Copy Markdown
Member

Maintainer Review — R5b (mtime-watched config hot-reload)

Thanks @choguun for the thorough work. The hot-reload design is sound — mtime polling, DailyRefreshCache stale-fallback, asyncio.to_thread for sync YAML loading, and the _MISSING sentinel fix are all well-executed. The cubic review findings were addressed diligently, and the commit messages are exemplary in their detail.

A few observations for human maintainer attention before merge:

1. Stacked dependency on R0 (#8739)
This PR bundles R0 changes (15 new lanes, expanded SUPPORTED_AUTO_LANE_IDS, Evidence.placeholder schema change, 1200+ lines of YAML config) alongside R5b hot-reload. PR #8739 is still open. If both merge, there will be conflicts. Consider: should this PR be split so R0 lands first, or is bundling intentional to avoid a rebase cycle? This needs a maintainer sequencing decision.

2. Model/provider routing surface
This expands the lane taxonomy from 1 to 16 lanes and touches model/provider routing — a security-sensitive surface. The shadow-mode rollout (percent=0, active==LKG) is the right day-one posture, but the architectural scope warrants maintainer sign-off on the lane taxonomy itself (are these the right 15 capabilities? correct objectives? appropriate credential policies?).

3. get_gateway_config() is now async
get_gateway_config() changed from a sync @lru_cache to an async function. FastAPI handles this transparently via Depends(), but any other callers in the codebase that invoke it synchronously would break. A codebase-wide grep shows only health.py and openai_compatible.py use it — both are FastAPI routes that handle async deps. This looks clean, but worth confirming no other module imports it.

4. Stale-fallback edge case
The stale-fallback design is correct (verified: DailyRefreshCache.invalidate() preserves _value, so the fallback works even after mtime-driven invalidation). One thing to note for ops: if config is corrupted and stays corrupted, the gateway serves the stale config indefinitely with only WARNING logs. This is the intended degraded posture, but ensure monitoring/alerting catches the WARNING.

5. Scope expansion in config_loader.py
Wrapping yaml.safe_load in try/except YAMLError is a reasonable hardening beyond strict R5b scope. It's small and correct, but it means this PR modifies the config loading contract, not just the caching layer.

Labels added: needs-maintainer-review, feature-fit-review, backend

Not formally approving — this is a large architectural PR touching model routing with a stacked dependency. Needs human maintainer judgment on the lane taxonomy and PR sequencing.

@Git-on-my-level

Copy link
Copy Markdown
Member

Independent Review — R5b (mtime-watched config hot-reload)

Thanks @choguun for the high-quality work. The hot-reload architecture is well-designed: mtime polling via os.stat(), DailyRefreshCache with double-checked locking, asyncio.to_thread for sync YAML loads, and the _MISSING sentinel fix are all correct and well-tested. CI is green across all 5 checks.

One technical finding the existing reviews haven't flagged:

Test fragility: sync mock for now-async get_gateway_config()
In test_llm_gateway_readiness.py, the invalid-config tests monkeypatch health.get_gateway_config with a sync function (def invalid_config(): raise ConfigValidationError(...)), but the /ready endpoint now calls await get_gateway_config(). This passes today only because the exception fires synchronously during the function call — before await evaluates the return value. If someone later changes the mock to return a value (or if the real function's error path changes), the await on a non-coroutine would raise TypeError. Consider updating the mocks to async def so they match the real interface contract. Not blocking, but worth addressing before merge.

Confirmations:

  • openai_compatible.py uses Depends(get_gateway_config) — FastAPI handles async deps transparently, so the sync->async change is safe for this caller.
  • required_lane_ids cross-validation in load_gateway_config is a good fail-fast guard.
  • Stale-fallback on persistent corruption serves indefinitely with only WARNING logs — ops should ensure monitoring catches this (as noted above).

Not formally approving. This is a large (2540-line) architectural PR that bundles R0 lane-taxonomy expansion (15 new lanes touching model/provider routing) alongside the R5b hot-reload mechanism, with a stacked dependency on #8739. Needs human maintainer judgment on PR sequencing and the lane taxonomy itself.

@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

backend Backend Task (python) feature-fit-review Needs review of product/feature direction with Omi mission/vision needs-maintainer-review Needs a human maintainer to sign off before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants