Skip to content

perf(notifications): select daily-summary recipients with an indexed query instead of re-reading every user (#13210) - #13213

Merged
Git-on-my-level merged 3 commits into
mainfrom
perf/notifications-materialized-schedule
Sep 9, 2026
Merged

Git-on-my-level merged 3 commits into
mainfrom
perf/notifications-materialized-schedule

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

Fixes #13210

Summary

The hourly notifications cron reads every user document that carries a time_zone on 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)

  • Materialize only the two existing preference fields, under their existing names. The Python defaults become write-time defaults on every path that writes time_zone or 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 explicit False or hour 0 is never overwritten. Legacy readers are unaffected, so the backfill is forward- and backward-compatible.
  • Keep the timezone → local-hour translation at read time (tzdata) and push it into the query as time_zone IN <=30 zones. The new per-hour-group, per-chunk query is daily_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 derived notification_hour_utc/notification_tz_offset/morning_hour_utc fields and the DST reconciliation job entirely — nothing can drift because nothing is derived.
  • Registered query. DAILY_SUMMARY_RECIPIENTS_QUERY in database/firestore_index_registry.py, built via spec.build(...); firestore.indexes.json regenerated (composite (daily_summary_enabled, daily_summary_hour_local, time_zone, __name__)). Equality + in with no orderBy is also servable by Firestore's automatic single-field indexes, so there is no FAILED_PRECONDITION cliff before the composite deploys.
  • Staged cutover. DAILY_SUMMARY_SELECTION_MODE=legacy|shadow|indexed (code default legacy, i.e. no behaviour change on merge). shadow sends from the legacy result and logs one daily_summary_selection_shadow hour=… legacy=N indexed=M only_legacy=K only_indexed=J sample_… line per hour group.
  • Overlap guard. start_cron_job takes a Redis SET NX EX lock (notifications_job:run_lock, 55 min) with a token compare-and-delete release; an overlapping execution logs notifications_job_run_skipped reason=overlap and skips the notification section (the existing checkpoint resumes the tail). Redis acquire errors fail open and record the shared daily_summary fallback counter.
  • One-time backfill backend/scripts/backfill_daily_summary_schedule_fields.py: pages users by __name__ with a field projection, writes only absent fields in <=500-op batches, dry-run by default (--apply), --start-after <uid> resume, --limit for smoke runs, JSON summary.

Deliberately out of scope

  • The 08:00 morning push (_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 on fcm_tokens.time_zone.
  • fcm_token_count denormalisation: post-fix the subcollection sweep is per recipient (<=1 per user per day).
  • Removing the legacy selector (follow-up after indexed has run in prod).
  • Runtime identity / SA migration and switching the audit log off (tracked in the issue).

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-retries are worth a look — something is multiplying executions.

Cutover runbook

  1. Merge; deploy the backend (write-time defaults go live; legacy cron behaviour unchanged).
  2. Run the backfill against prod once: python scripts/backfill_daily_summary_schedule_fields.py (dry-run, read the counts), then --apply. Re-runnable; writes only absent fields.
  3. Set DAILY_SUMMARY_SELECTION_MODE=shadow on notifications-job (runtime-env overlay), deploy, read one execution's daily_summary_selection_shadow lines: only_legacy should be 0 for every hour.
  4. Set DAILY_SUMMARY_SELECTION_MODE=indexed, deploy. Confirm read_ops_count on users drops; then turn off the data-access audit log per the issue.

Verification

Repository BasedHardware/omi, branch perf/notifications-materialized-schedule on top of origin/main f42089f53c, backend venv from ./scripts/sync-python-deps.sh (Python 3.11.15). Unit layer only; no live Firestore/Redis was touched.

backend/.venv/bin/python backend/scripts/generate_firestore_indexes.py         # matches the registry
backend/.venv/bin/python backend/scripts/firestore_query_coverage.py --check-ratchet   # pass (registered 77→81)
scripts/pr-preflight --pr-body-file /tmp/pr-body.md   (this body)
  → PR preflight passed: 30 checks   (incl. firestore-index-manifest, firestore-query-coverage, backend-import-purity, backend-runtime-image-source-closure, lifecycle-headers, agents-md-lean, dead-code-ratchet)
scripts/check_module_stub_pollution.py      → 1168 test files, 0 violations
scripts/scan_import_time_side_effects.py    → 987 production files, 0 violations

cd backend && .venv/bin/python -m pytest -q -p no:cacheprovider <file>   (run per file)
  test_daily_summary_selection_mode.py          13 passed   (new)
  test_daily_summary_schedule_fields.py         14 passed   (new)
  test_daily_summary_indexed_selection.py        6 passed   (new)
  test_backfill_daily_summary_schedule_fields.py 4 passed   (new)
  test_daily_summary_job_resilience.py          21 passed
  test_daily_summary_generation.py              30 passed
  test_daily_summary_race_condition.py          16 passed
  test_daily_notification_timezone_selection.py  2 passed
  test_notifications_job_orchestrator.py         8 passed
  test_other_notifications_async_boundaries.py   6 passed
  test_notification_async_boundaries.py          5 passed
  test_notifications_job_import.py               1 passed
  test_daily_summary_hour_midnight.py            3 passed
  test_desktop_daily_usage.py                    6 passed
  test_notification_database_sync_boundaries.py  1 passed
  test_notification_token_cleanup.py             3 passed
  test_firestore_indexes.py                      1 passed

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 shadow log line is the proof the selection sets match before indexed is 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

Review in cubic

Git-on-my-level and others added 3 commits September 8, 2026 17:37
…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]>
@Git-on-my-level Git-on-my-level added the backend Backend Task (python) label Sep 8, 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.

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 hour 0 during 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-after passes a UID string instead of a users document 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 before send_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)

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

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 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 [])

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

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 --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>
Suggested change
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

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

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: 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>

@Git-on-my-level
Git-on-my-level merged commit f32fef1 into main Sep 9, 2026
49 of 50 checks passed
@Git-on-my-level
Git-on-my-level deleted the perf/notifications-materialized-schedule branch September 9, 2026 01:57
Git-on-my-level added a commit that referenced this pull request Sep 9, 2026
## 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. -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(notifications): hourly cron re-reads entire users collection - materialize notification scheduling fields (~20-25% of all Firestore reads)

1 participant