Repository navigation
fix(webhooks): claim the pause under a row lock before alerting owners - #13823
Conversation
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.
|
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
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.
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.
| @@ -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); | |||
| } | |||
|
|
|||
There was a problem hiding this comment.
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!
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.
What does this PR do?
Two deliveries for the same webhook can both read
attemptspast_APP_WEBHOOK_MAX_FAILED_ATTEMPTSand 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 flipsenabledfrom 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 resettingattemptsto 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 inFunctions.php:320andMemberships/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
mainthe 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 twofind()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 frommain) →OK (3 tests, 26 assertions)utopia-php/database:getDocument(forUpdate: true)skips the document cache and appendsFOR UPDATEon Postgres/MariaDB, and the worker's pooleddbForPlatformpins one connection for the wholewithTransaction, so the read and the write share the lock.NotificationsBase::seedWebhookFailureAlertstill drives a real webhook to its pause and finds the alert in/v1/notificationsand maildev.No new test.
mainonly 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 onmaintoo. 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::withTransactionreturns the callback directly and the adapter ignoresforUpdate. The freshenabledre-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