Skip to content

perf(backend): adapt developer polling caches behind a cohort switch - #24413

Merged
Git-on-my-level merged 6 commits into
mainfrom
lane/ic-reads-devapi
Nov 2, 2026
Merged

Git-on-my-level merged 6 commits into
mainfrom
lane/ic-reads-devapi

Conversation

@Git-on-my-level

@Git-on-my-level Git-on-my-level commented Nov 2, 2026 •

Copy link
Copy Markdown
Member

Frequent developer-API conversation/memory list pollers may opt into 60–300-second responses, disclosed by X-Omi-List-Cache: fast-poller; max-age=N. Other clients and cursor pages retain 10 seconds. The adaptive cache is off by default through OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED=false and _PERCENT=0; the existing global list-cache switch also kills it. No rate limits or global TTL increase.

Cadence is atomic Redis time, scoped by hashed owner/app/key/credential and normalized query. Two distinct intervals under a minute qualify for 60 seconds, five for 120, ten for 300. Subsecond bursts do not qualify. Slow polls, faults, disabled cohorts and missing disclosure responses use the original namespace and cannot consume old extended entries. Authorization and scope validation still run before cache/list access; 401/403 regression coverage verifies this existing ordering. Actual conversation, daily-summary and goal item misses get a bounded 10-second negative cache within the same default-off cohort. Delayed fills cannot extend that lease; deleted, locked or corrupt nonempty objects are not admitted as missing.

Enabled-cohort goal detail GETs use the existing owner-scoped point reader, which can distinguish actual absence from a corrupt row skipped by list projection. Normalization errors retain an uncached 404 and repairs are visible on the next request. Off-cohort goal GETs keep the old list reader. Grade goals:get_all_goals and goals:get_goal_by_id together; a caller-label shift is not a saving. Disabled policy never touches identity metadata; unusable metadata bypasses the optimization safely.

Rollout owner: infracost. Enable 5%, require two verify ticks PASS, then 100% only against this item's own freshly pinned absolute reads/day baseline with clean 5xx and latency guards. First ramp decision is due within three days of deploy. Rollback: adaptive env off or existing global list cache off. The reviewed $13–16/day is estimated, not measured. Authentication already precedes list reads and action-item GET-by-ID is not a route, so status-code shares do not establish extra savings.

Validation: 140 targeted unit tests passed across eight files through bin/omi-heavy run -- nice -n 19 env BACKEND_UNIT_TEST_FILE_LIST=... BACKEND_PYTEST_WORKERS=4 bash backend/test.sh. The selection includes the three files identified by the first CI run. Tests cover encrypted list hits, real atomic Lua cadence, slow-poller/kill-switch namespace isolation while old long-lived entries remain, query/cursor isolation, no disclosure, fail-closed config, negative expiry/late fill, malformed-goal repair, off-policy metadata bypass and auth even on cache hits. Targeted type checks and the normal full push type gate report zero errors; all normal push hooks passed at the fix head. The router delegates cached item reads to a typed helper and is smaller than main; no line-count allowance is needed. Layer: hermetic route/cache and source-contract behavior; production savings await deployment and the graded ramp.

Product invariants affected

INV-MEM-4: existing canonical list authority is retained; only already-authorized complete responses may enter the explicitly disclosed fast-poller class.

Initiative: unit-economics
ANX: card:ic-reads-1102

@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 9 files

Confidence score: 3/5

  • In external_list_reads.py, Redis client construction can escape the cache’s fail-open boundary, so a construction failure may prevent the fallback read. Keep construction inside the exception boundary or catch the failure and use the 10-second fallback.
  • In external_list_reads.py, the fast-poller max-age can be sent even when the final page is not cache-eligible, which may cause clients to delay polling for uncached data. Emit the header only after confirming final-response eligibility.
  • In test_external_list_routes.py, the enabled-path test depends on the ambient OMI_EXTERNAL_LIST_CACHE_ENABLED value and can fail when the documented kill switch is set. Set the global cache switch to true in the test.
  • In external-list-reads.md, the rollback guidance says unset or 0 leaves every lever on, which conflicts with the polling controls’ default-closed behavior. Scope that guidance to the origin cache controls.
Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="backend/utils/external_list_reads.py">

<violation number="1" location="backend/utils/external_list_reads.py:240">
P1: The adaptive lookup can bypass the cache’s fail-open boundary when Redis client construction raises. Keep this call inside the existing exception boundary or catch construction failures and fall back to the 10-second TTL.</violation>

<violation number="2" location="backend/utils/external_list_reads.py:242">
P2: The response advertises a fast-poller max-age even when the final page is ineligible for caching. Emit this header only after final-response eligibility is confirmed, otherwise clients may suppress polls for data the server never cached.</violation>
</file>

<file name="backend/tests/unit/test_external_list_routes.py">

<violation number="1" location="backend/tests/unit/test_external_list_routes.py:126">
P2: This enabled-path test depends on the ambient `OMI_EXTERNAL_LIST_CACHE_ENABLED` value. Set the global cache switch to `true` here as well, otherwise a developer or CI environment with the documented kill switch set to `false` makes the test fail while it is intended to exercise the polling cache.</violation>
</file>

<file name="backend/docs/runbooks/external-list-reads.md">

<violation number="1" location="backend/docs/runbooks/external-list-reads.md:14">
P2: The rollback paragraph still says unset or `0` leaves every lever on, contradicting the new polling controls, which default closed and require `true` plus a positive cohort percentage. Scope the old rule to the original levers and document the polling enable conditions explicitly.</violation>
</file>

<file name="backend/utils/developer_item_reads.py">

<violation number="1" location="backend/utils/developer_item_reads.py:38">
P3: The negative-cache response repeats a hard-coded 10-second TTL instead of using `NEGATIVE_TTL`. Use the shared constant in all three headers so the disclosure stays aligned with Redis expiry.</violation>
</file>

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

View guided diff | Turn on auto-fix | Re-trigger cubic

return None # Busy or unavailable: origin only, never a short-cache fallback.
ttl = VERSIONED_TTL_SECONDS
elif response is not None and route in {'/v1/dev/user/conversations', '/v1/dev/user/memories'}:
ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)

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: The adaptive lookup can bypass the cache’s fail-open boundary when Redis client construction raises. Keep this call inside the existing exception boundary or catch construction failures and fall back to the 10-second TTL.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/external_list_reads.py, line 240:

<comment>The adaptive lookup can bypass the cache’s fail-open boundary when Redis client construction raises. Keep this call inside the existing exception boundary or catch construction failures and fall back to the 10-second TTL.</comment>

<file context>
@@ -234,6 +236,10 @@ def cached_list_response(
             return None  # Busy or unavailable: origin only, never a short-cache fallback.
         ttl = VERSIONED_TTL_SECONDS
+    elif response is not None and route in {'/v1/dev/user/conversations', '/v1/dev/user/memories'}:
+        ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)
+        if ttl > TTL_SECONDS:
+            response.headers['X-Omi-List-Cache'] = f'fast-poller; max-age={ttl}'
</file context>
Suggested change
ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)
try:
ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)
except Exception:
_fail_open('poll_cadence')
ttl = TTL_SECONDS

Comment thread backend/routers/developer.py Resolved
elif response is not None and route in {'/v1/dev/user/conversations', '/v1/dev/user/memories'}:
ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)
if ttl > TTL_SECONDS:
response.headers['X-Omi-List-Cache'] = f'fast-poller; max-age={ttl}'

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 response advertises a fast-poller max-age even when the final page is ineligible for caching. Emit this header only after final-response eligibility is confirmed, otherwise clients may suppress polls for data the server never cached.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/external_list_reads.py, line 242:

<comment>The response advertises a fast-poller max-age even when the final page is ineligible for caching. Emit this header only after final-response eligibility is confirmed, otherwise clients may suppress polls for data the server never cached.</comment>

<file context>
@@ -234,6 +236,10 @@ def cached_list_response(
+    elif response is not None and route in {'/v1/dev/user/conversations', '/v1/dev/user/memories'}:
+        ttl = polling_cache.adaptive_ttl(_redis(), request, uid, context, query)
+        if ttl > TTL_SECONDS:
+            response.headers['X-Omi-List-Cache'] = f'fast-poller; max-age={ttl}'
     identity = {
         'collection_version': version,
</file context>

@pytest.mark.parametrize('kind', ['conversations', 'daily-summaries', 'goals'])
def test_item_404_cache_runs_after_auth_and_isolates_owner_key_and_item(routes, monkeypatch, kind):
client, state, calls, _ = routes
monkeypatch.setenv('OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED', 'true')

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: This enabled-path test depends on the ambient OMI_EXTERNAL_LIST_CACHE_ENABLED value. Set the global cache switch to true here as well, otherwise a developer or CI environment with the documented kill switch set to false makes the test fail while it is intended to exercise the polling cache.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/tests/unit/test_external_list_routes.py, line 126:

<comment>This enabled-path test depends on the ambient `OMI_EXTERNAL_LIST_CACHE_ENABLED` value. Set the global cache switch to `true` here as well, otherwise a developer or CI environment with the documented kill switch set to `false` makes the test fail while it is intended to exercise the polling cache.</comment>

<file context>
@@ -109,10 +114,47 @@ def test_real_routes_cache_final_array_bytes_and_still_authorize(routes, path, o
[email protected]('kind', ['conversations', 'daily-summaries', 'goals'])
+def test_item_404_cache_runs_after_auth_and_isolates_owner_key_and_item(routes, monkeypatch, kind):
+    client, state, calls, _ = routes
+    monkeypatch.setenv('OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED', 'true')
+    monkeypatch.setenv('OMI_EXTERNAL_LIST_POLLING_CACHE_PERCENT', '100')
+    if kind == 'conversations':
</file context>
Suggested change
monkeypatch.setenv('OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED', 'true')
monkeypatch.setenv('OMI_EXTERNAL_LIST_CACHE_ENABLED', 'true')
monkeypatch.setenv('OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED', 'true')

Comment on lines +14 to 15
The original env levers default **on**. The polling controls below default **off** (false / zero). Only a case-insensitive, whitespace-trimmed
`false` disables a lever; unset, `0`, and other values leave it on.

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 rollback paragraph still says unset or 0 leaves every lever on, contradicting the new polling controls, which default closed and require true plus a positive cohort percentage. Scope the old rule to the original levers and document the polling enable conditions explicitly.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/docs/runbooks/external-list-reads.md, line 14:

<comment>The rollback paragraph still says unset or `0` leaves every lever on, contradicting the new polling controls, which default closed and require `true` plus a positive cohort percentage. Scope the old rule to the original levers and document the polling enable conditions explicitly.</comment>

<file context>
@@ -11,7 +11,7 @@ own write-invalidated negative cache. Hosted MCP JSON-RPC tools are outside this
 ## Behavior and rollback
 
-All env levers default **on**. Only a case-insensitive, whitespace-trimmed
+The original env levers default **on**. The polling controls below default **off** (false / zero). Only a case-insensitive, whitespace-trimmed
 `false` disables a lever; unset, `0`, and other values leave it on.
 
</file context>
Suggested change
The original env levers default **on**. The polling controls below default **off** (false / zero). Only a case-insensitive, whitespace-trimmed
`false` disables a lever; unset, `0`, and other values leave it on.
The original env levers default **on**; only a case-insensitive, whitespace-trimmed
`false` disables those original levers. The polling controls below default **off**: polling requires `OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED=true` and `OMI_EXTERNAL_LIST_POLLING_CACHE_PERCENT` between 1 and 100.

raise HTTPException(
404,
detail='Conversation ID not found or unknown conversation sub-route',
headers={'X-Omi-List-Cache': 'negative; max-age=10'},

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: The negative-cache response repeats a hard-coded 10-second TTL instead of using NEGATIVE_TTL. Use the shared constant in all three headers so the disclosure stays aligned with Redis expiry.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At backend/utils/developer_item_reads.py, line 38:

<comment>The negative-cache response repeats a hard-coded 10-second TTL instead of using `NEGATIVE_TTL`. Use the shared constant in all three headers so the disclosure stays aligned with Redis expiry.</comment>

<file context>
@@ -0,0 +1,83 @@
+            raise HTTPException(
+                404,
+                detail='Conversation ID not found or unknown conversation sub-route',
+                headers={'X-Omi-List-Cache': 'negative; max-age=10'},
+            )
+        conversation = conversations_db.get_conversation(uid, conversation_id)
</file context>

@Git-on-my-level
Git-on-my-level merged commit 6e226ea into main Nov 2, 2026
71 of 72 checks passed
@Git-on-my-level
Git-on-my-level deleted the lane/ic-reads-devapi branch November 2, 2026 19:35
Git-on-my-level added a commit that referenced this pull request Nov 2, 2026
…libration (#24426)

Add `omi_delivery_outcome_total{kind,outcome}` at durable summary
terminals, sync callback returns and action-item export boundaries.
Labels use only the fixed kinds `summary|sync|action_item_export` and
outcomes `delivered|no_op|deferred|failed`; unknown values are rejected
before creating metric children. Outcomes use the shared closed enum and
reason-label adapter without adding debt or allowlist exceptions.

Summary observations emit after the existing transaction commits, once
across retries, without changing existing first-summary receipts or
business state. An open summary obligation is deferred; deliberately
waived short-clip debt stays no-op. Sync holds, absent/redirected/open
targets and fences are deferred; discarded results remain no-ops even if
old summary text is retained. Deferred/locked processing results cannot
become delivered. Export counters observe each public result without
changing return values or provider calls; a device enqueue is deferred.
The counters measure attempts, including retries, rather than unique
deliveries. Helpers keep the existing oversized owner files from
growing.

The no-op alarm remains **unarmed**. Infracost records serving release
identities, traffic and visible counters, then collects seven full clean
days per kind and service after all serving traffic runs the new code.
Only then may a separate monitoring change propose a minimum-volume
six-hour no-op ratio threshold from the baseline. First baseline
progress decision is due within three days of deploy; it cannot shorten
the seven-day hold. No alert rule or production action is part of this
PR.

Both GMP keep-lists retain delivery/People counters, all existing metric
families, `omi_firestore_billed_reads_by_*` and
`omi_fsr_leader_lease_total`. The inventory refresh uses ro-prod
aggregate metric names, keeps observed names distinct from declarations
and preserves admission holds and legacy debt. No production account
data is read. Metrics ship on; lead-owned rollback is a later
code-revert train. No savings are booked for this instrumentation.

Validation: 1,086 unique unit cases passed across 20 selected files over
the implementation. After R1's two classification findings, all 113
focused debt/transaction/sync/parity cases and 29 hermetic E2E cases
passed again. Integration with the merged B/C main line then passed 241
combined unit cases, 29 E2E cases and monitoring lint. The
label-contract/audio selection passed all 149 cases (36 delivery, 19
enum contract, 94 audio-outbox); the old CI worker's nonzero audio
status did not reproduce locally. Targeted types report zero errors. All
tests ran through `bin/omi-heavy run -- nice -n 19`; units use
`backend/test.sh`, explicit file lists and four workers. Tests cover
committed-only emission through retries, debt preparation/waivers,
discard precedence, deferred/locked results, bounded labels,
canonical/legacy parity, export results and both GMP profiles. Malformed
observations preserve business results. The oversized owners retain
their exact original line counts (4652 and 3965), with no exception.

Main through `1708dc7859b0` (including merged #24413/#24422) is
integrated. The three GMP/inventory conflicts were resolved from the
full incoming main configuration, preserving every existing family and
admission/legacy-debt metadata. The fresh aggregate inventory contains
2,280 observed names and 17 declarations. Final CI and delta review
remain required.

## Product invariants affected

none

Initiative: unit-economics
ANX: card:ic-reads-1102
Git-on-my-level added a commit that referenced this pull request Nov 4, 2026
… polling cache (#24623)

## What

Config only. This turns on the adaptive developer-API polling cache from
#24413 (merged dark 11-02) for 5% of API keys on the Cloud Run `backend`
service:

- `OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED=true`
- `OMI_EXTERNAL_LIST_POLLING_CACHE_PERCENT=5`

Behavior is per `backend/docs/runbooks/external-list-reads.md`. Only
repeated identical Developer conversation/memory list queries from fast
pollers get the disclosed `X-Omi-List-Cache: fast-poller; max-age=N`
reuse (60/120/300s). Cursor requests and MCP keep their original
freshness, and grants, scope and rate limits still run before every
lookup.

## Why

The `/v1/dev/user/conversations` origin is about 0.45M reads/h
(firestore-reads snapshot 2026-11-04 16Z, coverage 0.70). This is part
of David's 2026-11-04 12-hour Firestore savings.
`config/feature-flags.yaml` names infracost (now cl2-infracost) as
expander with a 2026-11-05 decision date.

## Rollout

5% of API keys under the ordinary-lever policy (1-2h with guards), then
100% in a follow-up. Rollback: `ENABLED=false` or `PERCENT=0`, or the
global `OMI_EXTERNAL_LIST_CACHE_ENABLED=false`.

## Verification

- `pytest tests/unit/test_render_backend_runtime_env.py
tests/unit/test_backend_runtime_env_validator.py
tests/unit/test_runtime_env_manifest_compat.py
tests/unit/test_external_*`: all pass. The offline Cloud Run state
fixture gains the two declared envs.
- Local push gate ran with `BACKEND_UNIT_FILE_BUDGET_SECONDS=900`
because this host was at load ~50 and `test_firestore_query_shapes.py`
needed 202s just for fixture setup (it passes 544/544 when run
directly). CI keeps its own 300s budget.

## Product invariants affected

- INV-MEM-4 (path match on `backend/deploy/runtime_env.yaml` only; no
memory promotion behavior changes)

🤖 Generated with [Claude Code](https://claude.com/claude-code)


<!-- This is an auto-generated description by cubic. -->
<a
href="https://cubic.dev/pr/BasedHardware/omi/pull/24623?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/BasedHardware/omi/24623?returnTo=https%3A%2F%2Fgithub.com%2FBasedHardware%2Fomi%2Fpull%2F24623&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>
<!-- End of auto-generated description by cubic. -->
Dimank92 pushed a commit to Dimank92/omi that referenced this pull request Nov 4, 2026
… polling cache

Sets OMI_EXTERNAL_LIST_POLLING_CACHE_ENABLED=true and _PERCENT=5 on the Cloud
Run backend service (merged dark in BasedHardware#24413; owner infracost, decision due
2026-11-05 per config/feature-flags.yaml). Repeated identical developer
conversation/memory list polls get the disclosed 60/120/300s reuse; cursor
requests and MCP stay on their original path. Rollback: ENABLED=false or
PERCENT=0 (or the global OMI_EXTERNAL_LIST_CACHE_ENABLED=false).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant