Skip to content

fix(webhooks): claim the pause under a row lock before alerting owners - #13823

Merged
HarshMN2345 merged 11 commits into
mainfrom
fix/issue-12944
Sep 24, 2026
Merged

HarshMN2345 merged 11 commits into
mainfrom
fix/issue-12944

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Two deliveries for the same webhook can both read attempts past _APP_WEBHOOK_MAX_FAILED_ATTEMPTS and both send the "webhook paused" alert, so owners get duplicate emails for one pause.

This claims the pause inside a transaction that re-reads the row with forUpdate, so only the handler whose write flips enabled from true to false notifies the owners. The alert now reports the locked attempt count rather than the one read before the lock — otherwise a concurrent successful delivery resetting attempts to 0 could still trigger a pause quoting a stale number.

Also returns early if the webhook row is gone by the time the claim reads it, matching the isEmpty() guards in Functions.php:320 and Memberships/Status/Update.php:198.

Known trade-off: the pause now commits before the alert is sent. If the owner lookup or the notification enqueue fails right after that commit, the webhook stays paused and that pause is never alerted; on main the webhook stayed enabled and the next failure alerted again. It needs a DB or Redis error in that window, and enqueueing inside the transaction instead would hold the row lock across two find()s and the Redis pushes.

Test Plan

  • composer lint src/Appwrite/Platform/Workers/Webhooks.php → {"tool":"pint","result":"passed"}
  • tests/unit/Platform/Workers/WebhooksTest.php (unchanged from main) → OK (3 tests, 26 assertions)
  • Read the lock path in utopia-php/database: getDocument(forUpdate: true) skips the document cache and appends FOR UPDATE on Postgres/MariaDB, and the worker's pooled dbForPlatform pins one connection for the whole withTransaction, so the read and the write share the lock.
  • The existing e2e NotificationsBase::seedWebhookFailureAlert still drives a real webhook to its pause and finds the alert in /v1/notifications and maildev.

No new test. main only double-alerts when deliveries of the same webhook overlap at the threshold, and the CI stack has no failing target slow enough to force that overlap, so an e2e "exactly one alert" would pass on main too. A unit test would only see the alert through a mocked publisher on an in-memory database, which has no row lock.

Related PRs and Issues

Caveat worth recording: on a MongoDB platform DB that is not a replica set there is no transaction or lock — Mongo::withTransaction returns the callback directly and the adapter ignores forUpdate. The fresh enabled re-read still stops a delivery that runs after the pause, but two that re-read before either writes can both alert. PostgreSQL is the documented default platform DB.

Checklist

  • Have you read the Contributing Guidelines on issues?
  • If the PR includes a change to an API's metadata (desc, label, params, etc.), does it also include updated API specs and example docs? — no metadata change

Two deliveries for the same webhook can both read attempts past
_APP_WEBHOOK_MAX_FAILED_ATTEMPTS and both send the "webhook paused"
alert. Claim the pause inside a transaction that re-reads the row with
forUpdate, so only the handler whose write flips enabled from true to
false notifies the owners, and report the locked attempt count rather
than the one read before the lock.

Returns early when the webhook was deleted mid-delivery, so the
transaction is not retried against a missing row.

On a MongoDB platform DB that is not a replica set this degrades to the
previous behaviour: withTransaction runs the callback directly and the
adapter does not emit a row lock.
@greptile-apps

greptile-apps Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 5/5

The PR appears safe to merge; no actionable regressions remain in the current changes.

Fix All in Claude CodeFindings

  1. P2 Tests Mirror Worker Internals ▶
Fix with agent prompt
### Issue 1
tests/unit/Platform/Workers/WebhooksTest.php:34-58
These tests call the worker's new `prepareAlert()` method directly and then manually repeat its production enqueue loop. The same pattern also appears in the personalization and deduplication tests. This tests the refactoring shape instead of observable worker behavior and violates the repository directive that workers must be covered through E2E rather than unit tests. This repository requirement must be satisfied before merging.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

The PR serializes webhook pause claims by re-reading and disabling the webhook under a row lock, ensuring only the delivery that transitions the webhook from enabled to disabled alerts its owners.

  • Uses the locked attempt count in the pause notification.
  • Safely returns when the webhook was deleted during delivery.
  • Keeps log updates sparse and within the transaction.
  • Removes the transient implementation-coupled worker test and its test-only HTTP-client injection.

Reviews (11) · Last reviewed commit: "revert(webhooks): drop the pause-claim u..."

@github-actions

github-actions Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/issue-12944 (after).

Metric Before After Change
🚀 Requests/sec 182.53 160.08 🔴 -12.3%
⏱️ Latency P50 95.2 ms 109.12 ms 🔴 +14.6%
⏱️ Latency P95 222.93 ms 249.3 ms 🔴 +11.8%
Per-scenario breakdown & investigation details

Metrics below reflect the current branch (after). Δ P95 compares against the base.

Scenario P50 (ms) P95 (ms) Requests RPS Δ P95 (ms)
API total 109.12 249.3 10,260 160.08 +26.37
Account 200.59 375.92 540 9.08 +42.88
TablesDB 105.58 193.66 5,580 89.51 +9.06
Storage 102.76 211.45 2,700 44.79 +25.11
Functions 155.74 315.01 1,440 24.53 +58.64

Top API waits (after)

API request Max wait (ms)
account.prefs.update 521.78
functions.create 516.36
account.name.update 503.57
tablesdb.rows.decrement 499.23
tablesdb.rows.get 490.78

HarshMN2345 and others added 2 commits September 22, 2026 16:01
Claiming the pause under the lock made a lost alert permanent: the row
already read enabled = false, so a retried delivery could not take the
claim again and owners were never told. Re-enable the webhook when
sendAlert throws and let the failure propagate, so the queue retry
re-claims the pause and sends the alert.
HarshMN2345 and others added 2 commits September 22, 2026 16:22
The owner alert was built after the transaction had already committed
enabled=false, so a failed membership lookup or template render lost the
alert for good: the retry read enabled=false and returned early. The
recovery path re-enabled the webhook unconditionally, which overwrote an
owner who had disabled it while the alert was in flight.

Build the notification messages first, then claim the pause under the row
lock, then publish. A handler only claims the pause when it has the alert
in hand, so nothing but the queue push remains after the flip and no stale
write can re-enable a webhook.
Comment on lines +34 to +58
@@ -48,11 +48,14 @@ public function testSendAlertPublishesNotificationMessage(): void
'region' => 'fra',
]),
dbForPlatform: $database,
publisherForNotifications: $publisherForNotifications,
platform: ['consoleUrl' => 'https://console.example.test'],
plan: []
);

foreach ($alerts as $alert) {
$publisherForNotifications->enqueue($alert);
}

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.

P2 Tests Mirror Worker Internals

These tests call the worker's new prepareAlert() method directly and then manually repeat its production enqueue loop. The same pattern also appears in the personalization and deduplication tests. This tests the refactoring shape instead of observable worker behavior and violates the repository directive that workers must be covered through E2E rather than unit tests. This repository requirement must be satisfied before merging.

Context Used: Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/Platform/Workers/WebhooksTest.php
Line: 34-58

Comment:
**Tests Mirror Worker Internals**

These tests call the worker's new `prepareAlert()` method directly and then manually repeat its production enqueue loop. The same pattern also appears in the personalization and deduplication tests. This tests the refactoring shape instead of observable worker behavior and violates the repository directive that workers must be covered through E2E rather than unit tests. This repository requirement must be satisfied before merging.

**Context Used:** Call out and harshly judge implementation-coupled tests. We don't mirror source code, configuration, or version pins in assertions. We test observable behavior; use linters for syntax and schema checks. ([source](https://app.greptile.com/review/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Fix in Claude Code Fix in Codex

HarshMN2345 and others added 2 commits September 22, 2026 18:35
The owner alert was rendered from the attempt count read before the row
lock, while the pause itself was claimed from the locked document. A
concurrent failed delivery incrementing attempts between those two reads
made owners see an older count than the one that paused the webhook.

Send the alert after the transaction with the count returned by the
locked read, and drop the prepareAlert() split so sendAlert() keeps
enqueuing inline and its tests keep covering the published notification.
Two deliveries for the same webhook can read the project before it was
paused, pass the pre-delivery enabled check and both land past the
failure threshold. Drive the worker twice against an unreachable target
and assert a single owner alert, so the alert stays tied to the write
that flips enabled rather than to the attempt count each delivery read.

A single process cannot interleave the two deliveries, so this covers
the claim the transaction re-reads, not the row lock serializing it.
Match the shape the sibling pause-cycle test already uses: the document
that stays the same across runs is built once above the loop, and only
the per-job message varies inside it.
The worker built its own curl client per delivery, so its unit test had
to fail deliveries through a real refused connection to reach the pause
path. Register a client resource next to the other client-backed
resources and inject it; the worker still applies the per-webhook
timeouts, TLS and basic auth through the immutable with* helpers, which
clone, so the shared base instance is never mutated.

The test now passes a named fake adapter answering 500, like the spy
adapters the other worker suites use, and asserts the failure propagates
so the queue retries it, as NotificationsTest does.
…tion

Reverts 849cb33, 440b598 and c084a1c. The test only observed
the alert through a MockPublisher on an in-memory database, and the
'client' resource existed only so it could swap in a fake adapter. The
race it targets needs overlapping deliveries on a real database, which
no single-process test can produce.
@HarshMN2345
HarshMN2345 merged commit 28a6dbb into main Sep 24, 2026
48 of 49 checks passed
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.

Concurrent webhook failures can send duplicate "webhook paused" alerts at the retry threshold

2 participants