Skip to content

fix(backend): make repeat GET /v1/action-items polls read-free - #12618

Merged
Git-on-my-level merged 2 commits into
mainfrom
fix/action-items-read-kill-switch
Sep 3, 2026
Merged

Git-on-my-level merged 2 commits into
mainfrom
fix/action-items-read-kill-switch

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

What exists today (measured, not assumed)

GET /v1/action-items was 65.6% of all backend requests and
48.8% of every billable Firestore document read (~$328/day) until #12258 made the
action_items:list policy immune to RATE_LIMIT_BOOST, so its 12/min per-uid cap
finally started firing. That fix worked, and it is not undone here.

I re-measured the route this afternoon before writing any code.

Prometheus, 24h means (2026-09-02):

before #12258 now
action_items_list docs/sec 6,600 692
action_items_list ops/sec 121 3.11
docs per operation 54.5 ~223
action_items_list share of stackdriver_..._document_read_count 48.8% ~13%

Cloud Run, untruncated fixed window 2026-09-02T17:46–17:49Z (545 requests, read-only capture):

  • 3.03 req/s (was 128–132), 97 distinct remote IPs — the drop came from each
    client polling less, not from clients disappearing.
  • 480 × 200, 64 × 429 (11.7%), 1 × 401. 63 of the 64 429s are omi-windows.
  • Client mix: 490 omi-windows, 31 Dart, 23 macOS CFNetwork, 1 Bun.
  • Query mix: limit=500&offset=0&completed=false 223, ...&completed=true 194,
    limit=50 37, limit=100 31, offset=500 28.

Two things follow, and they are the whole design rationale:

  1. The remaining problem is fan-out, not frequency. Documents-per-operation went
    up, 54.5 → ~223, because the cheap requests are exactly the ones the cap removed.
    What survives is large-backlog accounts re-reading an unchanged backlog on every
    allowed poll — 12 full backlog reads per minute per uid, forever.
  2. The stale fleet is still the traffic. 90% of surviving requests are the pre-fix
    omi-windows/1.0.0 build asking for limit=500, two weeks after its client-side fix
    (65249902cb, SYNC_THROTTLE_MS = 5 min, PAGE_LIMIT = 100) merged. Its rollout is
    still unobservable, so the backstop has to be server-side.

Honest scoping, stated up front: at 692 docs/sec this route is now ~$32/day
(marginal $0.05395/100k) out of a App Engine | Cloud Firestore Read Ops line running
$376.71/day (mean of the six complete post-ship days 08-27…09-01). This route is no
longer what dominates that line.
This PR takes the rest of it and caps the regression
path; it does not claim the other ~$340/day, which is uninstrumented read volume and
needs its own attribution work.

What changes

Three things, each independently disableable by one env var.

1. Repeat polls read zero Firestore documents (database/action_items_cache.py)

A per-uid Redis response cache for the unfiltered listing (98.6% of measured
traffic), plus an ETag / If-None-Match → 304 path.

  • Key is ail:{uid}:{version}:{param fingerprint}. The version is a per-uid counter
    that every action-item write bumps — one INCR, no key enumeration, no
    per-mutation invalidation list to drift out of sync. Invalidation is hooked into all
    12 mutating helpers in database/action_items.py, plus the two writers that touch the
    collection from outside that module (goals.transition_goal_lifecycle's detach
    disposition and staged_tasks.restore_legacy_conversation_items).
  • The TTL is the safety net, not the mechanism. If a future writer forgets to bump,
    the worst case is bounded staleness of ACTION_ITEMS_LIST_CACHE_TTL_SECONDS
    (default 30s, clamped to 300), never a permanently wrong list. The version key's
    own TTL is 7 days so a version can never expire back onto a live cached entry.
  • Truncated pages are never cached — caching a budget-exhaustion artifact would pin
    a partial page for the whole TTL and make a client's retry free.
  • Date- and conversation-scoped reads bypass the cache entirely (rare, high cardinality).
  • Redis is fail-open, matching _enforce_rate_limit's first-party contract: an
    outage degrades to today's behaviour (a real read), never to a wrong answer.

Why zero UX impact for an up-to-date client: any write by that user — from any
device, including the server-side conversation pipeline — bumps the version and the next
read is fresh. The only staleness window is a write that does not go through the hooked
paths, bounded at 30s. macOS and Flutter already reconcile at a 5-minute cadence.

2. A second, stricter ceiling for the hot-loop client class (utils/action_items_list_guard.py)

action_items:list_hot_client, default 4/60s per uid, env-tunable via
ACTION_ITEMS_LIST_HOT_CLIENT_MAX (0 disables). Returns 429 with Retry-After.

It composes with the existing limiter rather than conflicting with it. Two
independent Redis buckets: every client is still governed by action_items:list
(12/min), charged in the auth Depends() before the route body; a client additionally
classified as the hot-loop build is charged this second bucket inside the route, before
any Firestore work. Both must admit. Nothing about the existing policy's key, window, or
value changes, and the new policy is added to RATE_LIMIT_BOOST_EXEMPT's default for
the same reason as its parent — a cap chosen to stop a hot loop is not something an
event boost should widen 100×.

Classification is deliberately narrow: only the exact omi-windows/1.0.0 product token
counts as stale_windows. An unrecognised or absent user agent is not classified,
because a misclassification here degrades a real client and the 12/min policy already
covers the general case. (The stale build sends no X-App-Platform/X-App-Version on
this route, so the UA token is the only available discriminator.)

Blast radius: the ~90 hot-loop clients see a refresh every ~15s instead of every ~5s.
Their data stays correct, and that build already has 429-storm handling
(53d5b9e54a, observability/backendDegraded.ts).

3. Metrics that prove it (utils/metrics.py)

  • omi_action_items_list_cache_total{outcome} — hit | not_modified | miss | bypass | unavailable.
  • omi_action_items_list_throttled_total{client,policy} — 429s by client class.

These exist because the last three mitigations on this route were all merged and inert
in production, and nobody could tell for a week. hit/not_modified are, by
construction, the requests that performed zero Firestore reads.

What I did not build: the minimum-client-version gate

The backend has no client-version gate pattern to reuse, so per the brief I am
proposing rather than inventing one. What exists is routers/firmware.py's min_version
(device firmware, not API clients) and routers/desktop_chat.py:1592's 426 Upgrade Required for a chat contract version — neither is a general client gate, and there is
no X-App-Version header on this route to gate on. A proper version gate would need
(a) the Windows client to send X-App-Platform/X-App-Version on apiFetch as it
already does for JIT and listen, (b) a shared utils/client_version_gate.py reading a
per-platform minimum from env, and (c) a client that renders "update required" instead
of retrying. That is a cross-tree change with a client release in it; it should be its
own PR, and it is strictly worse than this one as a first move because it depends on
the same unobservable auto-update reach that made the server-side backstop necessary.

Can completed=false and completed=true be served from one read?

Not for these callers, and I would not change it here. The completed=None path already
reads both buckets in one request (active-first, then completed, product-sorted) — but
that returns one merged page, not the two bucket-scoped pages the Windows client asks
for, and swapping them changes pagination semantics for every client. The realistic wins,
both taken or already present: both buckets now share one invalidation version, so a
single write invalidates the pair and a paired poll costs at most one read per bucket per
TTL instead of two per cycle; and GET /v1/action-items/ids?completed= already exists as
the projection-only reconciliation path (action_items_visible_ids, 67 docs/sec in prod)
for clients that only need the id census.

Expected saving, and its basis

Basis: avg_over_time(sum(rate(omi_firestore_documents_per_operation_sum{family="action_items_list"}[1h]))[24h:10m])
= 691.9 docs/sec = 5.98e7 reads/day; marginal price $0.05395/100k (OLS on 14
complete billing-export days, r = 1.00000, evidence/2026-08-26-c006-falsification.md)
→ $32.3/day is the entire remaining prize for this family.

At a 30s TTL the cache bounds an idle user's polls to 2 Firestore reads/min instead of
12 — an 83% ceiling reduction — and the docs/op histogram says the hit rate will be high
(25.7% of these requests read zero documents even before caching). Discounting for
write-driven misses and the uncached filtered reads:

Expected: $20–27/day (~$7–10k/year), taking the line from a $376.71/day six-day
mean to roughly $350–357/day. Not a headline number — the headline was already
taken by #12258 (−$172.73/day, −31.4%, holding six days).

Kill-check — the metric that decides this within 24h of deploy

Measured 24h after the revision is confirmed serving (revision env / release SHA, never
merge status). Drop the newest two Cloud Monitoring buckets.

Primary (mechanism, decides it):

  1. sum(rate(omi_action_items_list_cache_total{outcome=~"hit|not_modified"}[1h])) / sum(rate(omi_action_items_list_cache_total[1h]))
    ≥ 0.5. Below 0.3 → the cache is not being hit and the change did not work; roll back.
  2. avg_over_time(sum(rate(omi_firestore_documents_per_operation_sum{family="action_items_list"}[1h]))[24h:10m])
    < 250 docs/sec (from 691.9). ≥ 500 → not supported.
  3. avg_over_time(sum(rate(omi_firestore_read_operations_total{family="action_items_list"}[1h]))[24h:10m])
    < 1.2 ops/sec (from 3.11).

Void conditions (re-run, do not record a result):

  • Distinct remoteIp on /v1/action-items in a 60s window drops below 60 (from 97) —
    a drop that comes from clients disappearing is churn or an outage, not a saving.
  • omi_action_items_list_throttled_total rises for any client other than
    stale_windows — that is a misclassification, and the ceiling should be zeroed.
  • /v1/action-items non-200/429 rate above 1%.

Money (confirmatory, 7 days): App Engine | Cloud Firestore Read Ops net $/day,
complete days only (verify MAX(usage_end_time)), against the 08-27…09-01 mean of
$376.71/day. Expect $350–357/day. This line is no longer dominated by this route, so
it cannot decide the change on its own — that is what the mechanism checks are for.

Rollback

Both levers are env vars on the serving revision; neither needs a code deploy:

  • ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=0 — disables the cache and the 304 path entirely;
    every read goes straight to Firestore, exactly as today.
  • ACTION_ITEMS_LIST_HOT_CLIENT_MAX=0 — disables the second ceiling; the 12/min
    action_items:list policy is untouched and keeps enforcing.
  • RATE_LIMIT_BOOST_EXEMPT still accepts an explicit list if the new policy needs to go
    back under the global boost.

Tests

backend/tests/unit/test_action_items_list_read_cost.py — 25 tests. They assert the
cost property, not just the body: a cache hit and a 304 are pinned to zero calls to
action_items_db.get_action_items
, the one function that streams documents. A test
that only checked the response would pass on a design that reads Firestore and throws the
result away — which is exactly the failure this change exists to prevent. Also covered:
write-driven invalidation, truncated pages never cached, filtered reads bypassing,
TTL clamping and typo tolerance, Redis-outage fail-open on both the cache and the ceiling,
the ceiling refusing before the database call, non-hot clients never touching the second
bucket, the 0 kill switch, UA classification (including "a UA that merely mentions
Windows is not the hot-loop build"), and RFC 9110 If-None-Match weak comparison.

Self-test — the real HTTP path, not the function

Unit tests call the handler directly, which does not exercise FastAPI's response
handling. I also drove the router over HTTP with TestClient (fake Firestore rows, fake
Redis, ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=30, ACTION_ITEMS_LIST_HOT_CLIENT_MAX=2),
counting calls to action_items_db.get_action_items across the sequence:

1  first        200 db_calls= 1 etag= W/"c000909dde9858350f2836fa6d929047"
2  repeat       200 db_calls= 1 same_body= True
3  If-None-Match 304 db_calls= 1 len(body)= 0
4  after write  200 db_calls= 2
5  hot 1/2/3 -> 200 200 429  retry_after= 11  db_calls= 4
6  mac after hot refusals -> 200

omi_action_items_list_cache_total{outcome="hit"} 1.0
omi_action_items_list_cache_total{outcome="not_modified"} 1.0
omi_action_items_list_cache_total{outcome="miss"} 5.0
omi_action_items_list_throttled_total{client="stale_windows",policy="action_items:list_hot_client"} 1.0

Line 2 and line 3 are the change: the repeat poll and the conditional request both return
without db_calls moving. Line 4 shows a write invalidating. Line 5 shows the hot-loop
ceiling refusing the third request with Retry-After and no database call, and line 6
shows a macOS client is unaffected by those refusals (separate bucket, separate key).

Gates run locally: make preflight — 28/28 pass. scripts/typecheck.sh — 0
errors. scripts/scan_async_blockers.py --dirs routers utils — 0 blocking findings.
Backend unit suites (run per file; batching these files has a pre-existing cross-module
import-pollution artifact on main as well): test_action_items_list_read_cost 25
passed, test_rate_limiting 84 passed/1 skipped, test_action_items_pagination_order 11
passed, test_action_items_router_pagination 4 passed, test_action_item_ids_endpoint 13
passed, test_action_items_conversation_list_malformed 3 passed,
test_action_item_canonical_contract 18 passed, test_mcp_action_item_writes 43 passed,
plus test_rate_limit_cache_cap, test_rate_limit_json_failopen,
test_action_item_dedup, test_action_item_date_validation,
test_action_items_date_coercion, test_action_items_due_range_index_contract,
test_conversation_action_items_count, test_action_items_timezone,
test_action_items_date_range_validation, test_action_item_reminder_cancel_on_complete,
test_action_item_vector_best_effort — all green.

Failure-Class: none

This is a cost control on a route that is behaving as designed, not a repair of a
semantic defect. scripts/failure-class prepare found no definition whose scope hints
overlap the change. (The nearest historical class, FC-alert-never-provably-fired,
belongs to #12258 — a limiter that shipped and never fired — and is already fixed; the
two new counters here exist so this change cannot repeat it.)

Line-Count-Exception: backend/database/action_items.py | 1543 -> 1562 | one bump_action_items_list_version(uid) call after each of the module's committed writes, plus the import; the module is the canonical mutation owner for this collection, so splitting it to add cache invalidation would move the invalidation away from the writes it must follow

🤖 Generated with Claude Code

Review in cubic

`action_items_list` was 48.8% of every billable Firestore document read
(~$328/day) until #12258 exempted the `action_items:list` policy from
`RATE_LIMIT_BOOST` and its 12/min per-uid cap started firing. That removed the
*frequency* half of the problem: 6,600 -> 692 docs/sec (24h mean, 2026-09-02),
121 -> 3.1 ops/sec, and a 3-minute prod capture shows the route at 3.0 req/s
with 11.7% 429s, 98% of them `omi-windows`.

What is left is fan-out, not frequency. Documents-per-operation went the other
way, 54.5 -> ~223, because the cheap requests are exactly the ones the cap
removed. The surviving traffic is large-backlog accounts, still 90% on the
pre-fix `omi-windows/1.0.0` build asking for `limit=500`, re-reading an
unchanged backlog on every allowed poll.

Three changes, all env-tunable and all off-by-one-env-var:

1. Per-uid response cache + ETag/`If-None-Match` -> 304 for the unfiltered
   listing. A cache hit and a 304 both perform zero Firestore reads. The key
   carries a per-uid version that every action-item write bumps, so a write
   invalidates every cached page for that user in one INCR — no key
   enumeration, no per-mutation invalidation list to keep in sync. The TTL
   (`ACTION_ITEMS_LIST_CACHE_TTL_SECONDS`, default 30s, 0 disables) is the
   safety net rather than the mechanism: a writer that ever forgets to bump
   costs bounded staleness, never a permanently wrong list.

2. A second, stricter ceiling for the known hot-loop client class
   (`action_items:list_hot_client`, `ACTION_ITEMS_LIST_HOT_CLIENT_MAX`,
   default 4/min, 0 disables). It composes with `action_items:list` rather
   than replacing it: every client keeps the 12/min bucket, and only the stale
   build is additionally charged the second one. Refusal happens before any
   Firestore work, so a throttled poll costs zero reads.

3. `omi_action_items_list_cache_total{outcome}` and
   `omi_action_items_list_throttled_total{client,policy}` — the metrics that
   prove within 24h of a deploy that the reads actually went away, instead of
   inferring it from the billing export a week later.

Classification is deliberately narrow: only the exact `omi-windows/1.0.0`
product token counts as hot. An unrecognised user agent is not, because a
misclassification here degrades a real client and the 12/min policy already
covers the general case. Redis is fail-open on both paths, matching
`_enforce_rate_limit`'s first-party contract.

Failure-Class: none

Co-Authored-By: Claude Fable 5.1 <[email protected]>

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

13 issues found across 10 files

Confidence score: 2/5

  • backend/routers/action_items.py can cache a pre-write Firestore snapshot under the new version during a concurrent write, causing subsequent polls to serve stale action items — capture the post-write state or invalidate after the commit.
  • backend/database/action_items.py leaves cached lists valid after candidate resolution and after partial update/delete commits, so newly created, changed, or deleted tasks can remain incorrect until TTL expiry — invalidate the UID after every successful mutation chunk or completed write.
  • backend/database/action_items_cache.py can serve stale version-0 data or accept malformed cached bodies/ETags, while backend/routers/action_items.py masks Redis errors as ordinary misses — treat malformed versions and entries as cache bypasses and propagate availability metrics distinctly.
  • backend/utils/action_items_list_guard.py still returns 429 when RATE_LIMIT_SHADOW_MODE=true, making the additive hot-client ceiling disruptive during shadow rollout — honor the shadow-mode setting before raising.
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/routers/action_items.py">

<violation number="1" location="backend/routers/action_items.py:426">
P1: When an action-item write commits while this request is reading Firestore, `_store_action_items_list_in_cache` can cache the pre-write snapshot under the new version. The next poll then serves stale data; capture the version for the read and publish only if that version is still current, or discard the result when it changed.</violation>

<violation number="2" location="backend/routers/action_items.py:434">
P2: When Redis fails while reading the cached entry, this branch records `miss` because `read_cached_list` returns `None` for both misses and errors. Propagate an unavailable result from the cache helper so rollout metrics distinguish Redis outages from genuine cache misses.</violation>
</file>

<file name="backend/database/goals.py">

<violation number="1" location="backend/database/goals.py:782">
P2: When this lifecycle uses `retain` or replays an idempotent request, no action-item document changes, but this unconditional bump invalidates the list cache and forces the next GET to read Firestore. Bump only after a successful, non-idempotent `detach` mutation.</violation>
</file>

<file name="backend/database/action_items.py">

<violation number="1" location="backend/database/action_items.py:14">
P1: Candidate resolution writes directly to the `action_items` collection without bumping the list version, so cached GETs can omit newly created or changed tasks until TTL expiry. Invalidate the UID after `resolve_task_candidate` commits, or route these writes through the shared mutation hook.</violation>

<violation number="2" location="backend/database/action_items.py:383">
P2: When an idempotent create retries an existing action item, this call invalidates the cached list even though Firestore was not mutated, forcing the next poll to read Firestore. Return whether the transaction created a document and bump the version only for an actual write.</violation>

<violation number="3" location="backend/database/action_items.py:383">
P2: When a later item update fails after earlier items were committed, this deferred bump is skipped and repeat polls can serve the pre-update cached list until TTL expiry. Invalidate once any update succeeds, including on partial-failure paths.</violation>

<violation number="4" location="backend/database/action_items.py:383">
P2: When a multi-chunk delete fails after an earlier chunk committed, this line is never reached and cached GET results can still contain deleted items for the TTL. Invalidate after each successful chunk, or invalidate from the failure path once any chunk has committed.</violation>
</file>

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

<violation number="1" location="backend/utils/metrics.py:558">
P2: When a pod has not yet served an action-items request or throttled a client, these counters export no series instead of zero-valued outcomes. Preinitialize the closed outcome and client/policy label combinations so monitoring can distinguish idle traffic from a missing scrape target.</violation>
</file>

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

<violation number="1" location="backend/utils/action_items_list_guard.py:53">
P3: A prerelease or patch-suffixed UA such as `omi-windows/1.0.0-beta` is classified as stale and limited to 4/min. Require a delimiter that excludes semver suffix characters after `1.0.0`.</violation>

<violation number="2" location="backend/utils/action_items_list_guard.py:96">
P2: When Redis is unavailable, this silently disables the hot-loop ceiling, so operators cannot distinguish healthy low throttling from a Redis outage. Record the shared `redis_ratelimit` degraded fallback before returning.</violation>

<violation number="3" location="backend/utils/action_items_list_guard.py:104">
P2: When `RATE_LIMIT_SHADOW_MODE=true`, this new hot-client bucket still rejects requests with 429. Honor `RATE_LIMIT_SHADOW` before raising so shadow mode also disables this additive ceiling.</violation>
</file>

<file name="backend/database/action_items_cache.py">

<violation number="1" location="backend/database/action_items_cache.py:77">
P2: When the Redis version value is malformed, `get_action_items_list_version` returns version `0` and can serve a stale version-0 page. Return `None` for malformed values so the route bypasses the cache and reads Firestore.</violation>

<violation number="2" location="backend/database/action_items_cache.py:150">
P2: When a Redis entry is valid JSON but has a non-dict `body` or non-string `etag`, `read_cached_list` accepts it and the route can raise or return a malformed cached response. Validate both value types here so corrupt or incompatible cache data is treated as a miss.</violation>
</file>

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

Re-trigger cubic

if params is None:
record_action_items_list_cache('bypass')
return None
version = get_action_items_list_version(uid)

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: When an action-item write commits while this request is reading Firestore, _store_action_items_list_in_cache can cache the pre-write snapshot under the new version. The next poll then serves stale data; capture the version for the read and publish only if that version is still current, or discard the result when it changed.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/action_items.py, line 426:

<comment>When an action-item write commits while this request is reading Firestore, `_store_action_items_list_in_cache` can cache the pre-write snapshot under the new version. The next poll then serves stale data; capture the version for the read and publish only if that version is still current, or discard the result when it changed.</comment>

<file context>
@@ -347,6 +359,128 @@ def _ensure_aware(value: datetime) -> datetime:
+    if params is None:
+        record_action_items_list_cache('bypass')
+        return None
+    version = get_action_items_list_version(uid)
+    if version is None:
+        # Redis could not answer. Fail open to a real read rather than risk
</file context>

@@ -11,6 +11,7 @@
from google.cloud import firestore

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: Candidate resolution writes directly to the action_items collection without bumping the list version, so cached GETs can omit newly created or changed tasks until TTL expiry. Invalidate the UID after resolve_task_candidate commits, or route these writes through the shared mutation hook.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/action_items.py, line 14:

<comment>Candidate resolution writes directly to the `action_items` collection without bumping the list version, so cached GETs can omit newly created or changed tasks until TTL expiry. Invalidate the UID after `resolve_task_candidate` commits, or route these writes through the shared mutation hook.</comment>

<file context>
@@ -11,6 +11,7 @@
 from google.cloud import firestore
 from google.cloud.firestore_v1 import FieldFilter
 
+from database.action_items_cache import bump_action_items_list_version
 from database.firestore_transaction_retry import run_with_transaction_contention_retry
 from database.firestore_read_metrics import FirestoreReadFamily, FirestoreReadMode, record_firestore_read
</file context>

return None
entry = read_cached_list(list_cache_key(uid, version, params))
if entry is None:
record_action_items_list_cache('miss')

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: When Redis fails while reading the cached entry, this branch records miss because read_cached_list returns None for both misses and errors. Propagate an unavailable result from the cache helper so rollout metrics distinguish Redis outages from genuine cache misses.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/routers/action_items.py, line 434:

<comment>When Redis fails while reading the cached entry, this branch records `miss` because `read_cached_list` returns `None` for both misses and errors. Propagate an unavailable result from the cache helper so rollout metrics distinguish Redis outages from genuine cache misses.</comment>

<file context>
@@ -347,6 +359,128 @@ def _ensure_aware(value: datetime) -> datetime:
+        return None
+    entry = read_cached_list(list_cache_key(uid, version, params))
+    if entry is None:
+        record_action_items_list_cache('miss')
+        return None
+
</file context>

Comment thread backend/database/goals.py
# A `detach` disposition clears goal_id on up to 450 action items, which
# changes what GET /v1/action-items returns. Invalidate the list cache here
# because this write does not go through database.action_items.
bump_action_items_list_version(uid)

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: When this lifecycle uses retain or replays an idempotent request, no action-item document changes, but this unconditional bump invalidates the list cache and forces the next GET to read Firestore. Bump only after a successful, non-idempotent detach mutation.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/goals.py, line 782:

<comment>When this lifecycle uses `retain` or replays an idempotent request, no action-item document changes, but this unconditional bump invalidates the list cache and forces the next GET to read Firestore. Bump only after a successful, non-idempotent `detach` mutation.</comment>

<file context>
@@ -774,7 +775,12 @@ def apply(write_transaction):
+    # A `detach` disposition clears goal_id on up to 450 action items, which
+    # changes what GET /v1/action-items returns. Invalidate the list cache here
+    # because this write does not go through database.action_items.
+    bump_action_items_list_version(uid)
+    return lifecycle_result
 
</file context>

operation_name="action_item_create",
),
)
bump_action_items_list_version(uid)

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: When an idempotent create retries an existing action item, this call invalidates the cached list even though Firestore was not mutated, forcing the next poll to read Firestore. Return whether the transaction created a document and bump the version only for an actual write.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/action_items.py, line 383:

<comment>When an idempotent create retries an existing action item, this call invalidates the cached list even though Firestore was not mutated, forcing the next poll to read Firestore. Return whether the transaction created a document and bump the version only for an actual write.</comment>

<file context>
@@ -371,14 +372,16 @@ def create_in_generation(write_transaction):
             operation_name="action_item_create",
         ),
     )
+    bump_action_items_list_version(uid)
+    return created_id
 
</file context>

allowed, _remaining, retry_after = check_rate_limit(
f"{uid}:{client_class}", HOT_CLIENT_POLICY, max_requests, window
)
except redis_pkg.exceptions.RedisError: # type: ignore[attr-defined]

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: When Redis is unavailable, this silently disables the hot-loop ceiling, so operators cannot distinguish healthy low throttling from a Redis outage. Record the shared redis_ratelimit degraded fallback before returning.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/action_items_list_guard.py, line 96:

<comment>When Redis is unavailable, this silently disables the hot-loop ceiling, so operators cannot distinguish healthy low throttling from a Redis outage. Record the shared `redis_ratelimit` degraded fallback before returning.</comment>

<file context>
@@ -0,0 +1,112 @@
+        allowed, _remaining, retry_after = check_rate_limit(
+            f"{uid}:{client_class}", HOT_CLIENT_POLICY, max_requests, window
+        )
+    except redis_pkg.exceptions.RedisError:  # type: ignore[attr-defined]
+        # Fail-open, exactly like the parent policy: the 12/min bucket already
+        # bounds this route, and a Redis outage must not 503 a read path.
</file context>

payload = json.loads(raw)
except (TypeError, ValueError):
return None
if not isinstance(payload, dict) or 'body' not in payload or 'etag' not in payload:

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: When a Redis entry is valid JSON but has a non-dict body or non-string etag, read_cached_list accepts it and the route can raise or return a malformed cached response. Validate both value types here so corrupt or incompatible cache data is treated as a miss.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/action_items_cache.py, line 150:

<comment>When a Redis entry is valid JSON but has a non-dict `body` or non-string `etag`, `read_cached_list` accepts it and the route can raise or return a malformed cached response. Validate both value types here so corrupt or incompatible cache data is treated as a miss.</comment>

<file context>
@@ -0,0 +1,179 @@
+        payload = json.loads(raw)
+    except (TypeError, ValueError):
+        return None
+    if not isinstance(payload, dict) or 'body' not in payload or 'etag' not in payload:
+        return None
+    return payload
</file context>
Suggested change
if not isinstance(payload, dict) or 'body' not in payload or 'etag' not in payload:
if not isinstance(payload, dict) or not isinstance(payload.get('body'), dict) or not isinstance(payload.get('etag'), str):

return

record_action_items_list_throttled(client=client_class, policy=HOT_CLIENT_POLICY)
raise HTTPException(

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: When RATE_LIMIT_SHADOW_MODE=true, this new hot-client bucket still rejects requests with 429. Honor RATE_LIMIT_SHADOW before raising so shadow mode also disables this additive ceiling.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/action_items_list_guard.py, line 104:

<comment>When `RATE_LIMIT_SHADOW_MODE=true`, this new hot-client bucket still rejects requests with 429. Honor `RATE_LIMIT_SHADOW` before raising so shadow mode also disables this additive ceiling.</comment>

<file context>
@@ -0,0 +1,112 @@
+        return
+
+    record_action_items_list_throttled(client=client_class, policy=HOT_CLIENT_POLICY)
+    raise HTTPException(
+        status_code=429,
+        detail=f"Rate limit exceeded. Try again in {retry_after}s.",
</file context>

logger.warning('ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=%r is not an integer; using default', raw)
return _TTL_DEFAULT_SECONDS
if ttl <= 0:
return 0

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: When the Redis version value is malformed, get_action_items_list_version returns version 0 and can serve a stale version-0 page. Return None for malformed values so the route bypasses the cache and reads Firestore.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/action_items_cache.py, line 77:

<comment>When the Redis version value is malformed, `get_action_items_list_version` returns version `0` and can serve a stale version-0 page. Return `None` for malformed values so the route bypasses the cache and reads Firestore.</comment>

<file context>
@@ -0,0 +1,179 @@
+        logger.warning('ACTION_ITEMS_LIST_CACHE_TTL_SECONDS=%r is not an integer; using default', raw)
+        return _TTL_DEFAULT_SECONDS
+    if ttl <= 0:
+        return 0
+    return min(ttl, _TTL_MAX_SECONDS)
+
</file context>
Suggested change
return 0
return None

# binaries producing this string are the ones whose sync engine predates
# 65249902cb). Anchored on the product token so an unrelated UA containing the
# word "windows" is never classified.
_STALE_WINDOWS_UA = re.compile(r"\bomi-windows/1\.0\.0\b")

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: A prerelease or patch-suffixed UA such as omi-windows/1.0.0-beta is classified as stale and limited to 4/min. Require a delimiter that excludes semver suffix characters after 1.0.0.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/action_items_list_guard.py, line 53:

<comment>A prerelease or patch-suffixed UA such as `omi-windows/1.0.0-beta` is classified as stale and limited to 4/min. Require a delimiter that excludes semver suffix characters after `1.0.0`.</comment>

<file context>
@@ -0,0 +1,112 @@
+# binaries producing this string are the ones whose sync engine predates
+# 65249902cb). Anchored on the product token so an unrelated UA containing the
+# word "windows" is never classified.
+_STALE_WINDOWS_UA = re.compile(r"\bomi-windows/1\.0\.0\b")
+
+
</file context>
Suggested change
_STALE_WINDOWS_UA = re.compile(r"\bomi-windows/1\.0\.0\b")
_STALE_WINDOWS_UA = re.compile(r"\bomi-windows/1\.0\.0(?![0-9A-Za-z.+-])")

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