Skip to content

fix(presences): delete a user's presence when the user is blocked or deleted - #14397

Merged
HarshMN2345 merged 13 commits into
mainfrom
fix-presence-user-cleanup
Oct 28, 2026
Merged

HarshMN2345 merged 13 commits into
mainfrom
fix-presence-user-cleanup

Conversation

@HarshMN2345

@HarshMN2345 HarshMN2345 commented Oct 12, 2026 •

Copy link
Copy Markdown
Member

What does this PR do?

  • Adds PresenceState::deleteForUser(), which deletes a user's presence, purges the presence list cache, decrements the presence usage metric and sends presences.[presenceId].delete to realtime subscribers.
  • It runs when a user is blocked (PATCH /v1/users/:userId/status with status: false, and PATCH /v1/account/status) and when a user is deleted (DELETE /v1/users/:userId, DELETE /v1/account). Before, a presence written over REST stayed readable, with no event, until its expiresAt.
  • The user is already blocked or deleted when it runs, so a failure is recorded on the span instead of failing the request.
  • Deletes::deleteUser() also calls deleteForUser(), so a presence left behind by a failed cleanup during the request is removed by the deletes worker, with the same cache purge, usage update and delete event. The worker now injects queueForRealtime; Cloud's Deletes worker calls parent::action() positionally, so its next server bump must inject and forward it.
  • testUpdateUserStatusDeletesPresence and testDeleteUserDeletesPresence cover the block and delete paths.

Verification

A user upserts a REST presence with read("any"); an observer is subscribed to presences. Then, on a local stack:

Action main this branch
Block with an API key GET 200, no event GET 404, one presences.<id>.delete
Block own account (PATCH /v1/account/status) GET 200, no event GET 404, one delete event
Delete with an API key GET 200, no event GET 404, one delete event

A presence held by a realtime connection is also removed when its user is blocked, and the observer gets exactly one delete event (3 of 3 runs), although the realtime server closes that connection at the same time. The deletes worker change was checked with an API on main (no cleanup during the request) and a deletes worker on this branch: the 4 of 8 user deletions that worker took removed their presences and sent one delete event each, the 4 taken by the main worker did neither.

The two new tests fail on main (GET 200) and pass here. E2E testUpdateUserStatus, testDeleteUser, testBlockedAccount, testSelfBlockedAccount, testDeleteAccount and testDeleteAccountWith* pass against this branch, as do PresenceCustomServerTest and PresenceCustomClientTest. Pint and PHPStan pass on the changed files.

Fixes #14344

…deleted

A REST presence outlived its user: blocking or deleting the user left it
readable and sent no event until it expired. Blocking a user (server or self)
and deleting a user (server or account) now delete their presence and send
presences.[presenceId].delete to subscribers.
@luxor-code-review

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

Copy link
Copy Markdown

Review complete. 🟡 2 medium

💬 Inline comments (2)

  • 🟡 Presence deletes skip the events queue — State.php:213
  • 🟡 Harden deleteForUser against purge failures — State.php:189

This PR introduces src/Appwrite/Presences/State.php::deleteForUser(), which batch-deletes all presence documents for a user, purges the presence list cache, and fires realtime triggers, then wires it into the legacy account and Users module endpoints so presence state no longer outlives a deleted or blocked user.

Files Change
src/Appwrite/Presences/State.php New deleteForUser() method: batch presence deletion, list-cache purge, per-presence realtime trigger, and negative presence metric accounting.
app/controllers/api/account.php Legacy account logout/delete paths now call deleteForUser() alongside session removal.
src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php User deletion endpoint purges presence via the pre-delete snapshot of the user.
src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php Blocking a user (status set to blocked) also purges their presence state.

Reviewed commit: 0d1f766

@ghost

ghost commented Oct 12, 2026 •

Copy link
Copy Markdown

🔵 Tier A · Mergeable after minor fixes

The previously reported swallowed-cleanup-failure issue in PresenceState remains open; the cache-purge ordering issue is fixed.

This PR removes a user's stored REST presences when their account is blocked or deleted, and repeats user-presence cleanup in deferred delete processing; cleanup purges list cache, adjusts usage, and emits per-presence realtime delete events. It also revokes MQTT connections in the relevant block/delete flows and makes a concurrent presence update/delete return presence_not_found. E2E and worker unit coverage exercise the cleanup paths.

Latest changes: The newest commit updates direct Deletes::action() calls in the unit tests to pass a stub for the injected realtime queue.

Verdict New comments Fixed Still open
💬 Commented 0 0 1

Note

Not approving while a bug finding is open: Swallowed cleanup failures leave no retry path

Fix with agent prompt
### Issue 1
src/Appwrite/Presences/State.php:224
**Swallowed cleanup failures leave no retry path**

If `deleteDocuments()` throws, for example during a transient database failure, this catch lets the block/delete request succeed even though the presence may remain, and it schedules no retry. For a deleted user, this cleanup cannot be retried through the same endpoint, so the presence can stay readable until expiry.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.
📂 Walkthrough · 8
File Change
app/controllers/api/account.php Runs presence cleanup and revokes MQTT connections when an account is blocked or deleted.
src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php Removes the user's presences and revokes MQTT connections during user deletion.
src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php Removes the user's presences and revokes MQTT connections when an administrator blocks the user.
src/Appwrite/Platform/Workers/Deletes.php Repeats presence cleanup during deferred user deletion and publishes the associated usage update.
src/Appwrite/Presences/State.php Adds per-user presence deletion with cache purge, usage adjustment, and realtime delete events.
src/Appwrite/Platform/Modules/Presences/HTTP/Update.php Returns not-found when a presence disappears during an update.
tests/e2e/Services/Presences/PresenceBase.php Adds E2E coverage for presence removal after blocking or deleting a user.
tests/unit/Platform/Workers/DeletesTest.php Passes the realtime queue dependency to direct worker-action test calls.
⏳ Still open from earlier reviews · 1

Merged main (4ac84d8); no changes to this PR's code since c7a5781 · 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

Comment thread src/Appwrite/Presences/State.php Resolved
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Security rules

No new WARNING or ERROR findings from security rules.

6 existing findings tracked in .semgrep/baseline.json
  • php.appwrite.guest-write-without-abuse-limit (3)
  • php.appwrite.secret-compare-timing (1)
  • 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.

@luxor-code-review luxor-code-review Bot 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.

Adds presence cleanup to user deletion, blocking, and logout paths via a new State::deleteForUser() that purges presence rows, flushes the list cache, and emits realtime triggers.

Key findings

  • 🟡 Presence deletes skip the events queue — State.php:213
  • 🟡 Harden deleteForUser against purge failures — State.php:189

Comment thread src/Appwrite/Presences/State.php Outdated
Comment on lines +213 to +221
$queueForRealtime
->reset()
->setProject($project)
->setUser($user)
->setEvent('presences.[presenceId].delete')
->setParam('presenceId', $presence->getId())
->setPayload($presence->getArrayCopy())
->trigger();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🟡 bug · medium

Presence deletes skip the events queue

The new State::deleteForUser publishes only to queueForRealtime (src/Appwrite/Presences/State.php:213-221), bypassing State::triggerEvent, which is how every other presence-delete path notifies consumers — the realtime disconnect cleanup uses it at app/realtime.php:1564, and the Presences REST delete route emits the event through its event/audits labels. As a result, user deletion, account deletion, and user blocking emit the presence delete to realtime subscribers but never to webhooks, functions events, audits, or the events worker. Integrations subscribed to presences.[presenceId].delete will not observe these forced presence removals.

📋 Prompt for AI Agents

In src/Appwrite/Presences/State.php around lines 180-222, make deleteForUser accept an additional Appwrite\Event\Event $queueForEvents parameter and, inside the foreach ($presences ...) loop, replace the direct $queueForRealtime->reset()->...->trigger() chain with $this->triggerEvent($queueForEvents, $queueForRealtime, $project, $user, 'presences.[presenceId].delete', $presence) so the events queue (webhooks, audits, events worker) is notified the same way as app/realtime.php:1564 and the Presences REST delete route. Then update the four callers to pass their queueForEvents dependency: src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php (~line 83), src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php (~line 76), and app/controllers/api/account.php (~line 600 and ~line 4095); each action already injects queueForEvents.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Keeping this realtime-only on purpose. triggerEvent() does not enqueue queueForEvents either; it only uses it to fill queueForRealtime->from(), so the realtime close path is realtime-only too, and the expiry cleanup sends nothing. The user change itself still goes through the events queue as users.[userId].update.status or users.[userId].delete, which is what webhooks and functions receive.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks for the explanation, but it doesn't fully hold up under scrutiny.

You're right that triggerEvent uses queueForEvents to populate queueForRealtime->from() (for subscriber matching), but triggerEvent also calls $queueForEvents->trigger() — which is what dispatches to webhooks, functions, audits, and the events worker. The realtime disconnect path at app/realtime.php:1564 does call triggerEvent, so it does enqueue the event. The argument that the parent users.[userId].delete or users.[userId].update.status event is sufficient isn't correct for consumers subscribed specifically to presences.[presenceId].delete — those subscribers will never observe forced removals via this path.

The current diff still shows only $queueForRealtime->reset()->...->trigger() with no queueForEvents parameter or triggerEvent call, so the finding remains unresolved.

Comment thread src/Appwrite/Presences/State.php Resolved
@github-actions

github-actions Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

✨ Benchmark results

Comparing main (before) → fix-presence-user-cleanup (after).

Metric Before After Change
🚀 Requests/sec 129.35 130.88 ⚪ +1.2%
⏱️ Latency P50 134.21 ms 131.36 ms ⚪ -2.1%
⏱️ Latency P95 321.94 ms 310.96 ms ⚪ -3.4%
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 131.36 310.96 8,094 130.88 -10.97
Account 260.23 440.17 426 7.05 -65.56
TablesDB 126.17 239.65 4,402 72.82 -11.27
Storage 125.08 286.67 2,130 37.35 -6.88
Functions 194.36 365.86 1,136 20.81 +5.59

Top API waits (after)

API request Max wait (ms)
account.name.update 684.56
functions.create 623.54
storage.buckets.create 521.49
functions.variables.update 517.75
functions.delete 512.59

…he request

The user is already blocked or deleted when its presence is cleaned up, so an
error there must not turn the request into a 500.

@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 · See the inline comments. Summary

->setPayload($presence->getArrayCopy())
->trigger();
}
} catch (Throwable $th) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Swallowed cleanup failures leave no retry path

If deleteDocuments() throws, for example during a transient database failure, this catch lets the block/delete request succeed even though the presence may remain, and it schedules no retry. For a deleted user, this cleanup cannot be retried through the same endpoint, so the presence can stay readable until expiry.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 224

Comment:
**Swallowed cleanup failures leave no retry path**

If `deleteDocuments()` throws, for example during a transient database failure, this catch lets the block/delete request succeed even though the presence may remain, and it schedules no retry. For a deleted user, this cleanup cannot be retried through the same endpoint, so the presence can stay readable until expiry.

---

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

🟡 Minor · error-handling · Reply if this doesn't apply.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

For deleted users, 00b6c60 makes the deletes worker the second attempt: deleteUser() now removes leftover presences, as it does sessions and tokens. Checked with an API on main and a deletes worker on this branch: the 4 of 8 jobs that worker took removed their presences, the 4 the main worker took did not. Blocking has no worker job, so a failed cleanup there leaves the presence until its expiresAt, as before this PR, and is recorded on the span.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

You’re right that the deletes worker retries removing presence rows for deleted users. That does not cover blocking: both status-update paths call deleteForUser(), but schedule no delete job (user status route, account status route). If cleanup fails, the catch only records the error and returns (State::deleteForUser); the blocked user’s presence can therefore remain until expiry unless the status update is explicitly retried. The finding still applies to blocked users.

Deleting a user removes its presence during the request. The deletes worker
now removes any presence left behind, as it already does for sessions and
tokens, so a failure during the request does not leave it until expiry.

@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 · See the inline comments. Summary

The deletes worker removed leftover presences without purging the presence
list cache, updating usage or telling subscribers. It now uses the same
PresenceState::deleteForUser(), so a presence it removes also sends
presences.[presenceId].delete. The worker injects queueForRealtime for it.
# Conflicts:
#	app/controllers/api/account.php
#	src/Appwrite/Platform/Modules/Users/Http/Users/Delete.php
#	src/Appwrite/Platform/Modules/Users/Http/Users/Status/Update.php
#	tests/e2e/Services/Presences/PresenceBase.php
@HarshMN2345 HarshMN2345 changed the title fix(presences): delete a user's presence when the user is blocked or deleted fix(presences): delete presences of blocked or deleted users and 404 on a concurrent delete Oct 27, 2026

@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 · See the inline comments. Summary

@HarshMN2345 HarshMN2345 changed the title fix(presences): delete presences of blocked or deleted users and 404 on a concurrent delete fix(presences): delete a user's presence when the user is blocked or deleted Oct 27, 2026
@HarshMN2345
HarshMN2345 merged commit 1c8e1a7 into main Oct 28, 2026
8 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.

🐛 Bug Report: Presences survive blocking or deleting the user

2 participants