Commit Graph
4157 Commits
Author SHA1 Message Date
Jason Robinson cb322e497f Ensure our own syncing user always gets their updates, even if they're not in any rooms 2026-07-08 11:45:41 +03:00
Jason Robinson 2ed4201dbc Adjust a few new tests after merging from develop 2026-07-07 22:52:55 +03:00
Jason Robinson cb81bd3a6b Merge remote-tracking branch 'origin/develop' into anoa/msc4429
# Conflicts:
#	synapse/rest/client/versions.py
2026-07-07 22:29:35 +03:00
Eric EastwoodandGitHub c63d77a79d Rust database access via Python database connection pool v2 (#19878)
This is a stepping stone before we can go full Rust everywhere. We're
providing a generic interface as we want database access to work in
Synapse and `synapse-rust-apps`. In `synapse-rust-apps`, we will use a
`tokio-postgres` based database connection pool so it's full Rust.

We want to avoid the situation where we have two database connection
pools (one for Python, one for Rust) as we've run into connection
exhaustion problems on Matrix.org before.

As an example of using it and sanity check for all this work (including
tests), I've also ported over the `/versions` handler to the Rust side
with database access. The `/versions` endpoint is the simplest endpoint
I could find that still had some database access. Hopefully the refactor
on `/versions` isn't that controversial as it's not really the point of
this PR. We can always remove it from this PR but it's just here as a
sanity check that all of this works.


### Why `runInteraction(...)`?

Using the same `runInteraction` pattern that we already have in Synapse
means we can port over existing Synapse code/endpoints without much
thought. But this pattern also makes sense because we want[^1]
transactions to have repeatable-read isolation (easy to think about,
less foot-guns). Having everything thappen in a function callback means
we can do retries for serialization/deadlock errors.

[^1]: To note: Ideally, we'd want the least isolation possible but the
problem is that there is no tooling to yell at you when your
queries/logic is wrong so repeatable-read isolation is a great balance.


> When an application receives this error message, it should abort the
current transaction and retry the whole transaction from the beginning.
The second time through, the transaction will see the
previously-committed change as part of its initial view of the database,
so there is no logical conflict in using the new version of the row as
the starting point for the new transaction's update.
> 
> Note that only updating transactions might need to be retried;
read-only transactions will never have serialization conflicts.
>
> *--
https://www.postgresql.org/docs/current/transaction-iso.html#XACT-REPEATABLE-READ*


As a note, this strategy is less of an impedance mismatch (aligns more
closely) with Synapse so the glue code for the `python_db_pool` should
also be simpler.


### How does this interact with logcontext (`LoggingContext`)?

See [docs on log
contexts](https://github.com/element-hq/synapse/blob/4e9f7757f17ba81b8747b7f8f9646d17df145aa3/docs/log_contexts.md)
for more background.

We already support normal logging from Rust -> Python with `pyo3-log`
and `log` but as soon as we pass a thread boundary, everything is logged
against the `sentinel` log context. Normally, we want logs and CPU/DB
usage correlated with the request that spawned the work.

You can see how I took a stab at fixing this in
https://github.com/element-hq/synapse/pull/19846 by capturing the
logcontext in a Tokio task local and re-activating as necessary. For
example, in that PR, I reactivated the logcontext in
`run_python_awaitable(...)` which we use to call `runInteraction(...)`
from the Rust side which means all of the database usage is correlated
with the request as expected. It also means any `log:info!(...)` done in
`run_interaction(...)` is correlated correctly. But there needs to be a
better story for when you want to log everywhere else.

I haven't explored tracking CPU usage on the Rust side.

I've left all of this out of this PR as I think it will be better to
tackle this as a dedicated follow-up. For example, I'm thinking about
instead creating a new `LoggingContext` with the `parent_context` set to
the calling context and try to avoid needing to call
`set_current_context(...)` on the Python side where possible (like
tracking CPU).



### Testing strategy

Added some tests that exercise some `async` Rust handlers for the
`/versions` endpoint:
```
SYNAPSE_TEST_LOG_LEVEL=INFO poetry run trial tests.rest.client.test_versions.VersionsTestCase
```

Real-world:

 1. `poetry run synapse_homeserver --config-path homeserver.yaml`
 1. `GET http://localhost:8008/_matrix/client/versions`
2026-07-07 13:07:35 -05:00
Jason Robinson f7d05558b6 Refactor profile updates behind the profile updates stream writer
Setting a profile field (including displayname / avatar_uri) now needs to happen on a profile updates stream writer. There are new "dispatch" methods to do the profile field set/delete, that handle pushing the update over replication, if required.

Profile field updates and profile updates stream writes are now in the same database transaction.
2026-07-07 18:50:59 +03:00
f8fefb09bd Re-expose the standalone format_event_* transforms for backwards compat (#19922)
The port of event serialization to Rust (#19837) removed
`format_event_raw`, `format_event_for_client_v1`,
`format_event_for_client_v2` and
`format_event_for_client_v2_without_room_id` from
`synapse.events.utils`, but there are modules in the wild that import
them from there.

Reimplement them as standalone pyfunctions in Rust, operating directly
on the Python dict so the original semantics are preserved exactly
(in-place mutation, returning the same dict, arbitrary non-JSON values
passing through, KeyError on a missing `unsigned` in the v1 format), and
re-export them from `synapse.events.utils`.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-07 13:47:03 +01:00
27c3b5394b Port the synchronous event serialization core to Rust (#19837)
### Summary

This moves the synchronous core of client event serialization out of
`synapse/events/utils.py` and into Rust
(`rust/src/events/serialize.rs`).

Event serialization is on the hot path for `/sync`, `/messages`, and
most client-facing endpoints. Previously it was a recursive pure-Python
routine (`_serialize_event` / `_inject_bundled_aggregations` /
`only_fields`) that interleaved
CPU-bound formatting with `async` DB/IO. This PR separates those two
concerns and moves the CPU-bound half to Rust:

- **Async prep stays in Python.**
`EventClientSerializer._prepare_serialization` does all DB/IO up front:
batch-fetching redaction events and running the registered module
`unsigned`-callback hooks, for the top-level events *and* every bundled
sub-event (edits and thread latest events, which are themselves
serialized). The admin/MSC4354 config is resolved once via
`_update_config`, rather than re-checked on every recursive call as the
old code did.
- **The synchronous core moves to Rust.** Given an event plus the
pre-fetched `redaction_map`, `unsigned_additions`, and
`bundle_aggregations`, the Rust code produces the client JSON entirely
in Rust — including the v1/v2 format transforms, `only_event_fields`
filtering, redaction handling, and recursive bundled aggregations.

### Details

- The Rust entry point is a single batch function, `serialize_events`,
taking a list of `(event, membership)` pairs. The three lookup maps are
shared across the whole batch, so they're read out of Python and
converted to Rust
structures **once** per batch rather than once per event.
`EventClientSerializer.serialize_event` (singular) is a thin wrapper
that calls it with a one-element list.
- `SerializeEventConfig` is now a Rust `pyclass`, and the old
`event_format` callable is replaced by the `EventFormat` enum (`Raw` /
`ClientV1` / `ClientV2` / `ClientV2WithoutRoomId`). Call sites in
`rest/admin/events.py` and
`rest/client/{notifications,room,sync}.py` are updated to pass the enum.
`make_config_for_admin` and MSC4354 enablement now go through
`SerializeEventConfig.for_admin()` / `with_msc4354()`.
- New accessors on `EventInternalMetadata` (`redacted_by`, `txn_id`,
`device_id`, `token_id`, `delay_id`, `soft_failed`,
`policy_server_spammy`) expose to Rust the fields the serializer reads.
- The `_split_field` unit tests move from `tests/events/test_utils.py`
to a Rust test in `serialize.rs`, since the implementation moved.

### Behaviour

This is intended to be a behaviour-preserving refactor — the Rust core
mirrors the previous Python output (field ordering, v1 key promotion,
redaction placement per room version, null-`redacts` handling,
transaction-ID gating).

Existing serialization, relations, and sync tests pass unchanged.

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Eric Eastwood <madlittlemods@gmail.com>
Co-authored-by: Eric Eastwood <erice@element.io>
2026-07-07 11:59:27 +01:00
Eric EastwoodandGitHub 026937b251 Update FakeChannel.await_result(...) to drive async Rust (Tokio runtime/thread pool) (#19879)
Split off from https://github.com/element-hq/synapse/pull/19878 (needed
to drive requests in tests that use async Rust)

Follow-up to https://github.com/element-hq/synapse/pull/19871
2026-07-07 04:07:19 -05:00
Jason Robinson 2bea8c0657 Revert "Add a prune job for the profile updates stream tables"
Extracted to a follow-up pr.

This reverts commit b657d2f8
2026-07-07 10:01:24 +03:00
Jason Robinson 10cccac913 Ensure we bust the lazy loading cache for profile updates, when field values change 2026-07-06 18:36:57 +03:00
963e486a70 Recreate user profile on account reactivation (#19902)
Co-authored-by: Andrew Morgan <1342360+anoadragon453@users.noreply.github.com>
2026-07-06 12:38:24 +00:00
Jason Robinson f431951fdb Add a test to ensure display name changes don't generate extra room_joined profile updates rows, due to membership event changes 2026-07-06 15:23:11 +03:00
Jason Robinson b571fcef4e Clear all old ProfileUpdate rows from profile_updates_per_user on a leave
Regardless of action. This is cleaner and also ensures a join/leave/join/leave case might not get confused.
2026-07-06 15:08:10 +03:00
Jason Robinson 425aa00a9b Add a join → leave → re-join → leave to try and rule out bugs in that aspect 2026-07-06 14:50:04 +03:00
Andrew MorganandGitHub c7a47bc121 Fix flaky 3PID inhibit error unit tests (#19913) 2026-07-06 11:34:41 +00:00
Jason Robinson 1955fbee22 Ensure falsey values survive the set_field / sync profile updates -cycle 2026-07-03 18:28:49 +03:00
807795e5ee Change the MSC3814 dehydrated device /events endpoint paging to match spec conventions (#19897)
To match [the spec requirements for
pagination](https://spec.matrix.org/v1.9/appendices/#pagination):

* rename the query parameter of
`/org.matrix.msc3814.v1/dehydrated_device/[device_id]/events` to `from`,
and
* omit `next_batch` from the response content if there are no more
events to fetch

This matches [the changes that are coming in
MSC3814](https://github.com/matrix-org/matrix-spec-proposals/pull/3814/files#r1540896531).

The previous change https://github.com/element-hq/synapse/pull/19896
kept the old POST API to support old clients. This preserves that
compatibility, so the POST API still works how it used to.

Depends on https://github.com/element-hq/synapse/pull/19896
Part of https://github.com/element-hq/element-meta/issues/2799


### Pull Request Checklist

* [x] Pull request is based on the develop branch
* [x] Pull request includes a [changelog
file](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#changelog).
The entry should:
* [x] [Code
style](https://element-hq.github.io/synapse/latest/code_style.html) is
correct (run the
[linters](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#run-the-linters))

---------

Co-authored-by: Richard van der Hoff <1389908+richvdh@users.noreply.github.com>
Co-authored-by: Quentin Gliech <quenting@element.io>
2026-07-03 14:48:43 +02:00
Jason Robinson d3dd12f027 Rewrite lazy_loaded_profile_fields_cache 2026-07-03 15:42:57 +03:00
Hugh Nimmo-SmithandGitHub 4104058e83 Make MSC4388 (sign-in with QR code) PUT requests idempotent (#19808) 2026-07-03 12:09:16 +00:00
Jason Robinson 6f6e633b5c Ensure we don't respond with profile fields the client didn't ask for 2026-07-03 14:58:33 +03:00
Eric EastwoodandGitHub 7da21a715d Update HomeserverTestCase.get_success(...) and friends to drive async Rust (Tokio runtime/thread pool) (#19871)
This means you can use `get_success(...)` anywhere regardless
of what kind of work needs to be done.

Spawning from adding some more async Rust things in
https://github.com/element-hq/synapse/pull/19846 and wanting something
more standard instead of the custom `till_deferred_has_result(...)` that
has crept in to a few files.

Alternative to https://github.com/element-hq/synapse/pull/19867 spurred
on by [this
comment](https://github.com/element-hq/synapse/pull/19867#discussion_r3441774685)
from @erikjohnston


### How does this work?

Previously, `get_success(...)` just ran in a hot-loop advancing the
Twisted reactor clock which didn't give any time for other threads to do
some work or acquire the GIL if necessary (whenever there is a hand-off
from Rust to Python, we need the GIL).

Now, `get_success(...)` loops until we see a result (until we hit the
~0.1s real-time timeout). In the loop, we call
[`time.sleep(0)`](https://docs.python.org/3/library/time.html#time.sleep)
which will "Suspend execution of the calling thread [...]" (CPU and GIL)
to allow other threads to do some work. Then like before, we advance the
Twisted reactor clock to run any scheduled callbacks which includes
anything the other threads may have scheduled.


### Does this slow down the entire test suite?

Seems just as fast as before. There is minutes variance in what we had
before and after but both are within the same range of each other.

(see PR for actual before/after timings)
2026-07-02 15:20:38 -05:00
Jason Robinson 2c7b418105 Ensure we filter out federated users in lazy loading sync when collecting profile updates from timeline events 2026-07-02 23:13:05 +03:00
Jason Robinson e68560a8a2 Don't dump to json string in tests 2026-07-02 22:21:00 +03:00
Olivier 'reivilibreandGitHub 5df6d1be65 Remove legacy MSC3861 auth delegation support (#19895)
Modern 'MAS integration' (as we call it now) is, of course, preserved.

Fixes: #19549

---------

Signed-off-by: Olivier 'reivilibre <oliverw@matrix.org>
2026-07-02 12:25:11 +01:00
2517db46b3 add before and after filter to redact user method (/_synapse/admin/v1/user/$user_id/redact) (#19802)
Closes #19441 

---------

Co-authored-by: Olivier 'reivilibre <oliverw@matrix.org>
2026-07-01 17:28:22 +01:00
Olivier 'reivilibreandGitHub acb0ae1a15 Remove wall-clock dependency of test_redact_messages_all_rooms test. (#19890)
Introduced in: #17847

This 10-second wall-clock timeout was troublesome as it fails flakily on
slow/struggling CI runners, like the
default ones for private GitHub repositories.

The loop also silently relied on the reactor advance in `make_request`,
whereas we could just deterministically advance the reactor the known
amount of times
instead.

---------

Signed-off-by: Olivier 'reivilibre <oliverw@matrix.org>
2026-07-01 17:12:48 +01:00
Jason Robinson 45e9a018af Don't unpact ProfileUpdateAction unnecessarily early 2026-07-01 17:32:08 +03:00
Jason Robinson e6aec556ab Merge remote-tracking branch 'origin/develop' into anoa/msc4429 2026-07-01 11:55:57 +03:00
Jason Robinson eb5aa2129a Ensure both initial and incremental syncs include our own profile and updates
Otherwise if the user has multiple clients doing incremental sync, they wont get their own profile updates to their other clients. For initial because it should probably match the incremental behaviour + it avoids clients needing to look up the profile separately potentially.
2026-07-01 11:22:57 +03:00
aa97687305 Change MSC3814 dehydrated device /events endpoint from POST to GET (#19896)
Change `/org.matrix.msc3814.v1/dehydrated_device/[device_id]/events` to
accept GET requests instead of POST.

The original version of
[MSC3814](https://github.com/matrix-org/matrix-spec-proposals/pull/3814)
said we should delete keys after returning them from this endpoint, but
it is being updated to say we should not delete them, and therefore the
appropriate verb is GET.

Synapse already doesn't delete anything, so we just need to change to a
GET with a `next_batch` query param. (Currently it is a POST with
`next_batch` in the JSON content.)

This code was initially written by @ara4n and Claude, but both he and I
have read it and think it makes sense. I am far from a Synapse expert,
so feel free to tell me it's all wrong and point me in the right
direction.

I don't know what system tests will be affected by this, but I guess we
will see when the CI runs (right?).

This is a change to an unstable endpoint so no need for notifications
about breaking changes or similar.

Part of https://github.com/element-hq/element-meta/issues/2704

### Pull Request Checklist

* [x] Pull request is based on the develop branch
* [x] Pull request includes a [changelog
file](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#changelog).
The entry should:
* [x] [Code
style](https://element-hq.github.io/synapse/latest/code_style.html) is
correct (run the
[linters](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#run-the-linters))

---------

Co-authored-by: Matthew Hodgson <matthew@matrix.org>
2026-06-30 21:20:26 +00:00
aa6e616470 Don't delete the dehydrated device when MAS syncs the device list (#19892)
`_synapse/mas/sync_devices` checks the device list against the set of
devices MAS knows about, but the dehydrated device (MSC3814) is
invisible to MAS, so it gets automatically deleted on each sync, which
prevents dehydrated devices from working.

This change excludes the dehydrated device from the check.

There is similar special case code in the admin devices API (which gives
it a special flag) and MAS's own legacy sync path (which filters it
out).

This code was initially written by @ara4n and Claude, but both he and I
have read it and think it makes sense. I am far from a Synapse expert,
so feel free to tell me it's all wrong and point me in the right
direction.

A system-level test for this bug is being written here:
https://github.com/element-hq/element-web/issues/34034 but if you think
we should have one somewhere else, please let me know.

Closes https://github.com/element-hq/synapse/issues/19889

### Pull Request Checklist

* [x] Pull request is based on the develop branch
* [x] Pull request includes a [changelog
file](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#changelog).
The entry should:
* [x] [Code
style](https://element-hq.github.io/synapse/latest/code_style.html) is
correct (run the
[linters](https://element-hq.github.io/synapse/latest/development/contributing_guide.html#run-the-linters))

Co-authored-by: Matthew <matthew@element.io>
2026-06-30 15:24:42 +02:00
Andrew MorganandGitHub 1639c30281 Fix the cargo-test and cargo-bench CI jobs not running (#19883) 2026-06-30 11:46:47 +00:00
Jason Robinson a460c285a7 Merge remote-tracking branch 'origin/develop' into anoa/msc4429 2026-06-29 21:58:15 +03:00
Jason Robinson 496728df15 Add docstrings to tests
Plus make a few tests actually do something sane..
2026-06-29 21:48:11 +03:00
Jason Robinson 2377165ebd Add test to prove initial sync doesn't include users updates who don't share a room 2026-06-29 16:33:36 +03:00
5edcb0f542 MSC4143: Advertise org.matrix.msc4143 in /versions unstable_features (#19646)
Closes #19580

---------

Co-authored-by: toonbr1me <toonbr1me@users.noreply.github.com>
2026-06-29 14:07:43 +01:00
Jason Robinson 60ed1758dc When user has left all rooms shared with a user, clear any previous profile updates
This ensures we don't accidentally leak any profile updates to users no longer sharing rooms.
2026-06-29 16:00:00 +03:00
Jason Robinson b0950f98df Merge remote-tracking branch 'origin/develop' into anoa/msc4429 2026-06-29 12:57:21 +03:00
Jason Robinson b459512725 Use include_profile_updates_in_sync config item instead of an experimental flag + alias.
The requirement for this comes from a customer commitment.
2026-06-26 18:08:12 +03:00
Will HuntandGitHub 2bb3aac839 Add metric to count number of non-deactivated users. (#19848)
This reports the total count of users (split by appservice) which is
meant to be the monthless counterpart to the MAU metric.

Context:

> So this is largely for billing purposes and wanting to know the change
in the number of users. If a user is deactivated then we no longer want
to count them. Consumers *might* want to count appservice users, and
maybe count them based on the service (perhaps you change more for users
under bridge X or bridge Y).
>
> *-- https://github.com/element-hq/synapse/pull/19848#discussion_r3402216234*
2026-06-25 11:57:36 -05:00
Jason Robinson 5f761ab5b4 Use set for uniqueness 2026-06-25 17:39:42 +03:00
Jason Robinson b657d2f8db Add a prune job for the profile updates stream tables
Taken and adapted from https://github.com/element-hq/synapse/pull/19473

Didn't add the "safety" table due to afaik that has more relevance with the device updates, and not so much here for the profile updates.
2026-06-24 19:11:41 +03:00
Jason Robinson 7c728ec61c Optimize profile handler user_joined_room and user_left_room
Save a db query if there are no users to add profile updates for.
2026-06-24 13:45:13 +03:00
Jason Robinson d3aacee235 Fix test_update_profile_set_field_writes_to_per_user_profile_tracking_table test
And remove unused `get_profile_updates_per_user_for_user` function
2026-06-24 13:32:19 +03:00
Jason Robinson 9d58d19934 Merge remote-tracking branch 'origin/develop' into anoa/msc4429 2026-06-24 11:52:58 +03:00
Jason Robinson 8504386b1f Send down full profile of user if user has joined during incremental sync
Also refactor the "user left" to not listen to the "user_left_room" dispatch hook since we only want to do this once, thus call the profile handler immediately in the instance responsible for receiving the event.
2026-06-23 16:44:39 +03:00
16fe5fb462 Expose MSC4354 Sticky Events over MSC4186 (Simplified) Sliding Sync. (#19591)
Follows: #19487
Part of: MSC4354 whose experimental feature tracking issue is #19409

This PR implements the Sliding Sync (MSC4186) extension described in
MSC4354, allowing sliding sync clients
to receive sticky events in a reliable way.

The logic is much the same as for oldschool sync (implementation in
#19487),
although in the sliding sync extension, the client can choose their own
limit
and must control their own pagination through an extra token in the
extension request/response bodies.

Note this does not yet send down existing sticky events in the
room when the room has been newly-joined.
This newly-discovered gap is tracked at #19662 and will be addressed for
both current sync and MSC4186 SSS soon.

---------

Signed-off-by: Olivier 'reivilibre <oliverw@matrix.org>
Co-authored-by: Eric Eastwood <erice@element.io>
2026-06-23 13:04:36 +00:00
Jason Robinson 2dbaec329b Send down a null when user has left all shared rooms
Restore test and switch from {} to null.
2026-06-23 15:37:35 +03:00
Jason Robinson 09e212537e Fix incremental lazy sync to send down profiles for users without profile updates
Remove the checking of any stream token changes and ensure we always collect profiles for users even if they have not done profile updates, if they have events in the timeline. Also fix the cache.
2026-06-23 14:53:33 +03:00
Stefan CeriuandGitHub 6d289f7ce0 Fix permanent badge inflation from read receipts before first rotation (#19785) 2026-06-23 11:31:32 +00:00