From 5e53f9e588571ac7a9e14380972fd8436bae3dda Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 02:16:56 +0000 Subject: [PATCH 01/25] Stop two devices flipping presence and flooding federation (ADR-0871 to ADR-0873) Two devices of one account, one syncing online and one unavailable, set the account's presence back and forth on every sync. Each change woke the other device's long-poll and queued an m.presence EDU for every server in the account's rooms, filling the dispatch queue so every other federation send was refused. - A device that synced online in the last 5 minutes holds the account online; a sync asking for unavailable then changes nothing, and set_presence=offline forgets the device (AccountPresenceTracker, ADR-0871). - An account's presence changes at most once every 5 s: the first change in the window is kept, later ones are dropped (sync) or refused with 429 M_LIMIT_EXCEEDED (PUT /presence) (ADR-0872). - A classic /sync whose only news is the caller's own presence row keeps waiting instead of answering nothing (ADR-0873). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + ...syncing-online-holds-its-account-online.md | 54 ++++ ...-change-in-a-five-second-window-is-kept.md | 54 ++++ ...-news-is-its-own-presence-keeps-waiting.md | 48 ++++ docs/adr/index.md | 3 + docs/matrix-v1.19-client-server-api.md | 2 +- docs/observability-audit.md | 8 +- docs/threat-model.md | 9 + docs/user-manual.md | 6 +- .../homeserver/AccountPresenceTracker.hpp | 89 +++++++ .../homeserver/ClientServerRuntime.hpp | 7 +- .../homeserver/HomeserverRuntime.hpp | 7 + .../homeserver/PresenceService.hpp | 21 +- .../merovingian/homeserver/PresenceWrite.hpp | 19 ++ .../homeserver/PresenceWriteStatus.hpp | 21 ++ src/homeserver/AGENTS.md | 13 +- src/homeserver/AccountPresenceTracker.cpp | 139 ++++++++++ src/homeserver/ClientServerRuntime.cpp | 71 ++++- src/homeserver/PresenceService.cpp | 84 ++++-- src/homeserver/meson.build | 1 + .../test_client_server_conformance.cpp | 4 +- ...test_database_nul_remaining_query_flow.cpp | 7 +- tests/integration/test_presence_flow.cpp | 251 +++++++++++++++++- .../test_security_audit_presence_flow.cpp | 4 + tests/integration/test_sync_handler_flow.cpp | 5 +- tests/meson.build | 1 + tests/unit/test_account_presence_tracker.cpp | 225 ++++++++++++++++ 27 files changed, 1111 insertions(+), 48 deletions(-) create mode 100644 docs/adr/0871-a-device-syncing-online-holds-its-account-online.md create mode 100644 docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md create mode 100644 docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md create mode 100644 include/merovingian/homeserver/AccountPresenceTracker.hpp create mode 100644 include/merovingian/homeserver/PresenceWrite.hpp create mode 100644 include/merovingian/homeserver/PresenceWriteStatus.hpp create mode 100644 src/homeserver/AccountPresenceTracker.cpp create mode 100644 tests/unit/test_account_presence_tracker.cpp diff --git a/CHANGELOG.md b/CHANGELOG.md index 7808725d9..37d607f8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -177,6 +177,12 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The Fedora 44 and 45 RPMs build again: GCC 16 refused `std::ranges::find` with a bare string literal under C++26, and `reject-unsafe.sh` now rejects that form in code and tests (ADR-0870). * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. +* Two clients of one account, one syncing online and one `unavailable`, no longer flip its presence on every sync: an + online device holds the account online for 5 minutes (ADR-0871). +* An account's presence changes at most once every 5 s: later changes in the window are dropped, and `PUT /presence` + answers 429. A flip loop no longer fills the federation queue for every other send (ADR-0872). +* A classic `/sync` whose only news is the caller's own presence keeps waiting instead of answering nothing (ADR-0873). +* `docs/observability-audit.md` named the wrong logger for `presence.sync.set`; it is `client_server`. ## Release notes diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md new file mode 100644 index 000000000..24d0d4785 --- /dev/null +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -0,0 +1,54 @@ +# A device syncing online holds its account online against another device syncing unavailable + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the owner's server logged `presence.outbound.refused` for every remote server, many times a second. +Two devices of one account were syncing at once, one with `set_presence` omitted (online) and one with +`set_presence=unavailable`. Each sync set the account's presence its own way, each change woke the other device's +long-poll, and the two flipped it every 50 to 250 ms. Each flip queued an `m.presence` EDU for each of about 470 +servers, which filled the outbound dispatch queue and so refused every other federation send. + +## Context and Problem Statement + +A presence row is one per account, but `set_presence` is sent per sync, and so per device. The spec says "Any activity +that bumps the last active time on any of the user's clients will cause the server to automatically set their presence +to `online`", so a client in the background asking for `unavailable` should not take the account down while another +client is in use. How should the asks of several devices become one presence? + +## Decision Drivers + +* The account must not flip with each device's sync. +* A device that stops syncing must not hold the account online for ever. +* Memory stays bounded whatever the number of accounts and devices. + +## Considered Options + +1. Note each device's last ask in memory (`AccountPresenceTracker`). A device that asked for `online` holds the account + online for `device_fresh_ms` (5 minutes, the idle timeout of ADR-0492). A sync asking for `unavailable` changes + nothing while another device holds the account online, and never raises the account to online. +2. Keep one ask per account, the latest, as before. +3. Store the devices' asks in the database. + +## Decision Outcome + +Chosen option: 1, because it matches the spec's "any of the user's clients" and ends the loop at its cause. + +* `set_presence=offline` forgets the device's ask: it no longer holds the account online. +* The freshness time is the idle timeout, so a closed client holds the account online exactly as long as the idle + sweep would leave it online after that client's last sync. +* At most `max_devices_per_account` (64) devices per account, the least recently seen replaced; at most `max_accounts` + (65,536) accounts, pruned by the idle sweep every 30 s. With the table full after a prune, a sync of an account it + does not hold asks for itself alone, as before this decision. +* The asks are in memory only: after a restart each device's next sync puts its ask back. +* The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. + +### Positive Consequences + +* Two clients of one account no longer set its presence back and forth. + +### Negative Consequences + +* After every online client closes, a background client asking for `unavailable` sets the account unavailable only + once the freshness time has passed, up to 5 minutes later (the idle sweep sets it unavailable at the same moment). +* Option 2 is the simpler model, and looks better in isolation; it is the one that made the loop. diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md new file mode 100644 index 000000000..2f4e85cb2 --- /dev/null +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -0,0 +1,54 @@ +# The first presence change in a five-second window is kept, and every other one in it is dropped + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the presence loop of ADR-0871. Even with the devices combined, anything that changes an account's +presence many times a second (a buggy client, two clients fighting through `PUT /presence`) queues an EDU for every +server in the account's rooms each time. + +## Context and Problem Statement + +Every change of a local user's presence is stored, wakes the syncs of everyone who shares a room with them and queues +one `m.presence` EDU per remote server in those rooms, each in its own transaction. How often may one account cause +that? + +## Decision Drivers + +* One account must not be able to fill the federation dispatch queue. +* The owner's rule: the first change in a window goes through and the rest are dropped. Keeping the last change for + later ("coalescing") is the same rate limit with a different change kept, and the last change is as likely to be the + wrong one as the first. +* `PUT /presence/{userId}/status` has only 200 and 429 in the spec. + +## Considered Options + +1. A window of `change_window_ms` (5 s) per account, started by a change kept. A change asked for inside it is dropped + (a sync: nothing stored, woken or sent) or refused (`PUT`: 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` and + `Retry-After`). Judged and noted under `runtime.mutex`, with the write. +2. Coalesce: hold the last change asked for in the window and send it when the window ends. +3. Limit only the outbound EDUs, and store every change. + +## Decision Outcome + +Chosen option: 1. + +* The window is per account, not per device, since the row and its EDUs are per account. +* A change is a change of the stored state by a sync, or any `PUT`. A sync that leaves the state as it is refreshes the + last-active time in memory as before and is not limited. +* Not limited: the idle sweep (the server's own change, at most once per idle period; a user who returns at once is + marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar, + and inbound presence from other servers (their own server's to limit). +* With `AccountPresenceTracker` full after a prune, a change of an account it does not hold is refused (fails closed, + as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. +* Tests move the clock with `HomeserverRuntime::test_presence_clock_advance_ms`. + +### Positive Consequences + +* One account causes at most one presence broadcast every 5 seconds. + +### Negative Consequences + +* A change asked for in the window is lost, not deferred: a client that set `unavailable` a second after a sync set it + `online` is refused, and its sync's next change is what counts. +* A client that does not retry a 429 on `PUT /presence` keeps whatever was set first. diff --git a/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md new file mode 100644 index 000000000..d19b69692 --- /dev/null +++ b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md @@ -0,0 +1,48 @@ +# A classic /sync whose only news is the caller's own presence keeps waiting + +* Status: accepted +* Date: 2026-11-21 + +Technical Story: the presence loop of ADR-0871. A classic `/sync` long-poll returned at once whenever the sync stream +moved past its `since`, even when the only new row was the caller's own presence, which `/sync` never sends to its own +user. Each presence change of an account answered every waiting sync of that account with nothing, and each client +synced again at once. + +## Context and Problem Statement + +The long-poll check of `GET /sync` is "has the sync stream or the timeline moved past `since`?". Sliding sync already +waits past bumps its response would not send (ADR-0863, ADR-0869). Classic `/sync` did not, so a change of the caller's +own presence, including the one the same request's `set_presence` just made, woke it into an empty answer. + +## Decision Drivers + +* ADR-0863's rule: never wake a poll with a test the response does not share, or it is answered with nothing, again. +* The check runs under `runtime.mutex` on every rerun, so it must cost a constant. + +## Considered Options + +1. When a `/sync` with a `since` token would answer and its only news is exactly one sync stream position, the + caller's own presence row (`only_own_presence_since`), answer `needs_wait` with the wait cursor advanced to the + stream's newest position. The response, when it comes, is built from the request's own `since`, as before. +2. Judge every position after `since` (a walk of each sync surface). +3. Send the caller their own presence, so the answer is not empty. + +## Decision Outcome + +Chosen option: 1, because it is a constant-time check and covers the case that loops: one device's change waking the +account's other devices, and a request's own `set_presence` waking itself. + +* With any other position after `since`, or several, the sync answers as before; the check never delays news. +* A sync with no `since` (an initial sync) is not affected. +* The rerun of a woken poll judges again from the same `since`: a new position that is not the caller's presence ends + the wait. + +### Positive Consequences + +* A client's own presence change no longer costs it, or its other devices, an empty round trip. + +### Negative Consequences + +* Two of the caller's own presence changes in a row (at least 5 s apart, ADR-0872) answer the second with nothing, as + before this decision. +* Option 3 changes what clients are sent; the spec's presence events are for other users. diff --git a/docs/adr/index.md b/docs/adr/index.md index 157616603..0c29b3e64 100644 --- a/docs/adr/index.md +++ b/docs/adr/index.md @@ -744,3 +744,6 @@ * [0868 - The typing and receipts extensions keep their event wrapper](0868-the-typing-and-receipts-extensions-keep-their-event-wrapper.md) * [0869 - A sliding sync long poll wakes only for what its response sends, and a room is sent again when its summary changes](0869-a-sliding-sync-long-poll-wakes-only-for-what-its-response-sends.md) * [0870 - A ranges algorithm takes a typed value, never a bare string literal](0870-a-ranges-algorithm-takes-a-typed-value-never-a-bare-string-literal.md) +* [0871 - A device syncing online holds its account online against another device syncing unavailable](0871-a-device-syncing-online-holds-its-account-online.md) +* [0872 - The first presence change in a five-second window is kept, and every other one in it is dropped](0872-the-first-presence-change-in-a-five-second-window-is-kept.md) +* [0873 - A classic /sync whose only news is the caller's own presence keeps waiting](0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md) diff --git a/docs/matrix-v1.19-client-server-api.md b/docs/matrix-v1.19-client-server-api.md index 7b82dee2e..30ffed44a 100644 --- a/docs/matrix-v1.19-client-server-api.md +++ b/docs/matrix-v1.19-client-server-api.md @@ -181,7 +181,7 @@ comparison (ADR-0631); any other `from` is `400 M_INVALID_PARAM`. | `GET` | `/_matrix/client/v3/presence/{userId}/status` | `getPresence` | access token | - | 200, 403, 404 | | `PUT` | `/_matrix/client/v3/presence/{userId}/status` | `setPresence` | access token | required application/json | 200, 429 | -`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". +`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. A device that synced `online` in the last 5 minutes holds the account online against another syncing `unavailable` (ADR-0871). An account's presence changes at most once in 5 s: a later `/sync` change in the window is dropped and a `PUT` is 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` (ADR-0872). A `/sync` long-poll whose only news is the caller's own presence keeps waiting (ADR-0873). `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". ## Push notifications diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 847c80ecd..0efd03262 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -130,8 +130,12 @@ is full. covered by `server.sso.redirect_url_allowlist` — see `docs/threat-model.md` ("Open redirect and login-token exfiltration via SSO redirectUrl"). - `presence.set` (debug, logger `client_server`) records a `PUT /presence/{userId}/status` - (fields `actor`, `presence`; never the status message). `presence.sync.set` (debug, logger - `presence`) records a `/sync` that changed the caller's state (fields `actor`, `presence`). + (fields `actor`, `presence`; never the status message). `presence.set.limited` (debug, logger + `client_server`) records one refused with 429 because the account's presence changed less than + 5 s before (fields `actor`, `presence`, `retry_after_ms`; ADR-0872). `presence.sync.set` (debug, + logger `client_server`) records a `/sync` that changed the caller's state (fields `actor`, + `presence`). `presence.change.limited` (debug, logger `presence`) records a `/sync` change dropped + for the same reason (fields `actor`, `device_id`, `presence`, `retry_after_ms`). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/docs/threat-model.md b/docs/threat-model.md index 81580300f..b542a7d61 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -2791,6 +2791,15 @@ nothing, all from trusting the worker's view or the hook's transport. reporting it. - **Presence off.** `presence.enabled=false` stores and sends nothing, so an operator who does not want to publish presence to the federation need not. +- **One account flooding the federation queue with presence.** Each change of a local user's + presence queues an `m.presence` EDU for every server in their rooms. Two clients of one account + fighting over `set_presence` changed it many times a second and filled the dispatch queue, so + every other federation send was refused. A device that synced online holds the account online + for 5 minutes (ADR-0871), a classic `/sync` no longer wakes for its own presence (ADR-0873), and + an account's presence changes at most once every 5 s, the first change kept (ADR-0872). The + tracker behind both is bounded and fails closed when full. **Residual risk:** one change every + 5 s per account still costs an EDU per remote server; many accounts at once are bounded only by + the dispatch queue's own shares. ### Remote space hierarchy answers (0.12.60) diff --git a/docs/user-manual.md b/docs/user-manual.md index 53c7dab02..507644d79 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1210,8 +1210,10 @@ the users who share a room with them in `/sync` (`presence.events`) and by `GET /presence/{userId}/status`, and sent to other servers that share a room with them as an `m.presence` EDU. `PUT /presence/{userId}/status` sets it, and so does `/sync`: omitting `set_presence` marks the user online, `unavailable` marks them idle, `offline` leaves it as it -is. Presence reaches only users who share a joined room with the user; anyone else asking for it -gets `403 M_FORBIDDEN`, as for a user who does not exist. +is. A device that synced online in the last 5 minutes keeps the user online while another of their devices syncs +`unavailable`. A user's presence changes at most once every 5 seconds: a later change by `/sync` in that time is +ignored, and `PUT /presence` answers `429` with `retry_after_ms`. Presence reaches only users who share a joined +room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. | Key | Default | When to change | |---|---|---| diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp new file mode 100644 index 000000000..22753ff6d --- /dev/null +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "merovingian/database/StateGroupKeyHash.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace merovingian::homeserver +{ + +// What each local account's devices last asked of its presence through a sync's `set_presence`, and when the account's +// presence last changed. In memory only; every operation takes the time in milliseconds of a clock that never goes back +// (`presence_limit_clock_ms`). +// +// Devices (ADR-0871): a device that syncs `online` holds its account online for `device_fresh_ms`, so another device +// syncing `unavailable` in that time does not set the account unavailable. Two clients of one account, one in the +// foreground and one in the background, otherwise set the presence back and forth on every sync. +// +// Changes (ADR-0872): the first change of an account's presence starts a window of `change_window_ms`; every other +// change asked for in the window is dropped (a sync) or refused with 429 (`PUT /presence`). The first one asked for is +// the one kept, never the last. +// +// Bounded: at most `max_accounts` accounts of `max_devices_per_account` devices each. A new device past the device cap +// replaces the account's least recently seen one. An account the table has no room for after a prune has its devices +// ignored (its sync asks for itself alone, as without this table) and every change refused until there is room, so a +// flood of accounts cannot lift the limit for itself. Not thread-safe: `runtime.mutex` serialises every use +// (`HomeserverRuntime::presence_tracker`). +class AccountPresenceTracker final +{ +public: + static constexpr auto change_window_ms = std::int64_t{5'000}; + // The idle timeout (`presence_idle_timeout_ms`): a device holds the account online for as long as the idle sweep + // would leave it online after that device's last sync. + static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; + // Far more devices than one person syncs from at once; each is a device ID and two integers. + static constexpr auto max_devices_per_account = std::size_t{64U}; + // Accounts that synced or changed presence within the last five minutes. + static constexpr auto max_accounts = std::size_t{65'536U}; + + // Notes that `device` of `user` synced asking for `online` (true) or `unavailable` (false) at `now_ms`. True when a + // device of the account, this one included, asked for online within `device_fresh_ms`. + [[nodiscard]] auto note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) + -> bool; + + // A sync with `set_presence=offline`: the device no longer holds the account online. + auto forget_device(std::string_view user, std::string_view device) -> void; + + // How long `user` must wait before a change of presence is kept, or nullopt when one may be kept now. + [[nodiscard]] auto change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const + -> std::optional; + + // Starts the window of `user` at `now_ms`: a change was just kept. + auto note_change(std::string_view user, std::int64_t now_ms) -> void; + + // Removes the devices not seen for `device_fresh_ms`, then every account left with no device whose window ended. + auto prune(std::int64_t now_ms) -> void; + + // Accounts held, ones a prune would remove included. + [[nodiscard]] auto account_count() const noexcept -> std::size_t; + +private: + struct Device final + { + std::string id{}; + std::int64_t seen_at_ms{0}; + bool online{false}; + }; + struct Account final + { + std::vector devices{}; + std::optional changed_at_ms{}; + }; + + // The account of `user`, made when there is room (after a prune when the table is full); nullptr when there is + // none. + [[nodiscard]] auto account_for(std::string_view user, std::int64_t now_ms) -> Account*; + + std::unordered_map> m_accounts{}; +}; + +} // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/ClientServerRuntime.hpp b/include/merovingian/homeserver/ClientServerRuntime.hpp index 01629c8db..f39647135 100644 --- a/include/merovingian/homeserver/ClientServerRuntime.hpp +++ b/include/merovingian/homeserver/ClientServerRuntime.hpp @@ -18,6 +18,7 @@ #include "merovingian/homeserver/LocalHttpResponse.hpp" #include "merovingian/homeserver/LoginTokenStore.hpp" #include "merovingian/homeserver/OperationResult.hpp" +#include "merovingian/homeserver/PresenceWrite.hpp" #include "merovingian/homeserver/RegistrationValidationSession.hpp" #include "merovingian/homeserver/SafetyReportIndex.hpp" #include "merovingian/homeserver/UiaSession.hpp" @@ -139,7 +140,11 @@ auto install_test_per_user_rate_limit_engine(ClientServerRuntime& runtime) -> vo std::vector changes) -> bool; [[nodiscard]] auto record_device_list_change(ClientServerRuntime& runtime, database::PersistentDeviceListChange change) -> bool; -[[nodiscard]] auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> bool; +// Stores a presence the user set (`PUT /presence`), wakes syncs and tells the servers that share a room with them. +// `limited` when the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago (ADR-0872): +// nothing is stored. Takes runtime.mutex. +[[nodiscard]] auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) + -> PresenceWrite; // One pass of the "presence-idle" job (CS API "Presence", "Idle timeout"; ADR-0492): every local user whose // presence is `online` and whose last active time is over `presence_idle_timeout_ms` is set to `unavailable`, // told to the servers that share a room with them, and long-polling syncs are woken. Takes runtime.mutex for diff --git a/include/merovingian/homeserver/HomeserverRuntime.hpp b/include/merovingian/homeserver/HomeserverRuntime.hpp index a212bf414..23455949e 100644 --- a/include/merovingian/homeserver/HomeserverRuntime.hpp +++ b/include/merovingian/homeserver/HomeserverRuntime.hpp @@ -17,6 +17,7 @@ #include "merovingian/federation/FederationRuntimeState.hpp" #include "merovingian/federation/RemoteDeviceListCache.hpp" #include "merovingian/federation/ServerDiscoveryNetwork.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/AccountSessionStore.hpp" #include "merovingian/homeserver/ActiveServerSigningKeySecret.hpp" #include "merovingian/homeserver/AppserviceDeliveryBackoff.hpp" @@ -261,6 +262,12 @@ struct HomeserverRuntime final // Test-only: added to the wall clock by `oauth_device_clock_ms`, so a test moves the device grant's time (expiry, // polling interval, the wrong-code window) without sleeping. Always 0 in production. std::uint64_t test_device_grant_clock_advance_ms{0U}; + // What each local account's devices last asked of its presence, and when its presence last changed (ADR-0871, + // ADR-0872). In memory only, bounded. Guarded by `mutex`. Takes its time from `presence_limit_clock_ms`. + AccountPresenceTracker presence_tracker{}; + // Test-only: added to the steady clock by `presence_limit_clock_ms`, so a test moves past a presence change window + // or a device's freshness without sleeping. Always 0 in production. + std::int64_t test_presence_clock_advance_ms{0}; // The signed-in sessions of the account pages at `/_merovingian/account` (plan P6, ADR-0796) and the cross-signing // reset approvals they grant (ADR-0797). In memory only, bounded. Here, not on `ClientServerRuntime`, because a // password change, a password reset and a deactivation (`AuthService.cpp`) end them. Guarded by `mutex`. diff --git a/include/merovingian/homeserver/PresenceService.hpp b/include/merovingian/homeserver/PresenceService.hpp index f81573a5b..857941af8 100644 --- a/include/merovingian/homeserver/PresenceService.hpp +++ b/include/merovingian/homeserver/PresenceService.hpp @@ -61,6 +61,10 @@ inline constexpr auto presence_idle_catch_up_interval = std::chrono::seconds{1}; // Wall-clock milliseconds since the Unix epoch. [[nodiscard]] auto presence_now_ms() -> std::int64_t; +// The clock of `HomeserverRuntime::presence_tracker` (ADR-0871, ADR-0872): steady-clock milliseconds, which never go +// back, plus `test_presence_clock_advance_ms`. Not a point in calendar time. +[[nodiscard]] auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t; + // "The last active time must be up to date whenever the server gives a presence event to the // client": the stored value plus the time since it was true. Never negative. [[nodiscard]] auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept @@ -115,12 +119,17 @@ auto note_local_message_activity(HomeserverRuntime& runtime, std::string_view us [[nodiscard]] auto parse_sync_presence_mode(std::optional value) noexcept -> std::optional; -// Applies a /sync's `set_presence` to a local user. Only a change of state is stored (and so only -// a change is sent to other users); an `online` user who syncs again just has their last-active -// time refreshed in memory. The caller holds runtime.mutex. Returns the new row when the state -// changed, so the caller can send it to other servers and wake long-polling syncs. -[[nodiscard]] auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, SyncPresenceMode mode) - -> std::optional; +// Applies the `set_presence` of a /sync from `device` to a local user. Only a change of state is stored (and so only +// a change is sent to other users); an `online` user who syncs again just has their last-active time refreshed in +// memory. The device's ask is noted in `runtime.presence_tracker`: +// * `offline` stores nothing and the device no longer holds the account online; +// * `unavailable` changes nothing while another device of the account asked for `online` within +// `AccountPresenceTracker::device_fresh_ms` (ADR-0871); +// * a change within `AccountPresenceTracker::change_window_ms` of the account's last one is dropped (ADR-0872). +// The caller holds runtime.mutex. Returns the new row when the state changed, so the caller can send it to other +// servers and wake long-polling syncs. +[[nodiscard]] auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional; // The `presence.events` of a /sync response for `user`: other users who share a joined room, // whose presence changed since `since_sync_stream_id` or who started sharing a room in diff --git a/include/merovingian/homeserver/PresenceWrite.hpp b/include/merovingian/homeserver/PresenceWrite.hpp new file mode 100644 index 000000000..6fab9eb47 --- /dev/null +++ b/include/merovingian/homeserver/PresenceWrite.hpp @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include "merovingian/homeserver/PresenceWriteStatus.hpp" + +#include + +namespace merovingian::homeserver +{ + +struct PresenceWrite final +{ + PresenceWriteStatus status{PresenceWriteStatus::failed}; + // When `status` is limited: how long until a change is kept, at least 1 ms. + std::uint32_t retry_after_ms{0U}; +}; + +} // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/PresenceWriteStatus.hpp b/include/merovingian/homeserver/PresenceWriteStatus.hpp new file mode 100644 index 000000000..9fadb1fde --- /dev/null +++ b/include/merovingian/homeserver/PresenceWriteStatus.hpp @@ -0,0 +1,21 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later +#pragma once + +#include + +namespace merovingian::homeserver +{ + +// What became of a presence a user set (`set_presence`). +enum class PresenceWriteStatus : std::uint8_t +{ + // Stored and sent, or accepted and dropped because presence is off. + stored, + // Not stored: the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago (ADR-0872). + limited, + // The store refused the row. + failed, +}; + +} // namespace merovingian::homeserver diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 8d9f27aa9..361516f10 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,6 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, failing closed at the cap. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | @@ -75,7 +76,7 @@ This is the largest and most complex module — read this file carefully before | `PushRoomFacts.cpp` | `push_room_facts`, `room_member_display_name`, `push_evaluation_context`: the evaluation context push delivery and unread counting share | | `PushBadgeCount.cpp` | `count_push_badge`: the Push Gateway `counts.unread` from one walk of the events, newest first in stream order, that stops once every room is settled, at most 10000 rows (ADR-0207) | | `PushRuleUnreadClassifier.cpp` | `PushRuleUnreadClassifier`: counts unread events by the user's push rules, from the start of their current join (R15, ADR-0205) | -| `PresenceService.cpp` | Presence (CS API "Presence", SS API `m.presence`): `read_presence` (GET), `apply_sync_presence` (the `/sync` `set_presence` parameter), `build_sync_presence_events` (`presence.events`), `accept_inbound_presence` (the EDU sink's presence case) and `record_presence`, the one place a presence row is stored. `expire_idle_presence` (the idle sweep, ADR-0492). `presence.enabled=false` turns every entry point into a no-op. Sending the EDU stays in `ClientServerRuntime.cpp` (`broadcast_presence_edu`), beside the other outbound EDUs | +| `PresenceService.cpp` | Presence (CS API "Presence", SS API `m.presence`): `read_presence` (GET), `apply_sync_presence` (the `/sync` `set_presence` parameter), `build_sync_presence_events` (`presence.events`), `accept_inbound_presence` (the EDU sink's presence case) and `record_presence`, the one place a presence row is stored. `expire_idle_presence` (the idle sweep, ADR-0492). `presence_limit_clock_ms`, the clock of `AccountPresenceTracker`. `presence.enabled=false` turns every entry point into a no-op. Sending the EDU stays in `ClientServerRuntime.cpp` (`broadcast_presence_edu`), beside the other outbound EDUs | | `PushRetry.cpp` | `attempt_push_delivery` (every push attempt: circuit breaker, rejected pushkeys, scheduling retries) and `PushRetryJob`, the one thread that sends retries (R14, ADR-0206); a run is bounded by a time budget, takes retries one recipient at a time in turn and sends with a shorter timeout (ADR-0410), and a slow answer counts against the gateway's circuit (ADR-0409) | | `PasswordReset.cpp` | Password reset by email (ADR-0481): `make_password_reset_token` (8 characters, 40 bits), `normalize_password_reset_token`, `send_password_reset_email` (a background task parked in `orphan_futures_`, at most 8 in flight, no lock held while it sends). The endpoints are in `ClientServerRuntime.cpp` before the auth gate; `reset_local_user_password` is in `AuthService.cpp` | | `ClientServerRuntime.cpp` (MatrixRTC) | `GET /_matrix/client/v1/rtc/transports` and `GET /_matrix/client/unstable/org.matrix.msc4143/rtc/transports` advertise `server.rtc.livekit.service_url` as `{"type":"livekit","livekit_service_url":...}` (`livekit_transport_json`): `transports` and `[]` when none on the stable path, `rtc_transports` and `{}` on the unstable one; both flags `org.matrix.msc4143` and `org.matrix.msc4143.stable` are always in `/versions`, and the well-known document gains `org.matrix.msc4143.rtc_foci` only with a URL (ADR-0822). With the built-in token service instead (`server.rtc.livekit.url`, ADR-0829) they list `{"type":"livekit","url":...}` (`livekit_sfu_transport_json`), the stable path `m.livekit` after it, and `org.matrix.msc4195` and `.stable` are true; `rtc_foci` stays for the external service only. `voip/turnServer` returns `server.turn.server` or, when that is empty, each `server.turn.uris` entry in order (ADR-0821) | @@ -1379,6 +1380,16 @@ without that check ignores `presence.enabled=false`. Rules: - A `/sync` changes presence only on a change of state (`apply_sync_presence`), and only a change is sent to other servers (`broadcast_presence_edu`); a sync loop must never cost a row, a stream position or an EDU per poll. +- Each device's `set_presence` is noted in `HomeserverRuntime::presence_tracker` (`AccountPresenceTracker`, ADR-0871): + a device that asked for `online` in the last 5 minutes holds the account online, so a sync asking for `unavailable` + then changes nothing and never raises the account; `offline` forgets the device. The idle sweep prunes the table. +- A change of an account's presence starts a 5 s window in which no other change is kept (ADR-0872): a sync's is + dropped, a `PUT /presence` is 429 (`set_presence` returns `PresenceWrite`). Judge and note it under `runtime.mutex` + with the write, and keep the first change, never the last. The idle sweep and the profile propagation are not + limited. A new path that changes a local user's presence state is limited the same way. Tests move the clock with + `test_presence_clock_advance_ms`, never with a sleep. +- A classic `/sync` whose only news is the caller's own presence row waits on (`only_own_presence_since`, ADR-0873): + never wake a poll for what its response does not send. - `accept_inbound_presence` binds `user_id` to the sending origin, bounds the entries it looks at, and keeps only users who share a joined room with a local user (one pass over the memberships per EDU). A new field accepted from the EDU needs a bound. diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp new file mode 100644 index 000000000..1efbdffd7 --- /dev/null +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -0,0 +1,139 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later + +#include "merovingian/homeserver/AccountPresenceTracker.hpp" + +#include +#include + +namespace merovingian::homeserver +{ +namespace +{ + + // True when a device last seen at `seen_at_ms` still speaks for its account at `now_ms`. A time ahead of `now_ms` + // (which the clock does not produce) counts as just seen. + [[nodiscard]] auto device_is_fresh(std::int64_t seen_at_ms, std::int64_t now_ms) noexcept -> bool + { + return now_ms <= seen_at_ms || now_ms - seen_at_ms < AccountPresenceTracker::device_fresh_ms; + } + + // True when a window started at `changed_at_ms` has ended at `now_ms`. + [[nodiscard]] auto window_has_ended(std::optional changed_at_ms, std::int64_t now_ms) noexcept -> bool + { + return !changed_at_ms.has_value() || + (now_ms > *changed_at_ms && now_ms - *changed_at_ms >= AccountPresenceTracker::change_window_ms); + } + +} // namespace + +auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now_ms) -> Account* +{ + if (auto const found = m_accounts.find(user); found != m_accounts.end()) + { + return &found->second; + } + if (m_accounts.size() >= max_accounts) + { + prune(now_ms); + if (m_accounts.size() >= max_accounts) + { + return nullptr; + } + } + return &m_accounts.try_emplace(std::string{user}).first->second; +} + +auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) + -> bool +{ + auto* const account = account_for(user, now_ms); + if (account == nullptr) + { + return online; + } + auto& devices = account->devices; + auto const same_device = [device](Device const& held) { + return held.id == device; + }; + if (auto const held = std::ranges::find_if(devices, same_device); held != devices.end()) + { + held->seen_at_ms = now_ms; + held->online = online; + } + else + { + if (devices.size() >= max_devices_per_account) + { + auto const oldest = std::ranges::min_element(devices, std::ranges::less{}, &Device::seen_at_ms); + devices.erase(oldest); + } + devices.push_back(Device{std::string{device}, now_ms, online}); + } + return std::ranges::any_of(devices, [now_ms](Device const& held) { + return held.online && device_is_fresh(held.seen_at_ms, now_ms); + }); +} + +auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device) -> void +{ + if (auto const found = m_accounts.find(user); found != m_accounts.end()) + { + std::erase_if(found->second.devices, [device](Device const& held) { + return held.id == device; + }); + } +} + +auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const + -> std::optional +{ + auto const found = m_accounts.find(user); + if (found == m_accounts.end()) + { + // No window to wait for, unless there is no room to start one: then the change is refused (fails closed). + return m_accounts.size() >= max_accounts ? std::optional{change_window_ms} : std::nullopt; + } + auto const changed_at_ms = found->second.changed_at_ms; + if (window_has_ended(changed_at_ms, now_ms)) + { + return std::nullopt; + } + // A start ahead of `now_ms` (which the clock does not produce) is waited for in full, never longer. + auto const elapsed = now_ms > *changed_at_ms ? now_ms - *changed_at_ms : std::int64_t{0}; + return change_window_ms - elapsed; +} + +auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now_ms) -> void +{ + if (auto* const account = account_for(user, now_ms); account != nullptr) + { + account->changed_at_ms = now_ms; + } +} + +auto AccountPresenceTracker::prune(std::int64_t now_ms) -> void +{ + for (auto entry = m_accounts.begin(); entry != m_accounts.end();) + { + auto& account = entry->second; + std::erase_if(account.devices, [now_ms](Device const& held) { + return !device_is_fresh(held.seen_at_ms, now_ms); + }); + if (account.devices.empty() && window_has_ended(account.changed_at_ms, now_ms)) + { + entry = m_accounts.erase(entry); + } + else + { + entry = std::next(entry); + } + } +} + +auto AccountPresenceTracker::account_count() const noexcept -> std::size_t +{ + return m_accounts.size(); +} + +} // namespace merovingian::homeserver diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index c5761db19..523a74751 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -80,6 +80,7 @@ #include "merovingian/federation/PublicRoomsRefusal.hpp" #include "merovingian/federation/Security.hpp" #include "merovingian/homeserver/AccountPage.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/AppserviceDelivery.hpp" #include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/homeserver/AuthService.hpp" @@ -122,6 +123,8 @@ #include "merovingian/homeserver/PasswordReset.hpp" #include "merovingian/homeserver/PresenceReadStatus.hpp" #include "merovingian/homeserver/PresenceService.hpp" +#include "merovingian/homeserver/PresenceWrite.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include "merovingian/homeserver/PublicRooms.hpp" #include "merovingian/homeserver/PushRuleUnreadClassifier.hpp" #include "merovingian/homeserver/RecentlyUnreachableServers.hpp" @@ -7070,6 +7073,20 @@ namespace joined_room.push_back(json_member(std::string{events::unstable_sticky_field}, section)); } + // True when the one sync stream position after `since` is `user`'s own presence row (ADR-0873). A /sync never sends + // the caller their own presence (`build_sync_presence_events`), so its response would hold nothing new. Only one + // position is judged: with any other after `since` the sync answers, as before. + [[nodiscard]] auto only_own_presence_since(database::PersistentStore const& store, std::string_view user, + std::uint64_t since) -> bool + { + if (store.next_sync_stream_id <= since || store.next_sync_stream_id - since != 1U) + { + return false; + } + auto const* const own = database::find_presence_state(store, user); + return own != nullptr && own->stream_id == store.next_sync_stream_id; + } + [[nodiscard]] auto sync_json(ClientServerRuntime& rt, std::string_view user, std::string_view device_id, core::SyncRequest const& request, bool can_wait = true) -> DispatchResult { @@ -7123,12 +7140,16 @@ namespace auto const capped_timeout_ms = std::min(*request.timeout, sync::k_max_sync_timeout_ms); auto const has_timeline_advance = visible_stream_position(rt.homeserver.database) > since_ordering; auto const has_sync_advance = store.next_sync_stream_id > since_sync_stream_id; - if (!has_timeline_advance && !has_sync_advance) + // ADR-0873: the caller's own presence row is never in their response, so a sync whose only news it is + // waits on, past it, rather than answering nothing and being sent again at once. + auto const only_own_presence = + since_token.has_value() && only_own_presence_since(store, user, since_sync_stream_id); + if (!has_timeline_advance && (!has_sync_advance || only_own_presence)) { return DispatchResult{ DispatchResult::Status::needs_wait, {}, - {since_ordering, since_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, + {since_ordering, store.next_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, std::string{user}, std::string{device_id}} }; } @@ -22326,7 +22347,8 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, *presence_mode); changed.has_value()) + if (auto const changed = apply_sync_presence(rt.homeserver, *user, device_id, *presence_mode); + changed.has_value()) { log_diagnostic("presence.sync.set", { {"actor", *user, false}, @@ -22388,7 +22410,8 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, *sliding_presence_mode); changed.has_value()) + if (auto const changed = apply_sync_presence(rt.homeserver, *user, device_id_4186, *sliding_presence_mode); + changed.has_value()) { log_diagnostic("presence.sync.set", { {"actor", *user, false}, @@ -24353,7 +24376,20 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp state.status_msg = status_msg != nullptr ? *status_msg : std::string{}; state.last_active_ago = 0; state.currently_active = (presence_state == "online"); - if (!set_presence(rt, state)) + auto const written = set_presence(rt, state); + if (written.status == PresenceWriteStatus::limited) + { + // ADR-0872: the spec's 429 for this endpoint. The change is refused, not kept for later. + log_diagnostic("presence.set.limited", + { + {"actor", *user, false}, + {"presence", presence_state, false}, + {"retry_after_ms", std::to_string(written.retry_after_ms), false} + }); + return dispatch_err(req, rt, 429U, "M_LIMIT_EXCEEDED", "presence changed too recently", + written.retry_after_ms); + } + if (written.status == PresenceWriteStatus::failed) { return dispatch_err(req, rt, 500U, "M_UNKNOWN", "presence persistence failed"); } @@ -25348,22 +25384,31 @@ auto record_device_list_change(ClientServerRuntime& runtime, database::Persisten return stored; } -auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> bool +auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> PresenceWrite { auto guard = RuntimeLock{runtime.homeserver.mutex}; if (!presence_enabled(runtime.homeserver)) { // Nothing is tracked, so there is nothing to fail: the caller's update is accepted and dropped. - return true; + return PresenceWrite{PresenceWriteStatus::stored, 0U}; } - auto const stored = record_presence(runtime.homeserver, state); - if (stored) + auto& tracker = runtime.homeserver.presence_tracker; + auto const clock_ms = presence_limit_clock_ms(runtime.homeserver); + // ADR-0872: judged and noted under the same lock as the write, so two requests at once cannot both be first. + if (auto const blocked = tracker.change_blocked_for_ms(state.user_id, clock_ms); blocked.has_value()) { - std::ignore = ensure_sync_notifier(runtime); - // The servers that share a room with the user are told; the row is as stored just now. - broadcast_presence_edu(runtime.homeserver, state); + auto const retry_after_ms = std::clamp(*blocked, 1, AccountPresenceTracker::change_window_ms); + return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms)}; } - return stored; + if (!record_presence(runtime.homeserver, state)) + { + return PresenceWrite{PresenceWriteStatus::failed, 0U}; + } + tracker.note_change(state.user_id, clock_ms); + std::ignore = ensure_sync_notifier(runtime); + // The servers that share a room with the user are told; the row is as stored just now. + broadcast_presence_edu(runtime.homeserver, state); + return PresenceWrite{PresenceWriteStatus::stored, 0U}; } auto run_presence_idle_sweep(ClientServerRuntime& runtime) -> std::chrono::milliseconds diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 96049d67f..fa3384f55 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -7,18 +7,23 @@ #include "merovingian/canonicaljson/ParseError.hpp" #include "merovingian/canonicaljson/Parser.hpp" #include "merovingian/canonicaljson/Serializer.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" +#include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/homeserver/PresenceRead.hpp" #include "merovingian/homeserver/PresenceReadStatus.hpp" #include "merovingian/homeserver/SyncPresenceMode.hpp" -#include "merovingian/homeserver/AppserviceEphemeral.hpp" #include "merovingian/observability/LogEventSeverity.hpp" #include "merovingian/observability/SingleLog.hpp" #include "merovingian/sync/SyncFilter.hpp" #include #include +#include #include #include +#include +#include +#include #include #include #include @@ -72,6 +77,18 @@ namespace }); } + // The user's row, through the presence index (ADR-0659), for a change in place; nullptr when there is none. + [[nodiscard]] auto find_mutable_row(database::PersistentStore& store, std::string_view user_id) + -> database::PersistentPresence* + { + auto const* const row = database::find_presence_state(store, user_id); + if (row == nullptr) + { + return nullptr; + } + return &store.presence_states[static_cast(row - store.presence_states.data())]; + } + [[nodiscard]] auto joined_rooms_of(database::PersistentStore const& store, std::string_view user) -> std::unordered_set { @@ -129,6 +146,14 @@ auto presence_now_ms() -> std::int64_t .count(); } +auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t +{ + auto const steady_ms = + std::chrono::duration_cast(std::chrono::steady_clock::now().time_since_epoch()) + .count(); + return static_cast(steady_ms) + runtime.test_presence_clock_advance_ms; +} + auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept -> std::int64_t { auto ago = std::max(row.last_active_ago, std::int64_t{0}); @@ -196,6 +221,10 @@ auto expire_idle_presence(HomeserverRuntime& runtime, std::int64_t now_ms, std:: { return changed; } + // The pass also drops the devices and change windows that no longer speak for an account (ADR-0871). Its own + // changes are neither limited nor noted: the server sets an account idle at most once per idle period, and a user + // who comes back at once is marked online at once. + runtime.presence_tracker.prune(presence_limit_clock_ms(runtime)); // Chosen first, written after: recording a row must not run while the rows are being walked. At most `max_changes` // are chosen; the rest are found by the next pass. auto idle = std::vector{}; @@ -297,23 +326,35 @@ auto parse_sync_presence_mode(std::optional value) noexcept -> return std::nullopt; } -auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, SyncPresenceMode mode) - -> std::optional +auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional { - if (mode == SyncPresenceMode::offline || !presence_enabled(runtime)) + if (!presence_enabled(runtime)) { return std::nullopt; } + auto& tracker = runtime.presence_tracker; + auto const clock_ms = presence_limit_clock_ms(runtime); + if (mode == SyncPresenceMode::offline) + { + // "offline": the client is not to be marked online, so it no longer holds the account online either. + tracker.forget_device(user, device); + return std::nullopt; + } + auto const asks_online = mode == SyncPresenceMode::online; + auto const any_device_online = tracker.note_sync(user, device, asks_online, clock_ms); + if (!asks_online && any_device_online) + { + // ADR-0871: another device of the account asked for online in the freshness time; online beats unavailable. + return std::nullopt; + } auto& store = runtime.database.persistent_store; auto const now_ms = presence_now_ms(); - auto const desired = - mode == SyncPresenceMode::online ? std::string_view{"online"} : std::string_view{"unavailable"}; - auto const existing = std::ranges::find_if(store.presence_states, [user](database::PersistentPresence const& row) { - return row.user_id == user; - }); - if (existing != store.presence_states.end() && existing->presence == desired) + auto const desired = asks_online ? std::string_view{"online"} : std::string_view{"unavailable"}; + auto* const existing = find_mutable_row(store, user); + if (existing != nullptr && existing->presence == desired) { - if (mode == SyncPresenceMode::online) + if (asks_online) { // Still online: nothing to tell anyone, but the user did just do something. existing->last_active_ago = 0; @@ -322,17 +363,28 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, Sync } return std::nullopt; } - auto row = existing != store.presence_states.end() ? *existing : database::PersistentPresence{}; + if (auto const blocked = tracker.change_blocked_for_ms(user, clock_ms); blocked.has_value()) + { + // ADR-0872: the first change in the window was kept; this one is dropped, not kept for later. + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", std::string{desired}, false}, + {"retry_after_ms", std::to_string(*blocked), false} + }); + return std::nullopt; + } + auto row = existing != nullptr ? *existing : database::PersistentPresence{}; row.user_id = std::string{user}; row.presence = std::string{desired}; - row.last_active_ago = mode == SyncPresenceMode::online || existing == store.presence_states.end() - ? std::int64_t{0} - : presence_last_active_ago(*existing, now_ms); - row.currently_active = mode == SyncPresenceMode::online; + row.last_active_ago = + asks_online || existing == nullptr ? std::int64_t{0} : presence_last_active_ago(*existing, now_ms); + row.currently_active = asks_online; if (!record_presence(runtime, row)) { return std::nullopt; } + tracker.note_change(user, clock_ms); row.observed_at_ms = now_ms; return row; } diff --git a/src/homeserver/meson.build b/src/homeserver/meson.build index 0c8d9b076..b38d76e5b 100644 --- a/src/homeserver/meson.build +++ b/src/homeserver/meson.build @@ -14,6 +14,7 @@ homeserver_sources = files( 'PendingAuthorisationStore.cpp', 'DeviceAuthorisationStore.cpp', 'UserCodeAttemptThrottle.cpp', + 'AccountPresenceTracker.cpp', 'RequestHeaders.cpp', 'SafetyReportIndex.cpp', 'RetentionSweep.cpp', diff --git a/tests/conformance/test_client_server_conformance.cpp b/tests/conformance/test_client_server_conformance.cpp index 4cb1a81fe..30695a595 100644 --- a/tests/conformance/test_client_server_conformance.cpp +++ b/tests/conformance/test_client_server_conformance.cpp @@ -49,6 +49,7 @@ #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include #include @@ -3104,7 +3105,8 @@ SCENARIO("GET /sync returns the full top-level v1.19 sync envelope", "[conforman REQUIRE(merovingian::homeserver::record_device_list_change(started.runtime, {0U, user_id, "@carol:example.org", "left"})); REQUIRE(merovingian::homeserver::set_presence(started.runtime, - {0U, "@dave:example.org", "online", "Coding!", 1000U, true})); + {0U, "@dave:example.org", "online", "Coding!", 1000U, true}) + .status == merovingian::homeserver::PresenceWriteStatus::stored); REQUIRE( merovingian::database::store_one_time_key(started.runtime.homeserver.database.persistent_store, {user_id, "DEVICE1", "signed_curve25519:AAA", R"({"key":"x"})"})); diff --git a/tests/integration/test_database_nul_remaining_query_flow.cpp b/tests/integration/test_database_nul_remaining_query_flow.cpp index 11cfcc6b0..2f262dbae 100644 --- a/tests/integration/test_database_nul_remaining_query_flow.cpp +++ b/tests/integration/test_database_nul_remaining_query_flow.cpp @@ -5,9 +5,9 @@ #include "../support/TempDirectory.hpp" #include "merovingian/canonicaljson/CanonicalJsonError.hpp" #include "merovingian/canonicaljson/ParseError.hpp" -#include "merovingian/canonicaljson/Value.hpp" #include "merovingian/canonicaljson/Parser.hpp" #include "merovingian/canonicaljson/Serializer.hpp" +#include "merovingian/canonicaljson/Value.hpp" #include "merovingian/config/ClientRateLimitsConfig.hpp" #include "merovingian/config/Config.hpp" #include "merovingian/config/DatabaseBackend.hpp" @@ -20,13 +20,14 @@ #include "merovingian/database/ExaminedRows.hpp" #include "merovingian/database/PersistentStore.hpp" #include "merovingian/database/PersistentStoreOpenResult.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" +#include "merovingian/homeserver/AuthService.hpp" #include "merovingian/homeserver/ClientServerClock.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/CreateRoomOptions.hpp" #include "merovingian/homeserver/LocalHttpRequest.hpp" #include "merovingian/homeserver/LocalHttpResponse.hpp" -#include "merovingian/homeserver/AuthService.hpp" #include "merovingian/homeserver/RoomService.hpp" #include @@ -287,6 +288,8 @@ SCENARIO("Profile, presence and room identities ignore unrelated raw query text" {"avatar_url", avatar_url} })); } + // Each case changes the presence, so the change window of the last one is let end (ADR-0872). + runtime.homeserver.test_presence_clock_advance_ms += hs::AccountPresenceTracker::change_window_ms; std::ignore = send_request("PUT", presence_path + with_marker("/status"), "{\"presence\":\"" + presence + "\",\"status_msg\":\"" + status_msg + "\"}"); diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index 030c44c49..4f750b610 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -30,8 +30,10 @@ #include "merovingian/federation/EduDispositionStatus.hpp" #include "merovingian/federation/EduType.hpp" #include "merovingian/federation/InboundEduEnvelope.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" +#include "merovingian/homeserver/DispatchResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" #include "merovingian/homeserver/PresenceService.hpp" @@ -203,6 +205,18 @@ auto install_unstarted_dispatch_worker(ClientServerRuntime& runtime) -> void std::string{presence} + R"(","last_active_ago":5000)" + std::string{extra} + "}]}"; } +// The clock of the presence change window and of the devices' freshness moves on without a sleep (ADR-0871, ADR-0872). +auto advance_presence_clock(ClientServerRuntime& runtime, std::int64_t by_ms) -> void +{ + runtime.homeserver.test_presence_clock_advance_ms += by_ms; +} + +// Lets the window opened by the last presence change end, so the next change is kept. +auto let_presence_window_end(ClientServerRuntime& runtime) -> void +{ + advance_presence_clock(runtime, merovingian::homeserver::AccountPresenceTracker::change_window_ms); +} + [[nodiscard]] auto sync_presence_senders(ClientServerRuntime& runtime, std::string const& token) -> std::vector { @@ -544,7 +558,8 @@ namespace constexpr auto minute_ms = std::int64_t{60 * 1000}; // Presence rows hold when they were last observed; moving that back is the passage of time without a -// sleep. The row is changed in place, as `record_presence` would restamp it. +// sleep. The row is changed in place, as `record_presence` would restamp it. The clock of the change window and of +// the devices' freshness (ADR-0871, ADR-0872) moves on by as much. auto age_presence(ClientServerRuntime& runtime, std::string_view user_id, std::int64_t by_ms) -> void { for (auto& row : runtime.homeserver.database.persistent_store.presence_states) @@ -554,6 +569,7 @@ auto age_presence(ClientServerRuntime& runtime, std::string_view user_id, std::i row.observed_at_ms -= by_ms; } } + advance_presence_clock(runtime, by_ms); } [[nodiscard]] auto read_alice_presence(ClientServerRuntime& runtime, std::string const& token) -> std::string @@ -637,6 +653,7 @@ SCENARIO("A user idle past the presence threshold is set unavailable", "[integra WHEN("alice set herself offline, a long time ago, and the idle sweep runs") { + let_presence_window_end(runtime); REQUIRE(put_alice_presence(runtime, token, R"({"presence":"offline"})").status == 200U); age_presence(runtime, local_alice, 60 * minute_ms); std::ignore = merovingian::homeserver::run_presence_idle_sweep(runtime); @@ -710,6 +727,7 @@ SCENARIO("A user who keeps sending messages is not set unavailable", "[integrati WHEN("she is unavailable by her own choice and sends a message") { + let_presence_window_end(runtime); REQUIRE(put_alice_presence(runtime, token, R"({"presence":"unavailable"})").status == 200U); REQUIRE(send(1).status == 200U); @@ -924,3 +942,234 @@ SCENARIO("Sliding sync honours set_presence", "[integration][presence][sliding-s } } } + +namespace +{ + +// A second device of alice's, for the scenarios where two clients of one account sync at once. +[[nodiscard]] auto log_alice_in_on(ClientServerRuntime& runtime, std::string_view device_id) -> std::string +{ + auto const login = call(runtime, "POST", "/_matrix/client/v3/login", {}, + R"({"type":"m.login.password","identifier":{"type":"m.id.user","user":"alice"},)" + R"("password":"CorrectHorse7!","device_id":")" + + std::string{device_id} + R"("})"); + REQUIRE(login.status == 200U); + auto const body = parse_object(login.body); + auto const* token = string_member(body, "access_token"); + REQUIRE(token != nullptr); + return *token; +} + +// A /sync that answers at once, asking for `mode` (online, unavailable or offline). +auto sync_once(ClientServerRuntime& runtime, std::string const& token, std::string_view mode) -> void +{ + REQUIRE(call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=" + std::string{mode}, token).status == + 200U); +} + +[[nodiscard]] auto alice_presence_state(ClientServerRuntime const& runtime) -> std::string +{ + auto const row = stored_presence(runtime, local_alice); + return row.has_value() ? row->presence : std::string{"none"}; +} + +} // namespace + +// Spec: Matrix Client-Server API v1.19, Presence, "Idle timeout": "Any activity that bumps the last active time on any +// of the user's clients will cause the server to automatically set their presence to `online`." +// +// ADR-0871: a device that syncs online holds the account online for AccountPresenceTracker::device_fresh_ms, so another +// device syncing unavailable does not set it unavailable in between. Without this, a client in the foreground and one +// in the background set the presence back and forth on every sync, each change waking the other's sync and queueing an +// EDU for every server in the user's rooms. +SCENARIO("Two devices of one account syncing online and unavailable do not set its presence back and forth", + "[integration][presence][sync][devices]") +{ + GIVEN("alice shares a room with bob on another server and her desktop has synced online") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const desktop = register_alice(runtime); + auto const phone = log_alice_in_on(runtime, "PHONE"); + share_room_with_remote_bob(runtime); + sync_once(runtime, desktop, "online"); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("her phone syncs unavailable and her desktop online, in turn, with every change window ended") + { + for (auto round = 0; round < 10; ++round) + { + let_presence_window_end(runtime); + sync_once(runtime, phone, "unavailable"); + let_presence_window_end(runtime); + sync_once(runtime, desktop, "online"); + } + + THEN("she stays online and bob's server was told once") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("her desktop stops syncing for longer than a device holds the account and her phone syncs unavailable") + { + advance_presence_clock(runtime, merovingian::homeserver::AccountPresenceTracker::device_fresh_ms); + sync_once(runtime, phone, "unavailable"); + + THEN("she is unavailable and bob's server is told") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("her desktop syncs with set_presence=offline and then her phone syncs unavailable") + { + sync_once(runtime, desktop, "offline"); + let_presence_window_end(runtime); + sync_once(runtime, phone, "unavailable"); + + THEN("the desktop no longer holds her online, so she is unavailable") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + } + } + } +} + +// ADR-0872: the first change of an account's presence opens a window of AccountPresenceTracker::change_window_ms in +// which no other change is kept: a sync's is dropped, a PUT is answered 429 M_LIMIT_EXCEEDED, which the spec gives this +// endpoint. The first change asked for is the one kept, never the last. +// +// Spec: Matrix Client-Server API v1.19, PUT /_matrix/client/v3/presence/{userId}/status, responses 200 and 429. +SCENARIO("Only the first presence change in a window is kept", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server and has just synced online") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + sync_once(runtime, token, "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + auto const& store = runtime.homeserver.database.persistent_store; + auto const watermark = store.next_sync_stream_id; + + WHEN("she syncs unavailable at once") + { + sync_once(runtime, token, "unavailable"); + + THEN("the change is dropped: nothing is stored, woken or sent") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("she syncs unavailable once the window has ended") + { + let_presence_window_end(runtime); + sync_once(runtime, token, "unavailable"); + + THEN("the change is kept and bob's server is told") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("she sets her presence at once") + { + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable","status_msg":"away"})"); + + THEN("it is refused with 429 M_LIMIT_EXCEEDED and when to retry, and nothing is stored or sent") + { + REQUIRE(put.status == 429U); + auto const body = parse_object(put.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_LIMIT_EXCEEDED"); + auto const* retry_after_ms = int_member(body, "retry_after_ms"); + REQUIRE(retry_after_ms != nullptr); + REQUIRE(*retry_after_ms > 0); + REQUIRE(*retry_after_ms <= merovingian::homeserver::AccountPresenceTracker::change_window_ms); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + + WHEN("she sets her presence once the window has ended") + { + let_presence_window_end(runtime); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("it is stored and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + } +} + +// ADR-0873: a /sync never sends the caller their own presence, so a long-poll whose only news is the caller's own +// presence row would be answered with nothing, and its client would sync again at once. It keeps waiting instead, as +// sliding sync does for what its response does not send (ADR-0869). +SCENARIO("A long-polling /sync whose only news is the caller's own presence keeps waiting", + "[integration][presence][sync][long_poll]") +{ + GIVEN("alice has synced with set_presence=offline and holds its next_batch") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const token = register_alice(runtime); + auto const initial = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=offline", token); + REQUIRE(initial.status == 200U); + auto const initial_body = parse_object(initial.body); + auto const* since = string_member(initial_body, "next_batch"); + REQUIRE(since != nullptr); + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&since=" + *since, token, {}}; + auto const& store = runtime.homeserver.database.persistent_store; + + WHEN("she long-polls from it without set_presence, which marks her online") + { + auto const result = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + + THEN("she is online and the sync waits past her own presence row") + { + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + REQUIRE(result.wait.since_sync_stream_id == store.next_sync_stream_id); + } + } + + WHEN("something else is stored for her after her own presence, and the sync runs again") + { + std::ignore = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(call(runtime, "PUT", "/_matrix/client/v3/user/%40alice%3Aexample.org/account_data/org.example.a", + token, R"({"a":1})") + .status == 200U); + auto const result = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + + THEN("it is answered") + { + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(result.response.status == 200U); + } + } + } +} diff --git a/tests/integration/test_security_audit_presence_flow.cpp b/tests/integration/test_security_audit_presence_flow.cpp index f346cbda2..0adfb29d7 100644 --- a/tests/integration/test_security_audit_presence_flow.cpp +++ b/tests/integration/test_security_audit_presence_flow.cpp @@ -15,6 +15,7 @@ #include "merovingian/database/ExaminedRows.hpp" #include "merovingian/database/PersistentPresence.hpp" #include "merovingian/database/PersistentStore.hpp" +#include "merovingian/homeserver/AccountPresenceTracker.hpp" #include "merovingian/homeserver/ClientServerClock.hpp" #include "merovingian/homeserver/ClientServerRuntime.hpp" #include "merovingian/homeserver/ClientServerStartResult.hpp" @@ -248,6 +249,9 @@ SCENARIO("Sync presence is visible only between users with current shared room m { REQUIRE(set_presence(runtime, localpart, token, R"({"presence":"online"})").status == 200U); } + // Each user's next change is kept, not refused inside the window this one opened (ADR-0872). + runtime.homeserver.test_presence_clock_advance_ms += + merovingian::homeserver::AccountPresenceTracker::change_window_ms; WHEN("Alice performs an initial sync and then an incremental sync after everyone updates presence") { diff --git a/tests/integration/test_sync_handler_flow.cpp b/tests/integration/test_sync_handler_flow.cpp index 43b351a77..2e3276919 100644 --- a/tests/integration/test_sync_handler_flow.cpp +++ b/tests/integration/test_sync_handler_flow.cpp @@ -53,6 +53,7 @@ #include "merovingian/homeserver/ClientServerStartResult.hpp" #include "merovingian/homeserver/DispatchResult.hpp" #include "merovingian/homeserver/LocalHttpRouter.hpp" +#include "merovingian/homeserver/PresenceWriteStatus.hpp" #include "merovingian/homeserver/RoomService.hpp" #include "merovingian/homeserver/WorkerPool.hpp" #include "merovingian/sync/StreamToken.hpp" @@ -256,8 +257,8 @@ SCENARIO("Sync surfaces account_data, to_device, device_lists, presence, and key REQUIRE(merovingian::homeserver::push_to_device_message( rt, {0U, "@bob:example.org", alice_id, device_id, "m.room_key", R"({"session":"abc"})"})); REQUIRE(merovingian::homeserver::record_device_list_change(rt, {0U, alice_id, "@bob:example.org", "changed"})); - REQUIRE( - merovingian::homeserver::set_presence(rt, {0U, "@charlie:example.org", "online", "Coding!", 1000, true})); + REQUIRE(merovingian::homeserver::set_presence(rt, {0U, "@charlie:example.org", "online", "Coding!", 1000, true}) + .status == merovingian::homeserver::PresenceWriteStatus::stored); REQUIRE(merovingian::database::store_one_time_key( store, {alice_id, device_id, "signed_curve25519:AAA", R"({"key":"x"})"})); REQUIRE(merovingian::database::store_one_time_key( diff --git a/tests/meson.build b/tests/meson.build index 85facb0af..043aef5ee 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -506,6 +506,7 @@ shell = find_program('sh') 'unit/test_oauth_account_session_store.cpp', 'unit/test_oauth_cross_signing_reset_approvals.cpp', 'unit/test_oauth_device_authorisation_store.cpp', + 'unit/test_account_presence_tracker.cpp', 'unit/test_oauth_pending_authorisation_store.cpp', 'unit/test_oauth_pkce.cpp', 'unit/test_oauth_redirect_uri.cpp', diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp new file mode 100644 index 000000000..0b06d2b76 --- /dev/null +++ b/tests/unit/test_account_presence_tracker.cpp @@ -0,0 +1,225 @@ +// SPDX-FileCopyrightText: 2026 James Chapman +// SPDX-License-Identifier: GPL-3.0-or-later + +// ADR-0871 and ADR-0872: what an account's devices last asked of its presence, and the window after a change in which +// no other change is kept. Every operation takes the time, so no scenario sleeps. + +#include "merovingian/homeserver/AccountPresenceTracker.hpp" + +#include + +#include +#include +#include +#include +#include +#include + +namespace +{ + +using merovingian::homeserver::AccountPresenceTracker; + +constexpr auto start_ms = std::int64_t{1'000'000}; +constexpr auto alice = std::string_view{"@alice:example.org"}; +constexpr auto bob = std::string_view{"@bob:example.org"}; +constexpr auto phone = std::string_view{"PHONE"}; +constexpr auto desktop = std::string_view{"DESKTOP"}; + +} // namespace + +SCENARIO("A device syncing online holds its account online against a device syncing unavailable", + "[unit][presence][account_presence_tracker]") +{ + GIVEN("alice's desktop synced asking for online") + { + auto tracker = AccountPresenceTracker{}; + REQUIRE(tracker.note_sync(alice, desktop, true, start_ms)); + + WHEN("her phone syncs asking for unavailable a moment later") + { + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 100); + + THEN("a device of the account still asks for online") + { + REQUIRE(any_online); + } + } + + WHEN("her phone syncs asking for unavailable once the desktop has not synced for the freshness time") + { + auto const any_online = + tracker.note_sync(alice, phone, false, start_ms + AccountPresenceTracker::device_fresh_ms); + + THEN("no device asks for online any more") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("the desktop itself syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, desktop, false, start_ms + 100); + + THEN("its earlier ask is replaced, so no device asks for online") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("the desktop syncs with set_presence=offline and the phone asks for unavailable") + { + tracker.forget_device(alice, desktop); + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 100); + + THEN("the desktop no longer holds the account online") + { + REQUIRE_FALSE(any_online); + } + } + + WHEN("another account's device asks for unavailable") + { + auto const any_online = tracker.note_sync(bob, phone, false, start_ms + 100); + + THEN("alice's desktop does not speak for bob") + { + REQUIRE_FALSE(any_online); + } + } + } +} + +SCENARIO("The first presence change in a window is kept and the rest wait for it to end", + "[unit][presence][account_presence_tracker]") +{ + GIVEN("an account whose presence has not changed") + { + auto tracker = AccountPresenceTracker{}; + + THEN("a change may be kept at once") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(alice, start_ms).has_value()); + } + + WHEN("a change is kept") + { + tracker.note_change(alice, start_ms); + + THEN("another change two seconds later waits for the rest of the window") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 2'000); + REQUIRE(blocked.has_value()); + REQUIRE(*blocked == AccountPresenceTracker::change_window_ms - 2'000); + } + THEN("a change once the window has ended may be kept") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(alice, start_ms + AccountPresenceTracker::change_window_ms) + .has_value()); + } + THEN("another account's change is not held back") + { + REQUIRE_FALSE(tracker.change_blocked_for_ms(bob, start_ms + 1).has_value()); + } + } + } +} + +SCENARIO("A prune removes what no longer speaks for an account", "[unit][presence][account_presence_tracker]") +{ + GIVEN("alice changed her presence and synced from one device") + { + auto tracker = AccountPresenceTracker{}; + tracker.note_change(alice, start_ms); + std::ignore = tracker.note_sync(alice, desktop, true, start_ms); + REQUIRE(tracker.account_count() == 1U); + + WHEN("a prune runs inside the window and the freshness time") + { + tracker.prune(start_ms + 1'000); + + THEN("the account is kept") + { + REQUIRE(tracker.account_count() == 1U); + REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 1'000).has_value()); + } + } + + WHEN("a prune runs once the device is stale and the window has ended") + { + tracker.prune(start_ms + AccountPresenceTracker::device_fresh_ms); + + THEN("the account is removed") + { + REQUIRE(tracker.account_count() == 0U); + } + } + } +} + +SCENARIO("The tracker is bounded per account and in all", "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("an account with as many devices as the cap, the oldest of them the only one asking for online") + { + auto tracker = AccountPresenceTracker{}; + std::ignore = tracker.note_sync(alice, "OLDEST", true, start_ms); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + std::ignore = tracker.note_sync(alice, "D" + std::to_string(index), false, + start_ms + static_cast(index)); + } + + WHEN("one more device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); + + THEN("it replaces the least recently seen device, so none asks for online") + { + REQUIRE_FALSE(any_online); + } + } + } + + GIVEN("a table holding as many accounts as the cap, each inside its window") + { + auto tracker = AccountPresenceTracker{}; + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + { + tracker.note_change("@user" + std::to_string(index) + ":example.org", start_ms); + } + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + + WHEN("an account with no entry asks to change its presence") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 1); + tracker.note_change(alice, start_ms + 1); + + THEN("it is refused and the table does not grow: a flood of accounts cannot lift the limit") + { + REQUIRE(blocked.has_value()); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + } + } + + WHEN("it syncs asking for online") + { + auto const any_online = tracker.note_sync(alice, desktop, true, start_ms + 1); + + THEN("its own ask is answered, as without the table") + { + REQUIRE(any_online); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + } + } + + WHEN("the windows have ended and an account with no entry syncs") + { + std::ignore = tracker.note_sync(alice, desktop, true, start_ms + AccountPresenceTracker::change_window_ms); + + THEN("the ended accounts are pruned to make room and it is held") + { + REQUIRE(tracker.account_count() == 1U); + } + } + } +} From 9352cb57bbb4c6ebaaf134b5afaccd45e70f873e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 03:49:35 +0000 Subject: [PATCH 02/25] Address review of the presence fix: expiry index, full_state, tidy - AccountPresenceTracker files each account under the time it stops mattering, so a prune (the idle sweep's or one made because the table is full) visits only expired accounts, never all 65,536 under runtime.mutex; a full table with an expired account admits a change. - A classic /sync with full_state=true never long-polls: the spec says its timeout is ignored. - device_fresh_ms is asserted equal to presence_idle_timeout_ms. - change_blocked_for_ms and a unit test read the optional only behind a check clang-tidy can see (bugprone-unchecked-optional-access). - CHANGELOG: the rate limit moves to Security Fixes; user manual states the offline exception and that the idle sweep is not limited; ADR-0871 to ADR-0873 and src/homeserver/AGENTS.md updated. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 +- ...syncing-online-holds-its-account-online.md | 9 +- ...-change-in-a-five-second-window-is-kept.md | 5 +- ...-news-is-its-own-presence-keeps-waiting.md | 3 + docs/user-manual.md | 6 +- .../homeserver/AccountPresenceTracker.hpp | 40 +++++-- src/homeserver/AGENTS.md | 2 +- src/homeserver/AccountPresenceTracker.cpp | 110 +++++++++++++----- src/homeserver/ClientServerRuntime.cpp | 4 +- src/homeserver/PresenceService.cpp | 7 ++ tests/integration/test_presence_flow.cpp | 14 +++ tests/unit/test_account_presence_tracker.cpp | 49 +++++++- 12 files changed, 200 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 37d607f8d..ceb6e1a9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -77,6 +77,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) so the worker stops serving the removed event (ADR-0862). * A sliding sync `pos` is bound to the user and device it was issued to; any other is `M_UNKNOWN_POS`, so one user can no longer continue another's connection (ADR-0866). +* An account's presence changes at most once every 5 s (a later sync's change is dropped, `PUT /presence` is 429), so a + flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0872). ## Bug fixes @@ -179,9 +181,9 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * The AlmaLinux and openSUSE CI suites install diffutils, which the integration shard check needs for `cmp` and `diff`. * Two clients of one account, one syncing online and one `unavailable`, no longer flip its presence on every sync: an online device holds the account online for 5 minutes (ADR-0871). -* An account's presence changes at most once every 5 s: later changes in the window are dropped, and `PUT /presence` - answers 429. A flip loop no longer fills the federation queue for every other send (ADR-0872). * A classic `/sync` whose only news is the caller's own presence keeps waiting instead of answering nothing (ADR-0873). +* A classic `/sync` with `full_state=true` is answered at once, whatever its `timeout`, as the spec says; it waited + like any other long poll (ADR-0873). * `docs/observability-audit.md` named the wrong logger for `presence.sync.set`; it is `client_server`. ## Release notes diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index 24d0d4785..db92bdd20 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -36,10 +36,13 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and * `set_presence=offline` forgets the device's ask: it no longer holds the account online. * The freshness time is the idle timeout, so a closed client holds the account online exactly as long as the idle - sweep would leave it online after that client's last sync. + sweep would leave it online after that client's last sync; a `static_assert` in `PresenceService.cpp` keeps the + two equal. * At most `max_devices_per_account` (64) devices per account, the least recently seen replaced; at most `max_accounts` - (65,536) accounts, pruned by the idle sweep every 30 s. With the table full after a prune, a sync of an account it - does not hold asks for itself alone, as before this decision. + (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. Each account is filed under the + time it stops mattering (its latest device stale and its window ended), so a prune visits only expired accounts, + never the table: a flood of overflow requests under `runtime.mutex` costs no scan. With the table full after a prune, + a sync of an account it does not hold asks for itself alone, as before this decision. * The asks are in memory only: after a restart each device's next sync puts its ask back. * The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md index 2f4e85cb2..ba0c2bcd6 100644 --- a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -39,8 +39,9 @@ Chosen option: 1. * Not limited: the idle sweep (the server's own change, at most once per idle period; a user who returns at once is marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar, and inbound presence from other servers (their own server's to limit). -* With `AccountPresenceTracker` full after a prune, a change of an account it does not hold is refused (fails closed, - as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. +* With `AccountPresenceTracker` full and no account in it expired, a change of an account it does not hold is refused + (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself; once an + account has expired, the change is allowed and takes its place. * Tests move the clock with `HomeserverRuntime::test_presence_clock_advance_ms`. ### Positive Consequences diff --git a/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md index d19b69692..cb562a694 100644 --- a/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md +++ b/docs/adr/0873-a-classic-sync-whose-only-news-is-its-own-presence-keeps-waiting.md @@ -34,6 +34,9 @@ account's other devices, and a request's own `set_presence` waking itself. * With any other position after `since`, or several, the sync answers as before; the check never delays news. * A sync with no `since` (an initial sync) is not affected. +* A sync with `full_state=true` never waits, this check or any other: the spec says that with it "the `timeout` + parameter will be ignored and the query will return immediately". The long-poll gate waited for it before this + decision. * The rerun of a woken poll judges again from the same `since`: a new position that is not the caller's presence ends the wait. diff --git a/docs/user-manual.md b/docs/user-manual.md index 507644d79..f043bb32b 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1211,8 +1211,10 @@ the users who share a room with them in `/sync` (`presence.events`) and by `m.presence` EDU. `PUT /presence/{userId}/status` sets it, and so does `/sync`: omitting `set_presence` marks the user online, `unavailable` marks them idle, `offline` leaves it as it is. A device that synced online in the last 5 minutes keeps the user online while another of their devices syncs -`unavailable`. A user's presence changes at most once every 5 seconds: a later change by `/sync` in that time is -ignored, and `PUT /presence` answers `429` with `retry_after_ms`. Presence reaches only users who share a joined +`unavailable`; a sync from that device with `set_presence=offline` ends its hold at once. A user's presence changes at +most once every 5 seconds: a later change by `/sync` in that time is ignored, and `PUT /presence` answers `429` with +`retry_after_ms`. The server's own idle change (an online user inactive for 5 minutes becomes `unavailable`) is not +limited and does not start those 5 seconds. Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. | Key | Default | When to change | diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index 22753ff6d..8ebe5fd1f 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -8,9 +8,11 @@ #include #include #include +#include #include #include #include +#include #include namespace merovingian::homeserver @@ -29,16 +31,18 @@ namespace merovingian::homeserver // the one kept, never the last. // // Bounded: at most `max_accounts` accounts of `max_devices_per_account` devices each. A new device past the device cap -// replaces the account's least recently seen one. An account the table has no room for after a prune has its devices -// ignored (its sync asks for itself alone, as without this table) and every change refused until there is room, so a -// flood of accounts cannot lift the limit for itself. Not thread-safe: `runtime.mutex` serialises every use -// (`HomeserverRuntime::presence_tracker`). +// replaces the account's least recently seen one. Each account is filed under the time it stops mattering (its last +// online device stale and its window ended), so a prune visits only the accounts that have expired, never the table: an +// overflow request does as much work as there are accounts to remove. An account the table has no room for, once the +// expired ones are gone, has its devices ignored (its sync asks for itself alone, as without this table) and every +// change refused until there is room, so a flood of accounts cannot lift the limit for itself. Not thread-safe: +// `runtime.mutex` serialises every use (`HomeserverRuntime::presence_tracker`). class AccountPresenceTracker final { public: static constexpr auto change_window_ms = std::int64_t{5'000}; // The idle timeout (`presence_idle_timeout_ms`): a device holds the account online for as long as the idle sweep - // would leave it online after that device's last sync. + // would leave it online after that device's last sync. `PresenceService.cpp` asserts the two are equal. static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; // Far more devices than one person syncs from at once; each is a device ID and two integers. static constexpr auto max_devices_per_account = std::size_t{64U}; @@ -60,12 +64,15 @@ class AccountPresenceTracker final // Starts the window of `user` at `now_ms`: a change was just kept. auto note_change(std::string_view user, std::int64_t now_ms) -> void; - // Removes the devices not seen for `device_fresh_ms`, then every account left with no device whose window ended. + // Removes every account whose devices are all stale and whose window ended by `now_ms`. auto prune(std::int64_t now_ms) -> void; // Accounts held, ones a prune would remove included. [[nodiscard]] auto account_count() const noexcept -> std::size_t; + // Accounts a prune has looked at since the table was made, for tests that prove its cost. + [[nodiscard]] auto accounts_examined() const noexcept -> std::uint64_t; + private: struct Device final { @@ -77,13 +84,26 @@ class AccountPresenceTracker final { std::vector devices{}; std::optional changed_at_ms{}; + // When the account stops mattering: its latest device stale and its window ended. Its key in `m_by_expiry`. + std::int64_t expires_at_ms{0}; }; + using Accounts = std::unordered_map>; + using ExpiryKey = std::pair; + + // The account of `user`, made when there is room (after removing the expired accounts when the table is full); + // `m_accounts.end()` when there is none. + [[nodiscard]] auto account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator; + + // Files `entry` under its expiry again, after its devices or window changed. + auto refile(Accounts::iterator entry, std::int64_t now_ms) -> void; - // The account of `user`, made when there is room (after a prune when the table is full); nullptr when there is - // none. - [[nodiscard]] auto account_for(std::string_view user, std::int64_t now_ms) -> Account*; + // True when an account has expired by `now_ms`, so a prune would make room. + [[nodiscard]] auto has_expired_account(std::int64_t now_ms) const noexcept -> bool; - std::unordered_map> m_accounts{}; + Accounts m_accounts{}; + // (expires_at_ms, user) of every account, soonest first. + std::set m_by_expiry{}; + std::uint64_t m_accounts_examined{0U}; }; } // namespace merovingian::homeserver diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 361516f10..b40e13a8d 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,7 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | -| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, failing closed at the cap. Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, each filed under its expiry so a prune visits only expired accounts (`accounts_examined()` counts them), failing closed at the cap while none has expired. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 1efbdffd7..43f1df40a 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -4,7 +4,7 @@ #include "merovingian/homeserver/AccountPresenceTracker.hpp" #include -#include +#include namespace merovingian::homeserver { @@ -25,34 +25,75 @@ namespace (now_ms > *changed_at_ms && now_ms - *changed_at_ms >= AccountPresenceTracker::change_window_ms); } + // `at_ms + by_ms`, held at the largest value instead of overflowing. + [[nodiscard]] auto saturating_after(std::int64_t at_ms, std::int64_t by_ms) noexcept -> std::int64_t + { + return at_ms > std::numeric_limits::max() - by_ms ? std::numeric_limits::max() + : at_ms + by_ms; + } + } // namespace -auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now_ms) -> Account* +auto AccountPresenceTracker::refile(Accounts::iterator entry, std::int64_t now_ms) -> void +{ + auto& account = entry->second; + // The account matters until its latest device is stale and its window has ended; with neither, it is done now. + auto expires_at_ms = now_ms; + for (auto const& held : account.devices) + { + expires_at_ms = std::max(expires_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + } + if (account.changed_at_ms.has_value()) + { + expires_at_ms = std::max(expires_at_ms, saturating_after(*account.changed_at_ms, change_window_ms)); + } + if (expires_at_ms == account.expires_at_ms) + { + return; + } + m_by_expiry.erase(ExpiryKey{account.expires_at_ms, entry->first}); + account.expires_at_ms = expires_at_ms; + m_by_expiry.emplace(expires_at_ms, entry->first); +} + +auto AccountPresenceTracker::has_expired_account(std::int64_t now_ms) const noexcept -> bool +{ + return !m_by_expiry.empty() && m_by_expiry.begin()->first <= now_ms; +} + +auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator { if (auto const found = m_accounts.find(user); found != m_accounts.end()) { - return &found->second; + return found; } if (m_accounts.size() >= max_accounts) { prune(now_ms); if (m_accounts.size() >= max_accounts) { - return nullptr; + return m_accounts.end(); } } - return &m_accounts.try_emplace(std::string{user}).first->second; + auto const made = m_accounts.try_emplace(std::string{user}).first; + made->second.expires_at_ms = now_ms; + m_by_expiry.emplace(now_ms, made->first); + return made; } auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) -> bool { - auto* const account = account_for(user, now_ms); - if (account == nullptr) + auto const entry = account_for(user, now_ms); + if (entry == m_accounts.end()) { return online; } - auto& devices = account->devices; + auto& devices = entry->second.devices; + // A stale device speaks for nothing; dropping it here keeps an account that keeps syncing from holding them. + std::erase_if(devices, [now_ms](Device const& held) { + return !device_is_fresh(held.seen_at_ms, now_ms); + }); auto const same_device = [device](Device const& held) { return held.id == device; }; @@ -70,19 +111,24 @@ auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view d } devices.push_back(Device{std::string{device}, now_ms, online}); } - return std::ranges::any_of(devices, [now_ms](Device const& held) { - return held.online && device_is_fresh(held.seen_at_ms, now_ms); + refile(entry, now_ms); + return std::ranges::any_of(devices, [](Device const& held) { + return held.online; }); } auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device) -> void { - if (auto const found = m_accounts.find(user); found != m_accounts.end()) + auto const found = m_accounts.find(user); + if (found == m_accounts.end()) { - std::erase_if(found->second.devices, [device](Device const& held) { - return held.id == device; - }); + return; } + std::erase_if(found->second.devices, [device](Device const& held) { + return held.id == device; + }); + // The account may now expire sooner; it is never kept past its old time, and a prune judges it by the new one. + refile(found, std::numeric_limits::min()); } auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const @@ -92,42 +138,37 @@ auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::i if (found == m_accounts.end()) { // No window to wait for, unless there is no room to start one: then the change is refused (fails closed). - return m_accounts.size() >= max_accounts ? std::optional{change_window_ms} : std::nullopt; + auto const no_room = m_accounts.size() >= max_accounts && !has_expired_account(now_ms); + return no_room ? std::optional{change_window_ms} : std::nullopt; } auto const changed_at_ms = found->second.changed_at_ms; - if (window_has_ended(changed_at_ms, now_ms)) + if (!changed_at_ms.has_value() || window_has_ended(changed_at_ms, now_ms)) { return std::nullopt; } + auto const started_ms = changed_at_ms.value(); // A start ahead of `now_ms` (which the clock does not produce) is waited for in full, never longer. - auto const elapsed = now_ms > *changed_at_ms ? now_ms - *changed_at_ms : std::int64_t{0}; + auto const elapsed = now_ms > started_ms ? now_ms - started_ms : std::int64_t{0}; return change_window_ms - elapsed; } auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now_ms) -> void { - if (auto* const account = account_for(user, now_ms); account != nullptr) + if (auto const entry = account_for(user, now_ms); entry != m_accounts.end()) { - account->changed_at_ms = now_ms; + entry->second.changed_at_ms = now_ms; + refile(entry, now_ms); } } auto AccountPresenceTracker::prune(std::int64_t now_ms) -> void { - for (auto entry = m_accounts.begin(); entry != m_accounts.end();) + while (has_expired_account(now_ms)) { - auto& account = entry->second; - std::erase_if(account.devices, [now_ms](Device const& held) { - return !device_is_fresh(held.seen_at_ms, now_ms); - }); - if (account.devices.empty() && window_has_ended(account.changed_at_ms, now_ms)) - { - entry = m_accounts.erase(entry); - } - else - { - entry = std::next(entry); - } + auto const soonest = m_by_expiry.begin(); + ++m_accounts_examined; + m_accounts.erase(soonest->second); + m_by_expiry.erase(soonest); } } @@ -136,4 +177,9 @@ auto AccountPresenceTracker::account_count() const noexcept -> std::size_t return m_accounts.size(); } +auto AccountPresenceTracker::accounts_examined() const noexcept -> std::uint64_t +{ + return m_accounts_examined; +} + } // namespace merovingian::homeserver diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 523a74751..fbeb217a5 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -7135,7 +7135,9 @@ namespace // Spec §9.4: omitting `timeout` means respond immediately — no default. // HTTP-4: cap the client-supplied timeout so a single sync cannot pin a // worker indefinitely; the client receives the capped wait. - if (can_wait && request.timeout.has_value() && *request.timeout > 0U) + // Spec (GET /sync, `full_state`): with it true "the `timeout` parameter will be ignored and the query will + // return immediately", so such a sync never waits. + if (can_wait && !request.full_state.value_or(false) && request.timeout.has_value() && *request.timeout > 0U) { auto const capped_timeout_ms = std::min(*request.timeout, sync::k_max_sync_timeout_ms); auto const has_timeline_advance = visible_stream_position(rt.homeserver.database) > since_ordering; diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index fa3384f55..d52486d1c 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -32,6 +32,13 @@ namespace merovingian::homeserver { + +// ADR-0871: a device's online ask goes stale exactly when the idle sweep would set its account unavailable. With the +// two apart, a background device's `unavailable` would win while the sweep still counts the user active, or a closed +// client would hold the account online past the sweep. +static_assert(AccountPresenceTracker::device_fresh_ms == presence_idle_timeout_ms, + "a device's online ask must last exactly as long as the idle timeout"); + namespace { diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index 4f750b610..cd8b17c2a 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1157,6 +1157,20 @@ SCENARIO("A long-polling /sync whose only news is the caller's own presence keep } } + WHEN("she long-polls from it with full_state=true and nothing new to send") + { + std::ignore = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + auto const full_state = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&full_state=true&since=" + *since, token, {}}; + auto const result = merovingian::homeserver::handle_client_server_request(runtime, full_state); + + THEN("the timeout is ignored and it is answered at once, as the spec requires") + { + REQUIRE(result.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(result.response.status == 200U); + } + } + WHEN("something else is stored for her after her own presence, and the sync runs again") { std::ignore = merovingian::homeserver::handle_client_server_request(runtime, long_poll); diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 0b06d2b76..b5925c7f5 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -109,8 +109,7 @@ SCENARIO("The first presence change in a window is kept and the rest wait for it THEN("another change two seconds later waits for the rest of the window") { auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 2'000); - REQUIRE(blocked.has_value()); - REQUIRE(*blocked == AccountPresenceTracker::change_window_ms - 2'000); + REQUIRE(blocked == std::optional{AccountPresenceTracker::change_window_ms - 2'000}); } THEN("a change once the window has ended may be kept") { @@ -223,3 +222,49 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco } } } + +SCENARIO("A prune of a full table looks only at the accounts that have expired", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a full table in which one account's window ended as the others' began") + { + auto tracker = AccountPresenceTracker{}; + tracker.note_change("@early:example.org", start_ms); + auto const later_ms = start_ms + AccountPresenceTracker::change_window_ms; + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) + { + tracker.note_change("@user" + std::to_string(index) + ":example.org", later_ms); + } + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + + WHEN("an account with no entry asks to change its presence") + { + auto const blocked = tracker.change_blocked_for_ms(alice, later_ms + 1); + tracker.note_change(alice, later_ms + 1); + + THEN("it is allowed and takes the expired account's place, the one account a prune looked at") + { + REQUIRE_FALSE(blocked.has_value()); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.change_blocked_for_ms(alice, later_ms + 2).has_value()); + } + } + + WHEN("the table is full again and a flood of accounts with no entry syncs") + { + tracker.note_change(alice, later_ms + 1); + for (auto index = 0; index < 1'000; ++index) + { + std::ignore = + tracker.note_sync("@flood" + std::to_string(index) + ":example.org", desktop, true, later_ms + 2); + } + + THEN("no request looks at the table, since no account has expired") + { + REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + } + } + } +} From 7a229e1709ede9391563ea9db696e872cc2a403f Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 04:23:38 +0000 Subject: [PATCH 03/25] Tell a full presence tracker apart from a window, and own its hash - A change refused because AccountPresenceTracker has no room now waits for the soonest account to expire (retry_after_ms up to the 5-minute freshness time), not a 5 s window it never opened; PresenceWrite carries tracker_full, and presence.set.limited and presence.change.limited log cause=tracker_full or cause=window. - The tracker keys its accounts with its own transparent UserHash, not database::detail::StateGroupKeyHash. - Threat model and ADR-0872: a profile change stores the presence row again but sends no m.presence EDU, so it is not a way round the limit. Co-Authored-By: Claude Opus 5.5 --- ...-change-in-a-five-second-window-is-kept.md | 8 ++++--- docs/observability-audit.md | 5 +++-- docs/threat-model.md | 5 ++++- .../homeserver/AccountPresenceTracker.hpp | 19 +++++++++++++---- .../merovingian/homeserver/PresenceWrite.hpp | 5 ++++- src/homeserver/AccountPresenceTracker.cpp | 15 ++++++++++--- src/homeserver/ClientServerRuntime.cpp | 19 +++++++++++------ src/homeserver/PresenceService.cpp | 5 ++++- tests/unit/test_account_presence_tracker.cpp | 21 +++++++++++++++++++ 9 files changed, 81 insertions(+), 21 deletions(-) diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md index ba0c2bcd6..593a56100 100644 --- a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -37,11 +37,13 @@ Chosen option: 1. * A change is a change of the stored state by a sync, or any `PUT`. A sync that leaves the state as it is refreshes the last-active time in memory as before and is not limited. * Not limited: the idle sweep (the server's own change, at most once per idle period; a user who returns at once is - marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar, - and inbound presence from other servers (their own server's to limit). + marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar + (it stores the row for local syncs and appservices and sends no `m.presence` EDU), and inbound presence from other + servers (their own server's to limit). * With `AccountPresenceTracker` full and no account in it expired, a change of an account it does not hold is refused (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself; once an - account has expired, the change is allowed and takes its place. + account has expired, the change is allowed and takes its place. The refusal's `retry_after_ms` is the time until the + soonest account expires (at most `device_fresh_ms`), and its log line's `cause` is `tracker_full`, not `window`. * Tests move the clock with `HomeserverRuntime::test_presence_clock_advance_ms`. ### Positive Consequences diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 0efd03262..e8b9ee67d 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -132,10 +132,11 @@ is full. - `presence.set` (debug, logger `client_server`) records a `PUT /presence/{userId}/status` (fields `actor`, `presence`; never the status message). `presence.set.limited` (debug, logger `client_server`) records one refused with 429 because the account's presence changed less than - 5 s before (fields `actor`, `presence`, `retry_after_ms`; ADR-0872). `presence.sync.set` (debug, + 5 s before (`cause` `window`) or the presence tracker had no room for the account (`cause` + `tracker_full`) (fields `actor`, `presence`, `cause`, `retry_after_ms`; ADR-0872). `presence.sync.set` (debug, logger `client_server`) records a `/sync` that changed the caller's state (fields `actor`, `presence`). `presence.change.limited` (debug, logger `presence`) records a `/sync` change dropped - for the same reason (fields `actor`, `device_id`, `presence`, `retry_after_ms`). + for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/docs/threat-model.md b/docs/threat-model.md index b542a7d61..7bea966c0 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -2799,7 +2799,10 @@ nothing, all from trusting the worker's view or the hook's transport. an account's presence changes at most once every 5 s, the first change kept (ADR-0872). The tracker behind both is bounded and fails closed when full. **Residual risk:** one change every 5 s per account still costs an EDU per remote server; many accounts at once are bounded only by - the dispatch queue's own shares. + the dispatch queue's own shares. A profile change stores the user's presence row again (so local + syncs and appservices see the new name or avatar) but sends no `m.presence` EDU and is not + limited: its federation cost is its `m.room.member` events, bounded by the profile propagation + (ADR-0353). ### Remote space hierarchy answers (0.12.60) diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index 8ebe5fd1f..fcece72dd 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -2,8 +2,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later #pragma once -#include "merovingian/database/StateGroupKeyHash.hpp" - #include #include #include @@ -57,10 +55,14 @@ class AccountPresenceTracker final // A sync with `set_presence=offline`: the device no longer holds the account online. auto forget_device(std::string_view user, std::string_view device) -> void; - // How long `user` must wait before a change of presence is kept, or nullopt when one may be kept now. + // How long `user` must wait before a change of presence is kept, or nullopt when one may be kept now: the rest of + // the account's window, or, when `is_full_for`, the time until the table's soonest account expires. [[nodiscard]] auto change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const -> std::optional; + // True when a change of `user` is refused because the table has no room for the account, not because of a window. + [[nodiscard]] auto is_full_for(std::string_view user, std::int64_t now_ms) const -> bool; + // Starts the window of `user` at `now_ms`: a change was just kept. auto note_change(std::string_view user, std::int64_t now_ms) -> void; @@ -87,7 +89,16 @@ class AccountPresenceTracker final // When the account stops mattering: its latest device stale and its window ended. Its key in `m_by_expiry`. std::int64_t expires_at_ms{0}; }; - using Accounts = std::unordered_map>; + // Looks a user ID up as a string_view without making a string. + struct UserHash final + { + using is_transparent = void; + [[nodiscard]] auto operator()(std::string_view user) const noexcept -> std::size_t + { + return std::hash{}(user); + } + }; + using Accounts = std::unordered_map>; using ExpiryKey = std::pair; // The account of `user`, made when there is room (after removing the expired accounts when the table is full); diff --git a/include/merovingian/homeserver/PresenceWrite.hpp b/include/merovingian/homeserver/PresenceWrite.hpp index 6fab9eb47..96892cdab 100644 --- a/include/merovingian/homeserver/PresenceWrite.hpp +++ b/include/merovingian/homeserver/PresenceWrite.hpp @@ -12,8 +12,11 @@ namespace merovingian::homeserver struct PresenceWrite final { PresenceWriteStatus status{PresenceWriteStatus::failed}; - // When `status` is limited: how long until a change is kept, at least 1 ms. + // When `status` is limited: how long until a change can be kept, at least 1 ms. std::uint32_t retry_after_ms{0U}; + // When `status` is limited: true when `AccountPresenceTracker` had no room for the account (ADR-0872), false when + // the account's own window is open. + bool tracker_full{false}; }; } // namespace merovingian::homeserver diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 43f1df40a..41f7644bd 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -137,9 +137,13 @@ auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::i auto const found = m_accounts.find(user); if (found == m_accounts.end()) { - // No window to wait for, unless there is no room to start one: then the change is refused (fails closed). - auto const no_room = m_accounts.size() >= max_accounts && !has_expired_account(now_ms); - return no_room ? std::optional{change_window_ms} : std::nullopt; + // No window to wait for, unless there is no room to start one: then the change is refused (fails closed) until + // the soonest account expires, which is later than now since none has. + if (is_full_for(user, now_ms)) + { + return m_by_expiry.begin()->first - now_ms; + } + return std::nullopt; } auto const changed_at_ms = found->second.changed_at_ms; if (!changed_at_ms.has_value() || window_has_ended(changed_at_ms, now_ms)) @@ -152,6 +156,11 @@ auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::i return change_window_ms - elapsed; } +auto AccountPresenceTracker::is_full_for(std::string_view user, std::int64_t now_ms) const -> bool +{ + return m_accounts.size() >= max_accounts && !has_expired_account(now_ms) && !m_accounts.contains(user); +} + auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now_ms) -> void { if (auto const entry = account_for(user, now_ms); entry != m_accounts.end()) diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index fbeb217a5..c86dd0176 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -24384,11 +24384,14 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp // ADR-0872: the spec's 429 for this endpoint. The change is refused, not kept for later. log_diagnostic("presence.set.limited", { - {"actor", *user, false}, - {"presence", presence_state, false}, - {"retry_after_ms", std::to_string(written.retry_after_ms), false} + {"actor", *user, false}, + {"presence", presence_state, false}, + {"cause", written.tracker_full ? "tracker_full" : "window", false}, + {"retry_after_ms", std::to_string(written.retry_after_ms), false} }); - return dispatch_err(req, rt, 429U, "M_LIMIT_EXCEEDED", "presence changed too recently", + return dispatch_err(req, rt, 429U, "M_LIMIT_EXCEEDED", + written.tracker_full ? "too many accounts are changing presence" + : "presence changed too recently", written.retry_after_ms); } if (written.status == PresenceWriteStatus::failed) @@ -25399,8 +25402,12 @@ auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence con // ADR-0872: judged and noted under the same lock as the write, so two requests at once cannot both be first. if (auto const blocked = tracker.change_blocked_for_ms(state.user_id, clock_ms); blocked.has_value()) { - auto const retry_after_ms = std::clamp(*blocked, 1, AccountPresenceTracker::change_window_ms); - return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms)}; + // A full table waits for an account to expire, at most the freshness time; a window, at most the window. + auto const longest_ms = + std::max(AccountPresenceTracker::change_window_ms, AccountPresenceTracker::device_fresh_ms); + auto const retry_after_ms = std::clamp(*blocked, 1, longest_ms); + return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), + tracker.is_full_for(state.user_id, clock_ms)}; } if (!record_presence(runtime.homeserver, state)) { diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index d52486d1c..36bc06638 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -372,11 +372,14 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: } if (auto const blocked = tracker.change_blocked_for_ms(user, clock_ms); blocked.has_value()) { - // ADR-0872: the first change in the window was kept; this one is dropped, not kept for later. + // ADR-0872: the first change in the window was kept, or the tracker has no room for the account; this one is + // dropped, not kept for later. + auto const cause = std::string{tracker.is_full_for(user, clock_ms) ? "tracker_full" : "window"}; log_presence("presence.change.limited", { {"actor", std::string{user}, false}, {"device_id", std::string{device}, false}, {"presence", std::string{desired}, false}, + {"cause", cause, false}, {"retry_after_ms", std::to_string(*blocked), false} }); return std::nullopt; diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index b5925c7f5..f44944c73 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -221,6 +221,27 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco } } } + + GIVEN("a table holding as many accounts as the cap, each held online by a device") + { + auto tracker = AccountPresenceTracker{}; + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + { + std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms); + } + + WHEN("an account with no entry asks to change its presence") + { + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 1); + + THEN("it waits for an account to expire, not for a window it never opened, and the table is the cause") + { + REQUIRE(blocked == std::optional{AccountPresenceTracker::device_fresh_ms - 1}); + REQUIRE(tracker.is_full_for(alice, start_ms + 1)); + REQUIRE_FALSE(tracker.is_full_for("@user0:example.org", start_ms + 1)); + } + } + } } SCENARIO("A prune of a full table looks only at the accounts that have expired", From 96c6e1346344239076a344f9d98a3c200cb37918 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 04:43:08 +0000 Subject: [PATCH 04/25] Keep the long-poll cursor at since unless only own presence moved it - A classic /sync that waits with nothing new keeps its wait cursor at the request's since, as before ADR-0873; only a wait past the caller's own presence row takes the store's newest position, so the cursor never moves behind since. - New integration scenario: with the presence tracker full of other accounts, PUT /presence is 429 "too many accounts are changing presence" with retry_after_ms past the 5 s window, and a sync's change is dropped, storing and sending nothing. Co-Authored-By: Claude Opus 5.5 --- src/homeserver/ClientServerRuntime.cpp | 4 +- tests/integration/test_presence_flow.cpp | 59 ++++++++++++++++++++++++ 2 files changed, 62 insertions(+), 1 deletion(-) diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index c86dd0176..7df1660ae 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -7148,10 +7148,12 @@ namespace since_token.has_value() && only_own_presence_since(store, user, since_sync_stream_id); if (!has_timeline_advance && (!has_sync_advance || only_own_presence)) { + // Only the caller's own presence row moves the cursor; otherwise it stays at `since`, never behind it. + auto const wait_sync_stream_id = only_own_presence ? store.next_sync_stream_id : since_sync_stream_id; return DispatchResult{ DispatchResult::Status::needs_wait, {}, - {since_ordering, store.next_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, + {since_ordering, wait_sync_stream_id, std::chrono::milliseconds{capped_timeout_ms}, std::string{user}, std::string{device_id}} }; } diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index cd8b17c2a..b0f9ebfa4 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1123,6 +1123,65 @@ SCENARIO("Only the first presence change in a window is kept", "[integration][pr } } +// ADR-0872: at its cap, with no account expired, the presence tracker refuses a change of an account it does not hold +// (fails closed), so a flood of accounts cannot lift the limit for itself. The refusal says so and waits for an account +// to expire, not for a window the account never opened. +SCENARIO("A presence change is refused while the presence tracker is full", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server, and the tracker is full of other accounts held online") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + using merovingian::homeserver::AccountPresenceTracker; + auto& tracker = runtime.homeserver.presence_tracker; + auto const now_ms = merovingian::homeserver::presence_limit_clock_ms(runtime.homeserver); + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + { + std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":other.example", "D", true, now_ms); + } + auto const& store = runtime.homeserver.database.persistent_store; + auto const watermark = store.next_sync_stream_id; + + WHEN("she sets her presence") + { + auto const put = put_alice_presence(runtime, token, R"({"presence":"online"})"); + + THEN("it is 429 naming the full tracker, told to wait for an account to expire, and nothing is kept") + { + REQUIRE(put.status == 429U); + auto const body = parse_object(put.body); + auto const* error = string_member(body, "error"); + REQUIRE(error != nullptr); + REQUIRE(*error == "too many accounts are changing presence"); + auto const* retry_after_ms = int_member(body, "retry_after_ms"); + REQUIRE(retry_after_ms != nullptr); + REQUIRE(*retry_after_ms > AccountPresenceTracker::change_window_ms); + REQUIRE(*retry_after_ms <= AccountPresenceTracker::device_fresh_ms); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(store.next_sync_stream_id == watermark); + REQUIRE(queued_presence_edus(runtime).empty()); + } + } + + WHEN("she syncs, which asks for online") + { + sync_once(runtime, token, "online"); + + THEN("the change is dropped: nothing is stored or sent, and the tracker does not grow") + { + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(queued_presence_edus(runtime).empty()); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + } + } + } +} + // ADR-0873: a /sync never sends the caller their own presence, so a long-poll whose only news is the caller's own // presence row would be answered with nothing, and its client would sync again at once. It keeps waiting instead, as // sliding sync does for what its response does not send (ADR-0869). From c3be0b5ed75600c013887f9eb8276de57721f810 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 05:03:33 +0000 Subject: [PATCH 05/25] File a presence account by its online devices only A device whose last set_presence ask was unavailable never changes note_sync's answer, so it no longer keeps its account in the tracker: an account expires when its latest online device is stale and its window has ended, as the class comment says. A full table frees a place up to five minutes sooner. New unit case; ADR-0871 and the header comments say online. The unit test's meson entry moves out of the OAuth block. Co-Authored-By: Claude Opus 5.5 --- ...ce-syncing-online-holds-its-account-online.md | 7 ++++--- .../homeserver/AccountPresenceTracker.hpp | 5 +++-- src/homeserver/AccountPresenceTracker.cpp | 9 +++++++-- tests/meson.build | 2 +- tests/unit/test_account_presence_tracker.cpp | 16 ++++++++++++++++ 5 files changed, 31 insertions(+), 8 deletions(-) diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index db92bdd20..a54ea1789 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -40,9 +40,10 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and two equal. * At most `max_devices_per_account` (64) devices per account, the least recently seen replaced; at most `max_accounts` (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. Each account is filed under the - time it stops mattering (its latest device stale and its window ended), so a prune visits only expired accounts, - never the table: a flood of overflow requests under `runtime.mutex` costs no scan. With the table full after a prune, - a sync of an account it does not hold asks for itself alone, as before this decision. + time it stops mattering (its latest online device stale and its window ended; a device that last asked for + `unavailable` holds no place), so a prune visits only expired accounts, never the table: a flood of overflow requests + under `runtime.mutex` costs no scan. With the table full after a prune, a sync of an account it does not hold asks + for itself alone, as before this decision. * The asks are in memory only: after a restart each device's next sync puts its ask back. * The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index fcece72dd..523791fa3 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -44,7 +44,7 @@ class AccountPresenceTracker final static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; // Far more devices than one person syncs from at once; each is a device ID and two integers. static constexpr auto max_devices_per_account = std::size_t{64U}; - // Accounts that synced or changed presence within the last five minutes. + // Accounts with a device that asked for online within the last five minutes, or a window open. static constexpr auto max_accounts = std::size_t{65'536U}; // Notes that `device` of `user` synced asking for `online` (true) or `unavailable` (false) at `now_ms`. True when a @@ -86,7 +86,8 @@ class AccountPresenceTracker final { std::vector devices{}; std::optional changed_at_ms{}; - // When the account stops mattering: its latest device stale and its window ended. Its key in `m_by_expiry`. + // When the account stops mattering: its latest online device stale and its window ended. Its key in + // `m_by_expiry`. std::int64_t expires_at_ms{0}; }; // Looks a user ID up as a string_view without making a string. diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 41f7644bd..f4a7393b2 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -37,11 +37,16 @@ namespace auto AccountPresenceTracker::refile(Accounts::iterator entry, std::int64_t now_ms) -> void { auto& account = entry->second; - // The account matters until its latest device is stale and its window has ended; with neither, it is done now. + // The account matters until its latest online device is stale and its window has ended; with neither, it is done + // now. A device whose last ask was unavailable speaks for nothing (`note_sync` answers from online devices only), + // so it never keeps an account in a full table. auto expires_at_ms = now_ms; for (auto const& held : account.devices) { - expires_at_ms = std::max(expires_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + if (held.online) + { + expires_at_ms = std::max(expires_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + } } if (account.changed_at_ms.has_value()) { diff --git a/tests/meson.build b/tests/meson.build index 043aef5ee..0f1970d2d 100644 --- a/tests/meson.build +++ b/tests/meson.build @@ -323,6 +323,7 @@ shell = find_program('sh') 'unit/test_resolved_state_memo.cpp', 'unit/test_room_power.cpp', 'unit/test_stored_room_version.cpp', + 'unit/test_account_presence_tracker.cpp', 'unit/test_appservice_client.cpp', 'unit/test_appservice_ephemeral.cpp', 'unit/test_periodic_job.cpp', @@ -506,7 +507,6 @@ shell = find_program('sh') 'unit/test_oauth_account_session_store.cpp', 'unit/test_oauth_cross_signing_reset_approvals.cpp', 'unit/test_oauth_device_authorisation_store.cpp', - 'unit/test_account_presence_tracker.cpp', 'unit/test_oauth_pending_authorisation_store.cpp', 'unit/test_oauth_pkce.cpp', 'unit/test_oauth_redirect_uri.cpp', diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index f44944c73..77d77c7a3 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -154,6 +154,22 @@ SCENARIO("A prune removes what no longer speaks for an account", "[unit][presenc } } } + + GIVEN("bob, whose presence has not changed, synced from a device asking for unavailable") + { + auto tracker = AccountPresenceTracker{}; + std::ignore = tracker.note_sync(bob, phone, false, start_ms); + + WHEN("a prune runs at once") + { + tracker.prune(start_ms); + + THEN("the account is removed: a device asking for unavailable speaks for nothing and holds no place") + { + REQUIRE(tracker.account_count() == 0U); + } + } + } } SCENARIO("The tracker is bounded per account and in all", "[unit][presence][account_presence_tracker][bounds]") From d8aef690250fceccc2984f7b59c4a293627615ba Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 05:37:02 +0000 Subject: [PATCH 06/25] Never keep a dropped presence change, and let a busy full tracker admit - A parked /sync or sliding sync run again by rerun_waiting_sync does not apply its set_presence a second time (new ClientServerDispatchOptions::sync_rerun), so a change the window dropped is not stored and sent once the window ends. - AccountPresenceTracker files an account with an open window under the window's end and any other under its online devices' staleness. A full table evicts the closed account that goes stale soonest, so 65,536 accounts that keep syncing no longer refuse everyone else for as long as they sync; it fails closed only while every account has an open window, and then for at most the rest of the soonest window (5 s). An account with an open window is never evicted, so the limit holds. - forget_device takes the time; the full-table retry clamp is the window again. - ADR-0871 no longer says a full-table sync asks for itself alone; it and ADR-0872 and src/homeserver/AGENTS.md describe the eviction. Co-Authored-By: Claude Opus 5.5 --- ...syncing-online-holds-its-account-online.md | 12 +-- ...-change-in-a-five-second-window-is-kept.md | 13 ++- .../homeserver/AccountPresenceTracker.hpp | 54 +++++++----- .../ClientServerDispatchOptions.hpp | 4 + src/homeserver/AGENTS.md | 7 +- src/homeserver/AccountPresenceTracker.cpp | 87 ++++++++++++------- src/homeserver/ClientServerRuntime.cpp | 17 ++-- src/homeserver/HttpServer.cpp | 3 +- src/homeserver/PresenceService.cpp | 2 +- tests/integration/test_presence_flow.cpp | 60 +++++++++++-- tests/unit/test_account_presence_tracker.cpp | 25 +++--- 11 files changed, 193 insertions(+), 91 deletions(-) diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index a54ea1789..953e055f9 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -39,11 +39,13 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and sweep would leave it online after that client's last sync; a `static_assert` in `PresenceService.cpp` keeps the two equal. * At most `max_devices_per_account` (64) devices per account, the least recently seen replaced; at most `max_accounts` - (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. Each account is filed under the - time it stops mattering (its latest online device stale and its window ended; a device that last asked for - `unavailable` holds no place), so a prune visits only expired accounts, never the table: a flood of overflow requests - under `runtime.mutex` costs no scan. With the table full after a prune, a sync of an account it does not hold asks - for itself alone, as before this decision. + (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. An account with an open window + (ADR-0872) is filed under its end, any other under the time its latest online device goes stale (a device that last + asked for `unavailable` holds no place), so a prune visits only expired accounts, never the table: a flood of + overflow requests under `runtime.mutex` costs no scan. With the table still full, the account with no open window + whose devices go stale soonest is evicted to make room: it loses its devices' holds until it syncs again, never a + window. Only when every account has an open window does a sync of an account the table does not hold have its device + ignored and its change refused (ADR-0872), at most until the soonest window ends. * The asks are in memory only: after a restart each device's next sync puts its ask back. * The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md index 593a56100..4dd66305a 100644 --- a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -40,10 +40,15 @@ Chosen option: 1. marked online at once), the profile propagation that resends an unchanged presence with a new display name or avatar (it stores the row for local syncs and appservices and sends no `m.presence` EDU), and inbound presence from other servers (their own server's to limit). -* With `AccountPresenceTracker` full and no account in it expired, a change of an account it does not hold is refused - (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself; once an - account has expired, the change is allowed and takes its place. The refusal's `retry_after_ms` is the time until the - soonest account expires (at most `device_fresh_ms`), and its log line's `cause` is `tracker_full`, not `window`. +* An account with an open window is never removed from `AccountPresenceTracker`, or removing it would lift its limit. + A full table makes room by evicting an account with no open window (ADR-0871), so accounts that keep syncing never + shut others out. Only when every account in it has an open window is a change of an account it does not hold refused + (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. The + refusal's `retry_after_ms` is the rest of the soonest window (at most `change_window_ms`), and its log line's `cause` + is `tracker_full`, not `window`. +* A dropped change is never kept later: a parked `/sync` or sliding sync is run again after a wake-up or its timeout + (`rerun_waiting_sync`, `ClientServerDispatchOptions::sync_rerun`), and that rerun does not apply its `set_presence` + again, so a change dropped in the window is not stored once the window has ended. * Tests move the clock with `HomeserverRuntime::test_presence_clock_advance_ms`. ### Positive Consequences diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index 523791fa3..bb8ea4bad 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -29,12 +29,14 @@ namespace merovingian::homeserver // the one kept, never the last. // // Bounded: at most `max_accounts` accounts of `max_devices_per_account` devices each. A new device past the device cap -// replaces the account's least recently seen one. Each account is filed under the time it stops mattering (its last -// online device stale and its window ended), so a prune visits only the accounts that have expired, never the table: an -// overflow request does as much work as there are accounts to remove. An account the table has no room for, once the -// expired ones are gone, has its devices ignored (its sync asks for itself alone, as without this table) and every -// change refused until there is room, so a flood of accounts cannot lift the limit for itself. Not thread-safe: -// `runtime.mutex` serialises every use (`HomeserverRuntime::presence_tracker`). +// replaces the account's least recently seen one. An account with an open window is filed under the window's end; any +// other under the time its last online device goes stale, and an account moves from the first to the second when its +// window ends. A prune removes only the accounts whose time has passed, never visiting the table. When the table is +// full after a prune, the account with no open window whose devices go stale soonest makes room: it loses only its +// devices' holds, never a window, so the limit holds. Only when every account has an open window is there no room: a +// newcomer's devices are ignored and its change refused until the soonest window ends (at most `change_window_ms`), so +// a flood of accounts cannot lift the limit for itself. Every operation does O(log n) work per account it moves or +// removes. Not thread-safe: `runtime.mutex` serialises every use (`HomeserverRuntime::presence_tracker`). class AccountPresenceTracker final { public: @@ -52,27 +54,28 @@ class AccountPresenceTracker final [[nodiscard]] auto note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) -> bool; - // A sync with `set_presence=offline`: the device no longer holds the account online. - auto forget_device(std::string_view user, std::string_view device) -> void; + // A sync with `set_presence=offline` at `now_ms`: the device no longer holds the account online. + auto forget_device(std::string_view user, std::string_view device, std::int64_t now_ms) -> void; // How long `user` must wait before a change of presence is kept, or nullopt when one may be kept now: the rest of - // the account's window, or, when `is_full_for`, the time until the table's soonest account expires. + // the account's window, or, when `is_full_for`, the rest of the table's soonest window. Never over the window. [[nodiscard]] auto change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const -> std::optional; - // True when a change of `user` is refused because the table has no room for the account, not because of a window. + // True when a change of `user` is refused because the table has no room for the account (every account in it has an + // open window), not because of the account's own window. [[nodiscard]] auto is_full_for(std::string_view user, std::int64_t now_ms) const -> bool; // Starts the window of `user` at `now_ms`: a change was just kept. auto note_change(std::string_view user, std::int64_t now_ms) -> void; - // Removes every account whose devices are all stale and whose window ended by `now_ms`. + // Removes every account whose online devices are all stale and whose window ended by `now_ms`. auto prune(std::int64_t now_ms) -> void; // Accounts held, ones a prune would remove included. [[nodiscard]] auto account_count() const noexcept -> std::size_t; - // Accounts a prune has looked at since the table was made, for tests that prove its cost. + // Accounts a prune removed or a full table evicted since the table was made, for tests that prove the cost. [[nodiscard]] auto accounts_examined() const noexcept -> std::uint64_t; private: @@ -86,9 +89,10 @@ class AccountPresenceTracker final { std::vector devices{}; std::optional changed_at_ms{}; - // When the account stops mattering: its latest online device stale and its window ended. Its key in - // `m_by_expiry`. - std::int64_t expires_at_ms{0}; + // Its key: the end of its open window (in `m_open_windows`), or else the time its last online device goes stale + // or its window ended, whichever is later (in `m_closed`). + std::int64_t filed_at_ms{0}; + bool window_open{false}; }; // Looks a user ID up as a string_view without making a string. struct UserHash final @@ -100,21 +104,27 @@ class AccountPresenceTracker final } }; using Accounts = std::unordered_map>; - using ExpiryKey = std::pair; + using FiledKey = std::pair; - // The account of `user`, made when there is room (after removing the expired accounts when the table is full); + // The account of `user`, made when there is room (after a prune, and an eviction when the table is still full); // `m_accounts.end()` when there is none. [[nodiscard]] auto account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator; - // Files `entry` under its expiry again, after its devices or window changed. + // Files `entry` again, after its devices or window changed or its window ended. auto refile(Accounts::iterator entry, std::int64_t now_ms) -> void; - // True when an account has expired by `now_ms`, so a prune would make room. - [[nodiscard]] auto has_expired_account(std::int64_t now_ms) const noexcept -> bool; + // Moves every account whose window ended by `now_ms` from `m_open_windows` to `m_closed`. + auto close_ended_windows(std::int64_t now_ms) -> void; + + // True when the table can hold another account at `now_ms`: it is not full, or an account in it has no open window. + [[nodiscard]] auto has_room(std::int64_t now_ms) const noexcept -> bool; Accounts m_accounts{}; - // (expires_at_ms, user) of every account, soonest first. - std::set m_by_expiry{}; + // (window end, user) of every account whose window was open when it was filed, soonest first. + std::set m_open_windows{}; + // (stale-or-ended time, user) of every other account, soonest first: the ones a prune removes, and the one a full + // table evicts. + std::set m_closed{}; std::uint64_t m_accounts_examined{0U}; }; diff --git a/include/merovingian/homeserver/ClientServerDispatchOptions.hpp b/include/merovingian/homeserver/ClientServerDispatchOptions.hpp index 93d76acca..8e07e7aa6 100644 --- a/include/merovingian/homeserver/ClientServerDispatchOptions.hpp +++ b/include/merovingian/homeserver/ClientServerDispatchOptions.hpp @@ -17,6 +17,10 @@ struct ClientServerDispatchOptions final // The transport already counted this request against the rate limiter (the // media fetch pool running a deferred request again); do not count it twice. bool rate_limit_admitted{false}; + // A parked /sync or sliding sync run again after a wake-up or its timeout (`rerun_waiting_sync`). Its + // `set_presence` was applied on its first run and is not applied again, so a change the window dropped stays + // dropped (ADR-0872). + bool sync_rerun{false}; }; } // namespace merovingian::homeserver diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index b40e13a8d..8b30b8312 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,7 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | -| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, each filed under its expiry so a prune visits only expired accounts (`accounts_examined()` counts them), failing closed at the cap while none has expired. Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | @@ -1386,8 +1386,9 @@ without that check ignores `presence.enabled=false`. Rules: - A change of an account's presence starts a 5 s window in which no other change is kept (ADR-0872): a sync's is dropped, a `PUT /presence` is 429 (`set_presence` returns `PresenceWrite`). Judge and note it under `runtime.mutex` with the write, and keep the first change, never the last. The idle sweep and the profile propagation are not - limited. A new path that changes a local user's presence state is limited the same way. Tests move the clock with - `test_presence_clock_advance_ms`, never with a sleep. + limited. A new path that changes a local user's presence state is limited the same way. A parked poll's rerun + (`ClientServerDispatchOptions::sync_rerun`) never applies `set_presence` again, or a dropped change would be kept + once the window ends. Tests move the clock with `test_presence_clock_advance_ms`, never with a sleep. - A classic `/sync` whose only news is the caller's own presence row waits on (`only_own_presence_since`, ADR-0873): never wake a poll for what its response does not send. - `accept_inbound_presence` binds `user_id` to the sending origin, bounds the entries it looks at, and keeps diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index f4a7393b2..405887bbc 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -37,33 +37,49 @@ namespace auto AccountPresenceTracker::refile(Accounts::iterator entry, std::int64_t now_ms) -> void { auto& account = entry->second; - // The account matters until its latest online device is stale and its window has ended; with neither, it is done - // now. A device whose last ask was unavailable speaks for nothing (`note_sync` answers from online devices only), - // so it never keeps an account in a full table. - auto expires_at_ms = now_ms; - for (auto const& held : account.devices) - { - if (held.online) + auto const lowest = std::numeric_limits::min(); + auto const window_end_ms = + account.changed_at_ms.has_value() ? saturating_after(*account.changed_at_ms, change_window_ms) : lowest; + auto const window_open = window_end_ms > now_ms; + // A closed account matters until its latest online device is stale and its window has ended. A device whose last + // ask was unavailable speaks for nothing (`note_sync` answers from online devices only), so it never keeps an + // account. + auto filed_at_ms = window_end_ms; + if (!window_open) + { + for (auto const& held : account.devices) { - expires_at_ms = std::max(expires_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + if (held.online) + { + filed_at_ms = std::max(filed_at_ms, saturating_after(held.seen_at_ms, device_fresh_ms)); + } } } - if (account.changed_at_ms.has_value()) - { - expires_at_ms = std::max(expires_at_ms, saturating_after(*account.changed_at_ms, change_window_ms)); - } - if (expires_at_ms == account.expires_at_ms) + (account.window_open ? m_open_windows : m_closed).erase(FiledKey{account.filed_at_ms, entry->first}); + account.window_open = window_open; + account.filed_at_ms = filed_at_ms; + (window_open ? m_open_windows : m_closed).emplace(filed_at_ms, entry->first); +} + +auto AccountPresenceTracker::close_ended_windows(std::int64_t now_ms) -> void +{ + while (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms) { - return; + // Refiling erases this front entry, so the loop always moves on. + auto const ended = m_accounts.find(m_open_windows.begin()->second); + if (ended == m_accounts.end()) + { + m_open_windows.erase(m_open_windows.begin()); + continue; + } + refile(ended, now_ms); } - m_by_expiry.erase(ExpiryKey{account.expires_at_ms, entry->first}); - account.expires_at_ms = expires_at_ms; - m_by_expiry.emplace(expires_at_ms, entry->first); } -auto AccountPresenceTracker::has_expired_account(std::int64_t now_ms) const noexcept -> bool +auto AccountPresenceTracker::has_room(std::int64_t now_ms) const noexcept -> bool { - return !m_by_expiry.empty() && m_by_expiry.begin()->first <= now_ms; + return m_accounts.size() < max_accounts || !m_closed.empty() || + (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms); } auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now_ms) -> Accounts::iterator @@ -75,14 +91,23 @@ auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now if (m_accounts.size() >= max_accounts) { prune(now_ms); - if (m_accounts.size() >= max_accounts) + } + if (m_accounts.size() >= max_accounts) + { + if (m_closed.empty()) { + // Every account has an open window: evicting one would lift its limit. return m_accounts.end(); } + // The account whose devices go stale soonest loses their holds; it has no window to lose. + auto const evicted = m_closed.begin(); + ++m_accounts_examined; + m_accounts.erase(evicted->second); + m_closed.erase(evicted); } auto const made = m_accounts.try_emplace(std::string{user}).first; - made->second.expires_at_ms = now_ms; - m_by_expiry.emplace(now_ms, made->first); + made->second.filed_at_ms = std::numeric_limits::min(); + m_closed.emplace(made->second.filed_at_ms, made->first); return made; } @@ -122,7 +147,7 @@ auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view d }); } -auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device) -> void +auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device, std::int64_t now_ms) -> void { auto const found = m_accounts.find(user); if (found == m_accounts.end()) @@ -132,8 +157,7 @@ auto AccountPresenceTracker::forget_device(std::string_view user, std::string_vi std::erase_if(found->second.devices, [device](Device const& held) { return held.id == device; }); - // The account may now expire sooner; it is never kept past its old time, and a prune judges it by the new one. - refile(found, std::numeric_limits::min()); + refile(found, now_ms); } auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::int64_t now_ms) const @@ -143,10 +167,10 @@ auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::i if (found == m_accounts.end()) { // No window to wait for, unless there is no room to start one: then the change is refused (fails closed) until - // the soonest account expires, which is later than now since none has. + // the soonest window ends, which is later than now since every window is open. if (is_full_for(user, now_ms)) { - return m_by_expiry.begin()->first - now_ms; + return m_open_windows.begin()->first - now_ms; } return std::nullopt; } @@ -163,7 +187,7 @@ auto AccountPresenceTracker::change_blocked_for_ms(std::string_view user, std::i auto AccountPresenceTracker::is_full_for(std::string_view user, std::int64_t now_ms) const -> bool { - return m_accounts.size() >= max_accounts && !has_expired_account(now_ms) && !m_accounts.contains(user); + return !has_room(now_ms) && !m_accounts.contains(user); } auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now_ms) -> void @@ -177,12 +201,13 @@ auto AccountPresenceTracker::note_change(std::string_view user, std::int64_t now auto AccountPresenceTracker::prune(std::int64_t now_ms) -> void { - while (has_expired_account(now_ms)) + close_ended_windows(now_ms); + while (!m_closed.empty() && m_closed.begin()->first <= now_ms) { - auto const soonest = m_by_expiry.begin(); + auto const soonest = m_closed.begin(); ++m_accounts_examined; m_accounts.erase(soonest->second); - m_by_expiry.erase(soonest); + m_closed.erase(soonest); } } diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 7df1660ae..657d2878c 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -22351,7 +22351,11 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, device_id, *presence_mode); + // ADR-0872: applied on the request's first run only. A rerun of a parked poll is the same request, and a + // change the window dropped stays dropped, never kept once the window has ended. + if (auto const changed = dispatch_options.sync_rerun + ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id, *presence_mode); changed.has_value()) { log_diagnostic("presence.sync.set", { @@ -22414,7 +22418,10 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - if (auto const changed = apply_sync_presence(rt.homeserver, *user, device_id_4186, *sliding_presence_mode); + // ADR-0872: on the request's first run only, as for /sync. + if (auto const changed = dispatch_options.sync_rerun ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id_4186, + *sliding_presence_mode); changed.has_value()) { log_diagnostic("presence.sync.set", { @@ -25404,10 +25411,8 @@ auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence con // ADR-0872: judged and noted under the same lock as the write, so two requests at once cannot both be first. if (auto const blocked = tracker.change_blocked_for_ms(state.user_id, clock_ms); blocked.has_value()) { - // A full table waits for an account to expire, at most the freshness time; a window, at most the window. - auto const longest_ms = - std::max(AccountPresenceTracker::change_window_ms, AccountPresenceTracker::device_fresh_ms); - auto const retry_after_ms = std::clamp(*blocked, 1, longest_ms); + // The account's own window, or a full table's soonest one: never longer than the window. + auto const retry_after_ms = std::clamp(*blocked, 1, AccountPresenceTracker::change_window_ms); return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), tracker.is_full_for(state.user_id, clock_ms)}; } diff --git a/src/homeserver/HttpServer.cpp b/src/homeserver/HttpServer.cpp index 7cf28747d..93693d751 100644 --- a/src/homeserver/HttpServer.cpp +++ b/src/homeserver/HttpServer.cpp @@ -1256,7 +1256,8 @@ namespace -> DispatchResult { return handle_client_server_request( - runtime, request, ClientServerDispatchOptions{.can_wait = can_wait, .rate_limit_admitted = true}); + runtime, request, + ClientServerDispatchOptions{.can_wait = can_wait, .rate_limit_admitted = true, .sync_rerun = true}); } // The long-poll of the transports with no sync pool: one wait for the whole timeout, no peer peek. True when diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 36bc06638..15b098a69 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -345,7 +345,7 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: if (mode == SyncPresenceMode::offline) { // "offline": the client is not to be marked online, so it no longer holds the account online either. - tracker.forget_device(user, device); + tracker.forget_device(user, device, clock_ms); return std::nullopt; } auto const asks_online = mode == SyncPresenceMode::online; diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index b0f9ebfa4..30942489c 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1123,12 +1123,56 @@ SCENARIO("Only the first presence change in a window is kept", "[integration][pr } } -// ADR-0872: at its cap, with no account expired, the presence tracker refuses a change of an account it does not hold -// (fails closed), so a flood of accounts cannot lift the limit for itself. The refusal says so and waits for an account -// to expire, not for a window the account never opened. +// ADR-0872: a change dropped in a window is dropped, never kept for later. A long-polling sync whose change was +// dropped is run again after a wake-up or its timeout (`rerun_waiting_sync`); that rerun is the same request and does +// not apply its `set_presence` again, even once the window has ended. +SCENARIO("A parked sync run again does not apply its set_presence a second time", "[integration][presence][long_poll]") +{ + GIVEN("alice shares a room with bob on another server, set herself online, and holds a next_batch") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + auto const initial = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&set_presence=offline", token); + REQUIRE(initial.status == 200U); + auto const initial_body = parse_object(initial.body); + auto const* since = string_member(initial_body, "next_batch"); + REQUIRE(since != nullptr); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she long-polls asking for unavailable inside the window, and the poll is run again once it has ended") + { + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "GET", "/_matrix/client/v3/sync?timeout=30000&set_presence=unavailable&since=" + *since, token, {}}; + auto const first = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(first.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + let_presence_window_end(runtime); + auto const rerun = merovingian::homeserver::handle_client_server_request( + runtime, long_poll, + merovingian::homeserver::ClientServerDispatchOptions{ + .can_wait = false, .rate_limit_admitted = true, .sync_rerun = true}); + + THEN("the dropped change stays dropped: she is still online and bob's server is told nothing more") + { + REQUIRE(rerun.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + +// ADR-0872: at its cap, with every account in its window, the presence tracker refuses a change of an account it does +// not hold (fails closed), so a flood of accounts cannot lift the limit for itself. The refusal says so and waits for +// the soonest window to end. SCENARIO("A presence change is refused while the presence tracker is full", "[integration][presence][rate_limit]") { - GIVEN("alice shares a room with bob on another server, and the tracker is full of other accounts held online") + GIVEN("alice shares a room with bob on another server, and the tracker is full of accounts that just changed") { REQUIRE(sodium_init() >= 0); auto started = merovingian::homeserver::start_client_server(presence_config()); @@ -1142,7 +1186,7 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in auto const now_ms = merovingian::homeserver::presence_limit_clock_ms(runtime.homeserver); for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) { - std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":other.example", "D", true, now_ms); + tracker.note_change("@user" + std::to_string(index) + ":other.example", now_ms); } auto const& store = runtime.homeserver.database.persistent_store; auto const watermark = store.next_sync_stream_id; @@ -1151,7 +1195,7 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in { auto const put = put_alice_presence(runtime, token, R"({"presence":"online"})"); - THEN("it is 429 naming the full tracker, told to wait for an account to expire, and nothing is kept") + THEN("it is 429 naming the full tracker, told to wait for the soonest window, and nothing is kept") { REQUIRE(put.status == 429U); auto const body = parse_object(put.body); @@ -1160,8 +1204,8 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in REQUIRE(*error == "too many accounts are changing presence"); auto const* retry_after_ms = int_member(body, "retry_after_ms"); REQUIRE(retry_after_ms != nullptr); - REQUIRE(*retry_after_ms > AccountPresenceTracker::change_window_ms); - REQUIRE(*retry_after_ms <= AccountPresenceTracker::device_fresh_ms); + REQUIRE(*retry_after_ms > 0); + REQUIRE(*retry_after_ms <= AccountPresenceTracker::change_window_ms); REQUIRE(alice_presence_state(runtime) == "none"); REQUIRE(store.next_sync_stream_id == watermark); REQUIRE(queued_presence_edus(runtime).empty()); diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 77d77c7a3..8d0c9be44 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -69,7 +69,7 @@ SCENARIO("A device syncing online holds its account online against a device sync WHEN("the desktop syncs with set_presence=offline and the phone asks for unavailable") { - tracker.forget_device(alice, desktop); + tracker.forget_device(alice, desktop, start_ms + 100); auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 100); THEN("the desktop no longer holds the account online") @@ -238,23 +238,28 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco } } - GIVEN("a table holding as many accounts as the cap, each held online by a device") + GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") { auto tracker = AccountPresenceTracker{}; - for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) { - std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms); + std::ignore = + tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); } - WHEN("an account with no entry asks to change its presence") + WHEN("an account with no entry asks to change its presence, however recently the others synced") { - auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 1); + auto const blocked = tracker.change_blocked_for_ms(alice, start_ms + 2); + tracker.note_change(alice, start_ms + 2); - THEN("it waits for an account to expire, not for a window it never opened, and the table is the cause") + THEN("it is allowed, and the account whose device goes stale soonest gives up its place") { - REQUIRE(blocked == std::optional{AccountPresenceTracker::device_fresh_ms - 1}); - REQUIRE(tracker.is_full_for(alice, start_ms + 1)); - REQUIRE_FALSE(tracker.is_full_for("@user0:example.org", start_ms + 1)); + REQUIRE_FALSE(blocked.has_value()); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 3).has_value()); + REQUIRE_FALSE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); } } } From 5603755f09b0e3e513c0f8adbdd82140b5f737da Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 06:12:03 +0000 Subject: [PATCH 07/25] Look a presence row up for change in place, and test the sliding rerun - database::find_mutable_presence_state sits beside find_presence_state; both answer from one position lookup, so PresenceService and upsert_presence no longer turn a const pointer back into an index. - New scenario: a parked sliding sync run again does not apply its set_presence a second time (sync_rerun on the MSC4186 path). - New scenario: a device's hold taken through sliding sync is released by its classic sync's set_presence=offline, so both transports file one device under one key. - src/database/AGENTS.md names the mutable accessor. Co-Authored-By: Claude Opus 5.5 --- .../merovingian/database/PersistentStore.hpp | 2 + src/database/AGENTS.md | 4 +- src/database/PersistentStore.cpp | 68 ++++++++----- src/homeserver/PresenceService.cpp | 14 +-- tests/integration/test_presence_flow.cpp | 97 +++++++++++++++++++ 5 files changed, 146 insertions(+), 39 deletions(-) diff --git a/include/merovingian/database/PersistentStore.hpp b/include/merovingian/database/PersistentStore.hpp index 9d2c9c124..3277ed6fc 100644 --- a/include/merovingian/database/PersistentStore.hpp +++ b/include/merovingian/database/PersistentStore.hpp @@ -1586,6 +1586,8 @@ auto for_each_user_filter(PersistentStore const& store, std::string_view user_id // The presence row of `user_id`, or nullptr, through the user index (ADR-0659). [[nodiscard]] auto find_presence_state(PersistentStore const& store, std::string_view user_id) -> PersistentPresence const*; +// The same row for a change in place, or nullptr. A change must keep `user_id`: the index is keyed on it. +[[nodiscard]] auto find_mutable_presence_state(PersistentStore& store, std::string_view user_id) -> PersistentPresence*; [[nodiscard]] auto upsert_presence(PersistentStore& store, PersistentPresence state) -> bool; // Store a sync filter uploaded by a client. On conflict the JSON is replaced. [[nodiscard]] auto store_filter(PersistentStore& store, PersistentFilter filter) -> bool; diff --git a/src/database/AGENTS.md b/src/database/AGENTS.md index d4b6abb0c..171f089a8 100644 --- a/src/database/AGENTS.md +++ b/src/database/AGENTS.md @@ -393,7 +393,7 @@ as `core::CopyableMutex` has. No production code copies a store; only tests do. `device_list_observer_index` (device-list changes by observer), `filter_user_index` (stored filters by user) and `presence_user_index` (presence rows by user) follow the row-index rule above: trusted only while built for the vector's current row count, rebuilt by their writer when found out of step and by `rebuild_key_indexes` after hydration. Read through -`for_each_observer_device_list_change`, `for_each_user_filter`, `find_filter` and `find_presence_state`, never by looping the -vector in a request. `record_device_list_changes` replaces a pair's row by erasing it (the last row moves into the gap, so the +`for_each_observer_device_list_change`, `for_each_user_filter`, `find_filter` and `find_presence_state` (`find_mutable_presence_state` +for a change in place: never turn the const accessor's pointer back into a position), never by looping the vector in a request. `record_device_list_changes` replaces a pair's row by erasing it (the last row moves into the gap, so the vector has no order) and appending the new one. Tests prove cost with `device_list_rows_examined`, `filter_rows_examined` and `presence_rows_examined`. diff --git a/src/database/PersistentStore.cpp b/src/database/PersistentStore.cpp index 6f4f0a70c..49996f501 100644 --- a/src/database/PersistentStore.cpp +++ b/src/database/PersistentStore.cpp @@ -8744,6 +8744,40 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str return record_device_list_changes(store, std::move(batch)); } +namespace +{ + + // The position in `store.presence_states` of `user_id`'s row, or nullopt, through the user index (ADR-0659). The + // const and the mutable lookup both answer from it, so neither turns the other's pointer back into a position. + [[nodiscard]] auto presence_position(PersistentStore const& store, + std::string_view user_id) -> std::optional + { + if (store.presence_user_index.in_step(store.presence_states.size())) + { + store.presence_rows_examined.add(1U); + auto const position = store.presence_user_index.find(std::string{user_id}); + if (!position.has_value()) + { + return std::nullopt; + } + if (*position < store.presence_states.size() && store.presence_states[*position].user_id == user_id) + { + return *position; + } + } + store.presence_rows_examined.add(store.presence_states.size()); + auto const found = std::ranges::find_if(store.presence_states, [user_id](PersistentPresence const& row) { + return row.user_id == user_id; + }); + if (found == store.presence_states.end()) + { + return std::nullopt; + } + return static_cast(std::ranges::distance(store.presence_states.begin(), found)); + } + +} // namespace + [[nodiscard]] auto upsert_presence(PersistentStore& store, PersistentPresence state) -> bool { if (state.user_id.empty() || state.presence.empty()) @@ -8765,9 +8799,9 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str return false; } sync_presence_index(store); - if (auto const* current = find_presence_state(store, state.user_id); current != nullptr) + if (auto* const current = find_mutable_presence_state(store, state.user_id); current != nullptr) { - store.presence_states[static_cast(current - store.presence_states.data())] = std::move(state); + *current = std::move(state); return true; } store.presence_states.push_back(std::move(state)); @@ -8778,28 +8812,14 @@ auto for_each_observer_device_list_change(PersistentStore const& store, std::str [[nodiscard]] auto find_presence_state(PersistentStore const& store, std::string_view user_id) -> PersistentPresence const* { - if (store.presence_user_index.in_step(store.presence_states.size())) - { - store.presence_rows_examined.add(1U); - auto const position = store.presence_user_index.find(std::string{user_id}); - if (!position.has_value()) - { - return nullptr; - } - if (*position < store.presence_states.size() && store.presence_states[*position].user_id == user_id) - { - return &store.presence_states[*position]; - } - } - store.presence_rows_examined.add(store.presence_states.size()); - for (auto const& row : store.presence_states) - { - if (row.user_id == user_id) - { - return &row; - } - } - return nullptr; + auto const position = presence_position(store, user_id); + return position.has_value() ? &store.presence_states[*position] : nullptr; +} + +[[nodiscard]] auto find_mutable_presence_state(PersistentStore& store, std::string_view user_id) -> PersistentPresence* +{ + auto const position = presence_position(store, user_id); + return position.has_value() ? &store.presence_states[*position] : nullptr; } [[nodiscard]] auto store_room_alias(PersistentStore& store, PersistentRoomAlias alias) -> bool diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 15b098a69..e4ee0fbb9 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -84,18 +84,6 @@ namespace }); } - // The user's row, through the presence index (ADR-0659), for a change in place; nullptr when there is none. - [[nodiscard]] auto find_mutable_row(database::PersistentStore& store, std::string_view user_id) - -> database::PersistentPresence* - { - auto const* const row = database::find_presence_state(store, user_id); - if (row == nullptr) - { - return nullptr; - } - return &store.presence_states[static_cast(row - store.presence_states.data())]; - } - [[nodiscard]] auto joined_rooms_of(database::PersistentStore const& store, std::string_view user) -> std::unordered_set { @@ -358,7 +346,7 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: auto& store = runtime.database.persistent_store; auto const now_ms = presence_now_ms(); auto const desired = asks_online ? std::string_view{"online"} : std::string_view{"unavailable"}; - auto* const existing = find_mutable_row(store, user); + auto* const existing = database::find_mutable_presence_state(store, user); if (existing != nullptr && existing->presence == desired) { if (asks_online) diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index 30942489c..b3f9c7370 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1167,6 +1167,103 @@ SCENARIO("A parked sync run again does not apply its set_presence a second time" } } +namespace +{ + +constexpr auto sliding_sync_target = std::string_view{"/_matrix/client/unstable/org.matrix.msc4186/sync"}; + +// The `pos` of a sliding sync that answers at once and leaves alice's presence alone. +[[nodiscard]] auto sliding_sync_pos(ClientServerRuntime& runtime, std::string const& token) -> std::string +{ + auto const synced = call(runtime, "POST", std::string{sliding_sync_target}, token, R"({"set_presence":"offline"})"); + REQUIRE(synced.status == 200U); + auto const body = parse_object(synced.body); + auto const* pos = string_member(body, "pos"); + REQUIRE(pos != nullptr); + return *pos; +} + +} // namespace + +SCENARIO("A parked sliding sync run again does not apply its set_presence a second time", + "[integration][presence][sliding-sync][long_poll]") +{ + GIVEN("alice shares a room with bob on another server, set herself online, and holds a sliding sync pos") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + auto const pos = sliding_sync_pos(runtime, token); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she long-polls asking for unavailable inside the window, and the poll is run again once it has ended") + { + auto const long_poll = merovingian::homeserver::LocalHttpRequest{ + "POST", std::string{sliding_sync_target} + "?timeout=30000&pos=" + pos, token, + R"({"set_presence":"unavailable"})"}; + auto const first = merovingian::homeserver::handle_client_server_request(runtime, long_poll); + REQUIRE(first.status == merovingian::homeserver::DispatchResult::Status::needs_wait); + let_presence_window_end(runtime); + auto const rerun = merovingian::homeserver::handle_client_server_request( + runtime, long_poll, + merovingian::homeserver::ClientServerDispatchOptions{ + .can_wait = false, .rate_limit_admitted = true, .sync_rerun = true}); + + THEN("the dropped change stays dropped: she is still online and bob's server is told nothing more") + { + REQUIRE(rerun.status == merovingian::homeserver::DispatchResult::Status::complete); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + +// ADR-0871: a device is one device whichever sync API it uses, so the hold one transport takes is released by the +// other's set_presence=offline. +SCENARIO("A device's hold taken through sliding sync is released by its classic sync", + "[integration][presence][sliding-sync][devices]") +{ + GIVEN("alice's desktop sliding-synced online and she has a phone too") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const desktop = register_alice(runtime); + auto const phone = log_alice_in_on(runtime, "PHONE"); + REQUIRE(call(runtime, "POST", std::string{sliding_sync_target}, desktop, "{}").status == 200U); + REQUIRE(alice_presence_state(runtime) == "online"); + let_presence_window_end(runtime); + + WHEN("the phone syncs asking for unavailable while the desktop holds the account") + { + sync_once(runtime, phone, "unavailable"); + + THEN("she stays online") + { + REQUIRE(alice_presence_state(runtime) == "online"); + } + } + + WHEN("the desktop's classic sync says offline, and then the phone asks for unavailable") + { + sync_once(runtime, desktop, "offline"); + sync_once(runtime, phone, "unavailable"); + + THEN("the desktop no longer holds the account, so she becomes unavailable") + { + REQUIRE(alice_presence_state(runtime) == "unavailable"); + } + } + } +} + // ADR-0872: at its cap, with every account in its window, the presence tracker refuses a change of an account it does // not hold (fails closed), so a flood of accounts cannot lift the limit for itself. The refusal says so and waits for // the soonest window to end. From 65a01c29ef7d63f6496190e92b80abb0474f8d97 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 06:25:13 +0000 Subject: [PATCH 08/25] Log a sync held online, and keep the full-tracker test off the clock - apply_sync_presence logs presence.change.limited with cause device_online when a sync asks for unavailable while another device holds the account online (ADR-0871), the one drop that left no trace. - The full-tracker scenario starts its windows one window ahead, so none can end while it runs on the live clock under a slow shard. - docs/observability-audit.md names the new cause; docs/database-persistence.md names find_mutable_presence_state and that a change keeps the row's user_id. Co-Authored-By: Claude Opus 5.5 --- docs/database-persistence.md | 4 +++- docs/observability-audit.md | 4 +++- src/homeserver/PresenceService.cpp | 6 ++++++ tests/integration/test_presence_flow.cpp | 4 +++- 4 files changed, 15 insertions(+), 3 deletions(-) diff --git a/docs/database-persistence.md b/docs/database-persistence.md index 7bae77c9c..9da8ce62d 100644 --- a/docs/database-persistence.md +++ b/docs/database-persistence.md @@ -646,7 +646,9 @@ value. Test fixtures that do not exercise persistence select it through (256) rows with a thread root as `thread_id` in one room; a new one is committed with the delete of that user's own oldest (ADR-0737). The device-list change, stored filter and presence tables are read through standing indexes by observer, user and user (`for_each_observer_device_list_change`, `for_each_user_filter`, - `find_presence_state`; ADR-0659). `store_receipts` commits an inbound `m.receipt` + `find_presence_state`; ADR-0659). A presence row is changed in place only through `find_mutable_presence_state`, which + answers from the same position lookup, and the change keeps the row's `user_id`, the key of `presence_user_index`. + `store_receipts` commits an inbound `m.receipt` EDU's accepted rows in one transaction and, past `max_inbound_receipt_entries`, deletes the oldest remote rows in it, taken from the ordered `receipt_remote_by_stream` index (ADR-0652). - The v1 schema's media tables carry the upload names and pending uploads. diff --git a/docs/observability-audit.md b/docs/observability-audit.md index e8b9ee67d..0e21f9641 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -136,7 +136,9 @@ is full. `tracker_full`) (fields `actor`, `presence`, `cause`, `retry_after_ms`; ADR-0872). `presence.sync.set` (debug, logger `client_server`) records a `/sync` that changed the caller's state (fields `actor`, `presence`). `presence.change.limited` (debug, logger `presence`) records a `/sync` change dropped - for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`). + for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`), and a `/sync` asking for + `unavailable` while another device of the account holds it online (`cause` `device_online`, no `retry_after_ms`; + ADR-0871). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index e4ee0fbb9..1bc7ca132 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -341,6 +341,12 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: if (!asks_online && any_device_online) { // ADR-0871: another device of the account asked for online in the freshness time; online beats unavailable. + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", "unavailable", false}, + {"cause", "device_online", false} + }); return std::nullopt; } auto& store = runtime.database.persistent_store; diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index b3f9c7370..d3a2ae902 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1283,7 +1283,9 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in auto const now_ms = merovingian::homeserver::presence_limit_clock_ms(runtime.homeserver); for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) { - tracker.note_change("@user" + std::to_string(index) + ":other.example", now_ms); + // Started a window ahead, so no window can end while the scenario runs on the live clock. + tracker.note_change("@user" + std::to_string(index) + ":other.example", + now_ms + AccountPresenceTracker::change_window_ms); } auto const& store = runtime.homeserver.database.persistent_store; auto const watermark = store.next_sync_stream_id; From f320956e0a4f889eccded3ed5af996664c7d1e10 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 06:29:30 +0000 Subject: [PATCH 09/25] Apply a sliding sync's set_presence only once its pos is accepted A sliding sync refused with 400 M_UNKNOWN_POS had already stored its presence change and opened the ADR-0872 window, so a PUT /presence just after it was 429. The presence block now runs after the pos check, with its rerun guard, log, broadcast and notifier unchanged. New scenario: a sliding sync refused for an unknown pos changes no presence, and the caller may set it at once. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 ++ src/homeserver/ClientServerRuntime.cpp | 27 +++++++++++---------- tests/integration/test_presence_flow.cpp | 31 ++++++++++++++++++++++++ 3 files changed, 47 insertions(+), 13 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ceb6e1a9d..6a22d79be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -184,6 +184,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * A classic `/sync` whose only news is the caller's own presence keeps waiting instead of answering nothing (ADR-0873). * A classic `/sync` with `full_state=true` is answered at once, whatever its `timeout`, as the spec says; it waited like any other long poll (ADR-0873). +* A sliding sync refused with `M_UNKNOWN_POS` no longer changes the caller's presence: `set_presence` is applied + only once the `pos` is accepted (ADR-0872). * `docs/observability-audit.md` named the wrong logger for `presence.sync.set`; it is `client_server`. ## Release notes diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 657d2878c..1a08a95de 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -22418,19 +22418,6 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_INVALID_PARAM", "set_presence must be online, offline or unavailable"); } - // ADR-0872: on the request's first run only, as for /sync. - if (auto const changed = dispatch_options.sync_rerun ? std::nullopt - : apply_sync_presence(rt.homeserver, *user, device_id_4186, - *sliding_presence_mode); - changed.has_value()) - { - log_diagnostic("presence.sync.set", { - {"actor", *user, false}, - {"presence", changed->presence, false} - }); - broadcast_presence_edu(rt.homeserver, *changed); - std::ignore = ensure_sync_notifier(rt); - } // Prefer query-string pos/timeout; fall back to the newer body-level fields. MSC4186: "Servers MUST reject a // `pos` that was not issued to the requesting user and device, responding with `M_UNKNOWN_POS`": a pos with no // valid binding to this user and device, or one that does not read as a position, is refused whole, never @@ -22457,6 +22444,20 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_UNKNOWN_POS", "unknown sliding sync position"); } } + // ADR-0872: on the request's first run only, as for /sync, and only once `pos` is accepted, so a refused + // request changes no presence and opens no window. + if (auto const changed = dispatch_options.sync_rerun ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id_4186, + *sliding_presence_mode); + changed.has_value()) + { + log_diagnostic("presence.sync.set", { + {"actor", *user, false}, + {"presence", changed->presence, false} + }); + broadcast_presence_edu(rt.homeserver, *changed); + std::ignore = ensure_sync_notifier(rt); + } // MSC4186 `timeout`: "Ignored when no `pos` is set": a request without one is answered at once (ADR-0865). auto const timeout = pos.has_value() diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index d3a2ae902..e9de5d66c 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1224,6 +1224,37 @@ SCENARIO("A parked sliding sync run again does not apply its set_presence a seco } } +// MSC4186: "Servers MUST reject a `pos` that was not issued to the requesting user and device". A refused request does +// nothing else, so its set_presence opens no ADR-0872 window that would make a later PUT /presence 429. +SCENARIO("A sliding sync refused for an unknown pos changes no presence", "[integration][presence][sliding-sync]") +{ + GIVEN("a registered user with no presence row") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + auto const token = register_alice(runtime); + + WHEN("she sliding-syncs with a pos this server never issued, asking for unavailable") + { + auto const refused = call(runtime, "POST", std::string{sliding_sync_target} + "?pos=not-issued", token, + R"({"set_presence":"unavailable"})"); + + THEN("it is 400 M_UNKNOWN_POS, nothing is stored, and her presence may be set at once") + { + REQUIRE(refused.status == 400U); + auto const body = parse_object(refused.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_UNKNOWN_POS"); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + } + } + } +} + // ADR-0871: a device is one device whichever sync API it uses, so the hold one transport takes is released by the // other's set_presence=offline. SCENARIO("A device's hold taken through sliding sync is released by its classic sync", From dab1b10809342e4b75d223c6bfaab0b0706129ab Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 06:39:11 +0000 Subject: [PATCH 10/25] Apply sliding sync presence only for a current pos too sliding_sync_json also refuses with M_UNKNOWN_POS a pos from another stream epoch or ahead of the live watermarks (ADR-0592), after the dispatcher had applied set_presence. The check is now sliding_sync_token_is_current, which both ask, and the dispatcher applies presence only for a pos that passes it. The unknown-pos scenario gains a pos this server issued before a restore moved the stream epoch on. Co-Authored-By: Claude Opus 5.5 --- src/homeserver/ClientServerRuntime.cpp | 27 ++++++++++++++++++------ tests/integration/test_presence_flow.cpp | 24 +++++++++++++++++++-- 2 files changed, 42 insertions(+), 9 deletions(-) diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index 1a08a95de..c3b2a3288 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -8697,6 +8697,17 @@ namespace return false; } + // A token from this stream epoch and not ahead of the live watermarks (ADR-0592): the only kind a sliding sync + // serves. The dispatcher asks it too, before it applies `set_presence`, so a request this refuses changes nothing. + [[nodiscard]] auto sliding_sync_token_is_current(HomeserverRuntime const& runtime, + sync::StreamToken const& token) -> bool + { + auto const& store = runtime.database.persistent_store; + auto const event_watermark = visible_stream_position(runtime.database); + return token.epoch == store.stream_token_epoch && token.event_ordering <= event_watermark && + token.membership_ordering <= event_watermark && token.sync_stream_id <= store.next_sync_stream_id; + } + [[nodiscard]] auto sliding_sync_json(ClientServerRuntime& rt, std::string_view user, std::string_view device_id, sync::SlidingSyncRequest const& ssreq, std::optional const& request_pos, @@ -8739,8 +8750,7 @@ namespace { auto const event_watermark = visible_stream_position(rt.homeserver.database); auto const sync_watermark = store.next_sync_stream_id; - if (pos->epoch != store.stream_token_epoch || pos->event_ordering > event_watermark || - pos->membership_ordering > event_watermark || pos->sync_stream_id > sync_watermark) + if (!sliding_sync_token_is_current(rt.homeserver, *pos)) { // Drop the connection state: the client restarts with no pos // and must receive a full initial snapshot. @@ -22444,11 +22454,14 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp return dispatch_err(req, rt, 400U, "M_UNKNOWN_POS", "unknown sliding sync position"); } } - // ADR-0872: on the request's first run only, as for /sync, and only once `pos` is accepted, so a refused - // request changes no presence and opens no window. - if (auto const changed = dispatch_options.sync_rerun ? std::nullopt - : apply_sync_presence(rt.homeserver, *user, device_id_4186, - *sliding_presence_mode); + // ADR-0872: on the request's first run only, as for /sync, and only for a `pos` that is bound and current (the + // check `sliding_sync_json` refuses with M_UNKNOWN_POS), so a refused request changes no presence and opens no + // window. + auto const pos_is_current = !pos.has_value() || sliding_sync_token_is_current(rt.homeserver, pos->token); + if (auto const changed = + dispatch_options.sync_rerun || !pos_is_current + ? std::nullopt + : apply_sync_presence(rt.homeserver, *user, device_id_4186, *sliding_presence_mode); changed.has_value()) { log_diagnostic("presence.sync.set", { diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index e9de5d66c..ec59e4501 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1224,8 +1224,9 @@ SCENARIO("A parked sliding sync run again does not apply its set_presence a seco } } -// MSC4186: "Servers MUST reject a `pos` that was not issued to the requesting user and device". A refused request does -// nothing else, so its set_presence opens no ADR-0872 window that would make a later PUT /presence 429. +// MSC4186: "Servers MUST reject a `pos` that was not issued to the requesting user and device", and a pos from another +// stream epoch is unknown too (ADR-0592). A refused request does nothing else, so its set_presence opens no ADR-0872 +// window that would make a later PUT /presence 429. SCENARIO("A sliding sync refused for an unknown pos changes no presence", "[integration][presence][sliding-sync]") { GIVEN("a registered user with no presence row") @@ -1252,6 +1253,25 @@ SCENARIO("A sliding sync refused for an unknown pos changes no presence", "[inte REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); } } + + WHEN("she sliding-syncs with a pos this server issued before a restore moved the stream epoch on") + { + auto const pos = sliding_sync_pos(runtime, token); + runtime.homeserver.database.persistent_store.stream_token_epoch += 1U; + auto const refused = call(runtime, "POST", std::string{sliding_sync_target} + "?pos=" + pos, token, + R"({"set_presence":"unavailable"})"); + + THEN("it is 400 M_UNKNOWN_POS, nothing is stored, and her presence may be set at once") + { + REQUIRE(refused.status == 400U); + auto const body = parse_object(refused.body); + auto const* errcode = string_member(body, "errcode"); + REQUIRE(errcode != nullptr); + REQUIRE(*errcode == "M_UNKNOWN_POS"); + REQUIRE(alice_presence_state(runtime) == "none"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"online"})").status == 200U); + } + } } } From a594e5b1117b4b734ef4da44f4867b6ae546624e Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 07:11:12 +0000 Subject: [PATCH 11/25] Return the presence index's position without unwrapping it clang-tidy (bugprone-optional-value-conversion): presence_position dereferenced the index's std::optional only to wrap it again; it now returns the optional as found. Co-Authored-By: Claude Opus 5.5 --- src/database/PersistentStore.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/database/PersistentStore.cpp b/src/database/PersistentStore.cpp index 49996f501..34a500f37 100644 --- a/src/database/PersistentStore.cpp +++ b/src/database/PersistentStore.cpp @@ -8762,7 +8762,7 @@ namespace } if (*position < store.presence_states.size() && store.presence_states[*position].user_id == user_id) { - return *position; + return position; } } store.presence_rows_examined.add(store.presence_states.size()); From a8b70a2a719eb85dca8a662e3f846e3589f5e852 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 07:27:48 +0000 Subject: [PATCH 12/25] Never evict a presence hold for a device asking for unavailable - AccountPresenceTracker::note_sync answers false for a device asking for unavailable on an account the table does not hold, without taking a place: on a full table such a sync, even one that changed nothing, evicted another account's online hold. - ADR-0871 records that the hold runs on the steady clock and the idle sweep on the wall clock, so a wall-clock step moves them apart by the step (accepted: one limited change, never a loop); the static_assert comment no longer claims it closes that. - CHANGELOG cites ADR-0871 for the prune. - New unit scenario: a device asking for unavailable takes no place in the tracker, and on a full table evicts no hold. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 +- ...syncing-online-holds-its-account-online.md | 9 +++- src/homeserver/AccountPresenceTracker.cpp | 9 +++- src/homeserver/PresenceService.cpp | 3 +- tests/unit/test_account_presence_tracker.cpp | 44 +++++++++++++++++++ 5 files changed, 63 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6a22d79be..38da0e594 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -78,7 +78,7 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) * A sliding sync `pos` is bound to the user and device it was issued to; any other is `M_UNKNOWN_POS`, so one user can no longer continue another's connection (ADR-0866). * An account's presence changes at most once every 5 s (a later sync's change is dropped, `PUT /presence` is 429), so a - flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0872). + flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0871, ADR-0872). ## Bug fixes diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index 953e055f9..0af35c531 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -47,7 +47,14 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and window. Only when every account has an open window does a sync of an account the table does not hold have its device ignored and its change refused (ADR-0872), at most until the soonest window ends. * The asks are in memory only: after a restart each device's next sync puts its ask back. -* The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. +* The clock is the steady clock (`presence_limit_clock_ms`), which never goes back. The idle sweep measures activity on + the wall clock (`observed_at_ms`), so after a wall-clock step the hold and the sweep disagree by the step until the + device syncs again: after a backward step a background device's `unavailable` can win while the sweep still counts the + user active, and after a forward step the sweep can set the account unavailable while a hold stands. Accepted: either + is one change, limited by ADR-0872, never a loop. Judging the hold on the wall clock instead would let one clock step + lift or extend every hold at once, and the `static_assert` keeps only the two durations equal. +* An account the table does not hold takes no place for a device asking for `unavailable`, so such a sync never evicts + another account's hold. ### Positive Consequences diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 405887bbc..f131011e3 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -114,7 +114,14 @@ auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) -> bool { - auto const entry = account_for(user, now_ms); + // A device asking for unavailable holds nothing, so an account the table does not hold takes no place for it and + // never evicts another account's hold to make one. + auto const tracked = m_accounts.find(user); + if (tracked == m_accounts.end() && !online) + { + return false; + } + auto const entry = tracked != m_accounts.end() ? tracked : account_for(user, now_ms); if (entry == m_accounts.end()) { return online; diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 1bc7ca132..1cc371da7 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -35,7 +35,8 @@ namespace merovingian::homeserver // ADR-0871: a device's online ask goes stale exactly when the idle sweep would set its account unavailable. With the // two apart, a background device's `unavailable` would win while the sweep still counts the user active, or a closed -// client would hold the account online past the sweep. +// client would hold the account online past the sweep. This keeps the durations equal; the hold runs on the steady +// clock and the sweep on the wall clock, so a wall-clock step still moves them apart by the step (accepted in the ADR). static_assert(AccountPresenceTracker::device_fresh_ms == presence_idle_timeout_ms, "a device's online ask must last exactly as long as the idle timeout"); diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 8d0c9be44..ec7598ff3 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -310,3 +310,47 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", } } } + +SCENARIO("A device asking for unavailable takes no place in the tracker", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("an account the tracker does not hold") + { + auto tracker = AccountPresenceTracker{}; + + WHEN("its device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(bob, phone, false, start_ms); + + THEN("no device asks for online and the account is not held") + { + REQUIRE_FALSE(any_online); + REQUIRE(tracker.account_count() == 0U); + } + } + } + + GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") + { + auto tracker = AccountPresenceTracker{}; + std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) + { + std::ignore = + tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); + } + + WHEN("an account with no entry syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, phone, false, start_ms + 2); + + THEN("nothing is evicted: the account whose device goes stale soonest keeps its hold") + { + REQUIRE_FALSE(any_online); + REQUIRE(tracker.accounts_examined() == 0U); + REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); + } + } + } +} From c3342aa3351a6c27c13eb421e8de6eca2b236be8 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 07:43:56 +0000 Subject: [PATCH 13/25] State the presence tracker's fail-closed contracts - note_sync answers false when the table has no room for the account: nothing is recorded, so no device it holds asks for online. Its one caller reads the answer only for an unavailable ask, so nothing it does changes. - The header says note_sync records nothing for an account it does not hold when the ask is unavailable or the table is full, and that note_change does nothing for an account the table has no room for. - The full-table unit scenario expects false for an online sync of an account the table does not hold. Co-Authored-By: Claude Opus 5.5 --- include/merovingian/homeserver/AccountPresenceTracker.hpp | 8 ++++++-- src/homeserver/AccountPresenceTracker.cpp | 3 ++- tests/unit/test_account_presence_tracker.cpp | 4 ++-- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index bb8ea4bad..bd69b9d7c 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -50,7 +50,10 @@ class AccountPresenceTracker final static constexpr auto max_accounts = std::size_t{65'536U}; // Notes that `device` of `user` synced asking for `online` (true) or `unavailable` (false) at `now_ms`. True when a - // device of the account, this one included, asked for online within `device_fresh_ms`. + // device the table holds for the account, this one included, asked for online within `device_fresh_ms`. Records + // nothing and answers false for an account the table does not hold when the ask is `unavailable` (it needs no + // place) or when the table has no room for it (fails closed; room is made only by a prune or an eviction, and + // `is_full_for` tells the caller a change is refused). [[nodiscard]] auto note_sync(std::string_view user, std::string_view device, bool online, std::int64_t now_ms) -> bool; @@ -66,7 +69,8 @@ class AccountPresenceTracker final // open window), not because of the account's own window. [[nodiscard]] auto is_full_for(std::string_view user, std::int64_t now_ms) const -> bool; - // Starts the window of `user` at `now_ms`: a change was just kept. + // Starts the window of `user` at `now_ms`: a change was just kept. Does nothing for an account the table has no + // room for, which `change_blocked_for_ms` refused a change of first. auto note_change(std::string_view user, std::int64_t now_ms) -> void; // Removes every account whose online devices are all stale and whose window ended by `now_ms`. diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index f131011e3..f22995b14 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -124,7 +124,8 @@ auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view d auto const entry = tracked != m_accounts.end() ? tracked : account_for(user, now_ms); if (entry == m_accounts.end()) { - return online; + // No room (fails closed): nothing is recorded, so no device the table holds asks for anything. + return false; } auto& devices = entry->second.devices; // A stale device speaks for nothing; dropping it here keeps an account that keeps syncing from holding them. diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index ec7598ff3..93b3e1e51 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -220,9 +220,9 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco { auto const any_online = tracker.note_sync(alice, desktop, true, start_ms + 1); - THEN("its own ask is answered, as without the table") + THEN("nothing is recorded, so no device the table holds asks for online, and the table does not grow") { - REQUIRE(any_online); + REQUIRE_FALSE(any_online); REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); } } From 9f4ecd5b86a9b74a80a8596c6361e1095ec9df85 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 07:53:24 +0000 Subject: [PATCH 14/25] Say in ADR-0871 that a kept change still takes a place Only an unavailable ask takes no place in the presence tracker; a change that sync keeps opens a window (ADR-0872) and may evict a closed account like any kept change. The ADR no longer says such a sync never evicts a hold. Co-Authored-By: Claude Opus 5.5 --- .../0871-a-device-syncing-online-holds-its-account-online.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index 0af35c531..becdabf79 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -53,8 +53,9 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and user active, and after a forward step the sweep can set the account unavailable while a hold stands. Accepted: either is one change, limited by ADR-0872, never a loop. Judging the hold on the wall clock instead would let one clock step lift or extend every hold at once, and the `static_assert` keeps only the two durations equal. -* An account the table does not hold takes no place for a device asking for `unavailable`, so such a sync never evicts - another account's hold. +* An account the table does not hold takes no place for a device asking for `unavailable`: the ask alone never evicts + another account's hold. If that sync changes the stored state, the change still opens a window (ADR-0872) and may + evict a closed account to make room, as any kept change does. ### Positive Consequences From fcaa6f418038c1000a939505ca06a82e82524c7f Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 08:15:50 +0000 Subject: [PATCH 15/25] Let a test fill the presence tracker at a small account cap - AccountPresenceTracker takes an optional account cap (at least one; the default constructor keeps max_accounts, which the server uses), read through account_cap(). - The unit bound scenarios fill a tracker of 8 accounts instead of 65,536, so the file no longer builds about half a million accounts and its cost no longer follows the production constant. The integration scenario still fills the server's real table. - New unit scenario: the default cap is max_accounts, a given cap is kept, and a cap of zero holds one account. - src/homeserver/AGENTS.md says only a test makes a smaller tracker. Co-Authored-By: Claude Opus 5.5 --- .../homeserver/AccountPresenceTracker.hpp | 31 +++++++---- src/homeserver/AGENTS.md | 2 +- src/homeserver/AccountPresenceTracker.cpp | 16 ++++-- tests/unit/test_account_presence_tracker.cpp | 53 +++++++++++++------ 4 files changed, 72 insertions(+), 30 deletions(-) diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index bd69b9d7c..2f59feca3 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -28,15 +28,16 @@ namespace merovingian::homeserver // change asked for in the window is dropped (a sync) or refused with 429 (`PUT /presence`). The first one asked for is // the one kept, never the last. // -// Bounded: at most `max_accounts` accounts of `max_devices_per_account` devices each. A new device past the device cap -// replaces the account's least recently seen one. An account with an open window is filed under the window's end; any -// other under the time its last online device goes stale, and an account moves from the first to the second when its -// window ends. A prune removes only the accounts whose time has passed, never visiting the table. When the table is -// full after a prune, the account with no open window whose devices go stale soonest makes room: it loses only its -// devices' holds, never a window, so the limit holds. Only when every account has an open window is there no room: a -// newcomer's devices are ignored and its change refused until the soonest window ends (at most `change_window_ms`), so -// a flood of accounts cannot lift the limit for itself. Every operation does O(log n) work per account it moves or -// removes. Not thread-safe: `runtime.mutex` serialises every use (`HomeserverRuntime::presence_tracker`). +// Bounded: at most `max_accounts` accounts (the account cap, which a test may set lower) of `max_devices_per_account` +// devices each. A new device past the device cap replaces the account's least recently seen one. An account with an +// open window is filed under the window's end; any other under the time its last online device goes stale, and an +// account moves from the first to the second when its window ends. A prune removes only the accounts whose time has +// passed, never visiting the table. When the table is full after a prune, the account with no open window whose devices +// go stale soonest makes room: it loses only its devices' holds, never a window, so the limit holds. Only when every +// account has an open window is there no room: a newcomer's devices are ignored and its change refused until the +// soonest window ends (at most `change_window_ms`), so a flood of accounts cannot lift the limit for itself. Every +// operation does O(log n) work per account it moves or removes. Not thread-safe: `runtime.mutex` serialises every use +// (`HomeserverRuntime::presence_tracker`). class AccountPresenceTracker final { public: @@ -46,9 +47,15 @@ class AccountPresenceTracker final static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; // Far more devices than one person syncs from at once; each is a device ID and two integers. static constexpr auto max_devices_per_account = std::size_t{64U}; - // Accounts with a device that asked for online within the last five minutes, or a window open. + // Accounts with a device that asked for online within the last five minutes, or a window open: the account cap a + // tracker has unless it is made with another. static constexpr auto max_accounts = std::size_t{65'536U}; + AccountPresenceTracker() = default; + // A tracker holding at most `account_cap` accounts (at least one), so a test can fill the table without + // `max_accounts` of them. The server's tracker is made with the default. + explicit AccountPresenceTracker(std::size_t account_cap) noexcept; + // Notes that `device` of `user` synced asking for `online` (true) or `unavailable` (false) at `now_ms`. True when a // device the table holds for the account, this one included, asked for online within `device_fresh_ms`. Records // nothing and answers false for an account the table does not hold when the ask is `unavailable` (it needs no @@ -82,6 +89,9 @@ class AccountPresenceTracker final // Accounts a prune removed or a full table evicted since the table was made, for tests that prove the cost. [[nodiscard]] auto accounts_examined() const noexcept -> std::uint64_t; + // The most accounts the table holds. + [[nodiscard]] auto account_cap() const noexcept -> std::size_t; + private: struct Device final { @@ -130,6 +140,7 @@ class AccountPresenceTracker final // table evicts. std::set m_closed{}; std::uint64_t m_accounts_examined{0U}; + std::size_t m_account_cap{max_accounts}; }; } // namespace merovingian::homeserver diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 8b30b8312..1134b02e2 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,7 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | -| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts, an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts (`max_accounts`; a test makes a tracker with a smaller cap to fill it, never the server), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index f22995b14..93b25192a 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -34,6 +34,11 @@ namespace } // namespace +AccountPresenceTracker::AccountPresenceTracker(std::size_t account_cap) noexcept + : m_account_cap{std::max(account_cap, std::size_t{1U})} +{ +} + auto AccountPresenceTracker::refile(Accounts::iterator entry, std::int64_t now_ms) -> void { auto& account = entry->second; @@ -78,7 +83,7 @@ auto AccountPresenceTracker::close_ended_windows(std::int64_t now_ms) -> void auto AccountPresenceTracker::has_room(std::int64_t now_ms) const noexcept -> bool { - return m_accounts.size() < max_accounts || !m_closed.empty() || + return m_accounts.size() < m_account_cap || !m_closed.empty() || (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms); } @@ -88,11 +93,11 @@ auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now { return found; } - if (m_accounts.size() >= max_accounts) + if (m_accounts.size() >= m_account_cap) { prune(now_ms); } - if (m_accounts.size() >= max_accounts) + if (m_accounts.size() >= m_account_cap) { if (m_closed.empty()) { @@ -229,4 +234,9 @@ auto AccountPresenceTracker::accounts_examined() const noexcept -> std::uint64_t return m_accounts_examined; } +auto AccountPresenceTracker::account_cap() const noexcept -> std::size_t +{ + return m_account_cap; +} + } // namespace merovingian::homeserver diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 93b3e1e51..3df8cdc89 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -25,6 +25,9 @@ constexpr auto alice = std::string_view{"@alice:example.org"}; constexpr auto bob = std::string_view{"@bob:example.org"}; constexpr auto phone = std::string_view{"PHONE"}; constexpr auto desktop = std::string_view{"DESKTOP"}; +// The account cap of the trackers the bound scenarios fill: small, so a full table costs a handful of accounts. The cap +// is the same code at any size. +constexpr auto small_cap = std::size_t{8U}; } // namespace @@ -197,12 +200,12 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco GIVEN("a table holding as many accounts as the cap, each inside its window") { - auto tracker = AccountPresenceTracker{}; - for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_accounts; ++index) + auto tracker = AccountPresenceTracker{small_cap}; + for (auto index = std::size_t{0U}; index < small_cap; ++index) { tracker.note_change("@user" + std::to_string(index) + ":example.org", start_ms); } - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); WHEN("an account with no entry asks to change its presence") { @@ -212,7 +215,7 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco THEN("it is refused and the table does not grow: a flood of accounts cannot lift the limit") { REQUIRE(blocked.has_value()); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); } } @@ -223,7 +226,7 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco THEN("nothing is recorded, so no device the table holds asks for online, and the table does not grow") { REQUIRE_FALSE(any_online); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); } } @@ -240,9 +243,9 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") { - auto tracker = AccountPresenceTracker{}; + auto tracker = AccountPresenceTracker{small_cap}; std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); - for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) + for (auto index = std::size_t{1U}; index < small_cap; ++index) { std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); @@ -256,7 +259,7 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco THEN("it is allowed, and the account whose device goes stale soonest gives up its place") { REQUIRE_FALSE(blocked.has_value()); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); REQUIRE(tracker.accounts_examined() == 1U); REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 3).has_value()); REQUIRE_FALSE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); @@ -270,14 +273,14 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", { GIVEN("a full table in which one account's window ended as the others' began") { - auto tracker = AccountPresenceTracker{}; + auto tracker = AccountPresenceTracker{small_cap}; tracker.note_change("@early:example.org", start_ms); auto const later_ms = start_ms + AccountPresenceTracker::change_window_ms; - for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) + for (auto index = std::size_t{1U}; index < small_cap; ++index) { tracker.note_change("@user" + std::to_string(index) + ":example.org", later_ms); } - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); WHEN("an account with no entry asks to change its presence") { @@ -287,7 +290,7 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", THEN("it is allowed and takes the expired account's place, the one account a prune looked at") { REQUIRE_FALSE(blocked.has_value()); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); REQUIRE(tracker.accounts_examined() == 1U); REQUIRE(tracker.change_blocked_for_ms(alice, later_ms + 2).has_value()); } @@ -305,7 +308,7 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", THEN("no request looks at the table, since no account has expired") { REQUIRE(tracker.accounts_examined() == 1U); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); } } } @@ -332,9 +335,9 @@ SCENARIO("A device asking for unavailable takes no place in the tracker", GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") { - auto tracker = AccountPresenceTracker{}; + auto tracker = AccountPresenceTracker{small_cap}; std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); - for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_accounts; ++index) + for (auto index = std::size_t{1U}; index < small_cap; ++index) { std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); @@ -348,9 +351,27 @@ SCENARIO("A device asking for unavailable takes no place in the tracker", { REQUIRE_FALSE(any_online); REQUIRE(tracker.accounts_examined() == 0U); - REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.account_count() == small_cap); REQUIRE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); } } } } + +SCENARIO("A tracker holds max_accounts accounts unless it is made with another cap", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a tracker made as the server makes it, and two made with a cap") + { + auto const server = AccountPresenceTracker{}; + auto const small = AccountPresenceTracker{small_cap}; + auto const zero = AccountPresenceTracker{0U}; + + THEN("the server's holds max_accounts, the small one its cap, and a cap of zero holds one account") + { + REQUIRE(server.account_cap() == AccountPresenceTracker::max_accounts); + REQUIRE(small.account_cap() == small_cap); + REQUIRE(zero.account_cap() == 1U); + } + } +} From 3b81d9e63bb578765a0799f3bde27d8777066682 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 08:35:48 +0000 Subject: [PATCH 16/25] Describe both presence refusals, and where the full tracker is filled - PresenceWriteStatus::limited names the full-tracker refusal (PresenceWrite::tracker_full) as well as the account's own window. - src/homeserver/AGENTS.md says a unit test fills a small-cap tracker and only the integration scenario for the full table's 429 fills the server's, with windows dated ahead. Co-Authored-By: Claude Opus 5.5 --- include/merovingian/homeserver/PresenceWriteStatus.hpp | 4 +++- src/homeserver/AGENTS.md | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/include/merovingian/homeserver/PresenceWriteStatus.hpp b/include/merovingian/homeserver/PresenceWriteStatus.hpp index 9fadb1fde..440d46d04 100644 --- a/include/merovingian/homeserver/PresenceWriteStatus.hpp +++ b/include/merovingian/homeserver/PresenceWriteStatus.hpp @@ -12,7 +12,9 @@ enum class PresenceWriteStatus : std::uint8_t { // Stored and sent, or accepted and dropped because presence is off. stored, - // Not stored: the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago (ADR-0872). + // Not stored: refused by `AccountPresenceTracker` (ADR-0872). The account's presence changed less than + // `AccountPresenceTracker::change_window_ms` ago, or, when `PresenceWrite::tracker_full` is set, the table had no + // room for the account, whose presence need not have changed at all. limited, // The store refused the row. failed, diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 1134b02e2..bab406583 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,7 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | -| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts (`max_accounts`; a test makes a tracker with a smaller cap to fill it, never the server), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts (`max_accounts`; a unit test makes a tracker with a smaller cap to fill it, and only the integration scenario that proves the full table's 429 fills the server's tracker, once per case, with windows dated ahead), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | From 40163feb85b7a78b863c3eca0491f41a6574841b Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:10:33 +0000 Subject: [PATCH 17/25] Log a device_online drop only when it would have changed the stored state A sync asking for unavailable from an account already stored as unavailable lost nothing, yet logged presence.change.limited on every background-device sync for up to five minutes. Co-Authored-By: Claude Opus 5.5 --- docs/observability-audit.md | 4 ++-- src/homeserver/PresenceService.cpp | 17 +++++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 0e21f9641..e8534b3e2 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -137,8 +137,8 @@ is full. logger `client_server`) records a `/sync` that changed the caller's state (fields `actor`, `presence`). `presence.change.limited` (debug, logger `presence`) records a `/sync` change dropped for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`), and a `/sync` asking for - `unavailable` while another device of the account holds it online (`cause` `device_online`, no `retry_after_ms`; - ADR-0871). + `unavailable` while another device of the account holds it online and the account is not already `unavailable` + (`cause` `device_online`, no `retry_after_ms`; ADR-0871). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 1cc371da7..70efca27a 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -342,12 +342,17 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: if (!asks_online && any_device_online) { // ADR-0871: another device of the account asked for online in the freshness time; online beats unavailable. - log_presence("presence.change.limited", { - {"actor", std::string{user}, false}, - {"device_id", std::string{device}, false}, - {"presence", "unavailable", false}, - {"cause", "device_online", false} - }); + // Logged only when the ask would have changed the stored state: an account already unavailable loses nothing. + if (auto const* const row = database::find_presence_state(runtime.database.persistent_store, user); + row == nullptr || row->presence != "unavailable") + { + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", "unavailable", false}, + {"cause", "device_online", false} + }); + } return std::nullopt; } auto& store = runtime.database.persistent_store; From 7ee56ce40ec6acc44db447a1083585680b27befe Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:34:19 +0000 Subject: [PATCH 18/25] Warn when a full presence tracker refuses changes, and test a no-op sync A change refused because the presence tracker is full was logged only at debug, so an operator could not see the table saturate. It is now counted, and presence.tracker.full is logged at warning level at most once a minute with the number refused since the last one and no user IDs. A new scenario proves a /sync that leaves the stored presence as it is opens no change window, for both online and unavailable. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 2 + ...-change-in-a-five-second-window-is-kept.md | 5 +- docs/observability-audit.md | 3 ++ .../homeserver/AccountPresenceTracker.hpp | 15 ++++++ .../homeserver/PresenceService.hpp | 5 ++ src/homeserver/AGENTS.md | 4 +- src/homeserver/AccountPresenceTracker.cpp | 18 +++++++ src/homeserver/ClientServerRuntime.cpp | 8 ++- src/homeserver/PresenceService.cpp | 23 +++++++- tests/integration/test_presence_flow.cpp | 53 +++++++++++++++++++ tests/unit/test_account_presence_tracker.cpp | 30 +++++++++++ 11 files changed, 161 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 38da0e594..c7011e0e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,6 +79,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) no longer continue another's connection (ADR-0866). * An account's presence changes at most once every 5 s (a later sync's change is dropped, `PUT /presence` is 429), so a flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0871, ADR-0872). +* Presence changes refused because the presence tracker is full are logged at warning level as `presence.tracker.full`, + at most once a minute and with the number refused, so an operator sees the table saturate (ADR-0872). ## Bug fixes diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md index 4dd66305a..401644d9c 100644 --- a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -45,7 +45,10 @@ Chosen option: 1. shut others out. Only when every account in it has an open window is a change of an account it does not hold refused (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. The refusal's `retry_after_ms` is the rest of the soonest window (at most `change_window_ms`), and its log line's `cause` - is `tracker_full`, not `window`. + is `tracker_full`, not `window`. Such a refusal also counts towards `presence.tracker.full`, a warning logged at + most once a minute (`full_warning_interval_ms`) with the number refused since the last one and no user IDs: a user + who did nothing wrong is refused only here, so an operator must see it without debug logging, and one warning per + refusal would let the flood that fills the table flood the log too. * A dropped change is never kept later: a parked `/sync` or sliding sync is run again after a wake-up or its timeout (`rerun_waiting_sync`, `ClientServerDispatchOptions::sync_rerun`), and that rerun does not apply its `set_presence` again, so a change dropped in the window is not stored once the window has ended. diff --git a/docs/observability-audit.md b/docs/observability-audit.md index e8534b3e2..411344352 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -139,6 +139,9 @@ is full. for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`), and a `/sync` asking for `unavailable` while another device of the account holds it online and the account is not already `unavailable` (`cause` `device_online`, no `retry_after_ms`; ADR-0871). + `presence.tracker.full` (warning, logger `presence`) fires when a change is refused because the presence tracker + has no room (`cause` `tracker_full` above), at most once a minute, with the number refused since the last warning + (fields `refused`, `accounts`, `limit`; never a user ID; ADR-0872). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index 2f59feca3..e68d83dc6 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -50,6 +50,9 @@ class AccountPresenceTracker final // Accounts with a device that asked for online within the last five minutes, or a window open: the account cap a // tracker has unless it is made with another. static constexpr auto max_accounts = std::size_t{65'536U}; + // At most one warning that the table is full in this time, so a flood of refused changes costs one warning a + // minute, which counts what it stands for. + static constexpr auto full_warning_interval_ms = std::int64_t{60'000}; AccountPresenceTracker() = default; // A tracker holding at most `account_cap` accounts (at least one), so a test can fill the table without @@ -92,6 +95,14 @@ class AccountPresenceTracker final // The most accounts the table holds. [[nodiscard]] auto account_cap() const noexcept -> std::size_t; + // Counts a change refused at `now_ms` because the table is full (`is_full_for`). When a warning is due (the first + // refusal, or the first at least `full_warning_interval_ms` after the last warning), the number refused since the + // last warning, this one included; otherwise nullopt. + [[nodiscard]] auto note_full_refusal(std::int64_t now_ms) -> std::optional; + + // Changes refused because the table was full, since the table was made. + [[nodiscard]] auto full_refusals() const noexcept -> std::uint64_t; + private: struct Device final { @@ -141,6 +152,10 @@ class AccountPresenceTracker final std::set m_closed{}; std::uint64_t m_accounts_examined{0U}; std::size_t m_account_cap{max_accounts}; + std::uint64_t m_full_refusals{0U}; + // `m_full_refusals` when the last warning was due, and when that was. + std::uint64_t m_full_refusals_warned{0U}; + std::optional m_full_warned_at_ms{}; }; } // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/PresenceService.hpp b/include/merovingian/homeserver/PresenceService.hpp index 857941af8..66a2a895b 100644 --- a/include/merovingian/homeserver/PresenceService.hpp +++ b/include/merovingian/homeserver/PresenceService.hpp @@ -65,6 +65,11 @@ inline constexpr auto presence_idle_catch_up_interval = std::chrono::seconds{1}; // back, plus `test_presence_clock_advance_ms`. Not a point in calendar time. [[nodiscard]] auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t; +// A change of presence refused at `clock_ms` because the presence tracker is full: counts it and, at most once every +// `AccountPresenceTracker::full_warning_interval_ms`, logs `presence.tracker.full` at warning level with the number +// refused since the last one (ADR-0872). The caller holds `runtime.mutex`. +auto note_presence_tracker_full(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void; + // "The last active time must be up to date whenever the server gives a presence event to the // client": the stored value plus the time since it was true. Never negative. [[nodiscard]] auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index bab406583..47c13dedc 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -1388,7 +1388,9 @@ without that check ignores `presence.enabled=false`. Rules: with the write, and keep the first change, never the last. The idle sweep and the profile propagation are not limited. A new path that changes a local user's presence state is limited the same way. A parked poll's rerun (`ClientServerDispatchOptions::sync_rerun`) never applies `set_presence` again, or a dropped change would be kept - once the window ends. Tests move the clock with `test_presence_clock_advance_ms`, never with a sleep. + once the window ends. Tests move the clock with `test_presence_clock_advance_ms`, never with a sleep. A change + refused because the tracker is full (`is_full_for`) calls `note_presence_tracker_full`, which counts it and logs the + rate-limited `presence.tracker.full` warning; a new refusal site does too. - A classic `/sync` whose only news is the caller's own presence row waits on (`only_own_presence_since`, ADR-0873): never wake a poll for what its response does not send. - `accept_inbound_presence` binds `user_id` to the sending origin, bounds the entries it looks at, and keeps diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 93b25192a..9394bae13 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -239,4 +239,22 @@ auto AccountPresenceTracker::account_cap() const noexcept -> std::size_t return m_account_cap; } +auto AccountPresenceTracker::note_full_refusal(std::int64_t now_ms) -> std::optional +{ + ++m_full_refusals; + if (m_full_warned_at_ms.has_value() && now_ms - m_full_warned_at_ms.value() < full_warning_interval_ms) + { + return std::nullopt; + } + auto const since_last_warning = m_full_refusals - m_full_refusals_warned; + m_full_refusals_warned = m_full_refusals; + m_full_warned_at_ms = now_ms; + return since_last_warning; +} + +auto AccountPresenceTracker::full_refusals() const noexcept -> std::uint64_t +{ + return m_full_refusals; +} + } // namespace merovingian::homeserver diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index c3b2a3288..fa28a8d33 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -25427,8 +25427,12 @@ auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence con { // The account's own window, or a full table's soonest one: never longer than the window. auto const retry_after_ms = std::clamp(*blocked, 1, AccountPresenceTracker::change_window_ms); - return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), - tracker.is_full_for(state.user_id, clock_ms)}; + auto const tracker_full = tracker.is_full_for(state.user_id, clock_ms); + if (tracker_full) + { + note_presence_tracker_full(runtime.homeserver, clock_ms); + } + return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), tracker_full}; } if (!record_presence(runtime.homeserver, state)) { diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 70efca27a..19af81657 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -150,6 +150,22 @@ auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t return static_cast(steady_ms) + runtime.test_presence_clock_advance_ms; } +auto note_presence_tracker_full(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void +{ + auto& tracker = runtime.presence_tracker; + if (auto const refused = tracker.note_full_refusal(clock_ms); refused.has_value()) + { + // Aggregate only: the operator learns the tracker saturated, never which accounts were refused. + log_presence("presence.tracker.full", + { + {"refused", std::to_string(*refused), false}, + {"accounts", std::to_string(tracker.account_count()), false}, + {"limit", std::to_string(tracker.account_cap()), false} + }, + observability::LogEventSeverity::warning); + } +} + auto presence_last_active_ago(database::PersistentPresence const& row, std::int64_t now_ms) noexcept -> std::int64_t { auto ago = std::max(row.last_active_ago, std::int64_t{0}); @@ -374,7 +390,12 @@ auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std: { // ADR-0872: the first change in the window was kept, or the tracker has no room for the account; this one is // dropped, not kept for later. - auto const cause = std::string{tracker.is_full_for(user, clock_ms) ? "tracker_full" : "window"}; + auto const tracker_full = tracker.is_full_for(user, clock_ms); + if (tracker_full) + { + note_presence_tracker_full(runtime, clock_ms); + } + auto const cause = std::string{tracker_full ? "tracker_full" : "window"}; log_presence("presence.change.limited", { {"actor", std::string{user}, false}, {"device_id", std::string{device}, false}, diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index ec59e4501..ea3048ceb 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1123,6 +1123,57 @@ SCENARIO("Only the first presence change in a window is kept", "[integration][pr } } +// ADR-0872: a sync that leaves the stored presence as it is changes nothing, so it opens no window. Without this, a +// client polling /sync (an omitted set_presence asks for online) could never change its presence: every poll would +// open a window, and PUT /presence would answer 429. +SCENARIO("A sync that leaves the presence as it is opens no change window", "[integration][presence][rate_limit]") +{ + GIVEN("alice shares a room with bob on another server and her change to online has had its window end") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + sync_once(runtime, token, "online"); + let_presence_window_end(runtime); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + + WHEN("she syncs online again, which changes nothing, and at once sets her presence unavailable") + { + sync_once(runtime, token, "online"); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("the change is kept and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 2U); + } + } + + WHEN("she is set unavailable, the window ends, she syncs unavailable, and at once sets her presence online") + { + // Offline forgets the device's online ask, so the unavailable sync below is judged on the stored state + // alone. + sync_once(runtime, token, "offline"); + REQUIRE(put_alice_presence(runtime, token, R"({"presence":"unavailable"})").status == 200U); + let_presence_window_end(runtime); + sync_once(runtime, token, "unavailable"); + auto const put = put_alice_presence(runtime, token, R"({"presence":"online"})"); + + THEN("the unavailable sync changed nothing, so the change is kept and sent") + { + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "online"); + REQUIRE(queued_presence_edus(runtime).size() == 3U); + } + } + } +} + // ADR-0872: a change dropped in a window is dropped, never kept for later. A long-polling sync whose change was // dropped is run again after a wake-up or its timeout (`rerun_waiting_sync`); that rerun is the same request and does // not apply its `set_presence` again, even once the window has ended. @@ -1359,6 +1410,7 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in REQUIRE(alice_presence_state(runtime) == "none"); REQUIRE(store.next_sync_stream_id == watermark); REQUIRE(queued_presence_edus(runtime).empty()); + REQUIRE(tracker.full_refusals() == 1U); } } @@ -1371,6 +1423,7 @@ SCENARIO("A presence change is refused while the presence tracker is full", "[in REQUIRE(alice_presence_state(runtime) == "none"); REQUIRE(queued_presence_edus(runtime).empty()); REQUIRE(tracker.account_count() == AccountPresenceTracker::max_accounts); + REQUIRE(tracker.full_refusals() == 1U); } } } diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 3df8cdc89..f798d462a 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -375,3 +375,33 @@ SCENARIO("A tracker holds max_accounts accounts unless it is made with another c } } } + +// ADR-0872: a change refused because the table is full is counted, and a warning is due at most once every +// full_warning_interval_ms, carrying how many it stands for, so a flood of refusals costs one warning a minute. +SCENARIO("Changes refused by a full tracker are counted and warned about at most once an interval", + "[unit][presence][account_presence_tracker][bounds]") +{ + GIVEN("a tracker that has refused nothing") + { + auto tracker = AccountPresenceTracker{small_cap}; + REQUIRE(tracker.full_refusals() == 0U); + + WHEN("it refuses one change, two more within the interval, and one once the interval has passed") + { + auto const first = tracker.note_full_refusal(start_ms); + auto const second = tracker.note_full_refusal(start_ms + 1); + auto const third = + tracker.note_full_refusal(start_ms + AccountPresenceTracker::full_warning_interval_ms - 1); + auto const fourth = tracker.note_full_refusal(start_ms + AccountPresenceTracker::full_warning_interval_ms); + + THEN("the first and the fourth are due a warning, the fourth standing for the three since the first") + { + REQUIRE(first == std::optional{1U}); + REQUIRE_FALSE(second.has_value()); + REQUIRE_FALSE(third.has_value()); + REQUIRE(fourth == std::optional{3U}); + REQUIRE(tracker.full_refusals() == 4U); + } + } + } +} From 0e11dc48a71b360a3d776d93ade352362ff29225 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:43:46 +0000 Subject: [PATCH 19/25] Name the full-tracker refusal wherever the presence 429 is described The Client-Server API table, the user manual, and the set_presence and apply_sync_presence contracts said a presence 429 or dropped change meant only that the account changed in the last 5 s. A full presence tracker refuses an account that has not changed at all, and they now say so. Co-Authored-By: Claude Opus 5.5 --- docs/matrix-v1.19-client-server-api.md | 2 +- docs/user-manual.md | 8 +++++--- include/merovingian/homeserver/ClientServerRuntime.hpp | 5 +++-- include/merovingian/homeserver/PresenceService.hpp | 3 ++- 4 files changed, 11 insertions(+), 7 deletions(-) diff --git a/docs/matrix-v1.19-client-server-api.md b/docs/matrix-v1.19-client-server-api.md index 30ffed44a..06893a63b 100644 --- a/docs/matrix-v1.19-client-server-api.md +++ b/docs/matrix-v1.19-client-server-api.md @@ -181,7 +181,7 @@ comparison (ADR-0631); any other `from` is `400 M_INVALID_PARAM`. | `GET` | `/_matrix/client/v3/presence/{userId}/status` | `getPresence` | access token | - | 200, 403, 404 | | `PUT` | `/_matrix/client/v3/presence/{userId}/status` | `setPresence` | access token | required application/json | 200, 429 | -`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. A device that synced `online` in the last 5 minutes holds the account online against another syncing `unavailable` (ADR-0871). An account's presence changes at most once in 5 s: a later `/sync` change in the window is dropped and a `PUT` is 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` (ADR-0872). A `/sync` long-poll whose only news is the caller's own presence keeps waiting (ADR-0873). `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". +`GET` answers the caller's own presence, or another user's when they share a joined room (otherwise 403 `M_FORBIDDEN`, also for a user who does not exist); a local user with no presence is `offline`, a remote one is 404. `GET /sync` takes `set_presence` (`online` when omitted, `unavailable`, `offline`; another value is 400 `M_INVALID_PARAM`) and carries `presence.events` for users sharing a joined room. A device that synced `online` in the last 5 minutes holds the account online against another syncing `unavailable` (ADR-0871). An account's presence changes at most once in 5 s: a later `/sync` change in the window is dropped and a `PUT` is 429 `M_LIMIT_EXCEEDED` with `retry_after_ms` (ADR-0872). The same 429 (error `too many accounts are changing presence`) and dropped `/sync` change also come, for an account that has not changed at all, when every account in the server's presence tracker has a window open; `retry_after_ms` is then the soonest window's end, and the server logs `presence.tracker.full`. A `/sync` long-poll whose only news is the caller's own presence keeps waiting (ADR-0873). `presence.enabled=false` makes `GET` 404, `PUT` a 200 that stores nothing, and `/sync` presence-free. See `docs/user-manual.md` "Presence". ## Push notifications diff --git a/docs/user-manual.md b/docs/user-manual.md index f043bb32b..1e3e32304 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1213,9 +1213,11 @@ the users who share a room with them in `/sync` (`presence.events`) and by is. A device that synced online in the last 5 minutes keeps the user online while another of their devices syncs `unavailable`; a sync from that device with `set_presence=offline` ends its hold at once. A user's presence changes at most once every 5 seconds: a later change by `/sync` in that time is ignored, and `PUT /presence` answers `429` with -`retry_after_ms`. The server's own idle change (an online user inactive for 5 minutes becomes `unavailable`) is not -limited and does not start those 5 seconds. Presence reaches only users who share a joined -room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. +`retry_after_ms`. While as many accounts as the server tracks (65,536) have all changed in the last 5 seconds, a change +by any other account is refused the same way (`too many accounts are changing presence`) until the soonest of those +5 seconds ends, and the server logs the warning `presence.tracker.full` at most once a minute. The server's own idle +change (an online user inactive for 5 minutes becomes `unavailable`) is not limited and does not start those 5 seconds. +Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. | Key | Default | When to change | |---|---|---| diff --git a/include/merovingian/homeserver/ClientServerRuntime.hpp b/include/merovingian/homeserver/ClientServerRuntime.hpp index f39647135..dc67551a7 100644 --- a/include/merovingian/homeserver/ClientServerRuntime.hpp +++ b/include/merovingian/homeserver/ClientServerRuntime.hpp @@ -141,8 +141,9 @@ auto install_test_per_user_rate_limit_engine(ClientServerRuntime& runtime) -> vo [[nodiscard]] auto record_device_list_change(ClientServerRuntime& runtime, database::PersistentDeviceListChange change) -> bool; // Stores a presence the user set (`PUT /presence`), wakes syncs and tells the servers that share a room with them. -// `limited` when the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago (ADR-0872): -// nothing is stored. Takes runtime.mutex. +// `limited` when the account's presence changed less than `AccountPresenceTracker::change_window_ms` ago, or, with +// `PresenceWrite::tracker_full`, when the tracker has no room for the account (ADR-0872): nothing is stored. +// Takes runtime.mutex. [[nodiscard]] auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence const& state) -> PresenceWrite; // One pass of the "presence-idle" job (CS API "Presence", "Idle timeout"; ADR-0492): every local user whose diff --git a/include/merovingian/homeserver/PresenceService.hpp b/include/merovingian/homeserver/PresenceService.hpp index 66a2a895b..270d1dc9a 100644 --- a/include/merovingian/homeserver/PresenceService.hpp +++ b/include/merovingian/homeserver/PresenceService.hpp @@ -130,7 +130,8 @@ auto note_local_message_activity(HomeserverRuntime& runtime, std::string_view us // * `offline` stores nothing and the device no longer holds the account online; // * `unavailable` changes nothing while another device of the account asked for `online` within // `AccountPresenceTracker::device_fresh_ms` (ADR-0871); -// * a change within `AccountPresenceTracker::change_window_ms` of the account's last one is dropped (ADR-0872). +// * a change within `AccountPresenceTracker::change_window_ms` of the account's last one is dropped, and so is a +// change of an account the tracker has no room for (`is_full_for`, ADR-0872). // The caller holds runtime.mutex. Returns the new row when the state changed, so the caller can send it to other // servers and wake long-polling syncs. [[nodiscard]] auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, From bccc3061e6cd8660151937e727c8a832e3c41cc0 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 09:44:02 +0000 Subject: [PATCH 20/25] Wrap the user manual's presence paragraph Co-Authored-By: Claude Opus 5.5 --- docs/user-manual.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/user-manual.md b/docs/user-manual.md index 1e3e32304..ce1f4daf8 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1217,7 +1217,8 @@ most once every 5 seconds: a later change by `/sync` in that time is ignored, an by any other account is refused the same way (`too many accounts are changing presence`) until the soonest of those 5 seconds ends, and the server logs the warning `presence.tracker.full` at most once a minute. The server's own idle change (an online user inactive for 5 minutes becomes `unavailable`) is not limited and does not start those 5 seconds. -Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. +Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as +for a user who does not exist. | Key | Default | When to change | |---|---|---| From a6d93ce43b82f1a191288c27498c44f93d7701d0 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 10:27:09 +0000 Subject: [PATCH 21/25] Count a prune's re-filed accounts, and pin a refused /sync to no presence accounts_examined() counted only the accounts a prune removed or a full table evicted, so a prune that closed windows not yet ended would pass the cost tests. It now counts each account close_ended_windows visits. Every refusal of a classic /sync already comes before its set_presence is applied (sync_json serves any since and filter it is given); a comment at the call and a new scenario keep it so. Co-Authored-By: Claude Opus 5.5 --- .../homeserver/AccountPresenceTracker.hpp | 3 +- src/homeserver/AGENTS.md | 2 +- src/homeserver/AccountPresenceTracker.cpp | 4 ++- src/homeserver/ClientServerRuntime.cpp | 4 ++- tests/integration/test_presence_flow.cpp | 33 +++++++++++++++++++ tests/unit/test_account_presence_tracker.cpp | 7 ++-- 6 files changed, 46 insertions(+), 7 deletions(-) diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index e68d83dc6..facde75cc 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -89,7 +89,8 @@ class AccountPresenceTracker final // Accounts held, ones a prune would remove included. [[nodiscard]] auto account_count() const noexcept -> std::size_t; - // Accounts a prune removed or a full table evicted since the table was made, for tests that prove the cost. + // Accounts a prune re-filed when their window ended or removed, or a full table evicted, since the table was made, + // for tests that prove the cost. [[nodiscard]] auto accounts_examined() const noexcept -> std::uint64_t; // The most accounts the table holds. diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 47c13dedc..214166ac7 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -42,7 +42,7 @@ This is the largest and most complex module — read this file carefully before | `OAuthClock.cpp` | `oauth_wall_clock_ms`: the wall-clock milliseconds every OAuth store and handler passes; `oauth_device_clock_ms`, the same plus `HomeserverRuntime::test_device_grant_clock_advance_ms`, which the device grant's stores are given | | `OAuthDeviceAuthorization.cpp` | `POST /_merovingian/oauth2/device` (`handle_oauth_device_authorization`): the device grant's codes (ADR-0804) | | `DeviceAuthorisationStore.cpp` | `DeviceAuthorisationStore` (`HomeserverRuntime::oauth_device_authorisations`): device authorisations, 10 minutes, under the hash of the device code with an index by the hash of the user code; 4096 in all and 8 per client address, never evicting a live entry; one browser attached at a time (ADR-0805, ADR-0806). Guarded by `runtime.mutex` | -| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts (`max_accounts`; a unit test makes a tracker with a smaller cap to fill it, and only the integration scenario that proves the full table's 429 fills the server's tracker, once per case, with windows dated ahead), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts both); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | +| `AccountPresenceTracker.cpp` | `AccountPresenceTracker` (`HomeserverRuntime::presence_tracker`): each local account's devices' last `set_presence` ask (an `online` one holds the account online for 5 minutes, ADR-0871) and the 5 s window after a presence change (ADR-0872); 64 devices per account, 65,536 accounts (`max_accounts`; a unit test makes a tracker with a smaller cap to fill it, and only the integration scenario that proves the full table's 429 fills the server's tracker, once per case, with windows dated ahead), an account with an open window filed under its end and any other under its devices' staleness, so a prune visits only expired accounts and a full table evicts the closed account that goes stale soonest (`accounts_examined()` counts every account a prune re-files or removes, and every eviction); it fails closed only while every account has an open window, and never evicts one. Guarded by `runtime.mutex` | | `UserCodeAttemptThrottle.cpp` | `UserCodeAttemptThrottle` (`HomeserverRuntime::oauth_user_code_attempts`): five wrong user codes per client address key in ten minutes, 8192 windows, failing closed at the cap (ADR-0805). Guarded by `runtime.mutex` | | `AccountPage.cpp` | `GET` and `POST /_merovingian/account` (`handle_account_page`): the account pages' sign-in, overview, devices, device sign-out, password change, deactivation and cross-signing reset approval (ADR-0796 to ADR-0798) | | `AccountSessionStore.cpp` | `AccountSessionStore` (`HomeserverRuntime::account_sessions`): account-page sessions, 15 minutes fixed, hashed secret, 4096 in all and 4 per user (the user's oldest goes), and the session's form token (ADR-0796). Guarded by `runtime.mutex` | diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 9394bae13..54877cbc9 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -70,7 +70,9 @@ auto AccountPresenceTracker::close_ended_windows(std::int64_t now_ms) -> void { while (!m_open_windows.empty() && m_open_windows.begin()->first <= now_ms) { - // Refiling erases this front entry, so the loop always moves on. + // Refiling erases this front entry, so the loop always moves on. Each visit counts, so a prune that closed + // windows not yet ended would show in `accounts_examined`. + ++m_accounts_examined; auto const ended = m_accounts.find(m_open_windows.begin()->second); if (ended == m_accounts.end()) { diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index fa28a8d33..e0b4dd188 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -22362,7 +22362,9 @@ static auto handle_client_server_request_impl(ClientServerRuntime& rt, LocalHttp "set_presence must be online, offline or unavailable"); } // ADR-0872: applied on the request's first run only. A rerun of a parked poll is the same request, and a - // change the window dropped stays dropped, never kept once the window has ended. + // change the window dropped stays dropped, never kept once the window has ended. Every refusal of a /sync is + // above this line: `sync_json` serves any `since` (one it cannot use as no `since`, ADR-0315) and filter it is + // given, so a refused request never changes presence. Keep any new refusal above it. if (auto const changed = dispatch_options.sync_rerun ? std::nullopt : apply_sync_presence(rt.homeserver, *user, device_id, *presence_mode); diff --git a/tests/integration/test_presence_flow.cpp b/tests/integration/test_presence_flow.cpp index ea3048ceb..36f877e90 100644 --- a/tests/integration/test_presence_flow.cpp +++ b/tests/integration/test_presence_flow.cpp @@ -1174,6 +1174,39 @@ SCENARIO("A sync that leaves the presence as it is opens no change window", "[in } } +// A /sync refused with a 400 changes no presence, as a refused sliding sync does not (ADR-0872): the refusal would +// otherwise store a change, send it to every server in the user's rooms and open the window against the user's next +// real change. Every refusal of a /sync comes before its `set_presence` is applied. +SCENARIO("A /sync refused for its filter changes no presence", "[integration][presence][sync]") +{ + GIVEN("alice shares a room with bob on another server and has never set her presence") + { + REQUIRE(sodium_init() >= 0); + auto started = merovingian::homeserver::start_client_server(presence_config()); + REQUIRE(started.started); + auto& runtime = started.runtime; + install_unstarted_dispatch_worker(runtime); + auto const token = register_alice(runtime); + share_room_with_remote_bob(runtime); + + WHEN("she syncs online with an inline filter that is not JSON and with a filter ID she never stored") + { + auto const not_json = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&filter=%7Bnot", token); + auto const unknown = call(runtime, "GET", "/_matrix/client/v3/sync?timeout=0&filter=unknown", token); + auto const put = put_alice_presence(runtime, token, R"({"presence":"unavailable"})"); + + THEN("both are refused, nothing was stored or sent, and no window stops her next change") + { + REQUIRE(not_json.status == 400U); + REQUIRE(unknown.status == 400U); + REQUIRE(put.status == 200U); + REQUIRE(alice_presence_state(runtime) == "unavailable"); + REQUIRE(queued_presence_edus(runtime).size() == 1U); + } + } + } +} + // ADR-0872: a change dropped in a window is dropped, never kept for later. A long-polling sync whose change was // dropped is run again after a wake-up or its timeout (`rerun_waiting_sync`); that rerun is the same request and does // not apply its `set_presence` again, even once the window has ended. diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index f798d462a..51f4741c8 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -287,11 +287,12 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", auto const blocked = tracker.change_blocked_for_ms(alice, later_ms + 1); tracker.note_change(alice, later_ms + 1); - THEN("it is allowed and takes the expired account's place, the one account a prune looked at") + THEN("it is allowed and takes the expired account's place: a prune re-filed that one account as its window " + "ended, then removed it, and looked at no other") { REQUIRE_FALSE(blocked.has_value()); REQUIRE(tracker.account_count() == small_cap); - REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.accounts_examined() == 2U); REQUIRE(tracker.change_blocked_for_ms(alice, later_ms + 2).has_value()); } } @@ -307,7 +308,7 @@ SCENARIO("A prune of a full table looks only at the accounts that have expired", THEN("no request looks at the table, since no account has expired") { - REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.accounts_examined() == 2U); REQUIRE(tracker.account_count() == small_cap); } } From 6b871e4349b54564e2f9f5988f13ad66b459a5a5 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 11:00:41 +0000 Subject: [PATCH 22/25] Report a full presence tracker's evictions, and share the full-table fixture A full tracker evicted an account's device holds with nothing logged, though at the cap that is the usual case rather than a refusal. The tracker now counts evictions as well as refusals, and take_saturation_report hands both out at most once a minute. Each path that uses the tracker asks for it once when done (apply_sync_presence after judge_sync_presence, and set_presence), so presence.tracker.full carries refused and evicted counts. The two unit scenarios that built the same eight-account table now share fill_held_online. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +- ...-change-in-a-five-second-window-is-kept.md | 10 +- docs/observability-audit.md | 7 +- docs/user-manual.md | 4 +- .../homeserver/AccountPresenceTracker.hpp | 37 +++- .../homeserver/PresenceService.hpp | 9 +- src/homeserver/AGENTS.md | 5 +- src/homeserver/AccountPresenceTracker.cpp | 30 +++- src/homeserver/ClientServerRuntime.cpp | 5 +- src/homeserver/PresenceService.cpp | 167 ++++++++++-------- tests/unit/test_account_presence_tracker.cpp | 71 +++++--- 11 files changed, 214 insertions(+), 135 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c7011e0e6..04fda8dfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,8 +79,8 @@ Changes before 1.0.0 are in [CHANGELOG-pre-release.md](CHANGELOG-pre-release.md) no longer continue another's connection (ADR-0866). * An account's presence changes at most once every 5 s (a later sync's change is dropped, `PUT /presence` is 429), so a flip loop no longer fills the federation queue; a prune visits only expired accounts (ADR-0871, ADR-0872). -* Presence changes refused because the presence tracker is full are logged at warning level as `presence.tracker.full`, - at most once a minute and with the number refused, so an operator sees the table saturate (ADR-0872). +* A full presence tracker's refused changes and evicted accounts are logged at warning level as + `presence.tracker.full`, at most once a minute with how many of each, so an operator sees it saturate (ADR-0872). ## Bug fixes diff --git a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md index 401644d9c..5bf96496f 100644 --- a/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md +++ b/docs/adr/0872-the-first-presence-change-in-a-five-second-window-is-kept.md @@ -45,10 +45,12 @@ Chosen option: 1. shut others out. Only when every account in it has an open window is a change of an account it does not hold refused (fails closed, as `UserCodeAttemptThrottle` does), so a flood of accounts cannot lift the limit for itself. The refusal's `retry_after_ms` is the rest of the soonest window (at most `change_window_ms`), and its log line's `cause` - is `tracker_full`, not `window`. Such a refusal also counts towards `presence.tracker.full`, a warning logged at - most once a minute (`full_warning_interval_ms`) with the number refused since the last one and no user IDs: a user - who did nothing wrong is refused only here, so an operator must see it without debug logging, and one warning per - refusal would let the flood that fills the table flood the log too. + is `tracker_full`, not `window`. Such a refusal, and every eviction a full table makes (ADR-0871), counts towards + `presence.tracker.full`, a warning logged at most once a minute (`full_warning_interval_ms`) with the number of + each since the last one and no user IDs. A user who did nothing wrong is refused only here, and an evicted account + loses its devices' holds, so an operator must see both without debug logging; one warning per refusal or eviction + would let the flood that fills the table flood the log too. The report is asked for after each use of the table + (`take_saturation_report`, O(1)), so what a quiet minute leaves is reported by the next sync or `PUT`. * A dropped change is never kept later: a parked `/sync` or sliding sync is run again after a wake-up or its timeout (`rerun_waiting_sync`, `ClientServerDispatchOptions::sync_rerun`), and that rerun does not apply its `set_presence` again, so a change dropped in the window is not stored once the window has ended. diff --git a/docs/observability-audit.md b/docs/observability-audit.md index 411344352..9ef3b275a 100644 --- a/docs/observability-audit.md +++ b/docs/observability-audit.md @@ -139,9 +139,10 @@ is full. for either reason (fields `actor`, `device_id`, `presence`, `cause`, `retry_after_ms`), and a `/sync` asking for `unavailable` while another device of the account holds it online and the account is not already `unavailable` (`cause` `device_online`, no `retry_after_ms`; ADR-0871). - `presence.tracker.full` (warning, logger `presence`) fires when a change is refused because the presence tracker - has no room (`cause` `tracker_full` above), at most once a minute, with the number refused since the last warning - (fields `refused`, `accounts`, `limit`; never a user ID; ADR-0872). + `presence.tracker.full` (warning, logger `presence`) fires when the presence tracker refused a change because it + had no room (`cause` `tracker_full` above) or evicted an account to make room, at most once a minute, with the + number of each since the last warning (fields `refused`, `evicted`, `accounts`, `limit`; never a user ID; ADR-0871, + ADR-0872). `presence.inbound.refused` (warning, logger `presence`) fires when an inbound `m.presence` EDU has entries with a `presence` outside the enumeration or a `status_msg` that is not a string or is over 1024 bytes (fields `origin`, `refused`). `presence.inbound.truncated` (warning, logger diff --git a/docs/user-manual.md b/docs/user-manual.md index ce1f4daf8..750122fb1 100644 --- a/docs/user-manual.md +++ b/docs/user-manual.md @@ -1215,7 +1215,9 @@ is. A device that synced online in the last 5 minutes keeps the user online whil most once every 5 seconds: a later change by `/sync` in that time is ignored, and `PUT /presence` answers `429` with `retry_after_ms`. While as many accounts as the server tracks (65,536) have all changed in the last 5 seconds, a change by any other account is refused the same way (`too many accounts are changing presence`) until the soonest of those -5 seconds ends, and the server logs the warning `presence.tracker.full` at most once a minute. The server's own idle +5 seconds ends. With that many accounts tracked and some of them not changed lately, a new one takes the place of the +account whose devices went quiet soonest instead, which loses its online hold until it next syncs. Both are logged by +the warning `presence.tracker.full`, at most once a minute. The server's own idle change (an online user inactive for 5 minutes becomes `unavailable`) is not limited and does not start those 5 seconds. Presence reaches only users who share a joined room with the user; anyone else asking for it gets `403 M_FORBIDDEN`, as for a user who does not exist. diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index facde75cc..da50f628a 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -50,10 +50,21 @@ class AccountPresenceTracker final // Accounts with a device that asked for online within the last five minutes, or a window open: the account cap a // tracker has unless it is made with another. static constexpr auto max_accounts = std::size_t{65'536U}; - // At most one warning that the table is full in this time, so a flood of refused changes costs one warning a - // minute, which counts what it stands for. + // At most one report of what a full table cost in this time, so a flood of refusals or evictions costs one warning + // a minute, which counts what it stands for. static constexpr auto full_warning_interval_ms = std::int64_t{60'000}; + // What a full table did since the last report. + struct SaturationReport final + { + // Changes refused because the table had no room (`note_full_refusal`). + std::uint64_t refused{0U}; + // Accounts evicted to make room, which lost their devices' holds. + std::uint64_t evicted{0U}; + + [[nodiscard]] auto operator==(SaturationReport const&) const -> bool = default; + }; + AccountPresenceTracker() = default; // A tracker holding at most `account_cap` accounts (at least one), so a test can fill the table without // `max_accounts` of them. The server's tracker is made with the default. @@ -96,14 +107,20 @@ class AccountPresenceTracker final // The most accounts the table holds. [[nodiscard]] auto account_cap() const noexcept -> std::size_t; - // Counts a change refused at `now_ms` because the table is full (`is_full_for`). When a warning is due (the first - // refusal, or the first at least `full_warning_interval_ms` after the last warning), the number refused since the - // last warning, this one included; otherwise nullopt. - [[nodiscard]] auto note_full_refusal(std::int64_t now_ms) -> std::optional; + // Counts a change refused because the table is full (`is_full_for`). + auto note_full_refusal() noexcept -> void; // Changes refused because the table was full, since the table was made. [[nodiscard]] auto full_refusals() const noexcept -> std::uint64_t; + // Accounts a full table evicted to make room, since the table was made. + [[nodiscard]] auto evictions() const noexcept -> std::uint64_t; + + // What the table refused and evicted since the last report, when it did either and no report was taken in the + // `full_warning_interval_ms` before `now_ms`; the report is then taken as of `now_ms`. Otherwise nullopt. O(1), so + // a caller may ask after every use of the table. + [[nodiscard]] auto take_saturation_report(std::int64_t now_ms) -> std::optional; + private: struct Device final { @@ -154,9 +171,11 @@ class AccountPresenceTracker final std::uint64_t m_accounts_examined{0U}; std::size_t m_account_cap{max_accounts}; std::uint64_t m_full_refusals{0U}; - // `m_full_refusals` when the last warning was due, and when that was. - std::uint64_t m_full_refusals_warned{0U}; - std::optional m_full_warned_at_ms{}; + std::uint64_t m_evictions{0U}; + // The two counts when the last report was taken, and when that was. + std::uint64_t m_reported_refusals{0U}; + std::uint64_t m_reported_evictions{0U}; + std::optional m_reported_at_ms{}; }; } // namespace merovingian::homeserver diff --git a/include/merovingian/homeserver/PresenceService.hpp b/include/merovingian/homeserver/PresenceService.hpp index 270d1dc9a..be45210f6 100644 --- a/include/merovingian/homeserver/PresenceService.hpp +++ b/include/merovingian/homeserver/PresenceService.hpp @@ -65,10 +65,11 @@ inline constexpr auto presence_idle_catch_up_interval = std::chrono::seconds{1}; // back, plus `test_presence_clock_advance_ms`. Not a point in calendar time. [[nodiscard]] auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t; -// A change of presence refused at `clock_ms` because the presence tracker is full: counts it and, at most once every -// `AccountPresenceTracker::full_warning_interval_ms`, logs `presence.tracker.full` at warning level with the number -// refused since the last one (ADR-0872). The caller holds `runtime.mutex`. -auto note_presence_tracker_full(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void; +// Logs `presence.tracker.full` at warning level when the presence tracker refused a change or evicted an account since +// the last report, at most once every `AccountPresenceTracker::full_warning_interval_ms` (ADR-0872). Called after +// every use of the tracker that may refuse or evict; O(1) when there is nothing to report. The caller holds +// `runtime.mutex`. +auto report_presence_tracker_saturation(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void; // "The last active time must be up to date whenever the server gives a presence event to the // client": the stored value plus the time since it was true. Never negative. diff --git a/src/homeserver/AGENTS.md b/src/homeserver/AGENTS.md index 214166ac7..2bd246422 100644 --- a/src/homeserver/AGENTS.md +++ b/src/homeserver/AGENTS.md @@ -1389,8 +1389,9 @@ without that check ignores `presence.enabled=false`. Rules: limited. A new path that changes a local user's presence state is limited the same way. A parked poll's rerun (`ClientServerDispatchOptions::sync_rerun`) never applies `set_presence` again, or a dropped change would be kept once the window ends. Tests move the clock with `test_presence_clock_advance_ms`, never with a sleep. A change - refused because the tracker is full (`is_full_for`) calls `note_presence_tracker_full`, which counts it and logs the - rate-limited `presence.tracker.full` warning; a new refusal site does too. + refused because the tracker is full (`is_full_for`) calls `note_full_refusal`, and every path that uses the tracker + ends with `report_presence_tracker_saturation`, which logs the rate-limited `presence.tracker.full` warning of + refusals and evictions (`apply_sync_presence` does it once, after `judge_sync_presence`); a new path does too. - A classic `/sync` whose only news is the caller's own presence row waits on (`only_own_presence_since`, ADR-0873): never wake a poll for what its response does not send. - `accept_inbound_presence` binds `user_id` to the sending origin, bounds the entries it looks at, and keeps diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 54877cbc9..836678504 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -109,6 +109,7 @@ auto AccountPresenceTracker::account_for(std::string_view user, std::int64_t now // The account whose devices go stale soonest loses their holds; it has no window to lose. auto const evicted = m_closed.begin(); ++m_accounts_examined; + ++m_evictions; m_accounts.erase(evicted->second); m_closed.erase(evicted); } @@ -241,17 +242,9 @@ auto AccountPresenceTracker::account_cap() const noexcept -> std::size_t return m_account_cap; } -auto AccountPresenceTracker::note_full_refusal(std::int64_t now_ms) -> std::optional +auto AccountPresenceTracker::note_full_refusal() noexcept -> void { ++m_full_refusals; - if (m_full_warned_at_ms.has_value() && now_ms - m_full_warned_at_ms.value() < full_warning_interval_ms) - { - return std::nullopt; - } - auto const since_last_warning = m_full_refusals - m_full_refusals_warned; - m_full_refusals_warned = m_full_refusals; - m_full_warned_at_ms = now_ms; - return since_last_warning; } auto AccountPresenceTracker::full_refusals() const noexcept -> std::uint64_t @@ -259,4 +252,23 @@ auto AccountPresenceTracker::full_refusals() const noexcept -> std::uint64_t return m_full_refusals; } +auto AccountPresenceTracker::evictions() const noexcept -> std::uint64_t +{ + return m_evictions; +} + +auto AccountPresenceTracker::take_saturation_report(std::int64_t now_ms) -> std::optional +{ + auto const report = SaturationReport{m_full_refusals - m_reported_refusals, m_evictions - m_reported_evictions}; + if ((report.refused == 0U && report.evicted == 0U) || + (m_reported_at_ms.has_value() && now_ms - m_reported_at_ms.value() < full_warning_interval_ms)) + { + return std::nullopt; + } + m_reported_refusals = m_full_refusals; + m_reported_evictions = m_evictions; + m_reported_at_ms = now_ms; + return report; +} + } // namespace merovingian::homeserver diff --git a/src/homeserver/ClientServerRuntime.cpp b/src/homeserver/ClientServerRuntime.cpp index e0b4dd188..fd7c0be61 100644 --- a/src/homeserver/ClientServerRuntime.cpp +++ b/src/homeserver/ClientServerRuntime.cpp @@ -25432,8 +25432,9 @@ auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence con auto const tracker_full = tracker.is_full_for(state.user_id, clock_ms); if (tracker_full) { - note_presence_tracker_full(runtime.homeserver, clock_ms); + tracker.note_full_refusal(); } + report_presence_tracker_saturation(runtime.homeserver, clock_ms); return PresenceWrite{PresenceWriteStatus::limited, static_cast(retry_after_ms), tracker_full}; } if (!record_presence(runtime.homeserver, state)) @@ -25441,6 +25442,8 @@ auto set_presence(ClientServerRuntime& runtime, database::PersistentPresence con return PresenceWrite{PresenceWriteStatus::failed, 0U}; } tracker.note_change(state.user_id, clock_ms); + // The change may have evicted an account to make room (ADR-0871). + report_presence_tracker_saturation(runtime.homeserver, clock_ms); std::ignore = ensure_sync_notifier(runtime); // The servers that share a room with the user are told; the row is as stored just now. broadcast_presence_edu(runtime.homeserver, state); diff --git a/src/homeserver/PresenceService.cpp b/src/homeserver/PresenceService.cpp index 19af81657..3c8cde339 100644 --- a/src/homeserver/PresenceService.cpp +++ b/src/homeserver/PresenceService.cpp @@ -150,15 +150,16 @@ auto presence_limit_clock_ms(HomeserverRuntime const& runtime) -> std::int64_t return static_cast(steady_ms) + runtime.test_presence_clock_advance_ms; } -auto note_presence_tracker_full(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void +auto report_presence_tracker_saturation(HomeserverRuntime& runtime, std::int64_t clock_ms) -> void { auto& tracker = runtime.presence_tracker; - if (auto const refused = tracker.note_full_refusal(clock_ms); refused.has_value()) + if (auto const report = tracker.take_saturation_report(clock_ms); report.has_value()) { - // Aggregate only: the operator learns the tracker saturated, never which accounts were refused. + // Aggregate only: the operator learns the tracker saturated, never which accounts were refused or evicted. log_presence("presence.tracker.full", { - {"refused", std::to_string(*refused), false}, + {"refused", std::to_string(report->refused), false}, + {"evicted", std::to_string(report->evicted), false}, {"accounts", std::to_string(tracker.account_count()), false}, {"limit", std::to_string(tracker.account_cap()), false} }, @@ -338,86 +339,102 @@ auto parse_sync_presence_mode(std::optional value) noexcept -> return std::nullopt; } -auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, - SyncPresenceMode mode) -> std::optional +namespace { - if (!presence_enabled(runtime)) - { - return std::nullopt; - } - auto& tracker = runtime.presence_tracker; - auto const clock_ms = presence_limit_clock_ms(runtime); - if (mode == SyncPresenceMode::offline) - { - // "offline": the client is not to be marked online, so it no longer holds the account online either. - tracker.forget_device(user, device, clock_ms); - return std::nullopt; - } - auto const asks_online = mode == SyncPresenceMode::online; - auto const any_device_online = tracker.note_sync(user, device, asks_online, clock_ms); - if (!asks_online && any_device_online) + + // `apply_sync_presence` without the saturation report, so the report is made once, after every way out. + [[nodiscard]] auto judge_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional { - // ADR-0871: another device of the account asked for online in the freshness time; online beats unavailable. - // Logged only when the ask would have changed the stored state: an account already unavailable loses nothing. - if (auto const* const row = database::find_presence_state(runtime.database.persistent_store, user); - row == nullptr || row->presence != "unavailable") + if (!presence_enabled(runtime)) { - log_presence("presence.change.limited", { - {"actor", std::string{user}, false}, - {"device_id", std::string{device}, false}, - {"presence", "unavailable", false}, - {"cause", "device_online", false} - }); + return std::nullopt; } - return std::nullopt; - } - auto& store = runtime.database.persistent_store; - auto const now_ms = presence_now_ms(); - auto const desired = asks_online ? std::string_view{"online"} : std::string_view{"unavailable"}; - auto* const existing = database::find_mutable_presence_state(store, user); - if (existing != nullptr && existing->presence == desired) - { - if (asks_online) + auto& tracker = runtime.presence_tracker; + auto const clock_ms = presence_limit_clock_ms(runtime); + if (mode == SyncPresenceMode::offline) { - // Still online: nothing to tell anyone, but the user did just do something. - existing->last_active_ago = 0; - existing->observed_at_ms = now_ms; - existing->currently_active = true; + // "offline": the client is not to be marked online, so it no longer holds the account online either. + tracker.forget_device(user, device, clock_ms); + return std::nullopt; } - return std::nullopt; - } - if (auto const blocked = tracker.change_blocked_for_ms(user, clock_ms); blocked.has_value()) - { - // ADR-0872: the first change in the window was kept, or the tracker has no room for the account; this one is - // dropped, not kept for later. - auto const tracker_full = tracker.is_full_for(user, clock_ms); - if (tracker_full) + auto const asks_online = mode == SyncPresenceMode::online; + auto const any_device_online = tracker.note_sync(user, device, asks_online, clock_ms); + if (!asks_online && any_device_online) { - note_presence_tracker_full(runtime, clock_ms); + // ADR-0871: another device of the account asked for online in the freshness time; online beats unavailable. + // Logged only when the ask would have changed the stored state: an account already unavailable loses + // nothing. + if (auto const* const row = database::find_presence_state(runtime.database.persistent_store, user); + row == nullptr || row->presence != "unavailable") + { + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", "unavailable", false}, + {"cause", "device_online", false} + }); + } + return std::nullopt; } - auto const cause = std::string{tracker_full ? "tracker_full" : "window"}; - log_presence("presence.change.limited", { - {"actor", std::string{user}, false}, - {"device_id", std::string{device}, false}, - {"presence", std::string{desired}, false}, - {"cause", cause, false}, - {"retry_after_ms", std::to_string(*blocked), false} - }); - return std::nullopt; - } - auto row = existing != nullptr ? *existing : database::PersistentPresence{}; - row.user_id = std::string{user}; - row.presence = std::string{desired}; - row.last_active_ago = - asks_online || existing == nullptr ? std::int64_t{0} : presence_last_active_ago(*existing, now_ms); - row.currently_active = asks_online; - if (!record_presence(runtime, row)) - { - return std::nullopt; + auto& store = runtime.database.persistent_store; + auto const now_ms = presence_now_ms(); + auto const desired = asks_online ? std::string_view{"online"} : std::string_view{"unavailable"}; + auto* const existing = database::find_mutable_presence_state(store, user); + if (existing != nullptr && existing->presence == desired) + { + if (asks_online) + { + // Still online: nothing to tell anyone, but the user did just do something. + existing->last_active_ago = 0; + existing->observed_at_ms = now_ms; + existing->currently_active = true; + } + return std::nullopt; + } + if (auto const blocked = tracker.change_blocked_for_ms(user, clock_ms); blocked.has_value()) + { + // ADR-0872: the first change in the window was kept, or the tracker has no room for the account; this one + // is dropped, not kept for later. + auto const tracker_full = tracker.is_full_for(user, clock_ms); + if (tracker_full) + { + tracker.note_full_refusal(); + } + auto const cause = std::string{tracker_full ? "tracker_full" : "window"}; + log_presence("presence.change.limited", { + {"actor", std::string{user}, false}, + {"device_id", std::string{device}, false}, + {"presence", std::string{desired}, false}, + {"cause", cause, false}, + {"retry_after_ms", std::to_string(*blocked), false} + }); + return std::nullopt; + } + auto row = existing != nullptr ? *existing : database::PersistentPresence{}; + row.user_id = std::string{user}; + row.presence = std::string{desired}; + row.last_active_ago = + asks_online || existing == nullptr ? std::int64_t{0} : presence_last_active_ago(*existing, now_ms); + row.currently_active = asks_online; + if (!record_presence(runtime, row)) + { + return std::nullopt; + } + tracker.note_change(user, clock_ms); + row.observed_at_ms = now_ms; + return row; } - tracker.note_change(user, clock_ms); - row.observed_at_ms = now_ms; - return row; + +} // namespace + +auto apply_sync_presence(HomeserverRuntime& runtime, std::string_view user, std::string_view device, + SyncPresenceMode mode) -> std::optional +{ + auto changed = judge_sync_presence(runtime, user, device, mode); + // ADR-0872: an eviction (by the sync's online ask or its change) or a refusal made above is reported here. + report_presence_tracker_saturation(runtime, presence_limit_clock_ms(runtime)); + return changed; } auto build_sync_presence_events(database::PersistentStore const& store, sync::EventTypeFilter const& filter, diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index 51f4741c8..ac7a4192c 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -29,6 +29,17 @@ constexpr auto desktop = std::string_view{"DESKTOP"}; // is the same code at any size. constexpr auto small_cap = std::size_t{8U}; +// Fills a tracker of `small_cap` with accounts each held online by a desktop and none with a window open. @user0 synced +// at start_ms and the rest a millisecond later, so @user0's hold goes stale first and is the one a full table evicts. +auto fill_held_online(AccountPresenceTracker& tracker) -> void +{ + std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); + for (auto index = std::size_t{1U}; index < small_cap; ++index) + { + std::ignore = tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); + } +} + } // namespace SCENARIO("A device syncing online holds its account online against a device syncing unavailable", @@ -244,12 +255,7 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") { auto tracker = AccountPresenceTracker{small_cap}; - std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); - for (auto index = std::size_t{1U}; index < small_cap; ++index) - { - std::ignore = - tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); - } + fill_held_online(tracker); WHEN("an account with no entry asks to change its presence, however recently the others synced") { @@ -261,6 +267,11 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco REQUIRE_FALSE(blocked.has_value()); REQUIRE(tracker.account_count() == small_cap); REQUIRE(tracker.accounts_examined() == 1U); + REQUIRE(tracker.evictions() == 1U); + REQUIRE(tracker.take_saturation_report(start_ms + 2) == + std::optional{ + AccountPresenceTracker::SaturationReport{0U, 1U} + }); REQUIRE(tracker.change_blocked_for_ms(alice, start_ms + 3).has_value()); REQUIRE_FALSE(tracker.note_sync("@user0:example.org", phone, false, start_ms + 3)); } @@ -337,12 +348,7 @@ SCENARIO("A device asking for unavailable takes no place in the tracker", GIVEN("a table holding as many accounts as the cap, each held online by a device and none with a window open") { auto tracker = AccountPresenceTracker{small_cap}; - std::ignore = tracker.note_sync("@user0:example.org", desktop, true, start_ms); - for (auto index = std::size_t{1U}; index < small_cap; ++index) - { - std::ignore = - tracker.note_sync("@user" + std::to_string(index) + ":example.org", desktop, true, start_ms + 1); - } + fill_held_online(tracker); WHEN("an account with no entry syncs asking for unavailable") { @@ -377,31 +383,46 @@ SCENARIO("A tracker holds max_accounts accounts unless it is made with another c } } -// ADR-0872: a change refused because the table is full is counted, and a warning is due at most once every -// full_warning_interval_ms, carrying how many it stands for, so a flood of refusals costs one warning a minute. -SCENARIO("Changes refused by a full tracker are counted and warned about at most once an interval", +// ADR-0872: a full table's refusals and evictions are counted, and a report of them is due at most once every +// full_warning_interval_ms, carrying what it stands for, so a flood costs one warning a minute. Nothing to report is +// never a report. +SCENARIO("A full tracker's refusals and evictions are reported at most once an interval", "[unit][presence][account_presence_tracker][bounds]") { - GIVEN("a tracker that has refused nothing") + GIVEN("a tracker that has refused and evicted nothing") { auto tracker = AccountPresenceTracker{small_cap}; REQUIRE(tracker.full_refusals() == 0U); + REQUIRE(tracker.evictions() == 0U); + REQUIRE_FALSE(tracker.take_saturation_report(start_ms).has_value()); - WHEN("it refuses one change, two more within the interval, and one once the interval has passed") + WHEN("it refuses one change, then two more within the interval, and is asked after each") { - auto const first = tracker.note_full_refusal(start_ms); - auto const second = tracker.note_full_refusal(start_ms + 1); + using Report = AccountPresenceTracker::SaturationReport; + tracker.note_full_refusal(); + auto const first = tracker.take_saturation_report(start_ms); + tracker.note_full_refusal(); + auto const second = tracker.take_saturation_report(start_ms + 1); + tracker.note_full_refusal(); auto const third = - tracker.note_full_refusal(start_ms + AccountPresenceTracker::full_warning_interval_ms - 1); - auto const fourth = tracker.note_full_refusal(start_ms + AccountPresenceTracker::full_warning_interval_ms); + tracker.take_saturation_report(start_ms + AccountPresenceTracker::full_warning_interval_ms - 1); + auto const after_interval = + tracker.take_saturation_report(start_ms + AccountPresenceTracker::full_warning_interval_ms); + auto const nothing_new = + tracker.take_saturation_report(start_ms + 2 * AccountPresenceTracker::full_warning_interval_ms); - THEN("the first and the fourth are due a warning, the fourth standing for the three since the first") + THEN("the first is reported, the next two wait for the interval, and nothing new is never reported") { - REQUIRE(first == std::optional{1U}); + REQUIRE(first == std::optional{ + Report{1U, 0U} + }); REQUIRE_FALSE(second.has_value()); REQUIRE_FALSE(third.has_value()); - REQUIRE(fourth == std::optional{3U}); - REQUIRE(tracker.full_refusals() == 4U); + REQUIRE(after_interval == std::optional{ + Report{2U, 0U} + }); + REQUIRE_FALSE(nothing_new.has_value()); + REQUIRE(tracker.full_refusals() == 3U); } } } From 40e71f4bcca666e1011d03db9dabbde3a848dd49 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 11:33:04 +0000 Subject: [PATCH 23/25] Never let a device asking for unavailable take an online device's place At the 64-device cap the least recently seen device was replaced whatever it asked for, so a 65th device syncing unavailable could end the account's only online hold and flip its presence, the loop ADR-0871 prevents. make_device_place now gives up a device that asked for unavailable first; only a newcomer asking for online takes an online device's place, and an unavailable newcomer with no such place is not recorded. Co-Authored-By: Claude Opus 5.5 --- ...syncing-online-holds-its-account-online.md | 6 ++- .../homeserver/AccountPresenceTracker.hpp | 10 ++++- src/homeserver/AccountPresenceTracker.cpp | 30 ++++++++++--- tests/unit/test_account_presence_tracker.cpp | 44 ++++++++++++++++++- 4 files changed, 80 insertions(+), 10 deletions(-) diff --git a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md index becdabf79..ec2d3bd47 100644 --- a/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md +++ b/docs/adr/0871-a-device-syncing-online-holds-its-account-online.md @@ -38,7 +38,11 @@ Chosen option: 1, because it matches the spec's "any of the user's clients" and * The freshness time is the idle timeout, so a closed client holds the account online exactly as long as the idle sweep would leave it online after that client's last sync; a `static_assert` in `PresenceService.cpp` keeps the two equal. -* At most `max_devices_per_account` (64) devices per account, the least recently seen replaced; at most `max_accounts` +* At most `max_devices_per_account` (64) devices per account. At the cap a new device takes the place of the least + recently seen device that asked for `unavailable`; only a device asking for `online` takes the place of an online + one (the least recently seen), and a device asking for `unavailable` with no such place is not recorded, since it + holds nothing: replacing by age alone let a 65th device asking for `unavailable` end the only online hold, which is + the flip this decision prevents. At most `max_accounts` (65,536) accounts, pruned by the idle sweep every 30 s and when the table is full. An account with an open window (ADR-0872) is filed under its end, any other under the time its latest online device goes stale (a device that last asked for `unavailable` holds no place), so a prune visits only expired accounts, never the table: a flood of diff --git a/include/merovingian/homeserver/AccountPresenceTracker.hpp b/include/merovingian/homeserver/AccountPresenceTracker.hpp index da50f628a..62ed7ba30 100644 --- a/include/merovingian/homeserver/AccountPresenceTracker.hpp +++ b/include/merovingian/homeserver/AccountPresenceTracker.hpp @@ -45,7 +45,9 @@ class AccountPresenceTracker final // The idle timeout (`presence_idle_timeout_ms`): a device holds the account online for as long as the idle sweep // would leave it online after that device's last sync. `PresenceService.cpp` asserts the two are equal. static constexpr auto device_fresh_ms = std::int64_t{5 * 60 * 1000}; - // Far more devices than one person syncs from at once; each is a device ID and two integers. + // Far more devices than one person syncs from at once; each is a device ID and two integers. At the cap a new + // device takes the place of one that asked for unavailable first, and only one asking for online takes an online + // device's place (`make_device_place`). static constexpr auto max_devices_per_account = std::size_t{64U}; // Accounts with a device that asked for online within the last five minutes, or a window open: the account cap a // tracker has unless it is made with another. @@ -159,6 +161,12 @@ class AccountPresenceTracker final // Moves every account whose window ended by `now_ms` from `m_open_windows` to `m_closed`. auto close_ended_windows(std::int64_t now_ms) -> void; + // Makes a place in a full `devices` for a new device asking for `online` (true) or `unavailable`: the least + // recently seen device that asked for unavailable gives up its place, or, for an online newcomer when every device + // asked for online, the least recently seen of them. False when there is none to give: an unavailable newcomer + // holds nothing, so it never ends another device's online hold (ADR-0871). + [[nodiscard]] static auto make_device_place(std::vector& devices, bool online) -> bool; + // True when the table can hold another account at `now_ms`: it is not full, or an account in it has no open window. [[nodiscard]] auto has_room(std::int64_t now_ms) const noexcept -> bool; diff --git a/src/homeserver/AccountPresenceTracker.cpp b/src/homeserver/AccountPresenceTracker.cpp index 836678504..8a16ecb75 100644 --- a/src/homeserver/AccountPresenceTracker.cpp +++ b/src/homeserver/AccountPresenceTracker.cpp @@ -148,13 +148,8 @@ auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view d held->seen_at_ms = now_ms; held->online = online; } - else + else if (devices.size() < max_devices_per_account || make_device_place(devices, online)) { - if (devices.size() >= max_devices_per_account) - { - auto const oldest = std::ranges::min_element(devices, std::ranges::less{}, &Device::seen_at_ms); - devices.erase(oldest); - } devices.push_back(Device{std::string{device}, now_ms, online}); } refile(entry, now_ms); @@ -163,6 +158,29 @@ auto AccountPresenceTracker::note_sync(std::string_view user, std::string_view d }); } +auto AccountPresenceTracker::make_device_place(std::vector& devices, bool online) -> bool +{ + auto victim = devices.end(); + for (auto held = devices.begin(); held != devices.end(); ++held) + { + if (!held->online && (victim == devices.end() || held->seen_at_ms < victim->seen_at_ms)) + { + victim = held; + } + } + if (victim == devices.end() && online) + { + // Every device asked for online: the newcomer holds the account online as well as the one it replaces. + victim = std::ranges::min_element(devices, std::ranges::less{}, &Device::seen_at_ms); + } + if (victim == devices.end()) + { + return false; + } + devices.erase(victim); + return true; +} + auto AccountPresenceTracker::forget_device(std::string_view user, std::string_view device, std::int64_t now_ms) -> void { auto const found = m_accounts.find(user); diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index ac7a4192c..d235bcbd5 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -202,9 +202,49 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco { auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); - THEN("it replaces the least recently seen device, so none asks for online") + THEN("it takes the place of the least recently seen device that asked for unavailable, and the online hold " + "stays") { - REQUIRE_FALSE(any_online); + REQUIRE(any_online); + REQUIRE(tracker.note_sync(alice, "NEWEST", false, start_ms + 1'001)); + } + } + } + + GIVEN("an account with as many devices as the cap, every one of them asking for online") + { + auto tracker = AccountPresenceTracker{}; + for (auto index = std::size_t{0U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + std::ignore = tracker.note_sync(alice, "D" + std::to_string(index), true, + start_ms + static_cast(index)); + } + + WHEN("one more device syncs asking for unavailable") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); + + THEN("it is not recorded, since it holds nothing, and every online hold stays") + { + REQUIRE(any_online); + REQUIRE(tracker.note_sync(alice, "D0", true, start_ms + 1'001)); + } + } + + WHEN("one more device syncs asking for online") + { + auto const any_online = tracker.note_sync(alice, "NEWEST", true, start_ms + 1'000); + // Forgetting every device but D0 leaves the account held online only if D0 kept its place. + tracker.forget_device(alice, "NEWEST", start_ms + 1'001); + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + tracker.forget_device(alice, "D" + std::to_string(index), start_ms + 1'001); + } + + THEN("it takes the place of the least recently seen online device, D0") + { + REQUIRE(any_online); + REQUIRE_FALSE(tracker.note_sync(alice, "PROBE", false, start_ms + 1'002)); } } } From 07de778a74984d61bca788efefe0b62784472473 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 14:14:01 +0000 Subject: [PATCH 24/25] Split the tracker's bound scenario into device-cap and account-cap ones CodeQL flagged the scenario as a 132-line poorly documented function. The per-account device cap and the table's account cap are separate bounds, so each is now its own scenario with a comment naming its rule. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_account_presence_tracker.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index d235bcbd5..db72975c9 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -186,7 +186,10 @@ SCENARIO("A prune removes what no longer speaks for an account", "[unit][presenc } } -SCENARIO("The tracker is bounded per account and in all", "[unit][presence][account_presence_tracker][bounds]") +// ADR-0871: an account holds at most max_devices_per_account devices; at the cap a device that holds nothing gives up +// its place first, and only a device asking for online takes an online device's place. +SCENARIO("An account holds a bounded number of devices, and the cap never ends an online hold for nothing", + "[unit][presence][account_presence_tracker][bounds]") { GIVEN("an account with as many devices as the cap, the oldest of them the only one asking for online") { @@ -248,7 +251,12 @@ SCENARIO("The tracker is bounded per account and in all", "[unit][presence][acco } } } +} +// ADR-0871, ADR-0872: the table holds at most its account cap. A full table evicts the account whose devices go stale +// soonest, and refuses (fails closed) only while every account has an open window. +SCENARIO("The tracker holds a bounded number of accounts", "[unit][presence][account_presence_tracker][bounds]") +{ GIVEN("a table holding as many accounts as the cap, each inside its window") { auto tracker = AccountPresenceTracker{small_cap}; From 8009acb8c90e126ea29da183c5ebc29c5e646ec0 Mon Sep 17 00:00:00 2001 From: James Chapman Date: Sat, 21 Nov 2026 14:28:56 +0000 Subject: [PATCH 25/25] Prove D0 keeps its place without syncing it again The all-online case re-synced D0 online, which would put it back had the unavailable newcomer wrongly replaced it, and D1 to D63 kept the account online either way. The case now forgets D1 to D63 and probes with an unavailable device, which finds the account online only if D0 kept its place. Co-Authored-By: Claude Opus 5.5 --- tests/unit/test_account_presence_tracker.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/unit/test_account_presence_tracker.cpp b/tests/unit/test_account_presence_tracker.cpp index db72975c9..774199628 100644 --- a/tests/unit/test_account_presence_tracker.cpp +++ b/tests/unit/test_account_presence_tracker.cpp @@ -226,11 +226,17 @@ SCENARIO("An account holds a bounded number of devices, and the cap never ends a WHEN("one more device syncs asking for unavailable") { auto const any_online = tracker.note_sync(alice, "NEWEST", false, start_ms + 1'000); + // Forgetting every device but D0 leaves the account held online only if D0, the least recently seen, kept + // its place; it is never synced again, so the probe cannot put it back. + for (auto index = std::size_t{1U}; index < AccountPresenceTracker::max_devices_per_account; ++index) + { + tracker.forget_device(alice, "D" + std::to_string(index), start_ms + 1'001); + } - THEN("it is not recorded, since it holds nothing, and every online hold stays") + THEN("it is not recorded, since it holds nothing, and every online hold stays, D0's included") { REQUIRE(any_online); - REQUIRE(tracker.note_sync(alice, "D0", true, start_ms + 1'001)); + REQUIRE(tracker.note_sync(alice, "PROBE", false, start_ms + 1'002)); } }