Skip to content

fix(backend): keep daily summaries from dropping tail users - #12588

Closed
aryanorastar wants to merge 7 commits into
BasedHardware:mainfrom
aryanorastar:codex/12530-daily-summary-tail
Closed

aryanorastar wants to merge 7 commits into
BasedHardware:mainfrom
aryanorastar:codex/12530-daily-summary-tail

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 2, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Fixes #12530.

Daily summaries were being scheduled every minute even though the worker is designed to own one hourly batch. That created overlapping Cloud Run executions, OOM/timeout pressure, and tail users who never reached completion. The same path also launched developer webhooks as unowned executor work and rendered an unlimited day of conversation history into one model request.

This PR makes the deployment and worker lifecycle agree:

  • the notifications deploy now owns and verifies the exact retained 0 * * * * UTC Scheduler target, its run.invoker binding, and one 3600-second/no-retry/one-task execution;
  • deployment accepts only the current merged-main SHA with a successful first-attempt Release Eligibility proof, then rechecks that SHA before publishing and deployment;
  • each selected user returns an explicit delivered/skipped/failed outcome and the run emits bounded aggregate accounting;
  • daily-summary webhooks are awaited by the cron event loop before the Cloud Run job can return;
  • rendered conversation history is deterministically capped at 120,000 tokens, leaving output/profile/memory headroom instead of letting one heavy account overflow the model context.

Product invariants affected

  • INV-DATA-1 — preserves the existing production data-plane authority; this is not a migration exception and does not change customer identity, Firebase, Firestore, or serving-plane selection.
  • INV-MEM-4 — preserves canonical memory authority. The generated runtime manifest changes only notifications-job execution flags; it does not add a memory intake, promotion, projection, or mutation path.

How it was verified

  • The read-only production evidence recorded on Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530 shows the prior Scheduler at */1 * * * *, concurrent execution IDs, an OOM kill, and coroutine 'day_summary_webhook' was never awaited immediately before process exit.
  • A behavioral regression test blocks the developer webhook and proves _send_bulk_summary_notification cannot finish until that webhook is released.
  • Mixed-batch coverage proves delivered, skipped, failed, and webhook-completed users remain independently accounted rather than aborting the batch.
  • Scheduler tests exercise existing-job update/resume, missing-job create, exact target/cadence validation, and a permission failure that must not be misclassified as “not found.”
  • Prompt-budget tests prove unchanged small inputs and deterministic bounded large inputs.
  • backend/.venv/bin/pytest -q ... over the related daily-summary, webhook, scheduler, runtime-env, and workflow suites: 208 passed.
  • PATH="$PWD/backend/.venv/bin:$PATH" backend/scripts/pre-deploy-check.sh: 226 passed, with dev/prod runtime validation and workflow contracts green.
  • python3 backend/scripts/check_workflow_contracts.py: passed.
  • python3 .github/scripts/check_failure_class_guard_ratchet.py: passed.
  • make preflight: passed against the final committed diff and this PR body.

No production mutation was performed from a development machine. After merge, the protected notifications deployment must be dispatched with the admitted merged-main SHA; that run applies and then describes the Scheduler, failing if cadence, state, method, URI, or service account differs. This is backend/infrastructure-only and requires no iOS, Android, pendant, or physical-device verification.

Tests

  • backend/tests/unit/test_other_notifications_async_boundaries.py — event-loop responsiveness, awaited webhook lifecycle, and mixed user accounting.
  • backend/tests/unit/test_provision_notifications_scheduler.py — exact Scheduler create/update/validation and deployment manifest ownership.
  • backend/tests/unit/test_daily_summary_zero_coordinate_locations.py — prompt history remains unchanged below the cap and deterministic above it.
  • Existing webhook wiring guards now reject the former fire-and-forget asyncio.run submit pattern.

Failure class (fixes)

Failure-Class: new

Failure-class transition narrative (only when needed)

New class: FC-scheduled-batch-outlives-execution-contract.

The violated contract is that a scheduled batch worker's deployed cadence, deadline, concurrency, and owned async work must match the lifecycle assumed by its code. The canonical prevention is an exact deployment-owned and post-apply-verified Scheduler target, manifest-owned execution bounds, bounded provider input, awaited webhook completion, and explicit run accounting. The supporting guards are the scheduler contract, blocked-webhook lifecycle test, mixed-batch accounting test, and prompt-budget tests listed above.

New guards (only when adding a check or ratchet)

These guards would have caught #12530 before deployment. The exact Scheduler name/target/cadence is intentionally job-specific; the implementation still uses the repository's shared runtime-manifest renderer and async executor primitives rather than creating a second general deployment or concurrency framework.

Rollout and rollback

  • Rollout: merge, wait for Release Eligibility on the merged main SHA, then dispatch gcp_notifications_job.yml for the protected environment with that exact SHA.
  • Acceptance: the workflow's final Scheduler describe must report 0 * * * *, Etc/UTC, ENABLED, POST, the exact v2 notifications-job:run URI, and the configured service account.
  • Rollback: revert this PR and redeploy the last admitted main SHA. Do not restore the per-minute cadence or fire-and-forget webhook pattern as an operational workaround.

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.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Verification proof

This is the final evidence against current main (d1e83d90b090) after integrating upstream changes.

Failure mode from #12530 Guard/proof now in this PR
Hourly code was invoked by a live */1 * * * * Scheduler test_existing_scheduler_is_updated_to_exact_hourly_contract_and_resumed asserts 0 * * * *; the provisioner describes the applied job and rejects any wrong cadence, state, method, URI, timezone, or service account.
Missing Scheduler and permission failure looked equivalent Create and update paths are covered separately; PERMISSION_DENIED raises and cannot fall through to create.
Cloud Run could exit with the summary webhook still queued test_bulk_summary_waits_for_owned_webhook_before_returning blocks the webhook, proves the batch task is still unfinished, then releases it and observes webhook_completed=1.
One user failure obscured the batch tail Mixed-batch coverage observes selected=3, delivered=1, skipped=1, failed=1, and one completed webhook without aborting the other users.
A heavy day could overflow the model context The history helper returns small input byte-for-byte unchanged and deterministically truncates oversized input within the 120,000-token budget.
Live runtime drifted from the source deadline/concurrency assumptions Runtime manifest and workflow contract pin --task-timeout=3600s --max-retries=0 --tasks=1 --parallelism=1; the generated dev/prod manifest is checked for exact composition.

Commands and results

Related daily-summary/webhook/scheduler/runtime suites: 208 passed
backend/scripts/pre-deploy-check.sh: 226 passed
make preflight: 34 repository checks passed
bounded pre-push gate: passed
runtime-image contracts: 13 registered images passed
pyright: 0 errors

The production observations remain the read-only evidence already attached to #12530: per-minute cadence, overlapping execution IDs, an OOM termination, and the un-awaited webhook warning immediately before container exit. I did not mutate live infrastructure from a development machine. The protected post-merge deployment is the acceptance step and fails closed unless the final Scheduler describe matches the retained contract exactly.

No iOS, Android, pendant, or physical-device testing is applicable to this backend/Cloud Run fix.

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

All reported issues were addressed across 15 files

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

Re-trigger cubic

Comment thread backend/utils/other/notifications.py Resolved
Failure-Class: FC-scheduled-batch-outlives-execution-contract
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

CI follow-up proof

The first full backend unit run exposed one import-isolation test double that had not been updated for the new token-count dependency:

  • failing file: tests/unit/test_high_priority_usage_tracking.py
  • failure: its hand-written utils.llm.clients stub did not expose num_tokens_from_string
  • production code was not failing; the stub no longer matched the real client-module contract
  • fix: added the deterministic token counter to that stub in b6e0fb212b

Reproduced through the same runner CI requested:

BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-backend-unit-failures-12530.txt bash test.sh
21 passed in 0.34s

The push then passed the complete bounded pre-push gate again, including 34 PR-preflight checks, pyright (0 errors), runtime-image closure for 13 images, workflow/deployment contracts, and all 8 selected backend test files. A fresh authoritative GitHub Actions run is now in progress.

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed against #12530's production evidence — this is a well-executed fix for the tail-user drop, and the deployment contract now matches the worker's actual one-hourly-batch lifecycle. Notes by area:

Worker lifecycle — backend/utils/other/notifications.py

  • Every skip path in _send_summary_notification now returns a typed DailySummaryUserResult (skipped_lock, skipped_existing, skipped_no_conversations, skipped_no_unlocked_conversations, skipped_no_speech) instead of a bare return, and the new mixed-batch test observes selected=3/delivered=1/skipped=1/failed=1 without one user aborting the hour group — exactly the head-of-line poisoning in the issue.
  • send_daily_summary_notification replaces the single whole-loop try/except with per-hour-group isolation plus query_failures accounting, so one Firestore read failure no longer throws away the remaining timezone groups.
  • The fire-and-forget postprocess_executor.submit(asyncio.run, day_summary_webhook(...)) is gone; webhooks are gathered on the cron event loop per batch and counted (webhook_completed/webhook_failed). Since day_summary_webhook posts through the shared client (30s read / 2s connect timeouts, circuit breaker, 1/5/30s retry delays), awaiting it can't unboundedly stall the 3600s task budget. One behavioral note: a batch's webhooks now complete after that batch's pushes — slightly later than before, but owned and observable.

Context overflow — backend/utils/llm/external_integrations.py

Deployment contract — .github/workflows/gcp_notifications_job.yml, backend/scripts/provision_notifications_scheduler.py, runtime_env yamls

  • Replacing the free-form branch input with release_sha (must equal the current origin/main SHA, re-verified before image push and again before Cloud Run deploy, plus a first-attempt Release Eligibility proof) closes the deploy-any-branch hole — strictly a hardening.
  • The provisioner fails closed on PERMISSION_DENIED vs NOT_FOUND, pins 0 * * * * UTC with the exact run.googleapis.com URI and SA email, and re-validates final state after create/update/resume. Both paths plus identity rejection are unit-tested, and the cross-artifact test reads the workflow YAML and runtime manifest together so they can't drift.
  • --max-retries=0 --tasks=1 --parallelism=1 pinned across _base.yaml and both environments in runtime_env.yaml matches the one-task hourly design.

Records and docs — the new .github/failure-classes/FC-scheduled-batch-outlives-execution-contract.json accurately captures the violated contract and points at the right prevention tests, and the one-line backend/docs/subservice-internals.md update matches the code. The CI follow-up (num_tokens_from_string added to the hand-written clients stub in test_high_priority_usage_tracking.py) was a test-double refresh, not a production issue.

Two decision points for maintainer sign-off before merge, beyond the normal human read:

  1. The Scheduler invoker binding reuses memory-maintenance-scheduler@… for notifications-job. It works, but shared-vs-dedicated service-account identity is an infra call for a maintainer.
  2. The first manual deploy after merge re-provisions the live Scheduler to hourly and resumes it — dispatch is main-only and manual so merging alone touches nothing, but the first hourly run's daily_summary_run accounting line is the acceptance signal to watch.

Checks are green on this head, including the hermetic backend gates. No split needed — this is one cohesive lifecycle fix. Labels applied: backend, positive-signal, workflow-review, needs-maintainer-review.


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 backend Backend Task (python) positive-signal Automation verified a genuine fix/quality contribution workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior needs-maintainer-review Needs a human maintainer to sign off before merge labels Sep 2, 2026
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Reviewer follow-up: all five findings addressed

The five findings from the Cubic review on d43280a025 were valid and are fixed in 3c0763b7a9; the branch is now pushed at d49b6f22a2 after a clean merge of current origin/main (0f0f679e5f).

Finding Resolution Regression proof
P1: enabled Scheduler was always resumed Parse initial state, accept only ENABLED/PAUSED, and resume only an initially paused job Enabled/no-resume, paused/resume, and invalid-state fail-closed tests
P2: webhook await assertion was non-binding AST-locate the exact day_summary_webhook call and require it to be inside awaited asyncio.gather Structural test rejects bare/unowned webhook calls
P2: skipped/failed webhooks counted as completed Typed DaySummaryWebhookResult; separate delivered, skipped, and failed counters Outcome tests plus mixed accounting coverage
P2: truncation could split records and retain invalid mappings Render the largest budget-fitting prefix of complete conversations; build numbering/map only from retained records; keep aggregate stats over all records Complete-record prefix and retained-ID mapping tests
P3: marker could exceed a tiny token budget Return empty bounded history when even the marker cannot fit Dedicated marker-budget boundary test

Fresh verification against current main

Focused reviewer suite: 103 passed
Combined affected backend suites: 183 passed
backend/scripts/pre-deploy-check.sh: 226 passed
Python 3.11 pyright wrapper: 0 errors
make preflight: 34/34 checks passed
pre-push runtime-image contracts: 13/13 images passed
pre-push selected backend suites: all passed
black: 12 changed Python files unchanged
working tree: clean

The full push gate completed successfully before the new head was published. Fresh GitHub Actions runs are now executing. This remains a backend/Cloud Run lifecycle fix; no iOS, Android, pendant, or physical-device validation is applicable.

Failure-Class: FC-scheduled-batch-outlives-execution-contract
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

CI follow-up: import-isolation fixture corrected

The only failing job on d49b6f22a2 was the full backend unit suite. It identified one more hand-written module stub that had not been updated for the typed webhook result introduced by the reviewer fix:

  • failing file: tests/unit/test_daily_summary_race_condition.py
  • failure: its isolated utils.webhooks replacement exposed day_summary_webhook but not DaySummaryWebhookResult
  • scope: test-fixture compatibility only; the production module loaded normally and every runtime/contract job passed
  • fix: add the result type to that isolated stub in 0e262093a2

Exact CI-runner reproduction:

BACKEND_UNIT_TEST_FILE_LIST=/tmp/omi-backend-unit-failures-12530-review.txt bash test.sh
16 passed

Combined changed and related suite:

9 files, 201 passed

The full pre-push gate then passed again: 34/34 PR checks, Python 3.11 pyright with 0 errors, 13/13 runtime-image contracts, all 9 selected backend test files, module-isolation, workflow/deployment contracts, and formatting. A fresh GitHub Actions run is now authoritative for head 0e262093a2.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Current-main verification complete

The branch is synchronized with current origin/main and verified at head b3cecaf4251f0f078f36d9868cb40cd785e0e11c.

Fresh local proof after the clean main merge

  • Base divergence: 0 behind / 7 ahead
  • Focused affected backend suite: 9 files, 201 passed
  • Repository preflight: 34/34 checks passed
  • Python 3.11 pyright: 0 errors
  • Runtime image closure: 13/13 registered images passed
  • Workflow, deployment, module-isolation, OpenAPI, hygiene, and formatting contracts: passed
  • Full bounded pre-push gate: passed

Authoritative GitHub proof on this exact head

  • Backend unit suite: passed in 12m53s
  • Static Contracts: passed
  • Hermetic Backend E2E: passed
  • Listen Pusher Stack Gauntlet: passed in 8m05s
  • Sync Cloud Tasks Stack Gauntlet: passed
  • Replay Harness advisory: passed
  • Backend Hermetic Merge Gate: passed
  • Hygiene, Formatting, OpenAPI, and source closure: passed
  • Mobile, desktop, and web build jobs were correctly skipped by backend-only scope detection

Cubic reports all five review findings addressed. The PR is open and non-draft; its only remaining gate is maintainer review/approval. No merge or production deployment was performed, and no physical-device validation applies to this backend/Cloud Run lifecycle fix.

@Git-on-my-level

Copy link
Copy Markdown
Member

Follow-up verification on b3cecaf4 (current head), covering the delta since the earlier review on b6e0fb21:

Hardening commit 3c0763b7 — concerns verified resolved

  • backend/utils/llm/external_integrations.py: truncation now happens at conversation boundaries (_render_bounded_daily_summary_history) instead of mid-text, convo_id_map is rebuilt from the retained prefix only, the prompt states "N of M conversations" with a matching reference rule, and evidence entries whose conversation_number no longer resolves are dropped instead of persisted with a wrong id. The 120k budget leaves ample headroom under the daily_summary route's 400k context.
  • backend/scripts/provision_notifications_scheduler.py: an existing scheduler in an unknown state (not ENABLED/PAUSED) now fails closed before any mutation, and resume only fires when the prior state was PAUSED — both paths unit-tested in test_provision_notifications_scheduler.py.
  • backend/utils/other/notifications.py + backend/utils/webhooks.py: webhook_skipped accounting added, and a non-DaySummaryWebhookResult webhook return now counts as a failure rather than being silently credited.

Fixture-only follow-ups — 0e26209 (test_daily_summary_race_condition.py) and the earlier clients-stub sync (test_high_priority_usage_tracking.py) were hand-written module doubles lagging the new DaySummaryWebhookResult / num_tokens_from_string imports, not production regressions; both are correctly diagnosed in the thread above.

Deploy contract cross-check — notifications_job_flags is a real render_backend_runtime_env.py output for this job, and test_workflow_owns_scheduler_and_bounded_job_runtime_contract pins the exact flag set (--task-timeout=3600s --max-retries=0 --tasks=1 --parallelism=1) across _base.yaml and both environments, so workflow and manifest cannot drift silently. Worth noting explicitly: --max-retries=0 means Cloud Run no longer auto-retries a partially-completed batch — retries are now owned by the hourly cadence plus the existing Redis lock / date-idempotency guard, which matches the design intent.

Minor, non-blocking: _bound_daily_summary_history (the character-prefix variant) is now referenced only by tests since production switched to the conversation-boundary renderer — a small follow-up cleanup candidate.

The two maintainer decision points from the earlier review still stand before merge: shared memory-maintenance-scheduler@ invoker identity for notifications-job (vs a dedicated SA), and the first manual deploy after merge re-provisioning the live Scheduler to 0 * * * * — the first hourly daily_summary_run accounting line is the acceptance signal to watch. Checks are green on this head, including the hermetic backend gates.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar

aryanorastar commented Sep 3, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status change worth flagging before anyone re-reviews this: #12530 was closed on 2026-09-03, fixed on main by c82237e723 ("fix(backend): stop losing daily summaries for tail-of-batch users"). This PR is now largely superseded and conflicts with main in backend/utils/other/notifications.py.

main took a different approach to the same batching problem — a monotonic deadline plus a per-run cursor (daily_summary_budget.job_cursor_key, DAILY_SUMMARY_JOB_BUDGET_SECONDS, DailySummaryJobStats) — where this PR used per-hour-group isolation with DailySummaryRunSummary and query_failures accounting. Resolving the conflict by taking this side would revert a merged fix, so I have not touched it.


Edited in place to correct one claim. My first version of this comment said main had no equivalent to this PR's prompt-input bound, so the context_length_exceeded abort was still live. That is wrong.

main bounds the summary prompt in backend/utils/other/daily_summary_budget.py (select_conversations_within_budget), called from notifications.py:170 under DAILY_SUMMARY_MAX_HISTORY_CHARS (default 360,000). I had searched only backend/utils/llm/external_integrations.py, where this PR placed its bound, and read the empty result as absence — the guard exists, it just lives at the caller rather than in the generator.

It is also the better of the two on selection policy. main keeps the most recent conversations rather than an oldest-first prefix, which is the half of the day a recap is actually about; it always keeps at least one conversation, so an oversized single conversation still gets a summary attempt instead of an empty prompt; and it drops an unrenderable conversation rather than letting it sink the whole recap. This PR's version keeps the oldest prefix and returns empty history when even the truncation marker will not fit.

The one axis where this PR's version differs usefully is the measurement unit — tokens via num_tokens_from_string against a 120,000-token budget, versus characters. Characters are a proxy whose ratio moves with content, and token-dense material (code blocks, non-Latin scripts) fits fewer tokens per character than ordinary English. That is a tuning question on an existing guard, not a missing guard, and not worth a PR on its own unless the overflow recurs.

Revised picture

  1. _bound_daily_summary_history — the 120k-token bound; main has no equivalent. Withdrawn — main has one, and a better one.

  2. Webhook lifecycle — still absent from main, still live. notifications.py:536 on main is unchanged: postprocess_executor.submit(asyncio.run, day_summary_webhook(...)). That is the fire-and-forget submit behind the coroutine 'day_summary_webhook' was never awaited warning recorded immediately before container exit in Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups #12530's evidence. main's deadline/cursor work bounds the batch but does not own that coroutine, so a run ending on its budget can still exit with webhooks abandoned.

  3. Deploy-contract hardening — still absent on this job's lane. .github/workflows/gcp_notifications_job.yml on main still takes a free-form branch: input; release_sha gating landed in the shared deploy action but not on this workflow.

What I would rather do

With item 1 withdrawn, rescoping this branch is the wrong shape. Item 2 is a self-contained change to one function plus its test; item 3 is a workflow change. Neither needs the 1,132-line batching diff, and the conflicted file is one main now owns.

I would rather close this PR and open one small PR for the webhook drain, carrying #12530's evidence as its justification, than resolve a conflict against a merged fix. Item 3 can follow separately if the free-form branch: input on this lane is considered worth closing.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Closing in favour of #12742, which carries the one part of this branch that main does not already own.

c82237e723 fixed #12530 on main with a monotonic deadline and a resumable per-run cursor, and my earlier claim in this thread that main still lacked a prompt-input bound was wrong — select_conversations_within_budget does that, and does it better than this branch did. That correction is in the comment above.

What genuinely remained was the webhook lifecycle, and researching it for the replacement PR turned up a sharper root cause than this branch had. _deliver_current_day_summary already runs on postprocess_executor, so postprocess_executor.submit(asyncio.run, day_summary_webhook(...)) made the coordinator its own child on the pool it was running on — the arrangement backend/AGENTS.md:270 forbids — as well as leaving the work owned by no lifecycle. #12742 is 4 files, +179/−27, against the 1,132 lines here.

Not carried over: the batching and accounting half, which main now owns and which cannot be merged without reverting c82237e723; and the release_sha gating on gcp_notifications_job.yml, which is a real gap but an unrelated one. That lane still takes a free-form branch: input, and I would rather it be its own PR than ride along here.

@github-actions

github-actions Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Hey @aryanorastar 👋

Thank you so much for taking the time to contribute to Omi! We truly appreciate you putting in the effort to submit this pull request.

After careful review, we've decided not to merge this particular PR. Please don't take this personally — we genuinely try to merge as many contributions as possible, but sometimes we have to make tough calls based on:

  • Project standards — Ensuring consistency across the codebase
  • User needs — Making sure changes align with what our users need
  • Code best practices — Maintaining code quality and maintainability
  • Project direction — Keeping aligned with our product principles and locked invariants

Before your next PR, please skim:

  • PRODUCT.md — product north star
  • Product invariants — locked rules (shared chat, memory tiers, agent control plane, integrations, brand)

If this was declined for direction or taste, maintainers should cite an invariant ID or open a proposed one — ask if that citation is missing.

Your contribution is still valuable to us, and we'd love to see you contribute again in the future! If you'd like feedback on how to improve this PR or want to discuss alternative approaches, please don't hesitate to reach out.

Thank you for being part of the Omi community!

aryanorastar added a commit to aryanorastar/omi that referenced this pull request Sep 5, 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]>
kodjima33 pushed a commit that referenced this pull request Sep 6, 2026
* fix(backend): give the daily-summary webhook a lifecycle owner

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 #12530's evidence.

c82237e fixed the batching half of #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]>

* fix(backend): bound the daily-summary webhook inside its own budget

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

* docs(backend): correct the webhook wiring docstring and failure-class 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 (#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 #12588, which was closed unmerged. Replaced with #12742 rather
than the suggested #12635: #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]>

* fix(backend): run the daily-summary webhook after the owner's backfill

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

* test: name the dormant-day webhook test for what it asserts

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backend Backend Task (python) needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution workflow-review Needs maintainer review for workflow, automation, hooks, or CI behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Daily summaries silently stop for tail-of-batch users: notifications-job 600s timeout + one-user context overflow aborts whole hour groups

2 participants