Skip to content

fix(backend): give the daily-summary webhook a lifecycle owner - #12742

Merged
kodjima33 merged 7 commits into
BasedHardware:mainfrom
aryanorastar:fix/12530-daily-summary-webhook-drain
Sep 6, 2026
Merged

kodjima33 merged 7 commits into
BasedHardware:mainfrom
aryanorastar:fix/12530-daily-summary-webhook-drain

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 4, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

The daily-summary developer webhook was fire-and-forget:

postprocess_executor.submit(asyncio.run, day_summary_webhook(uid, str(summary_data), summary_data))

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_notification dispatches each user through run_blocking(postprocess_executor, _send_summary_notification, user_tokens) (notifications.py:665), so _deliver_current_day_summary is already executing on a postprocess_executor worker when it submits back into the same 24-slot pool. backend/AGENTS.md:270 states 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 = 8 users 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 the

coroutine 'day_summary_webhook' was never awaited

logged immediately before container exit in #12530's evidence.

c82237e723 fixed the batching half of #12530 with a monotonic deadline and a resumable cursor, and added DAILY_SUMMARY_MAX_ABANDONED_USERS to 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:

  • the push moves ahead of it and becomes a branch rather than an early return, so a user with no FCM token still reaches their webhook exactly 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 (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 as failed in 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 pool DAILY_SUMMARY_MAX_ABANDONED_USERS exists 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 — TestSendSummaryNotificationWiresSummaryJson still pins day_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 submit restored, all four fail:

  • test_webhook_completes_before_the_user_call_returns — AssertionError: the daily summary webhook must not be submitted back to postprocess_executor
  • test_tokenless_user_still_reaches_their_webhook — AssertionError: a tokenless user must still reach their developer webhook
  • test_webhook_receives_the_dict_payload_as_summary_json — no webhook recorded
  • test_a_failing_webhook_does_not_cost_the_user_their_recap — no webhook recorded

Suites run individually (a combined run cross-pollutes these import-isolation modules):

suite result
test_daily_summary_generation.py 20 passed
test_async_http_infrastructure.py 50 passed
test_async_webhooks.py 29 passed
test_daily_summary_race_condition.py 16 passed
test_daily_summary_empty_overview.py 2 passed
test_daily_summary_job_resilience.py 21 passed
test_other_notifications_async_boundaries.py 6 passed
test_lock_bypass_fixes.py 62 passed

test_lock_bypass_fixes.py::test_scheduled_summary_excludes_locked is worth calling out: it does not stub day_summary_webhook at 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 the try/except above.

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 hand asyncio.run a None and 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 requires asyncio.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_for owns 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-job execution picks it up.

Acceptance: coroutine 'day_summary_webhook' was never awaited stops appearing before container exit. A newly reachable daily_summary_webhook_failed line is the fix working, not a regression: those faults were being discarded before.

Rollback: revert. The previous behaviour returns along with the dropped webhooks.

Review in cubic

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

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

2 issues found across 4 files

Confidence score: 3/5

  • In backend/utils/other/notifications.py, the inline day_summary_webhook can consume up to 30 seconds of the per-user 90-second _send_summary_notification budget, 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 required daily_summary_webhook_failed log 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

Comment thread backend/utils/other/notifications.py Resolved
aryanorastar and others added 2 commits September 4, 2026 21:05
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]>
@aryanorastar
aryanorastar force-pushed the fix/12530-daily-summary-webhook-drain branch from e1e30aa to a7ab35a Compare September 4, 2026 15:43
@Git-on-my-level

Copy link
Copy Markdown
Member

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: send_daily_summary_notification really does dispatch _send_summary_notification through run_blocking(postprocess_executor, ...), so the old .submit(...) made the coordinator its own child on the pool it was running on (the exact arrangement backend/AGENTS.md's deadlock-prevention rule 3 forbids), and the discarded Future meant no one owned the coroutine when the Cloud Run Job exited. The inline asyncio.run(asyncio.wait_for(...)) with the new DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS bound, plus explicit containment and the daily_summary_webhook_failed log line, addresses both defects. The if tokens: restructure correctly preserves webhook delivery for tokenless users, and the payload call day_summary_webhook(uid, str(summary_data), summary_data) is byte-identical to before.

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 timeout=DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS pins the bound. One nit: the TestNotificationWebhookWiring class docstring still says "wired through storage_executor" - stale from two wirings ago, worth a one-line fix.

.github/failure-classes/FC-pool-submitted-work-without-lifecycle-owner.json - Ran the repo's scripts/failure-class validator against this declaration and the PR body in a sandbox replicating the change: passes clean. One documentation precision note: evidence_prs: [12588] cites a PR that was closed unmerged (superseded by #12635, which landed c82237e723); the validator doesn't distinguish, but citing the merged PR would be more faithful to the registry's own convention.

The earlier review's two concerns (webhook consuming the per-user 90s budget; missing log assertion) are verifiably resolved on a7ab35a - the 20s bound answers the first, the caplog assertion the second. Nice mutation-checking discipline on the test additions.

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 need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution backend Backend Task (python) labels Sep 4, 2026
… 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]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Both documentation notes fixed on e152c652d9.

Docstring. TestNotificationWebhookWiring said "wired through storage_executor" — stale across two rewirings, as you spotted. It now records the sequence rather than just the current state: storage_executor, then postprocess_executor (#7387), now an inline awaited call bounded by its own budget. The class name predates all three, so a docstring that only named the present wiring would go stale again the next time.

evidence_prs. You're right that #12588 is a closed, unmerged PR and citing it points at something that isn't in history. I went with [12742] rather than the suggested [12635], though, and want to be explicit about why since it's a deliberate departure from your note.

#12635 landed c82237e723, the monotonic-deadline and per-run-cursor work. That fix belongs to FC-batch-fault-domain-head-of-line-poison, and it never touched the pool-lifecycle defect this class describes — the fire-and-forget postprocess_executor.submit(asyncio.run, ...) survived it untouched on main, which is what this PR is fixing. Citing #12635 as evidence for this class would attribute the class to a change that didn't address it, which seems worse than the closed-PR problem you flagged.

This PR is where the class is both defined and fixed, which matches FC-task-candidate-unowned-commitment citing its own defining PR (evidence_prs: [11536]). Happy to switch to [12635, 12742] or drop it to [] — FC-batch-fault-domain-head-of-line-poison itself carries [] — if either reads more faithfully to you.

Verification

  • scripts/failure-class validate --pr-body-file — OK: validate (fix commits=True; declaration=new)
  • test_async_http_infrastructure.py — 50 passed
  • Diff is two files, documentation only; no production or test behaviour changes.

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 tokens guard so a tokenless user still reaches it), and 20s is a fraction of the 90s per-user budget chosen so a slow receiver cannot push a delivered user into user_budget_exceeded. Both are env-overridable, so neither is baked in.

…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]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Merged current main (23156505ff) on 74e74e2f2c. One real conflict and one mechanical follow-on.

The conflict was in _install_generation_fakes. 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 also re-added two stubs this branch deliberately removes: postprocess_executor.submit and a sync day_summary_webhook lambda. Both are superseded here rather than merely moved, so I dropped them:

  • the webhook is awaited inline now, so a sync stub would hand asyncio.run a None and make the harness the thing under test;
  • the submit stub would mask test_webhook_completes_before_the_user_call_returns, whose whole point is that submit raises if the pool wiring is reintroduced.

The real coroutine fake further down replaces both.

The follow-on: main added six tests that unpack the harness as a 4-tuple. This branch widened it to 5 to expose the recorded webhook calls, so those six call sites needed the same widening the pre-existing ones already had. Purely mechanical — no assertion changed.

After the merge

suite result
test_daily_summary_generation.py 27 passed
test_async_http_infrastructure.py 50 passed
test_async_webhooks.py 29 passed
test_daily_summary_race_condition.py 16 passed
test_daily_summary_job_resilience.py 21 passed
test_lock_bypass_fixes.py 62 passed
test_other_notifications_async_boundaries.py 6 passed
test_daily_summary_empty_overview.py 2 passed

Merged rather than rebased, so the review history on the earlier heads stays intact. The production change is unchanged by the merge — asyncio.run(asyncio.wait_for(day_summary_webhook(...), timeout=DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS)) with its containment and log line is still the only edit to notifications.py's delivery path.

@undivisible undivisible left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@undivisible

Copy link
Copy Markdown
Collaborator

Follow-up (after fuller re-read)

Still blocked on green Backend unit (unrelated models.client_processing hermetic stub — #12748 looks like the sibling cleanup).

Residual design ask once CI is green: the bounded webhook still runs inside _deliver_current_day_summary before _backfill_recent_daily_summaries, under the same 90s per-user budget. Today’s push is protected, but a slow receiver can still spend up to 20s that used to be available for owner backfill and can tip marginal users into user_budget_exceeded / abandoned-thread pressure. That sits awkwardly next to “a developer webhook must never cost owner work.” Prefer moving the bounded inline call to after backfill in _send_summary_notification (keep wait_for + contain + log), or explicitly document backfill starvation as an accepted tradeoff at the call site.

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]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed the reordering on 8620ae3b38. Your design point was right, and it contradicted a rule this PR's own comments already stated.

The webhook now runs after the backfill. Running it inline gave it an owner but put its cost inside DAILY_SUMMARY_USER_BUDGET_SECONDS, which the owner's backfill walk also spends. 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. Backfill is owner work, so "a developer webhook must never cost the owner their recap" has to cover it. Last in the budget means the webhook can only ever spend what nobody else still wants.

Lifted into _deliver_day_summary_webhook and driven from _send_summary_notification's finally, not a trailing call. 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. That is the same unowned-work loss this PR exists to stop, relocated 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, and the ordering one is mutation-checked — restoring the webhook to its old position gives:

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

On the red Backend unit suite

Re-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 undivisible left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: still request changes

Re-reviewed a3ddd55b against the prior REQUEST_CHANGES.

Addressed since last review

  • Webhook after owner backfill: _deliver_day_summary_webhook runs from _send_summary_notification's finally after the backfill walk (and still after a dormant early-return / raising backfill). Bound + containment + daily_summary_webhook_failed unchanged. Ordering / finally / dormant tests look right.
  • Ownership shape remains correct: no postprocess_executor.submit of day_summary_webhook; inline wait_for under DAILY_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.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

The gate you are waiting on now has a fix in flight: #12546.

Root cause confirmed and reproduced. utils/conversations/projection_payload.py imported models.client_processing at module scope, and seven suites under tests/unit replace sys.modules['models'] with a bare stub. While one of those stubs is installed, merely collecting a later module that reaches it dies with the ModuleNotFoundError — which is why the error lands on test_batch_upload_storage / test_merge_validation rather than on whatever caused it.

#12546 defers that import to its only consumer, so no models stub anywhere can break collection. Every one of the seven polluters, paired with the two erroring suites, now collects and runs; the same pairings produce 40 collection errors before the change. The regression test is mutation-checked against the exact production error.

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 undivisible left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_webhook runs inline via asyncio.run(asyncio.wait_for(..., timeout=DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS)) — no postprocess_executor.submit of day_summary_webhook. Source pin + submit-explodes behavioral test both hold.
  • After owner backfill: pending_webhook deferred; finally delivers 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_processing hermetic stub ERROR in merge suites is open #12779 on main — not introduced here.

Non-blocking follow-ups

  • test_a_dormant_owner_still_reaches_their_webhook docstring overstates: dormant early-return implies created=False, so pending_webhook is already None; finally is load-bearing for raising backfill, which is covered.
  • Assigning pending_webhook before _deliver_current_day_summary would keep the webhook if push raises (old submit had already queued). Marginal.

Not merging while Backend unit may be red on main.

@undivisible undivisible left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

CI has now confirmed the fix, so the blocker on this PR has a verified remedy rather than a candidate.

#12785's Backend unit suite is green — run 33961213829, 3m29s, with 1072 backend unit test files selected and zero occurrences of No module named 'models.client_processing'. The same required check is red with that exact error on every other open PR, including this one.

Root cause, for the record: utils/conversations/projection_payload.py imported models.client_processing at module scope, and seven suites under tests/unit replace sys.modules['models'] with a bare stub. While one of those stubs is installed, merely collecting a later module that reaches it dies — which is why the error surfaces on test_batch_upload_storage / test_merge_validation rather than on whatever caused it. #12785 defers that import to its only consumer, so no models stub anywhere can break collection.

Nothing changes on this PR. Once #12785 lands, a merge of main here should turn the check green.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed a3ddd55 end to end — diff, tests, and CI logs. The ownership analysis is correct and the iteration on this thread has been excellent.

What I verified, file by file:

  • backend/utils/other/notifications.py — Confirmed both halves of the diagnosis at head: _send_summary_notification is dispatched through run_blocking(postprocess_executor, ...) (line 752), so the old .submit(asyncio.run, ...) really did queue the webhook behind the pool it was already running on, and nothing awaited the Future — the "coroutine 'day_summary_webhook' was never awaited" from Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530's exit evidence. The new _deliver_day_summary_webhook (line 596) runs it inline under DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS (20s, env-overridable), contains every fault behind the daily_summary_webhook_failed log, and the pending_webhook + finally wiring in _send_summary_notification places it after the backfill walk while surviving the dormant early-return and a raising backfill. The webhook payload call stays byte-identical, and the push-becomes-a-branch restructure preserves tokenless webhook delivery. This is the only production edit in the file; _send_bulk_summary_notification and the job accounting are untouched.

  • backend/tests/unit/test_daily_summary_generation.py — 8 focused behavioral tests at head. The strongest three: test_webhook_completes_before_the_user_call_returns makes postprocess_executor.submit raise, so reintroducing the pool wiring cannot pass silently; test_a_slow_webhook_cannot_spend_the_users_recap_budget bounds a 30s-hanging receiver at a 0.05s budget and asserts the record, the push, and the log line all survive; test_the_webhook_runs_after_the_owner_backfill pins the ordering via generations_before. Using a coroutine-shaped fake rather than a sync lambda is the right harness for an inline asyncio.run, and the mutation checks described in the thread make the coverage trustworthy.

  • backend/tests/unit/test_async_http_infrastructure.py — Inverting the Backend storage_executor queue spikes from unbounded fan-out submissions #7387 source pin is the correct call: "not submitted anywhere" is a wiring shape a behavioral test cannot express, and the positive assertion now also pins timeout=DAILY_SUMMARY_WEBHOOK_BUDGET_SECONDS. The rewritten TestNotificationWebhookWiring docstring records the full rewiring history (storage_executor → postprocess_executor → inline), which is exactly how you keep a name that predates its own semantics from lying again.

  • .github/failure-classes/FC-pool-submitted-work-without-lifecycle-owner.json — Follows the registry's convention (mirrors FC-task-candidate-unowned-commitment, which likewise cites its own defining PR in evidence_prs), and the departure from the earlier [12635] suggestion is well argued on the thread: feat: follow-up chips, learned-memory review card, daily-summary tail fix, knows-list rotation #12635 fixed the batch-fault-domain half and knowingly left this defect on main, so citing it here would misattribute the class.

On the red Backend unit suite: I inspected the run logs directly. Every error is ModuleNotFoundError: No module named 'models.client_processing' from utils/conversations/projection_payload.py:19 during collection of test_batch_upload_storage.py / test_merge_validation.py — files this PR does not touch — and the same check fails on the base commit (#12779). That is a main-branch test-isolation failure, not a regression from this diff. The remedy (#12785, deferring that import to its consumer) merged to main at 11:38Z today with a green unit suite, so a merge of current main into this branch should flip the check green with no further change here.

One non-blocking note, echoing the earlier review: test_a_dormant_owner_still_reaches_their_webhook now overstates its subject — a dormant decline means created=False, so pending_webhook is already None and the finally is genuinely exercised by the raising-backfill test instead (which does that job well). A rename in a follow-up would keep the suite honest; nothing more.

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

Copy link
Copy Markdown
Collaborator Author

Pushed 5824e2f0 — the merge gate, plus the rename you flagged.

Merged current main. #12785 landed at 11:38Z, so origin/main no longer carries the module-scope from models.client_processing import in utils/conversations/projection_payload.py. The merge was clean — no conflicts against anything this branch touches. That should clear the Backend unit suite red, which was never this diff's: every error was a ModuleNotFoundError raised while collecting test_batch_upload_storage.py / test_merge_validation.py, files this PR does not touch, and it reproduced identically on the base commit.

Renamed test_a_dormant_owner_still_reaches_their_webhook → test_a_dormant_day_sends_no_webhook. You were right that the name overstated the subject: a dormant decline means created=False, so pending_webhook is None and there is nothing for the finally to deliver. The assertions were already generated_dates == [] and webhooks == [] — the name simply claimed the opposite of what the body checks.

The guarantee it actually pins is worth keeping, so the docstring now states it plainly: the finally must not invent a webhook on the early-return path. A finally that fired unconditionally would push an empty recap to every dormant account every night, which is a real regression this test would catch. The docstring also points at test_a_backfill_failure_does_not_swallow_the_webhook as the test that exercises delivery through finally, since that one reaches it with a real payload in hand.

No production code changed — the diff is one test name and its docstring. test_daily_summary_generation.py + test_async_http_infrastructure.py: 80 passed.

@kodjima33 kodjima33 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@kodjima33
kodjima33 merged commit eb9f005 into BasedHardware:main Sep 6, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants