Skip to content

fix(backend): fail-closed wear FCM on job-lock miss - #13356

Merged
Git-on-my-level merged 1 commit into
mainfrom
fix/wear-fcm-fail-closed
Sep 9, 2026
Merged

Git-on-my-level merged 1 commit into
mainfrom
fix/wear-fcm-fail-closed

Conversation

@Git-on-my-level

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

Copy link
Copy Markdown
Member

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.

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

Review in cubic

Wear bulk FCM rode notifications-job Redis fail-open and had no
per-user daily cap. Skip wear unless the run lock was acquired;
cap one send per uid per UTC day. Log notification_blast without uids.

Failure-Class: none

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

3 issues found across 4 files

Confidence score: 2/5

  • backend/database/redis_db.py can abort send_daily_notification() after users acquire locks but before buffered tokens are sent, leaving their 24-hour keys to suppress retries and potentially dropping notifications; catch Redis errors and retry or otherwise deliver the buffered tokens before returning.
  • backend/utils/other/notifications.py performs one blocking Redis round trip per user for large local-08 cohorts, which can significantly delay FCM delivery; use bounded concurrency or pipelined SET NX lock acquisition.
  • backend/tests/unit/test_daily_summary_selection_mode.py does not verify that wear_lock receives the required UTC date because _date is ignored, leaving a date-regression gap; assert the argument against notifications.datetime.now(...) in UTC.
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_selection_mode.py">

<violation number="1" location="backend/tests/unit/test_daily_summary_selection_mode.py:399">
P3: Because `wear_lock` ignores `_date`, this test passes even if `send_daily_notification()` supplies a local-calendar date instead of the required UTC date. Assert the argument against `notifications.datetime.now(notifications.pytz.utc).strftime('%Y-%m-%d')`, or freeze time, to cover the UTC-day invariant.</violation>
</file>

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

<violation number="1" location="backend/database/redis_db.py:1453">
P2: When Redis fails after one or more users acquire this lock, `send_daily_notification()` aborts before sending the buffered tokens, while those users' 24-hour keys prevent retrying them. Catch Redis errors here and return `False` so the caller skips only the affected UID and continues the blast.</violation>
</file>

<file name="backend/utils/other/notifications.py">

<violation number="1" location="backend/utils/other/notifications.py:940">
P2: When the wear flag is enabled for a large local-08 cohort, this loop performs one blocking Redis round trip per user sequentially before sending any FCM. Use bounded concurrent or pipelined `SET NX` lock acquisition so the per-user cap does not make the hourly job runtime scale with sequential network latency.</violation>
</file>

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

Re-trigger cubic


def try_acquire_daily_wear_lock(uid: str, date: str, ttl: int = 60 * 60 * 24) -> bool:
"""At most one wear FCM per uid per UTC day. True iff this caller may send."""
result = r.set(f'users:{uid}:daily_wear_lock:{date}', '1', ex=ttl, nx=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: When Redis fails after one or more users acquire this lock, send_daily_notification() aborts before sending the buffered tokens, while those users' 24-hour keys prevent retrying them. Catch Redis errors here and return False so the caller skips only the affected UID and continues the blast.

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

<comment>When Redis fails after one or more users acquire this lock, `send_daily_notification()` aborts before sending the buffered tokens, while those users' 24-hour keys prevent retrying them. Catch Redis errors here and return `False` so the caller skips only the affected UID and continues the blast.</comment>

<file context>
@@ -1448,6 +1448,12 @@ def try_acquire_daily_summary_lock(uid: str, date: str, ttl: int = 60 * 60 * 2)
 
+def try_acquire_daily_wear_lock(uid: str, date: str, ttl: int = 60 * 60 * 24) -> bool:
+    """At most one wear FCM per uid per UTC day. True iff this caller may send."""
+    result = r.set(f'users:{uid}:daily_wear_lock:{date}', '1', ex=ttl, nx=True)
+    return result is not None
+
</file context>
Suggested change
result = r.set(f'users:{uid}:daily_wear_lock:{date}', '1', ex=ttl, nx=True)
try:
result = r.set(f'users:{uid}:daily_wear_lock:{date}', '1', ex=ttl, nx=True)
except Exception as error:
logger.error('Failed to acquire daily wear lock uid=%s date=%s: %s', uid, date, error)
return False

for uid, tokens, _tz in recipients:
if not tokens:
continue
got = await run_blocking(db_executor, redis_db.try_acquire_daily_wear_lock, uid, date_str)

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 wear flag is enabled for a large local-08 cohort, this loop performs one blocking Redis round trip per user sequentially before sending any FCM. Use bounded concurrent or pipelined SET NX lock acquisition so the per-user cap does not make the hourly job runtime scale with sequential network latency.

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

<comment>When the wear flag is enabled for a large local-08 cohort, this loop performs one blocking Redis round trip per user sequentially before sending any FCM. Use bounded concurrent or pipelined `SET NX` lock acquisition so the per-user cap does not make the hourly job runtime scale with sequential network latency.</comment>

<file context>
@@ -926,31 +929,40 @@ async def send_daily_notification() -> None:
+        for uid, tokens, _tz in recipients:
+            if not tokens:
+                continue
+            got = await run_blocking(db_executor, redis_db.try_acquire_daily_wear_lock, uid, date_str)
+            if not got:
+                continue
</file context>

]
held: list[str] = []

def wear_lock(uid: str, _date: str, ttl: int = 60 * 60 * 24) -> bool:

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: Because wear_lock ignores _date, this test passes even if send_daily_notification() supplies a local-calendar date instead of the required UTC date. Assert the argument against notifications.datetime.now(notifications.pytz.utc).strftime('%Y-%m-%d'), or freeze time, to cover the UTC-day invariant.

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_selection_mode.py, line 399:

<comment>Because `wear_lock` ignores `_date`, this test passes even if `send_daily_notification()` supplies a local-calendar date instead of the required UTC date. Assert the argument against `notifications.datetime.now(notifications.pytz.utc).strftime('%Y-%m-%d')`, or freeze time, to cover the UTC-day invariant.</comment>

<file context>
@@ -365,7 +367,55 @@ def acquire(_token: str, ttl: int = 55 * 60) -> bool:
+        ]
+        held: list[str] = []
+
+        def wear_lock(uid: str, _date: str, ttl: int = 60 * 60 * 24) -> bool:
+            assert ttl == 60 * 60 * 24
+            if uid in held:
</file context>
Suggested change
def wear_lock(uid: str, _date: str, ttl: int = 60 * 60 * 24) -> bool:
def wear_lock(uid: str, date: str, ttl: int = 60 * 60 * 24) -> bool:
assert date == notifications.datetime.now(notifications.pytz.utc).strftime('%Y-%m-%d')

@Git-on-my-level
Git-on-my-level merged commit c9bb6ad into main Sep 9, 2026
46 checks passed
@Git-on-my-level
Git-on-my-level deleted the fix/wear-fcm-fail-closed branch September 9, 2026 20:48
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