Skip to content

fix: deadlock in stack_email_notification - #9941

Merged
sriramveeraghanta merged 1 commit into
previewfrom
fix/email-notification-deadlock
Nov 16, 2026
Merged

sriramveeraghanta merged 1 commit into
previewfrom
fix/email-notification-deadlock

Conversation

@pablohashescobar

@pablohashescobar pablohashescobar commented Oct 4, 2026 •

Copy link
Copy Markdown
Member

Description

stack_email_notification passed every one of a receiver's log ids to each per-issue send_email_notification task. When a receiver had notifications on multiple issues, the concurrent send tasks updated the same email_notification_logs rows (sent_at) and deadlocked. The first email to finish also marked every issue's logs as sent.

  • Scope log ids per issue, so each email only touches its own logs.
  • Mark logs processed_at before dispatching the send tasks, so that update can't race their sent_at updates on the same rows.
  • Add a unit test asserting each email receives only its issue's log ids and all logs are marked processed.

Type of Change

  • Bug fix (non-breaking change which fixes an issue)
  • Feature (non-breaking change which adds functionality)
  • Improvement (change that would cause existing functionality to not work as expected)
  • Code refactoring
  • Performance improvements
  • Documentation update

Screenshots and Media (if applicable)

Test Scenarios

  • Run pytest apps/api/plane/tests/unit/bg_tasks/test_stack_email_notification.py.
  • Create email notification logs for one receiver across two issues, run stack_email_notification, and verify two send tasks are dispatched, each with only its issue's log ids.
  • Verify all logs have processed_at set and no sent_at is set by the stacking task.

References

No work item.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Email notifications for multiple issues are now associated with the correct issue, preventing notification records from being mixed between issues.

- Each per-issue email previously received all of the receiver's log
  ids, so concurrent send tasks updated the same email_notification_logs
  rows and deadlocked. The first email also marked every issue's logs
  as sent.
- Track log ids per issue so each email only touches its own rows.
- Set processed_at before dispatching send tasks so that update can't
  race their sent_at updates on the same rows.
- Add a unit test checking each email gets only its issue's log ids.
Copilot AI balanced review requested due to automatic review settings October 4, 2026 18:02
@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b705ad84-30ae-440c-ae1c-899caeadc767
📥 Commits

Reviewing files that changed from the base of the PR and between c7a5afe and 0e6a29b.

📒 Files selected for processing (2)
  • apps/api/plane/bgtasks/email_notification_task.py
  • apps/api/plane/tests/unit/bg_tasks/test_stack_email_notification.py

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The notification task now associates each queued issue email with only that issue’s notification-log IDs. It marks the collected logs processed before dispatching email tasks. A unit test verifies both behaviors across two issues.

Changes

Issue email notifications

Layer / File(s) Summary
Scope log IDs and dispatch issue emails
apps/api/plane/bgtasks/email_notification_task.py, apps/api/plane/tests/unit/bg_tasks/test_stack_email_notification.py
The task queues each issue email with only that issue’s notification-log IDs and marks collected logs processed before dispatch. The test checks both behaviors across two issues.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to 0e6a2

The change is mergeable after normal checks. Email publication failures can still suppress notifications, so the owner should be aware of that limitation.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 0e6a2

Issue-scoped log IDs improve isolation between emails. However, marking the entire pending batch processed before queueing creates a recovery gap: an interruption can prevent email delivery across multiple receivers. Separately stored notifications remain intact, and no expanded external access was identified.

Retained concerns

  • Medium · reliability · inferred: Pre-dispatch batch processing creates an unrecoverable handoff window in the inspected flow. Interruption after the processed_at update, or a failed publication partway through dispatch, excludes all selected-but-undispatched logs from future scheduled scans. Because selection is unbounded across receivers and issues, one failure can affect the entire pending email batch.
Security review details

Security Blast Radius

  • inferred — The changed failure window can affect every pending email log selected by an invocation, across receivers and issues without a workspace filter. The supported outcome is missed email delivery, not deletion of separately persisted application notifications or compromise of underlying issue data.

Trust Boundaries and Controls

  • observed — The change adds no new request input, recipient-selection mechanism, or email sink. Persisted identifiers and data still feed the task; the consumer resolves the existing user and issue and sends to that user's email address. Production broker access and upstream authorization were not established by this assessment.

Resilience and Maintainability Implications

  • inferred — The send lock protects concurrent execution for an identical issue, receiver, and ID set, but cannot recover unpublished tasks. Overlapping stacking invocations are not atomically claimed in this function; that pre-existing limitation is not treated as a newly introduced concern.

Hardening Proposals

  • proposed — Consider a durable, replayable database-to-queue handoff with explicit publication state and idempotent consumption, preserving issue-scoped ownership without treating undispatched work as completed.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the deadlock fix in stack_email_notification, which is the main change.
Description check ✅ Passed The description explains the deadlock cause and fix, marks the change as a bug fix, and provides test scenarios and a reference note. It covers the template’s required sections; screenshots are not ap…
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Copilot review overview

🟡 Changes recommended

Failed or interrupted dispatch can leave unsent notifications permanently excluded from retries.

Review effort: Balanced
Findings: 1 High severity · 1 Medium severity

Open (2)
What changed in this PR

Reduces contention between email notification tasks by isolating each issue’s logs and updating processing state before dispatch.

Changes:

  • Pass only issue-specific log IDs to each send task.
  • Mark logs processed before enqueueing emails.
  • Add a regression test for log grouping and processing.
File Description
apps/​api/​plane/​tests/​unit/​bg_tasks/​test_stack_email_notification.py Tests per-issue log IDs and processed state.
apps/​api/​plane/​bgtasks/​email_notification_task.py Scopes log IDs and reorders processing before dispatch.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

# Update the email notification log
# Mark the logs processed before dispatching, so this update never races the
# send tasks' `sent_at` updates on the same rows
EmailNotificationLog.objects.filter(pk__in=processed_notifications).update(processed_at=timezone.now())
Comment on lines +40 to +45
with mock.patch("plane.bgtasks.email_notification_task.send_email_notification.delay") as delay:
stack_email_notification()

sent = {call.kwargs["issue_id"]: sorted(call.kwargs["email_notification_ids"]) for call in delay.call_args_list}
assert sent == {issue: sorted(ids) for issue, ids in logs.items()}
assert not EmailNotificationLog.objects.filter(processed_at__isnull=True).exists()
@AppSunder

Copy link
Copy Markdown
Contributor

Confirming this on a self-hosted instance running current preview (b98e1de). I applied this PR's change to email_notification_task.py and ran the email batch with two work items assigned to the same receiver. Both items' email logs were marked processed and sent, each with only its own log ids, and no deadlock or errors in the worker. This looks right to me and is worth merging.

@sriramveeraghanta sriramveeraghanta left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM. Each send task now touches only its own issue's log rows, and processed_at commits before dispatch. Trade-off worth knowing: if the broker fails partway through dispatch, the remaining logs stay marked processed and are never sent.

@sriramveeraghanta
sriramveeraghanta merged commit df2015a into preview Nov 16, 2026
19 of 20 checks passed
@sriramveeraghanta
sriramveeraghanta deleted the fix/email-notification-deadlock branch November 16, 2026 20:22
sriramveeraghanta pushed a commit that referenced this pull request Nov 16, 2026
- Each per-issue email previously received all of the receiver's log
  ids, so concurrent send tasks updated the same email_notification_logs
  rows and deadlocked. The first email also marked every issue's logs
  as sent.
- Track log ids per issue so each email only touches its own rows.
- Set processed_at before dispatching send tasks so that update can't
  race their sent_at updates on the same rows.
- Add a unit test checking each email gets only its issue's log ids.
Pawel-Kranzberg pushed a commit to klazwi/pi-plane that referenced this pull request Nov 18, 2026
- Each per-issue email previously received all of the receiver's log
  ids, so concurrent send tasks updated the same email_notification_logs
  rows and deadlocked. The first email also marked every issue's logs
  as sent.
- Track log ids per issue so each email only touches its own rows.
- Set processed_at before dispatching send tasks so that update can't
  race their sent_at updates on the same rows.
- Add a unit test checking each email gets only its issue's log ids.

(cherry picked from commit 431475d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants