Repository navigation
perf(notifications): select daily-summary recipients with an indexed query instead of re-reading every user (#13210) - #13213
Conversation
…d an indexed recipient query (#13210) The hourly daily-summary tick reads every user with a time_zone and filters daily_summary_enabled / daily_summary_hour_local in Python because both fields are absent on most documents. Make the two Python defaults (True, 22) write-time defaults on every path that writes time_zone or a preference, register a (daily_summary_enabled, daily_summary_hour_local, time_zone IN chunk) query in the Firestore index registry, and add get_users_for_daily_summary_indexed with the legacy selector's return shape. A one-time, dry-run-by-default backfill fills the absent fields on existing documents. Co-authored-by: Cursor <[email protected]>
…and guard overlapping job executions (#13210) DAILY_SUMMARY_SELECTION_MODE=legacy|shadow|indexed picks the per-chunk selector; legacy stays the code default until the backfill has run, and shadow logs per-hour set diffs between the two selectors so the flip is evidence-based. start_cron_job takes a Redis SET NX run lock with a token compare-and-delete release so an overlapping Cloud Scheduler fire skips the notification section instead of duplicating the pass; Redis acquire errors fail open and record the shared fallback counter. Co-authored-by: Cursor <[email protected]>
Co-authored-by: Cursor <[email protected]>
There was a problem hiding this comment.
6 issues found across 16 files
Confidence score: 2/5
- In
backend/utils/other/notifications.py, an indexed Firestore query failure is converted to an empty recipient list, after which the wrapper marks the chunk read; an outage could therefore acknowledge an hour without sending notifications. Propagate the query error before marking the chunk complete. - In
backend/database/notifications.py, a stale default patch can overwrite an explicit opt-out or hour0during concurrent schedule writes, potentially sending notifications to opted-out users or at the wrong time. Make the update conditional or preserve explicitly stored values. - In
backend/scripts/backfill_daily_summary_schedule_fields.py,--start-afterpasses a UID string instead of ausersdocument reference as the Firestore cursor, so resumable backfills fail before the next page. Convert the cursor to the expected document reference. - In
backend/utils/other/notifications.py, losing the run lock returns beforesend_daily_notification(), dropping regular push notifications for that hour rather than only skipping the daily-summary work. Separate lock handling for the daily-summary section from the regular notification path.
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/tests/unit/test_daily_summary_indexed_selection.py">
<violation number="1" location="backend/tests/unit/test_daily_summary_indexed_selection.py:51">
P2: The fake `_Query.stream` filters returned users only on `time_zone`, ignoring the `daily_summary_enabled == True` and `daily_summary_hour_local == H` filters that are the core of the new indexed query. Result-asserting tests would still pass if the implementation dropped or corrupted those two filters, as long as the filter object is still issued. Model the equality filters in the mock so the tests verify recipient selection, not just query issuance.</violation>
</file>
<file name="backend/utils/other/notifications.py">
<violation number="1" location="backend/utils/other/notifications.py:397">
P2: When an execution loses the run lock, this early `return` skips the entire hourly job, including `send_daily_notification()` — not just the daily-summary section — so that hour's regular push notifications are dropped too. The PR states the overlap guard should "resume from the existing checkpoint", but this returns out of `start_cron_job` entirely rather than resuming the summary from its checkpoint. Because the lock TTL (55 min) is shorter than the 60 min task timeout, a long-running prior tick makes the immediately following tick skip everything for everyone that hour.</violation>
<violation number="2" location="backend/utils/other/notifications.py:622">
P1: When an indexed Firestore query fails, the selector swallows the exception and returns an empty list. This wrapper then marks the chunk as read, so the hour can be acknowledged without sending any recipients; propagate chunk errors or return failure metadata so the next execution retries it.</violation>
</file>
<file name="backend/database/notifications.py">
<violation number="1" location="backend/database/notifications.py:94">
P1: When a token registration or daily-summary settings update races with another schedule write, this stale default patch can overwrite an explicit `False` or hour `0`, causing opted-out users or midnight users to receive summaries at the wrong setting. Materialize missing fields through a Firestore transaction or conditional update, and apply the same atomicity to the other new default writers.</violation>
</file>
<file name="backend/scripts/backfill_daily_summary_schedule_fields.py">
<violation number="1" location="backend/scripts/backfill_daily_summary_schedule_fields.py:61">
P2: When `--start-after` is used, the first Firestore query passes a UID string as the `__name__` cursor, so the resumable backfill fails before scanning the next page. Build a `users` document reference for the cursor, as the other Firestore pagination paths do.</violation>
</file>
<file name="backend/docs/runbooks/daily-summary-cutover.md">
<violation number="1" location="backend/docs/runbooks/daily-summary-cutover.md:28">
P3: In shadow mode the legacy selector is the primary pass whose result is sent, and the indexed selector is the one run additionally. 'Costs one extra legacy pass per execution' misstates which pass is extra; it costs one extra indexed pass.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| selector = notification_db.get_users_for_daily_summary | ||
| if DAILY_SUMMARY_SELECTION_MODE == 'indexed': | ||
| selector = notification_db.get_users_for_daily_summary_indexed | ||
| chunk_results = await _query_daily_summary_chunks(selector, timezone_chunks, target_hour) |
There was a problem hiding this comment.
P1: When an indexed Firestore query fails, the selector swallows the exception and returns an empty list. This wrapper then marks the chunk as read, so the hour can be acknowledged without sending any recipients; propagate chunk errors or return failure metadata so the next execution retries it.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/notifications.py, line 622:
<comment>When an indexed Firestore query fails, the selector swallows the exception and returns an empty list. This wrapper then marks the chunk as read, so the hour can be acknowledged without sending any recipients; propagate chunk errors or return failure metadata so the next execution retries it.</comment>
<file context>
@@ -521,26 +616,32 @@ async def _get_users_for_daily_summary(
+ selector = notification_db.get_users_for_daily_summary
+ if DAILY_SUMMARY_SELECTION_MODE == 'indexed':
+ selector = notification_db.get_users_for_daily_summary_indexed
+ chunk_results = await _query_daily_summary_chunks(selector, timezone_chunks, target_hour)
+ users, query_error, every_chunk_read = _reduce_daily_summary_chunks(chunk_results, target_hour)
+
</file context>
| if time_zone: | ||
| user_ref.set({'time_zone': time_zone}, merge=True) | ||
| schedule_patch['time_zone'] = time_zone | ||
| schedule_patch.update(daily_summary_schedule_defaults(user_data)) |
There was a problem hiding this comment.
P1: When a token registration or daily-summary settings update races with another schedule write, this stale default patch can overwrite an explicit False or hour 0, causing opted-out users or midnight users to receive summaries at the wrong setting. Materialize missing fields through a Firestore transaction or conditional update, and apply the same atomicity to the other new default writers.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/database/notifications.py, line 94:
<comment>When a token registration or daily-summary settings update races with another schedule write, this stale default patch can overwrite an explicit `False` or hour `0`, causing opted-out users or midnight users to receive summaries at the wrong setting. Materialize missing fields through a Firestore transaction or conditional update, and apply the same atomicity to the other new default writers.</comment>
<file context>
@@ -79,9 +85,15 @@ def save_token(uid: str, data: Dict[str, Any]) -> None:
if time_zone:
- user_ref.set({'time_zone': time_zone}, merge=True)
+ schedule_patch['time_zone'] = time_zone
+ schedule_patch.update(daily_summary_schedule_defaults(user_data))
+ if schedule_patch:
+ user_ref.set(schedule_patch, merge=True)
</file context>
| return [ | ||
| _UserDoc(uid, data) | ||
| for uid, data in self._collection.users.items() | ||
| if data.get('time_zone') in (zones or []) |
There was a problem hiding this comment.
P2: The fake _Query.stream filters returned users only on time_zone, ignoring the daily_summary_enabled == True and daily_summary_hour_local == H filters that are the core of the new indexed query. Result-asserting tests would still pass if the implementation dropped or corrupted those two filters, as long as the filter object is still issued. Model the equality filters in the mock so the tests verify recipient selection, not just query issuance.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/tests/unit/test_daily_summary_indexed_selection.py, line 51:
<comment>The fake `_Query.stream` filters returned users only on `time_zone`, ignoring the `daily_summary_enabled == True` and `daily_summary_hour_local == H` filters that are the core of the new indexed query. Result-asserting tests would still pass if the implementation dropped or corrupted those two filters, as long as the filter object is still issued. Model the equality filters in the mock so the tests verify recipient selection, not just query issuance.</comment>
<file context>
@@ -0,0 +1,184 @@
+ return [
+ _UserDoc(uid, data)
+ for uid, data in self._collection.users.items()
+ if data.get('time_zone') in (zones or [])
+ ]
+
</file context>
| last_uid: str | None = None | ||
| # The SDK only accepts a dict or a snapshot as a cursor; a bare uid string is | ||
| # rejected against ``order_by('__name__')``. Later pages cursor on the last snapshot. | ||
| cursor: Any = {'__name__': start_after} if start_after else None |
There was a problem hiding this comment.
P2: When --start-after is used, the first Firestore query passes a UID string as the __name__ cursor, so the resumable backfill fails before scanning the next page. Build a users document reference for the cursor, as the other Firestore pagination paths do.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/scripts/backfill_daily_summary_schedule_fields.py, line 61:
<comment>When `--start-after` is used, the first Firestore query passes a UID string as the `__name__` cursor, so the resumable backfill fails before scanning the next page. Build a `users` document reference for the cursor, as the other Firestore pagination paths do.</comment>
<file context>
@@ -0,0 +1,145 @@
+ last_uid: str | None = None
+ # The SDK only accepts a dict or a snapshot as a cursor; a bare uid string is
+ # rejected against ``order_by('__name__')``. Later pages cursor on the last snapshot.
+ cursor: Any = {'__name__': start_after} if start_after else None
+
+ batch = client.batch() if apply else None
</file context>
| cursor: Any = {'__name__': start_after} if start_after else None | |
| cursor: Any = {'__name__': client.collection('users').document(start_after)} if start_after else None |
| 'notifications_job_run_skipped reason=overlap utc_hour=%s', | ||
| datetime.now(pytz.utc).hour, | ||
| ) | ||
| return |
There was a problem hiding this comment.
P2: When an execution loses the run lock, this early return skips the entire hourly job, including send_daily_notification() — not just the daily-summary section — so that hour's regular push notifications are dropped too. The PR states the overlap guard should "resume from the existing checkpoint", but this returns out of start_cron_job entirely rather than resuming the summary from its checkpoint. Because the lock TTL (55 min) is shorter than the 60 min task timeout, a long-running prior tick makes the immediately following tick skip everything for everyone that hour.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/utils/other/notifications.py, line 397:
<comment>When an execution loses the run lock, this early `return` skips the entire hourly job, including `send_daily_notification()` — not just the daily-summary section — so that hour's regular push notifications are dropped too. The PR states the overlap guard should "resume from the existing checkpoint", but this returns out of `start_cron_job` entirely rather than resuming the summary from its checkpoint. Because the lock TTL (55 min) is shorter than the 60 min task timeout, a long-running prior tick makes the immediately following tick skip everything for everyone that hour.</comment>
<file context>
@@ -350,10 +376,33 @@ async def start_cron_job() -> None:
+ 'notifications_job_run_skipped reason=overlap utc_hour=%s',
+ datetime.now(pytz.utc).hour,
+ )
+ return
+
+ await send_daily_notification()
</file context>
| `--limit N` for a smoke run. Idempotent. | ||
| - **Mode** `DAILY_SUMMARY_SELECTION_MODE` (read by `utils/other/notifications.py`): | ||
| - `legacy` (code default) - the full-pass selector. | ||
| - `shadow` - legacy result is sent; the indexed selector also runs and one |
There was a problem hiding this comment.
P3: In shadow mode the legacy selector is the primary pass whose result is sent, and the indexed selector is the one run additionally. 'Costs one extra legacy pass per execution' misstates which pass is extra; it costs one extra indexed pass.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At backend/docs/runbooks/daily-summary-cutover.md, line 28:
<comment>In shadow mode the legacy selector is the primary pass whose result is sent, and the indexed selector is the one run additionally. 'Costs one extra legacy pass per execution' misstates which pass is extra; it costs one extra indexed pass.</comment>
<file context>
@@ -0,0 +1,51 @@
+ `--limit N` for a smoke run. Idempotent.
+- **Mode** `DAILY_SUMMARY_SELECTION_MODE` (read by `utils/other/notifications.py`):
+ - `legacy` (code default) - the full-pass selector.
+ - `shadow` - legacy result is sent; the indexed selector also runs and one
+ `daily_summary_selection_shadow hour=... legacy=N indexed=M only_legacy=K
+ only_indexed=J sample_only_legacy=[...] sample_only_indexed=[...]` line is
</file context>
## What changed and why Wear FCM (`omi says` / Wear your omi…) rode `notifications-job` Redis run-lock **fail-open** (maxmemory) and had no per-user daily cap, so a minute-cadence job could spam the local-08 cohort. - Call `send_daily_notification()` only when the job run lock was **acquired**. Summaries still fail-open (#13213). - Cap wear at one FCM per uid per UTC day (`try_acquire_daily_wear_lock`). - Log `notification_blast kind=wear users= tokens=` (no uid). Flag stays off (#3328). Related: #3328 (already closed — not Closes). Line-Count-Exception: backend/database/redis_db.py | 1605 -> 1611 | six-line wear daily lock next to daily_summary_lock; splitting redis_db is out of scope ## Product invariants affected none ## How it was verified `cd backend && python -m pytest tests/unit/test_wear_device_reminder.py tests/unit/test_daily_summary_selection_mode.py -m "not integration and not slow" -q` → 16 passed ## Failure-Class Failure-Class: none <!-- This is an auto-generated description by cubic. --> <a href="https://cubic.dev/pr/BasedHardware/omi/pull/13356?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="Review in cubic" src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a> <!-- End of auto-generated description by cubic. -->
Fixes #13210
Summary
The hourly notifications cron reads every user document that carries a
time_zoneon every execution and keeps ~1/24th of them in Python, because the two selection fields it filters on (daily_summary_enabled,daily_summary_hour_local) are absent on most documents and their defaults (True,22) exist only in code. This PR inverts the selection so Firestore returns only recipients, staged behind a mode so the cutover is evidence-based.Design (and where it differs from the issue's proposal)
time_zoneor a preference on the user doc (save_token,set_user_time_zone_if_missing,set_daily_summary_enabled,set_daily_summary_hour_local). Only absent fields are filled; an explicitFalseor hour0is never overwritten. Legacy readers are unaffected, so the backfill is forward- and backward-compatible.time_zone IN <=30 zones. The new per-hour-group, per-chunk query isdaily_summary_enabled == True AND daily_summary_hour_local == H AND time_zone IN chunk. Same result set as today's Python filter; ~30–40 small queries per execution that return only recipients, instead of one full pass. This drops the issue's derivednotification_hour_utc/notification_tz_offset/morning_hour_utcfields and the DST reconciliation job entirely — nothing can drift because nothing is derived.DAILY_SUMMARY_RECIPIENTS_QUERYindatabase/firestore_index_registry.py, built viaspec.build(...);firestore.indexes.jsonregenerated (composite(daily_summary_enabled, daily_summary_hour_local, time_zone, __name__)). Equality +inwith noorderByis also servable by Firestore's automatic single-field indexes, so there is no FAILED_PRECONDITION cliff before the composite deploys.DAILY_SUMMARY_SELECTION_MODE=legacy|shadow|indexed(code defaultlegacy, i.e. no behaviour change on merge).shadowsends from the legacy result and logs onedaily_summary_selection_shadow hour=… legacy=N indexed=M only_legacy=K only_indexed=J sample_…line per hour group.start_cron_jobtakes a RedisSET NX EXlock (notifications_job:run_lock, 55 min) with a token compare-and-delete release; an overlapping execution logsnotifications_job_run_skipped reason=overlapand skips the notification section (the existing checkpoint resumes the tail). Redis acquire errors fail open and record the shareddaily_summaryfallback counter.backend/scripts/backfill_daily_summary_schedule_fields.py: pagesusersby__name__with a field projection, writes only absent fields in <=500-op batches, dry-run by default (--apply),--start-after <uid>resume,--limitfor smoke runs, JSON summary.Deliberately out of scope
_get_users_in_timezones) reads ~1/24th of users once per day (~3K docs + subcollection sweeps) — <0.2% of this lane. Follow-up: collection-group query onfcm_tokens.time_zone.fcm_token_countdenormalisation: post-fix the subcollection sweep is per recipient (<=1 per user per day).indexedhas run in prod).Discrepancy worth checking during rollout
One full pass per execution is ~78K reads; 24 executions/day is ~1.9M reads/day. The measured 100–140M/day implies roughly 60 full passes per hour. This PR removes the per-pass cost regardless, but Cloud Scheduler cadence, the job's task count, and Cloud Run
--max-retriesare worth a look — something is multiplying executions.Cutover runbook
python scripts/backfill_daily_summary_schedule_fields.py(dry-run, read the counts), then--apply. Re-runnable; writes only absent fields.DAILY_SUMMARY_SELECTION_MODE=shadowonnotifications-job(runtime-env overlay), deploy, read one execution'sdaily_summary_selection_shadowlines:only_legacyshould be 0 for every hour.DAILY_SUMMARY_SELECTION_MODE=indexed, deploy. Confirmread_ops_countonusersdrops; then turn off the data-access audit log per the issue.Verification
Repository
BasedHardware/omi, branchperf/notifications-materialized-scheduleon top oforigin/mainf42089f53c, backend venv from./scripts/sync-python-deps.sh(Python 3.11.15). Unit layer only; no live Firestore/Redis was touched.Not exercised here: the indexed query against a real Firestore (emulator or dev) and the backfill against real data. Step 2–3 of the runbook is the live verification; the
shadowlog line is the proof the selection sets match beforeindexedis turned on.Product invariants affected
none
Failure class (fixes)
Failure-Class: none
Line-Count-Exception: backend/database/firestore_index_registry.py | 1510 -> 1527 | the registry is the repo-mandated single home for serving query specs (firestore-query-coverage ratchet); one new FirestoreQuerySpec
Line-Count-Exception: backend/database/redis_db.py | 1570 -> 1605 | run-lock acquire/release placed beside the existing daily-summary lock helpers it mirrors; the test harnesses stub this module by attribute