Repository navigation
fix(realtime): synchronise presence upsert and close - #14597
ArnabChatterjee20k wants to merge 20 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.
…ounter Replaces the cache-backed holder set, the per-worker lease-renewal ticker and the 180s lease from #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]>
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]>
…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]>
|
Review complete. 🟠 2 high 💬 Inline comments (2)
This PR introduces multi-connection presence holds: a Redis holder counter plus distributed locking in
Reviewed commit: de20a4e |
The REST-delete holder-balancing ran in the pubsub closure, which is
nested in onWorkerStart and had neither $presenceState nor $container in
scope. Thread $presenceState through onWorkerStart and resolve the lock
pool via $register->get('pools'), matching the rest of the file.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Security rulesNo new WARNING or ERROR findings from security rules. 19 existing findings tracked in
|
There was a problem hiding this comment.
Adds multi-holder presence accounting with a Redis-backed hold counter and distributed lock, but two high-severity counter-imbalance bugs can leak presence rows and usage metrics for up to 30 days.
Key findings
- 🟠 Stripping one presence releases the connection's whole hold — Realtime.php:278
- 🟠 Presence handler resurrects closed connection entry — Presence.php:117
| unset($this->connections[$connectionId]['presences'][$presenceId]); | ||
| $removed++; | ||
|
|
||
| $userId = (string) ($connection['userId'] ?? ''); | ||
| if ($userId !== '') { | ||
| $removed[$userId] = ($removed[$userId] ?? 0) + 1; | ||
| } |
There was a problem hiding this comment.
🟠 bug · high
Stripping one presence releases the connection's whole hold
The holder counter is incremented once per connection, no matter how many presences that connection holds (firstHold in src/Appwrite/Realtime/Message/Handlers/Presence.php). But removePresenceFromConnections counts one released holder for a connection whenever any presence is stripped from it, without checking whether the connection still holds other presences (src/Appwrite/Messaging/Adapter/Realtime.php:278-283). A connection holding presences A and B loses its whole hold when A is deleted via REST, driving the counter to zero early; on close, releaseConnection decrements again, goes negative, and keeps B's row alive until expiresAt (30 days) with no presences.[presenceId].delete event.
📋 Prompt for AI Agents
In src/Appwrite/Messaging/Adapter/Realtime.php, removePresenceFromConnections (lines 278-283): after unset($this->connections[$connectionId]['presences'][$presenceId]), increment $removed[$userId] only if the connection's 'presences' array is now empty; if other presences remain, the connection still holds one counted hold and must not be released. Update tests/unit/Messaging/MessagingTest.php to cover a connection holding two presences where only one is deleted.
There was a problem hiding this comment.
A realtime connection holds at most one presence, so the "A and B" case can't arise. presenceLogs has a unique index on userId (one row per user) and a connection is authenticated as exactly one user, so upsertForUser always resolves to that user's single row — the connection's presences map never holds more than one id. removePresenceFromConnections groups the stripped holders by userId, and each held exactly one presence and incremented the counter once, so the per-user decrement matches the increment. (If the one-row-per-user model were ever dropped, this would need per-presence counting.)
There was a problem hiding this comment.
The architectural claim is worth examining carefully, but it doesn't fully address the original finding.
Even accepting that one connection maps to one user and one presence row, the core counter mismatch remains: firstHold increments the holder count once when a connection subscribes, but the current diff increments $removed[$userId] once for every connection that held the removed presence — which could be multiple connections from the same user (e.g. two browser tabs). More critically, the fix in the diff does not add the guard called for in the original finding: it should only count a connection as 'released' when its presences array becomes empty after the unset. Without that check, a connection that somehow holds more than one presence (or if the one-row assumption is relaxed) would still be over-counted. The diff changes the grouping key from a flat counter to a per-user map, but does not add empty($this->connections[$connectionId]['presences']) as a condition before incrementing.
If the invariant 'one presence per connection' is guaranteed by the data model, please point to where that constraint is enforced (e.g. the unique index or the subscription logic), so the assumption can be validated. Otherwise, the safer fix — checking that presences is empty before counting a released hold — is still needed.
🟡 Tier B · Needs changes before merging
Adds distributed per-user locking and Redis holder counts so realtime presence rows remain while any connection holds them, with cleanup integrated into socket close, re-authentication, and REST-delete paths. It also configures websocket heartbeats, groups removed holders by user, and adds coverage for multi-connection presence retention. Latest changes: The latest commits move the lease refresh to immediately before each row deletion and skip holder registration when the connection disappeared while the upsert was suspended.
Fix with agent prompt### Issue 1
src/Appwrite/Realtime/Message/Handlers/Presence.php:123-124
**Clean up an upsert that finishes after its socket closes**
If the first upsert suspends and `onClose` removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.
### Issue 2
app/realtime.php:738
**Do not let a delayed delete event remove a newer hold**
A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.
### Issue 3
src/Appwrite/Realtime/Message/Handlers/Presence.php:127-129
**Do not acknowledge an upsert without tracking its holder**
When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.
### Issue 4
src/Appwrite/Presences/State.php:109
**Keep the lease valid through the database delete**
`refresh()` proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.
---
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 · 3
Reviewed the commits since |
| $deletedPresenceId, | ||
| ); | ||
| $deletedProjectId = (string) ($event['project'] ?? ''); | ||
| $strippedHolders = $realtime->removePresenceFromConnections($deletedProjectId, $deletedPresenceId); |
There was a problem hiding this comment.
Do not let a delayed delete event remove a newer hold
A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.
Prompt To Fix With AI
This is a comment left during a code review.
Path: app/realtime.php
Line: 738
Comment:
**Do not let a delayed delete event remove a newer hold**
A REST delete event can arrive after a realtime upsert has recreated the row with the same presence ID. This removes the new hold from connection state and schedules a decrement against the new counter, so the live row is no longer cleaned up when that socket closes. The delete and upsert paths are not serialized, and this handler also processes delete events generated by close cleanup.
---
For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.🟠 Major · concurrency · Reply if this doesn't apply.
There was a problem hiding this comment.
@hansi-codes what do you think can be a good way of doing this? we are refresh() where delete just giving up if token is changed
There was a problem hiding this comment.
refresh() fences only the database delete in releaseConnection(); it does not protect this pub/sub cleanup path. Here the event immediately strips the connection’s hold, then schedules the counter decrement separately (app/realtime.php lines 735–745, State.php lines 88–110). The delete event is matched by presence ID alone (Realtime.php lines 296–324), so it can’t distinguish an old delete from a newer hold for the same ID. REST delete also does not take this lock (Delete.php lines 62–84).
I’d make the cleanup generation-aware: include a lifecycle token/revision in the delete event and the connection’s hold, then under the same per-user lock as upsert, strip and decrement only matching holds. Alternatively, under that lock, verify the current row is still absent/the deleted generation is still current before stripping and decrementing. Just putting the strip under the lock is not enough: a delayed event can acquire it after the newer upsert and still remove that hold.
There was a problem hiding this comment.
Agreed it's a real race and the pub/sub strip isn't under the lock. In this design it's an uncoordinated cross-system event, so it falls to the expiresAt backstop like the other abnormal paths (worker crash, lock contention): the row is still correctly deleted by the REST call; the only residual is a counter that can drift for the sub-second window where a re-upsert and the delayed event overlap, which expiresAt reclaims.
For full race-freedom the generation-token idea works, or — since HTTP requests already have a lock resource (app/init/resources/request.php) — the REST Delete.php could take the same per-user lock and clear the counter atomically with the row delete, making the pub/sub path strip-only. I can do that to close the window rather than lean on expiry; the tradeoff is added coordination on the REST path vs. a self-healing soft-state drift.
There was a problem hiding this comment.
Locking REST Delete and clearing the counter would not close this race: after that lock is released, a new upsert can add a hold for the same presence ID before the old delete event is processed. The pub/sub handler still removes holds by project and presence ID alone (app/realtime.php, Realtime.php), while upsert records that ID as the connection’s hold (Presence.php). If the event also decrements, it can decrement the new counter; if it becomes strip-only, the new hold is still lost and its close cannot release it.
The delete event needs to identify the hold generation it invalidates, and the handler should strip/decrement only matching holds. The REST lock can serialize the row deletion and counter update, but it does not make a delayed event safe by itself. The finding still applies.
| } catch (Contention) { | ||
| // On contention, upsert anyway but skip the count and hold so they stay balanced. | ||
| return $upsert(); |
There was a problem hiding this comment.
Do not acknowledge an upsert without tracking its holder
When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 127-129
Comment:
**Do not acknowledge an upsert without tracking its holder**
When lock acquisition times out, this still commits the upsert but neither increments the shared count nor records the connection's hold. If another counted connection then closes, its decrement can reach zero and delete the row while this successfully-upserted connection is still live.
---
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.
Deliberate. On contention we skip the increment and the hold together, so no unsynchronised half-state is written. The timed-out connection isn't tracked, so if a counted holder closes the row can be removed and this connection re-publishes on its next presence message. Contention on a per-user lock around a millisecond op is rare; we take the brief gap over an unlocked increment (the read-modify-write flagged elsewhere).
There was a problem hiding this comment.
This still permits the failure the finding describes: after lock contention, the handler upserts and returns the normal response and event without recording a hold for that connection (Presence.php lines 134–157). If another counted holder then closes, its decrement reaches zero and deletes the row (State.php lines 92–110), even though the contended connection remains live. A later presence message is not guaranteed, so this is more than a brief gap. Please reject or retry the upsert on contention rather than acknowledge it without tracking its holder.
| continue; | ||
| } | ||
|
|
||
| $dbForProject->getAuthorization()->skip(fn () => $dbForProject->deleteDocument(self::COLLECTION_ID, $presenceId)); |
There was a problem hiding this comment.
Keep the lease valid through the database delete
refresh() proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Presences/State.php
Line: 109
Comment:
**Keep the lease valid through the database delete**
`refresh()` proves ownership only before the database read; the lease then lasts 10 seconds while the read and this unconditional delete run. If those calls outlast the lease, another upsert can acquire the lock and write the row, after which this delete can still remove that newer presence.
---
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.
Tightened in 300a354. The refresh() fence now sits immediately before each deleteDocument (after the read), so ownership is re-proven right before the destructive write rather than before the read. For a single-row delete the read -> refresh -> delete window is sub-millisecond. A token-fenced conditional delete would close the residual gap entirely, but utopia/database doesn't expose one; given the over-retention bias the remaining window fails safe (skip delete -> expiresAt).
There was a problem hiding this comment.
This narrows the race, but the lease is still not guaranteed through the delete. It can expire after refresh() succeeds and before deleteDocument() commits; a new upsert can then acquire the lock, write the row, and have that write removed by the old, unconditional delete (delete path). A slow or suspended database operation means the remaining window is not necessarily sub-millisecond, and this path does not skip the delete if the lease expires during it.
The lock implementation documents this limitation: refresh() proves ownership when it returns, not when a later write commits (Distributed.php). So the delete still needs protection through commit, such as a conditional/fenced delete or another guarantee that the lease cannot expire while it runs.
✨ Benchmark resultsComparing
Per-scenario breakdown & investigation detailsMetrics below reflect the current branch (after). Δ P95 compares against the base.
Top API waits (after)
|
- Presence upsert: after the (suspending) DB upsert, bail if onClose has since removed the connection, so the map write cannot resurrect a dead connection entry and leak an un-decrementable holder. - releaseConnection: move the refresh() fence to immediately before each deleteDocument so the lease is re-proven right before the destructive step, not before the preceding read. Co-Authored-By: Claude Opus 4.8 <[email protected]>
| if (!isset($realtime->connections[$connectionId])) { | ||
| return $presence; |
There was a problem hiding this comment.
Clean up an upsert that finishes after its socket closes
If the first upsert suspends and onClose removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/Appwrite/Realtime/Message/Handlers/Presence.php
Line: 123-124
Comment:
**Clean up an upsert that finishes after its socket closes**
If the first upsert suspends and `onClose` removes this connection before it resumes, this return skips recording a hold, but the database upsert has already created or refreshed the row and the close handler had no presence ID to release. The handler still emits the upsert event afterward, leaving a presence online until its 30-day expiry despite the socket being gone.
---
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.
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, which takes 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.Every holder-leave path feeds the counter, not just socket close, so the count can never drift above the live holders:
State::releaseConnection()(lock → decrement → fence → delete at zero).unsubscribe()clears the connection's holds, so the handler captures them first: a re-auth to the same user carries the holds across, a re-auth to a different user releases the previous user's holds.Lease safety. The destructive delete is fenced on lock ownership: before deleting,
refresh()proves the lease is still held (a token-guarded CAS). If the locked work outran the TTL or the key was evicted, another operation may already own the user, so the delete is skipped and the row left to itsexpiresAt. Lock contention falls the same way — toward keeping the row — never toward deleting a live one.Abnormal death (worker OOM/kill) decrements nothing; the row's
expiresAtis the intended backstop for that case.Dead sockets reach the close 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.*.deleteexpiresAtexpiresAtCovered by
testPresenceCloseKeepsPresenceHeldByAnotherConnection.Fixes #14342
Fixes #14343
🤖 Generated with Claude Code