Skip to content

fix(messaging): stop messages getting stranded in processing - #13091

Merged
HarshMN2345 merged 5 commits into
mainfrom
fix-messaging-stuck-processing
Aug 4, 2026
Merged

HarshMN2345 merged 5 commits into
mainfrom
fix-messaging-stuck-processing

Conversation

@HarshMN2345

Copy link
Copy Markdown
Member

What does this PR do?

A message sits at processing from the moment it is enqueued until the worker writes a terminal status. Any error in between stranded it there permanently — and because delete was also blocked on that state, the message could never be updated or removed through the API.

The trigger. sendExternalMessage is handed whatever getDocument('messages', $messageId) returns, with no isEmpty() guard. An unreadable document falls through with every attribute unset: $status is null so the idempotency guard doesn't catch it, and $providerType is null by the time we reach the provider lookup — findOne('providers', [Query::equal('type', [null])]) then throws Invalid query: Query value is invalid for attribute "type", three lines before the first status => failed write. providerType is hardcoded at create time for all three message types, so a null value always means the worker read the message back and did not find it.

This is live on production today. From worker-messaging over a 10h window, 5 errors, all identical:

{"level":"error","action":"worker.messaging","message.type":"external",
 "message.provider_type":null,
 "error.type":"Utopia\\Database\\Exception\\Query",
 "error.message":"Invalid query: Query value is invalid for attribute \"type\"",
 "error.line":8529,"span.duration":0.035}

Why it is permanent. The queue does not redeliver. Adapter::process() rejects a failed job, and Broker\Redis::reject() pushes the pid onto {namespace}.failed.{queue} — a dead-letter list. Nothing ever revisits the message.

The change:

  • Guard the message read in the worker, so an unreadable document fails with Message not found: <id> instead of a misleading query error further down.
  • Mark the message failed when the job dies before writing a terminal status, then rethrow so the error still reaches the dead-letter list and the logger. Best-effort — the write is skipped if the document is genuinely gone.
  • Allow deleting a processing message, so already-stranded ones can be cleared. This also drops a wrong error code: the processing branch threw MESSAGE_ALREADY_SCHEDULED.

Update remains blocked on processing — mutating a message mid-send is a different question from clearing one, and nothing here needs it.

Test Plan

testDeleteMessage asserted that deleting a message handed straight to the worker returns 400. That assertion encoded the behaviour being fixed, so it now asserts 204, and the POST that sets it up asserts 201 rather than going unchecked. The 404 case is unchanged.

Not run locally — the suite needs the full stack plus an email DSN, without which testDeleteMessage skips at setupSentEmailData. Relying on CI. Pint passes on all three files; PHPStan reports only a pre-existing error in an unrelated VCS file.

Worth a reviewer's eye: buildMessage at Messaging.php:645 sits outside the try/catch at :654, inside a batch() task. If it throws, the exception escapes the task coroutine rather than the job, so the new catch never sees it. Semaphore::withLock releases via finally so no lock leaks, but I could not verify locally whether batch() deadlocks or silently drops the result. Left alone here.

Related PRs and Issues

  • Support ticket: messages stuck in processing, deletion fails

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; the delete endpoint's params, labels and SDK method are untouched.

A message sits at 'processing' from the moment it is enqueued until the
worker writes a terminal status. Any error in between stranded it there
for good: a failed job is rejected to a dead-letter list rather than
redelivered, and delete was blocked on that state.

An unreadable message document was the common trigger. It fell through
with every attribute unset, so the provider lookup rejected a null type
and aborted the job with a misleading query error.

- guard the message read in the worker
- mark a message failed when the job dies before writing a status
- allow deleting a processing message so stranded ones can be cleared
@greptile-apps

greptile-apps Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR prevents external messaging jobs from remaining indefinitely in processing after worker failures and allows operators to delete processing messages.

  • Guards missing message documents before provider lookup.
  • Best-effort records nonterminal worker failures while preserving terminal statuses.
  • Updates deletion behavior and its end-to-end assertions.

Confidence Score: 4/5

This PR does not yet appear safe to merge because deleting a processing message can still race an active worker and permit an untracked external delivery.

The terminal-status preservation fix addresses the cleanup-overwrite thread, but the delete endpoint still removes processing messages without coordinating with workers that may already hold an in-memory copy and proceed to send before their final database update fails.

Files Needing Attention: app/controllers/api/messaging.php; src/Appwrite/Platform/Workers/Messaging.php

Important Files Changed

Filename Overview
src/Appwrite/Platform/Workers/Messaging.php Adds missing-document handling and best-effort failure persistence while preserving terminal delivery states.
app/controllers/api/messaging.php Allows processing-message deletion, but the previously reported race with an already-running delivery worker remains.
tests/e2e/Services/Messaging/MessagingBase.php Updates deletion expectations and verifies successful message creation before exercising the new behavior.

Reviews (5): Last reviewed commit: "Merge branch 'main' into fix-messaging-s..." | Re-trigger Greptile

Comment thread app/controllers/api/messaging.php Resolved
Delivery is followed by attachment cleanup, which throws on its own when
a bucket or file backing an attachment is gone. Reaching the fallback
with a status already written rewrote a delivered message to failed and
attributed a storage error to it, while it kept its delivery count and
timestamp.

Skip the fallback write once the message holds a terminal status.
@github-actions

github-actions Bot commented Aug 4, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-messaging-stuck-processing (after).

Metric Before After Change
🚀 Requests/sec 208.44 199.69 ⚪ -4.2%
⏱️ Latency P50 69.39 ms 71.79 ms ⚪ +3.5%
⏱️ Latency P95 243.28 ms 249.82 ms ⚪ +2.7%
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 71.79 249.82 12,483 199.69 +6.54
Account 135.11 349.57 657 11.05 +24.5
TablesDB 68.98 226.57 6,789 110.87 +4.76
Storage 63.58 228.46 3,285 55.28 -0.09
Functions 113.84 312.67 1,752 30.15 +29.44

Top API waits (after)

API request Max wait (ms)
functions.create 939.28
storage.files.delete 899.12
account.name.update 853.65
storage.files.preview 828.83
functions.variables.get 799.62

HarshMN2345 and others added 2 commits August 4, 2026 13:01
Drop the note describing the old fall-through, which the code no longer
does, and shorten the rest to match the density of the surrounding file.
@HarshMN2345
HarshMN2345 merged commit 6315f88 into main Aug 4, 2026
1 check 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.

2 participants