Skip to content

fix(workers): stop dead-lettering refusals a retry cannot fix - #14545

Merged
levivannoort merged 3 commits into
mainfrom
fix/permanent-refusals
Oct 15, 2026
Merged

levivannoort merged 3 commits into
mainfrom
fix/permanent-refusals

Conversation

@levivannoort

@levivannoort levivannoort commented Oct 15, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

Some function and screenshot jobs can never succeed, but they were thrown as ordinary errors, so they landed on the dead letter streams and counted toward the "Dead letter stream is growing" alert. This PR stops the ones a retry can't fix. Production evidence is in appwrite-labs/cloud#6470.

Functions: runs of a deleted project. A project the platform no longer has resolves to an empty document, and dbForProject falls back to the platform database. Every scheduled run then threw Collection not found at Functions.php:311, with project.id="". sfo3 got 13 of these from one deleted project, plus about 3 a night since. The worker now logs a warning and acknowledges the run. The project's database is gone, so nothing could run it on a later attempt either.

Deletes: why the schedules kept firing for about 4 minutes. deleteProject() did remove the project's schedules rows, but it hard-deleted them. The schedulers sync incrementally from rows whose resourceUpdatedAt moved (Scheduler::reconcile(): "a change feed cannot report a hard delete"), so the entries stayed in memory until the next full snapshot, which comes every 30 syncs (300s). The worker now deactivates the rows instead (active=false, resourceUpdatedAt=now), the same way function deletion does. The scheduler drops them on its next sync, about 10s later. The existing maintenance sweep (deleteSchedules, DELETE_TYPE_SCHEDULES) still removes the inactive rows of deleted projects once they are past _APP_MAINTENANCE_RETENTION_SCHEDULES.

Screenshots. These now throw PermanentFailure:

  • Host '<x>' is not publicly routable., from the browser service (HTTP 400). The customer's DNS points at a private address, so every attempt is refused the same way. nyc3 dead-lettered one site's screenshots over and over for this.
  • Deployment not found and Site not found, when the resource was deleted before the capture ran.
  • A deployment deleted during the capture. Before, the log append failed with Must define $id attribute, the retry then failed with Deployment not found, and the site's preview could be overwritten with an empty one. Now the log append skips a missing deployment, the site keeps its preview, and the job ends once.

Page timeouts (screenshot: Timeout 30000ms exceeded, which is also a 400), connection errors and certificate errors are still retried.

Test Plan

Unit tests, each seen failing with its production hunk reverted:

  • tests/unit/Platform/Workers/FunctionsTest.php::testRunOfDeletedProjectIsAcknowledgedWithoutExecuting (schedule and http). The database double throws NotFound('Collection not found'), like the platform database does. Red: the same Utopia\Database\Exception\NotFound: Collection not found seen in production.
  • tests/unit/Platform/Workers/DeletesTest.php::testDeletedProjectSchedulesStopFiringOnTheNextSync. This runs the real Scheduler with Source\Functions over a Memory-adapter database that uses the real schedules/projects/functions schemas. Red with the old hard delete: Failed asserting that 3 is identical to 1 after the incremental sync.
  • tests/unit/Platform/Modules/Functions/Workers/ScreenshotsTest.php, which drives the real worker with Memory databases and a fake browser that returns the service's real error bodies. Red: unroutable host as Appwrite\Screenshots\Exception, deleted deployment as Exception, deleted mid-capture as Utopia\Database\Exception (Must define $id attribute). The timeout case is a guard and passes both ways.

pint --test, phpstan on the changed files, and rector --dry-run on the tests are clean. tests/unit/Platform, tests/unit/Workers, tests/unit/Screenshots and tests/unit/Schedule pass (346 + 6 tests).

There is no E2E test for the scheduler ↔ deletes path. The Deletes test covers that seam in-process, but it doesn't run a real database engine.

Related PRs and Issues

  • Related: appwrite-labs/cloud#6470
  • Cloud counterpart (plan-limit refusals in the functions worker): appwrite-labs/cloud#6562

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 API change.)

…ing them

A schedule that fires after its project is deleted reaches the worker with a
project that resolves to nothing. dbForProject then falls back to the platform
database, and the run threw 'Collection not found' and was dead-lettered.
Nothing can run it on any attempt, so log a warning and acknowledge it.
…er drops them

The schedulers sync incrementally from rows whose resourceUpdatedAt moved, so a
hard-deleted schedule kept firing from memory until the next full snapshot (up
to five minutes). Deactivating the rows reaches them on the next sync; the
maintenance sweep removes the inactive rows of deleted projects as before.
An unroutable host, a deployment or site deleted before the capture, and a
deployment deleted during it now throw PermanentFailure, so they are not
retried. A deployment deleted mid-capture no longer fails on the log append
with 'Must define $id attribute' or overwrites the site's preview with an
empty one. Page timeouts and other browser errors stay retriable.
@luxor-code-review

luxor-code-review Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

Review complete. 🟡 1 medium

📍 Findings outside the diff (1) — 🟡 1 medium — defects on lines GitHub can't attach comments to

🟡 Medium — Screenshots worker lacks the deleted-project guard · Screenshots.php:65–78 · unchanged line

// src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php
65	        Span::add('project.id', $project->getId());
66	
67	        $payload = $message->getPayload();
68	
69	        if (empty($payload)) {
70	            throw new \Exception('Missing payload');
71	        }
72	
73	        $screenshotMessage = Screenshot::fromArray($payload);
74	        $counter = $telemetry->createCounter('worker.screenshots.capture');
75	
76	        $deploymentId = $screenshotMessage->deploymentId;

The patch adds $project->isEmpty() handling to the Functions worker (src/Appwrite/Platform/Workers/Functions.php:107) but the Screenshots worker has no equivalent guard (src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php:78). When a site's project is deleted after the capture was queued, app/init/worker/message.php:80 resolves dbForProject to dbForPlatform, so the getDocument('deployments', ...) read queries the platform DB where that collection does not exist. The message fails with a collection error instead of the intended PermanentFailure, and is redriven into the same failure.

🧹 Nitpicks (2) — 🟢 2 low
  • 🟢 Guard null $error before reading its class (ScreenshotsTest.php:129) — testPageTimeoutStaysRetriable reads $error::class without first asserting the exception exists (tests/unit/Platform/Modules/Functions/Workers/ScreenshotsTest.php:129).
  • 🟢 Dead-letter classification keyed to message substring (Screenshots.php:248) — The permanent/retriable verdict for browser-service refusals is decided by str_contains($th->getMessage(), 'is not publicly routable') at src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php:248, and the message is produced by src/Appwrite/Screenshots/Client.php:60 from whatever error string the browser service returns.

The change closes race windows where queued work races against project/deployment deletion. Deactivation-with-later-sweep replaces immediate schedule deletion so in-memory schedulers converge via resourceUpdatedAt syncs, and the screenshot worker now dead-letters work whose targets no longer exist.

Files Change
src/Appwrite/Platform/Workers/Deletes.php Adds deactivateSchedules() marking schedules active=false with a resourceUpdatedAt bump; the existing sweep reaps them after the retention window.
src/Appwrite/Platform/Workers/Functions.php Early-returns with a warning log when the queued execution's project document is empty, acknowledging the message without executing.
src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php Throws PermanentFailure for missing deployment/site and for the browser service's "not publicly routable" refusal; guards empty documents after updateDocument and in appendToLogs.
tests/unit/Platform/Workers/FunctionsTest.php New test asserting deleted-project messages are acknowledged without executor, bus, or queue side effects.
tests/unit/Platform/Workers/DeletesTest.php, tests/unit/Platform/Modules/Functions/Workers/ScreenshotsTest.php Unit coverage for schedule deactivation and the new screenshot failure paths.

Reviewed commit: 2c6b8ab

@github-actions

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

19 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (12)
  • php.appwrite.secret-compare-timing (5)
  • php.appwrite.weak-secret-env-default (2)

Posted by Checks / Rules. Re-runs update this comment in place. Rule details and baseline: .semgrep/README.md.

@ghost

ghost commented Oct 15, 2026

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The worker changes appear sound, but the added worker behavior tests violate the repository's explicit testing-tier rule.

The workers now acknowledge function runs whose projects have been deleted, deactivate schedules during project cleanup so schedulers see the change incrementally, and classify unrecoverable screenshot refusals as permanent failures. The screenshot worker also skips log updates for missing deployments and avoids replacing a site's preview when a deployment disappears during capture.

Verdict New comments Fixed Still open
✅ Approved 1 0 0
Finding Where
🟡 Keep worker behavior tests out of the unit tier tests/unit/Platform/Workers/DeletesTest.php:60
Fix with agent prompt
### Issue 1
tests/unit/Platform/Workers/DeletesTest.php:60
**Keep worker behavior tests out of the unit tier**

This test, the new screenshot tests, and the added Functions test invoke worker behavior directly from `tests/unit`. AGENTS.md's Tests rule explicitly says not to unit-test workers (E2E covers those surfaces), so these additions do not follow the repository's required test tier.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 6
File Change
src/Appwrite/Platform/Modules/Functions/Workers/Screenshots.php Classifies deleted resources and unroutable hosts as permanent failures and guards updates after deployment deletion.
src/Appwrite/Platform/Workers/Deletes.php Deactivates project schedules and updates their change-feed timestamp instead of hard-deleting them.
src/Appwrite/Platform/Workers/Functions.php Acknowledges function messages for projects that no longer exist.
tests/unit/Platform/Modules/Functions/Workers/ScreenshotsTest.php Adds coverage for permanent screenshot failures, retryable timeouts, and mid-capture deletion.
tests/unit/Platform/Workers/DeletesTest.php Adds coverage for scheduler reconciliation after project schedules are deactivated.
tests/unit/Platform/Workers/FunctionsTest.php Adds coverage for acknowledging deleted-project function messages.

Reviewed 2c6b8ab · Details · Comment @hansi-codes review to re-run, or mention @hansi-codes with a question.

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

🔵 Tier A · Looks good to merge. Summary

* project. Deleting the project has to reach the scheduler on its next
* incremental sync.
*/
public function testDeletedProjectSchedulesStopFiringOnTheNextSync(): void

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Keep worker behavior tests out of the unit tier

This test, the new screenshot tests, and the added Functions test invoke worker behavior directly from tests/unit. AGENTS.md's Tests rule explicitly says not to unit-test workers (E2E covers those surfaces), so these additions do not follow the repository's required test tier.

Prompt To Fix With AI
This is a comment left during a code review.
Path: tests/unit/Platform/Workers/DeletesTest.php
Line: 60

Comment:
**Keep worker behavior tests out of the unit tier**

This test, the new screenshot tests, and the added Functions test invoke worker behavior directly from `tests/unit`. AGENTS.md's Tests rule explicitly says not to unit-test workers (E2E covers those surfaces), so these additions do not follow the repository's required test tier.

---

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

🟡 Minor · testing · Reply if this doesn't apply.

@github-actions

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix/permanent-refusals (after).

Metric Before After Change
🚀 Requests/sec 208.64 208.46 ⚪ -0.1%
⏱️ Latency P50 81.23 ms 83.07 ms ⚪ +2.3%
⏱️ Latency P95 194.76 ms 191.18 ms ⚪ -1.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 83.07 191.18 12,882 208.46 -3.58
Account 157.42 293.48 678 11.23 +5.28
TablesDB 79.46 143.09 7,006 115.16 -9.9
Storage 79.38 172.48 3,390 57.69 -11.04
Functions 120.75 231.61 1,808 31.51 +9.24

Top API waits (after)

API request Max wait (ms)
functions.create 456.6
functions.variables.update 456.12
account.name.update 434.51
tablesdb.rows.create 372.26
account.prefs.update 366.64

@levivannoort
levivannoort merged commit 16da989 into main Oct 15, 2026
67 checks passed
@TorstenDittmann
TorstenDittmann deleted the fix/permanent-refusals branch October 15, 2026 11:04
@ChiragAgg5k ChiragAgg5k mentioned this pull request Oct 21, 2026
6 tasks
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.

2 participants