Repository navigation
fix(realtime): synchronise presence upsert and close - #14461
ArnabChatterjee20k wants to merge 19 commits into
Conversation
A client that lost its network, or a realtime server that was killed, left its presence online: nothing ever closed the connection, and a realtime presence expired only after 30 days. Swoole now closes a connection that sends nothing for 120 seconds (SDKs ping every 20), so the close path deletes its presence as usual. A realtime presence now expires after a 180-second lease that its server renews every minute while the connection is open, so one whose server died expires within the lease.
…olds it A user has one presence, but closing any connection that upserted it deleted it, even while another tab or device of the same user was still connected. Each connection that upserts the presence is now recorded as a holder in the shared cache, so this works across realtime servers. Closing a connection deletes the presence only when no other holder remains. Holders are renewed with the lease, so those of a server that died stop counting.
…t claimed A connection that upserted the user's presence while another one was closing was recorded as a holder only after its write, so the closing connection could miss it and delete the presence it had just written (4 of 40 runs with the two messages 0-2 ms apart). The upsert now records its holder before writing, and the close path deletes only rows not written since its holder check. A failed write releases the holder again.
🟡 Tier B · Needs changes before merging
The PR serializes realtime presence upserts and connection-close cleanup with per-user distributed locks and Redis holder counts, keeping a user's single presence row until its final connection releases it. It also configures Swoole heartbeat detection and balances holder counts when REST deletes remove presence references from realtime connections. The newest change preserves presence holds when a socket reauthenticates as the same user and releases the previous user's holds when identity changes. Latest changes: The newest commits preserve presence ownership across same-user reauthentication and release the previous user's holds, usage, and delete events when the socket switches identities.
Note Not approving while a bug finding is open: The lock can expire during a slow database operation Fix with agent prompt### Issue 1
src/Appwrite/Realtime/Message/Handlers/Presence.php:26
**The lock can expire during a slow database operation**
This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.
### Issue 2
src/Appwrite/Presences/State.php:40
**Orphaned counters never expire after a worker crash**
If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.
### Issue 3
src/Appwrite/Presences/State.php:137
**Lock contention drops the REST-delete counter compensation**
If the per-user lock stays busy past `LOCK_TIMEOUT`, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; `expiresAt` only expires the row, not the Redis counter.
### Issue 4
src/Appwrite/Realtime/Message/Handlers/Authentication.php:137-154
**Cover reauthentication while a connection holds presence**
This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.📂 Walkthrough · 8
⏳ Still open from earlier reviews · 4
Merged |
895b625 to
553d021
Compare
…ounter Replaces the cache-backed holder set, the per-worker lease-renewal ticker and the 180s lease from appwrite#14398 with a per-user distributed lock guarding a soft Redis connection counter: - A `presence:connections:{project}:{user}` counter in Redis tracks how many live connections hold the one presence row per user. First upsert of a connection INCRs it; close DECRs and deletes the row only when it hits zero. - Upsert and close take a `presence:{project}:{user}` Distributed lock, so counting a new holder never races a decrement-to-zero. No DB schema change. - The count is soft state: if Redis loses it the row just lives on until its expiresAt, which returns to +30 days as the crash backstop (OOM/SIGKILL is out of scope again). - The DB row stays the single source of truth; Redis holds only the lock and the counter. State::hold/release/renew, the LEASE constants and the renewal timer are removed. The Swoole heartbeat config is kept so dead sockets still reach onClose. Co-Authored-By: Claude Opus 4.8 <[email protected]>
553d021 to
81e0b4e
Compare
|
|
||
| class Presence extends Action | ||
| { | ||
| public const int LOCK_TTL = 10; |
There was a problem hiding this comment.
The lock can expire during a slow database operation
This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 26
Comment:
**The lock can expire during a slow database operation**
This 10-second lease is not refreshed, while the lock protects database work that can take longer than 10 seconds. If it expires mid-upsert or close, another server can acquire the lock and mutate the same counter and row concurrently, defeating the serialization this lock is meant to provide.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · concurrency · Reply if this doesn't apply.
There was a problem hiding this comment.
Addressed by fencing the destructive step on lease ownership rather than sizing the TTL to the worst case.
Before deleting a presence at zero holders, the close now calls $lock->refresh() — a token-guarded CAS. If it returns false (the locked work outran the TTL, or the key was evicted) we skip the delete and let expiresAt reclaim the row, instead of wiping a presence another operation may already own. The locked section is a single DECR plus a single-row get/delete — milliseconds against a 10s TTL — so a lapse is a degraded-DB edge, and the fence makes that edge fail toward over-retention, never a wrong delete.
We deliberately did not add a background refresh/watchdog (that pattern is for minutes-long holds); the inline fence is sufficient here. (commit 4f68d76)
There was a problem hiding this comment.
This does not fully close the lease-expiry race. refresh() extends the Redis lease once; it does not fence the database writes that follow it (lock refresh, close path). If the get/delete work outlasts that refreshed TTL, another upsert can acquire the lock and write the presence before the old close’s delete completes, leaving an active connection without its row.
The upsert path also performs its database write and counter increment without refreshing or checking lease ownership (upsert path). So the 10-second slow-operation case is still possible; this finding remains open.
| // Counts a connection as a holder of the user's presence. | ||
| public function incrementConnections(\Redis $redis, string $projectId, string $userId): void | ||
| { | ||
| $redis->incr(self::getConnectionCounterKey($projectId, $userId)); |
There was a problem hiding this comment.
Orphaned counters never expire after a worker crash
If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 40
Comment:
**Orphaned counters never expire after a worker crash**
If a realtime worker is killed, its connections never decrement this key, and the counter has no TTL. After reconnect, an upsert increments the stale count and a normal close leaves it positive, so the row can be retained beyond the claimed 30-day expiry rather than that expiry serving as the crash backstop.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · bug · Reply if this doesn't apply.
Addresses review findings on the lock + counter: - Determine the holder and record it inside the lock, so two concurrent presence messages on one connection cannot both count the same hold. - On lock-acquire timeout, upsert still writes the presence but leaves the counter and the hold untouched (no unsynchronised count); close leaves the row to its expiresAt instead of decrementing and deleting outside the lock. - Delete the row only on an exact zero count. A negative count means Redis lost the key while holders were open, so the row is kept for expiresAt rather than deleted out from under a live connection. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The findings that requested changes are resolved. See the summary comment for what is still open.
…s-refcount # Conflicts: # app/realtime.php
Replace the hand-rolled acquire() + try/finally/release() at the upsert and close sites with withLock(), which handles release itself. Behavior is unchanged: the contention fallbacks are preserved via catch(Contention). Co-Authored-By: Claude Opus 4.8 <[email protected]>
Before deleting a presence row at zero holders, refresh() to prove the lease is still held. If the locked work outran the TTL (or the key was evicted) another operation may already own the user and have re-created the row, so skip the delete and let expiresAt reclaim it rather than wipe a live presence. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Drop self-explanatory method comments and compress multi-line rationale to a single line; the full reasoning lives in the PR description. Co-Authored-By: Claude Opus 4.8 <[email protected]>
Move the close path's lock -> decrement -> fence -> delete into State::releaseConnection, so the one destructive path lives in one place. onClose now calls it; the upsert handler shares State's lock key, TTL constants and attribute stripping. No behaviour change. Co-Authored-By: Claude Opus 4.8 <[email protected]>
A REST DELETE strips the presence from each holder's in-memory map, so those connections' closes can no longer decrement the counter and the count leaks. removePresenceFromConnections now reports the per-user holders it stripped, and the realtime worker decrements the counter for them under the lock (counter only -- the row is already gone). Co-Authored-By: Claude Opus 4.8 <[email protected]>
unsubscribe() clears the connection's presence map on re-auth, so its later close could not decrement the counter and the count leaked. The handler now captures the holds first: a re-auth to the same user carries them across, and a re-auth to a different user releases the previous user's holds (decrement, delete at zero, emit delete) under the lock. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| try { | ||
| $lock->withLock(fn () => $this->decrementConnectionsBy($redis, $projectId, $userId, $count), timeout: self::LOCK_TIMEOUT); | ||
| } catch (Contention) { | ||
| // On contention, let the counter drift; the row is already gone and expiresAt covers it. |
There was a problem hiding this comment.
Lock contention drops the REST-delete counter compensation
If the per-user lock stays busy past LOCK_TIMEOUT, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; expiresAt only expires the row, not the Redis counter.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 137
Comment:
**Lock contention drops the REST-delete counter compensation**
If the per-user lock stays busy past `LOCK_TIMEOUT`, this silently skips the decrement permanently. A later upsert inherits the stale holder count, so its final close can leave the recreated presence row behind; `expiresAt` only expires the row, not the Redis counter.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟡 Minor · concurrency · Reply if this doesn't apply.
| if (!empty($presences) && !empty($projectId) && $projectId !== 'console') { | ||
| if ($previousUserId === $user->getId()) { | ||
| if (isset($realtime->connections[$connectionId])) { | ||
| $realtime->connections[$connectionId]['presences'] = $presences; | ||
| } | ||
| } else { | ||
| $this->releasePreviousHolds( | ||
| $pools, | ||
| $presenceState, | ||
| $database, | ||
| $publisherForUsage, | ||
| $queueForEvents, | ||
| $queueForRealtime, | ||
| $project, | ||
| (string) $projectId, | ||
| (string) $previousUserId, | ||
| \array_keys($presences), | ||
| ); |
There was a problem hiding this comment.
Cover reauthentication while a connection holds presence
This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Authentication.php
Line: 137-154
Comment:
**Cover reauthentication while a connection holds presence**
This branch changes presence ownership during reauthentication, but the e2e tests cover manual authentication and presence lifecycle separately rather than together. A same-user case should verify the hold is released on close, and a user-switch case should verify the prior user's presence is retained only while another holder remains; otherwise either transition can leak or prematurely delete presence without detection.
---
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.
|
Superseded by #14597, which is the same change on a branch in this repo (so CI runs there) and carries the CI fix plus the latest |
What does this PR do?
A user has one presence row (unique
userId), but several realtime connections (tabs, devices) can hold it, spread across workers and nodes. Two things went wrong:presences.*.deletefired, user shown offline).This synchronises the two paths so the row lives exactly as long as a connection holds it, whichever operation runs first.
How it synchronises
A per-user
Utopia\Lock\Distributedlock (presence:{project}:{user}) wraps both the upsert and the close, and a soft Redis counter (presence:connections:{project}:{user}) tracks how many connections hold the row:INCRthe counter.DECRthe counter and delete the row (and emitpresences.*.delete) only when it reaches zero; otherwise the row stays.Because both sides take the same lock, counting a new holder can never race a decrement-to-zero, so the outcome is the same no matter which runs first:
The counter arithmetic lives in
Presences\State::incrementConnections()/decrementConnections(), which take the Redis handle; the realtime layer only orchestrates the lock. The DB row stays the single source of truth — Redis holds only the lock and the counter, both soft state.Dead sockets reach this path too: the Swoole
heartbeat_check_interval/heartbeat_idle_timeconfig closes a silently-gone connection (lost network, suspended device), so itsonClosedecrements like a clean close.Behaviour
presences.*.deleteCovered by
testPresenceCloseKeepsPresenceHeldByAnotherConnection.Fixes #14342
Fixes #14343