Repository navigation
Conversation
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
2 issues found across 4 files
Confidence score: 3/5
- In
backend/utils/other/notifications.py, the inlineday_summary_webhookcan consume up to 30 seconds of the per-user 90-second_send_summary_notificationbudget, potentially delaying or preventing the user's recap and push; keep the webhook from consuming that user-facing timeout or add coverage for the timeout interaction. - In
backend/tests/unit/test_daily_summary_generation.py, the failure-path test does not verify the requireddaily_summary_webhook_failedlog line, leaving the stated observability acceptance criterion unprotected; assert the log entry and relevant failure details.
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_generation.py">
<violation number="1" location="backend/tests/unit/test_daily_summary_generation.py:421">
P3: test_a_failing_webhook_does_not_cost_the_user_their_recap verifies fault containment (recap + push survive) but never asserts the `daily_summary_webhook_failed` log line, which is the PR's stated acceptance criterion. If the `except Exception` branch's `logger.error` were later dropped, this test stays green and the failure becomes as silent as the old swallowed Future — the exact defect #12530 fixed. Add `caplog` and assert the record for the raising webhook.</violation>
</file>
<file name="backend/utils/other/notifications.py">
<violation number="1" location="backend/utils/other/notifications.py:567">
P2: The inline webhook now runs inside the per-user `asyncio.wait_for` budget (90s) that governs `_send_summary_notification`, but `day_summary_webhook` can block the postprocess worker thread for up to its 30s httpx timeout. A slow webhook therefore consumes budget that previously was not charged to the user, so a user whose push was already delivered can be marked `reason=user_budget_exceeded` and count toward `DAILY_SUMMARY_MAX_ABANDONED_USERS`, aborting the remaining batch. Consider bounding the webhook within its own sub-timeout (e.g. `asyncio.wait_for(..., timeout=...)`) so a slow receiver cannot exhaust the user's recap budget, or explicitly budget the webhook separately.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
The daily-summary developer webhook was submitted fire-and-forget:
postprocess_executor.submit(asyncio.run, day_summary_webhook(...))
Two defects in one line. _deliver_current_day_summary already runs *on*
postprocess_executor -- send_daily_summary_notification dispatches every
user through run_blocking(postprocess_executor, _send_summary_notification,
...) -- so the submit made the coordinator its own child on the pool it was
running on, the arrangement backend/AGENTS.md forbids. And nothing owned the
result: the per-user asyncio.wait_for budget covers the call, not what the
call spawns, and the Cloud Run Job exits without joining the pool. A webhook
still queued at exit was never scheduled, which is the
coroutine 'day_summary_webhook' was never awaited
logged immediately before container exit in BasedHardware#12530's evidence.
c82237e fixed the batching half of BasedHardware#12530 with a deadline and a resumable
cursor. That bounds the batch; it does not give this coroutine an owner.
Run it inline, inside the per-user budget that governs the rest of that
user's work. The push moves ahead of it and becomes a branch rather than an
early return, so a tokenless user still reaches their webhook as before. The
call is wrapped because inline changes who pays for a fault: day_summary_webhook
handles its own HTTP failures but not the work around them, and an escaping
error would mark a user whose push already went out as failed. The discarded
Future used to supply that containment by accident; make it a decision, and
log it, where the old path reported nothing.
Also returns 8 slots per batch to postprocess_executor -- the pool
DAILY_SUMMARY_MAX_ABANDONED_USERS exists to protect.
Failure-Class: new
Co-Authored-By: Claude Opus 5 <[email protected]>
Running the webhook inline gave it an owner, but it also moved its cost onto the user. day_summary_webhook posts through the shared client (30s read timeout, retries at 1/5/30s) and now sits inside the per-user asyncio.wait_for budget, so a slow receiver could burn most of DAILY_SUMMARY_USER_BUDGET_SECONDS and get a user whose push had already been delivered marked reason=user_budget_exceeded -- which counts toward DAILY_SUMMARY_MAX_ABANDONED_USERS and can abort the rest of the hour group. A developer webhook must not be able to cost anyone their recap. Bound it at DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS (20s, env-overridable), well inside the 90s budget it shares. The existing except already contains and logs the resulting timeout. Verified by mutation: with the bound removed the new test reports "the webhook must be abandoned at its own budget, took 30.0s"; with it, the webhook is abandoned at its own budget and the record and push both survive. Also assert the daily_summary_webhook_failed log line in the containment test. Containment without the log is the old swallowed Future by another name -- the fault disappears and BasedHardware#12530's evidence never reappears -- so the test now pins the record rather than only that nothing raised. The source pin follows the new wiring: it still forbids the submit, and now requires the timeout constant rather than a bare asyncio.run call. Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
e1e30aa to
a7ab35a
Compare
|
Verified this end to end against the head - the diagnosis holds up and the fix is the right shape. backend/utils/other/notifications.py - Confirmed the core claim: backend/tests/unit/test_daily_summary_generation.py - The behavioral coverage is thorough: completion-before-return (with a submit stub that raises, so reintroducing the pool wiring can't pass silently), tokenless delivery, dict payload shape, fault containment with the caplog assertion, and the real-time budget test. The harness fake becoming a real coroutine is the right call - a sync stub would have tested the harness. backend/tests/unit/test_async_http_infrastructure.py - Inverting the #7387 source pin is correct: the negative half ("not submitted anywhere") genuinely can't be expressed behaviorally, and the positive assertion on .github/failure-classes/FC-pool-submitted-work-without-lifecycle-owner.json - Ran the repo's The earlier review's two concerns (webhook consuming the per-user 90s budget; missing log assertion) are verifiably resolved on Leaving for human maintainer review: this sits in the same failure domain as the #12530 incident machinery, so the 20s webhook budget default and the push-before-webhook ordering deserve a sign-off from someone familiar with that incident's production evidence. by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with |
… evidence Two documentation-accuracy notes from review. The TestNotificationWebhookWiring docstring still said the webhook is "wired through storage_executor" -- stale across two rewirings. It was storage_executor, then postprocess_executor (BasedHardware#7387), and is now an inline awaited call bounded by its own budget. The class name predates all of that, so the docstring now records the sequence and why the current shape is what it is. evidence_prs cited BasedHardware#12588, which was closed unmerged. Replaced with BasedHardware#12742 rather than the suggested BasedHardware#12635: BasedHardware#12635 landed c82237e, the batching/cursor fix that belongs to FC-batch-fault-domain-head-of-line-poison, and it did not touch the pool-lifecycle defect this class describes. Citing it would attribute this class to a change that never addressed it. This PR is where the class is both defined and fixed, which matches FC-task-candidate-unowned-commitment citing its own defining PR. scripts/failure-class validate: OK (fix commits=True; declaration=new). Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
|
Both documentation notes fixed on Docstring.
#12635 landed This PR is where the class is both defined and fixed, which matches Verification
On the maintainer sign-off you flagged: agreed that the 20s webhook default and the push-before-webhook ordering are the two judgement calls here, and both sit in #12530's blast radius. For whoever picks it up — the ordering is deliberate (the recap is the owner-visible artifact, the webhook is developer integration, and the webhook stays outside the |
…ry-webhook-drain One conflict, in the daily-summary generation harness, plus a mechanical follow-on. main added a memories_learned_payload stub -- without it the scheduled path reaches the real MemoryService and issues a live Firestore query from a unit test, which hangs under api_core's retry. Kept, with its comment. The same hunk re-added two stubs this branch deliberately removes: postprocess_executor.submit and a *sync* day_summary_webhook lambda. Both are superseded here. The webhook is awaited inline now, so a sync stub would hand asyncio.run a None and make the harness the thing under test, and the submit stub would mask the assertion that nothing is submitted back to the pool. Dropped both; the real coroutine fake below replaces them. main also added six tests that unpack the harness as a 4-tuple, which this branch widened to 5 to expose the recorded webhook calls. Widened those six call sites the same way, matching the ones already converted. Suites after the merge: generation 27, async_http_infrastructure 50, async_webhooks 29, race_condition 16, job_resilience 21, lock_bypass_fixes 62, other_notifications_async_boundaries 6, empty_overview 2. Co-Authored-By: Claude Opus 5 <[email protected]>
|
Merged current The conflict was in The same hunk also re-added two stubs this branch deliberately removes:
The real coroutine fake further down replaces both. The follow-on: After the merge
Merged rather than rebased, so the review history on the earlier heads stays intact. The production change is unchanged by the merge — |
undivisible
left a comment
There was a problem hiding this comment.
Verdict: REQUEST_CHANGES
Direction is right for #12530: stop submitting day_summary_webhook back into postprocess_executor from a worker already on that pool, run it inline with explicit fault containment, keep it outside the FCM-token early-return, and bound it with DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS (cubic P2 addressed in a7ab35a). Tests + FC artifact look strong.
Blocking
Backend unit suite is red on this head (run):
tests/unit/test_batch_upload_storage.py/tests/unit/test_merge_validation.py- Setup ERROR:
ModuleNotFoundError: No module named 'models.client_processing'
Those paths are not in this PR’s diff (only notifications.py + daily-summary / async-http tests + FC json). Looks environmental / unrelated — please re-run the Backend Unit Tests workflow (or fix the missing module on the branch) so the required check is green before merge.
Non-blocking
- Cubic P3 log assertion was addressed — good.
- Once unit suite is green I’ll re-review toward approve.
Not merging.
Follow-up (after fuller re-read)Still blocked on green Backend unit (unrelated Residual design ask once CI is green: the bounded webhook still runs inside |
Review point, and it is right. Running the webhook inline gave it an owner but put its cost inside DAILY_SUMMARY_USER_BUDGET_SECONDS, which the owner's own backfill walk also spends. Sitting ahead of the backfill, a slow receiver could take up to DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS that the owner's missing days needed, and tip a marginal user into user_budget_exceeded -- counting toward DAILY_SUMMARY_MAX_ABANDONED_USERS and abandoning the rest of the hour group. That contradicted the rule this change exists to uphold, which the code comments already stated: a developer webhook must never cost the owner their recap. Backfill is owner work. Last in the per-user budget means the webhook can only ever spend what nobody else still wants. Lifted out of _deliver_current_day_summary into _deliver_day_summary_webhook and driven from _send_summary_notification's finally. finally rather than a trailing call, because the dormant-owner branch returns before the backfill and the backfill itself can raise: either would drop the webhook for a user whose summary was already generated, stored and pushed -- the same unowned-work loss this PR exists to stop, just moved to a different exit. The bound, the containment and the daily_summary_webhook_failed log are unchanged, as is the payload call, so TestSendSummaryNotificationWiresSummaryJson still pins day_summary_webhook(uid, str(summary_data), summary_data) exactly. Three tests. Ordering is mutation-checked: with the webhook restored to its old position the assertion reports "the webhook must run after every backfill generation, not before them", assert 1 == 4. The other two cover the finally -- a raising backfill still sends the webhook, and a dormant owner is unaffected. Suites: generation 30, async_http_infrastructure 50, async_webhooks 29, job_resilience 21, lock_bypass_fixes 62, other_notifications_async_boundaries 6, race_condition 16, empty_overview 2. Failure-Class: none Co-Authored-By: Claude Opus 5 <[email protected]>
|
Pushed the reordering on The webhook now runs after the backfill. Running it inline gave it an owner but put its cost inside Lifted into The bound, the containment and the Three tests, and the ordering one is mutation-checked — restoring the webhook to its old position gives: The other two cover the On the red Backend unit suiteRe-running will not clear it — I checked before answering, and it is not this branch.
Filed as #12779 with that evidence, since it blocks unrelated PRs and a re-run can go green by luck and hide it. Not something I can fix from here — it sits in the conversations/merge isolation harness. |
undivisible
left a comment
There was a problem hiding this comment.
Verdict: still request changes
Re-reviewed a3ddd55b against the prior REQUEST_CHANGES.
Addressed since last review
- Webhook after owner backfill:
_deliver_day_summary_webhookruns from_send_summary_notification'sfinallyafter the backfill walk (and still after a dormant early-return / raising backfill). Bound + containment +daily_summary_webhook_failedunchanged. Ordering / finally / dormant tests look right. - Ownership shape remains correct: no
postprocess_executor.submitofday_summary_webhook; inlinewait_forunderDAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS.
Still blocking
Backend unit suite is still red on this head (run 33949824478):
- Setup ERROR:
ModuleNotFoundError: No module named 'models.client_processing' - Paths not in this PR’s diff (
test_batch_upload_storage/test_merge_validation)
Agree this matches open #12779 / red main, not a defect introduced here. Still: required check is red, so keeping CHANGES_REQUESTED until unit is green (merge of a #12779 fix, or equivalent). Happy to approve the webhook change the moment that gate flips.
Not merging.
|
The gate you are waiting on now has a fix in flight: #12546. Root cause confirmed and reproduced. #12546 defers that import to its only consumer, so no Nothing about this PR changes. Flagging it because the condition you named — unit green via "merge of a #12779 fix, or equivalent" — now has a candidate. |
undivisible
left a comment
There was a problem hiding this comment.
Verdict: APPROVE
Re-reviewed a3ddd55b (reorder after prior REQUEST_CHANGES). Design ask is met; residual Backend unit red is #12779 / main noise, not this PR.
Verified
- Lifecycle owner:
_deliver_day_summary_webhookruns inline viaasyncio.run(asyncio.wait_for(..., timeout=DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS))— nopostprocess_executor.submitofday_summary_webhook. Source pin + submit-explodes behavioral test both hold. - After owner backfill:
pending_webhookdeferred;finallydelivers after_backfill_recent_daily_summaries(and still after a raising backfill). Ordering / backfill-failure tests look right. Webhook can only spend budget nobody else still wants. - Containment:
daily_summary_webhook_failed+ try/except; push is a branch so tokenless users still reach the webhook; slow webhook bound keeps it from burning the 90s user budget. - Diff scope: 4 files (
notifications.py+ daily-summary / async-http tests + FC json).models.client_processinghermetic stub ERROR in merge suites is open #12779 on main — not introduced here.
Non-blocking follow-ups
test_a_dormant_owner_still_reaches_their_webhookdocstring overstates: dormant early-return impliescreated=False, sopending_webhookis already None;finallyis load-bearing for raising backfill, which is covered.- Assigning
pending_webhookbefore_deliver_current_day_summarywould keep the webhook if push raises (old submit had already queued). Marginal.
Not merging while Backend unit may be red on main.
undivisible
left a comment
There was a problem hiding this comment.
Verdict: approve (re-review)
Superseding my prior REQUEST_CHANGES on review state only, aligning with CoS GLM re-review @ a3ddd55.
Verified
- Webhook after owner backfill (
finally) + ownership/budget containment look correct.
Still not merging
Backend unit suite remains red via #12779 (models.client_processing fixture path). Approve for code/design; ship only once that required check is green.
|
CI has now confirmed the fix, so the blocker on this PR has a verified remedy rather than a candidate. #12785's Root cause, for the record: Nothing changes on this PR. Once #12785 lands, a merge of |
kodjima33
left a comment
There was a problem hiding this comment.
Backend bug fix (webhook lifecycle owner), root cause well-documented with tests. Diff is 403 lines (over the 300-line scoped-diff bar) so scores 4/5 on confidence. Backend unit suite failure looked unrelated to this diff (test_batch_upload_storage.py, test_merge_validation.py — files this PR doesn't touch, consistent with an unrelated flake seen on other PRs today); reran it but mergeStateStatus is now UNKNOWN and the check still pending, so per policy approve-only, not merging.
|
Reviewed What I verified, file by file:
On the red Backend unit suite: I inspected the run logs directly. Every error is One non-blocking note, echoing the earlier review: The remaining gate is operational, not code: merge current main (picking up #12785), confirm Backend unit goes green on this branch, then ship. Thanks for the exceptional discipline on this one — the two real design calls (the 20s bound and the webhook-last ordering) were both surfaced, argued, and pinned in tests. by AI on behalf of David — remaining step is the merge gate: land main (with #12785), see the unit check green, then merge. |
The test asserts no webhook is sent when a dormant owner declines the day, but was named as though it proved one survives. Review on BasedHardware#12742 caught it: a dormant decline means created=False, so pending_webhook is already None and the finally has nothing to deliver. Renamed to test_a_dormant_day_sends_no_webhook and rewrote the docstring to state the real guarantee -- the finally must not push an empty recap on the early-return path -- and to point at the raising-backfill test, which is what actually exercises delivery through finally.
|
Pushed Merged current main. #12785 landed at 11:38Z, so Renamed The guarantee it actually pins is worth keeping, so the docstring now states it plainly: the No production code changed — the diff is one test name and its docstring. |
kodjima33
left a comment
There was a problem hiding this comment.
Confirmed: notifications.py:583 still submits day_summary_webhook into the same postprocess_executor pool it runs on — real bug, not already fixed. Now inline + owned by per-user budget, well-tested (mutation-checked), CI green. Merging.
What changed and why
The daily-summary developer webhook was fire-and-forget:
That line has two independent defects, both visible in the production evidence on #12530.
It submitted into the pool it was already running on.
send_daily_summary_notificationdispatches each user throughrun_blocking(postprocess_executor, _send_summary_notification, user_tokens)(notifications.py:665), so_deliver_current_day_summaryis already executing on apostprocess_executorworker when it submits back into the same 24-slot pool.backend/AGENTS.md:270states the rule this breaks: "Coordinators must not share a pool with their children." It is not a deadlock, because nothing waits on the returned Future — but with_BATCH_SIZE = 8users in flight, each webhook queues behind the very workers that produced it.Nothing owned the submitted work. The per-user budget is
asyncio.wait_for(run_blocking(...), timeout=per_user_timeout), which covers the call and not what the call spawns. The Cloud Run Job exits without joining the pool. A webhook still sitting in the queue at exit was therefore never scheduled at all — which is exactly thelogged immediately before container exit in #12530's evidence.
c82237e723fixed the batching half of #12530 with a monotonic deadline and a resumable cursor, and addedDAILY_SUMMARY_MAX_ABANDONED_USERSto stop the job when timed-out threads have eaten the pool. That work bounds the batch; it does not give this coroutine an owner. This change does.The webhook now runs inline, inside the same per-user budget that governs the rest of that user's work:
return, so a user with no FCM token still reaches their webhook exactly as before;day_summary_webhookhandles its own HTTP failures but not the work around them (URL assembly, the webhook-status reads). Left bare, one of those would propagate out of a user whose push had already been delivered and count them asfailedin the run's accounting. The discarded Future used to provide that containment as an accident; this makes it a decision, and logs it, where the old path reported nothing at all.It also returns 8 slots per batch to
postprocess_executor, which is the poolDAILY_SUMMARY_MAX_ABANDONED_USERSexists to protect.Product invariants affected
None. This changes the lifecycle of an existing outbound call. No identity, storage, memory, or serving-plane behaviour changes, and the webhook payload is byte-identical —
TestSendSummaryNotificationWiresSummaryJsonstill pinsday_summary_webhook(uid, str(summary_data), summary_data)unchanged.How it was verified
Every new test was mutation-checked against the previous production line before being kept. With the old
submitrestored, all four fail:test_webhook_completes_before_the_user_call_returns—AssertionError: the daily summary webhook must not be submitted back to postprocess_executortest_tokenless_user_still_reaches_their_webhook—AssertionError: a tokenless user must still reach their developer webhooktest_webhook_receives_the_dict_payload_as_summary_json— no webhook recordedtest_a_failing_webhook_does_not_cost_the_user_their_recap— no webhook recordedSuites run individually (a combined run cross-pollutes these import-isolation modules):
test_daily_summary_generation.pytest_async_http_infrastructure.pytest_async_webhooks.pytest_daily_summary_race_condition.pytest_daily_summary_empty_overview.pytest_daily_summary_job_resilience.pytest_other_notifications_async_boundaries.pytest_lock_bypass_fixes.pytest_lock_bypass_fixes.py::test_scheduled_summary_excludes_lockedis worth calling out: it does not stubday_summary_webhookat all, and it passed before this change only because the submit swallowed the resulting exception into a Future nobody read. It fails loudly against the uncontained inline version. That test finding the fault is the argument for thetry/exceptabove.This is backend-only. No iOS, Android, pendant, or physical-device verification applies.
Tests
backend/tests/unit/test_daily_summary_generation.py— four behavioural tests: the webhook is complete by the time the call returns, it runs after the push, it still fires for a tokenless user, and a raising webhook costs neither the record nor the push. The harness's webhook fake becomes a real coroutine, since a sync stub would handasyncio.runaNoneand make the harness the thing under test.backend/tests/unit/test_async_http_infrastructure.py— the source pin from Backend storage_executor queue spikes from unbounded fan-out submissions #7387 asserted the old wiring by exact string and had to be inverted. It now requiresasyncio.run(day_summary_webhook(and forbids.submit(asyncio.run, day_summary_webhook(. It stays a source check because the negative half — not submitted anywhere — is not something a behavioural test can express.Failure class (fixes)
Failure-Class: new
Failure-class transition narrative
New class:
FC-pool-submitted-work-without-lifecycle-owner.The violated contract is that work handed to a thread pool must have an owner that outlives it: a coordinator must not submit into the pool it is running on, and no submitted unit of work may belong to a process that exits without joining that pool. A per-item
asyncio.wait_forowns only the call it wraps, so anything that call spawns and does not await sits outside every budget. The canonical prevention is to run the work inline inside the same per-item budget and contain its faults explicitly, with a source pin for the negative half of the wiring.Rollout and rollback
Rollout: merge. No deployment flag, schedule, or infrastructure change — the next
notifications-jobexecution picks it up.Acceptance:
coroutine 'day_summary_webhook' was never awaitedstops appearing before container exit. A newly reachabledaily_summary_webhook_failedline is the fix working, not a regression: those faults were being discarded before.Rollback: revert. The previous behaviour returns along with the dropped webhooks.