The config documentation said `allowed_lifetime_min` bounds a room's
`min_lifetime`. It actually sets the minimum allowed value for
`max_lifetime`: purge jobs raise a room's `max_lifetime` to
`allowed_lifetime_min` when it is lower
(`synapse/handlers/pagination.py`), and
`synapse/rest/client/retention.py` reports both `allowed_lifetime_*`
options as bounds on `max_lifetime`.
`docs/message_retention_policies.md` already describes this correctly.
The runtime-deps stage adds arm64 as a foreign architecture before
running `apt-cache depends`, which makes apt emit some dependencies with
an explicit `:arm64` qualifier and an explicit qualifier overrides `-o
APT::Architecture`, so those packages were downloaded as arm64 into the
amd64 tree and shipped in the final amd64 image as an unusable ~31MB
second copy of glibc, OpenSSL and zlib. Stripping the qualifier from the
package list fixes it.
### Pull Request Checklist
<!-- Please read
https://element-hq.github.io/synapse/latest/development/contributing_guide.html
before submitting your pull request -->
* [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:
- Be a short description of your change which makes sense to users.
"Fixed a bug that prevented receiving messages from other servers."
instead of "Moved X method from `EventStore` to `EventWorkerStore`.".
- Use markdown where necessary, mostly for `code blocks`.
- End with either a period (.) or an exclamation mark (!).
- Start with a capital letter.
- Feel free to credit yourself, by adding a sentence "Contributed by
@github_username." or "Contributed by [Your Name]." to the end of the
entry.
* [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))
Next step in adding Rust postgres driver. Follows on from #19996.
This adds a query lifecycle state machine that is used to implement the
Python transaction interface (e.g. `txn.fetchall()`, `txn.rowcount`,
etc). The state machine is an enum over `Idle`/`Active`/`Closed`. The
`fetch` APIs are only allowed during the `Active` phase, while
`rowcount` is allowed during `Active` or `Closed`.
So for each query on a connection, the state starts of at `Idle` and
transitions to `Active` when `execute` completes. Rows can then be read
until there are no more rows, at which point we transition to `Closed`.
The state transitions back to `Idle` on the next query. If at any point
a error is returned, e.g. a postgres error or failing to parse a row,
the error is returned and the state immediately transitions back to
`Idle`.
Note that calling `txn.rowcount` will implicitly close the query state
(and discard any unread rows), unlike for `sqlite3` and `psycopg2`. This
is because Postgres only sends the affected row count *after* all the
rows have been sent down the connection. `psycopg2` avoids this by
buffering all the rows in-memory. We could do the same, but a) that's a
waste, and b) we generally never need to know the affected row count up
front (and even if we did we can manually buffer).
The query state enum won't be exposed directly to Python, instead it
will be wrapped by a transaction class.
Also adds a `fetch_next_batch`, which waits for at least the next row
but then returns any already buffered rows. This is to allow efficient
implementation of iterating in Python over the rows, where we want to
avoid doing FFI for each row.
Reviewable commit-by-commit.
---------
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
From https://github.com/element-hq/synapse/pull/20522
We can tell this change works because we changed
`.github/workflows/schema_diff.yml` which triggers it to run but we're
not seeing a "Schema Diff" comment on this PR (no `pg_attver` noise)
This PR changes the behavior of ACL matching to match literal entries
via a hashset instead of regex which drastically reduces the memory
usage on the python side given that the vast majority of ACL entries
arent globs.
(This was/is assisted by claude)
### Pull Request Checklist
<!-- Please read
https://element-hq.github.io/synapse/latest/development/contributing_guide.html
before submitting your pull request -->
* [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:
- Be a short description of your change which makes sense to users.
"Fixed a bug that prevented receiving messages from other servers."
instead of "Moved X method from `EventStore` to `EventWorkerStore`.".
- Use markdown where necessary, mostly for `code blocks`.
- End with either a period (.) or an exclamation mark (!).
- Start with a capital letter.
- Feel free to credit yourself, by adding a sentence "Contributed by
@github_username." or "Contributed by [Your Name]." to the end of the
entry.
* [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))
[More internal context
here](https://claude.ai/artifact/2BcZgjUcvHJjV1jdsuPHLv#6a7be7a8-1857),
this is part of a series of PRs to try and fix many buggy membership
transitions.
Replaces #19959 and #20440.
This PR fixes 500 errors when reading a room your homeserver is not in,
after you were invited to it or knocked on it. This is what happens when
your *leave* membership is stored *out of band*, which is the case in
two main scenarios:
- a remote invite, your local homeserver doesn't have the full state of
the room; when you reject that invite, your *leave membership* is stored
out of band
- you knock on a room, same: your local HS doesn't have the room state,
stores the knock out of band; when you then rescind (cancel) the knock,
that *leave membership* is also stored out of band
Now that currently breaks a few APIs which try to look at the state of
the room: [`GET
/rooms/{roomId}/state`](https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidstate),
`/state/{eventType}/{stateKey}`, `/members` and
`/rooms/{roomId}/initialSync`.
Previously, Synapse would try to serve the state and fail to do so if
your leave event is stored out of band. Because the only reason your
leave event would be stored out of band is when you *never were in the
room in the first place*, this changes the response of those endpoints
to a 403 (because you were never in the room) when your leave event is
stored OOB.
The check is in `Auth.check_user_in_room`, so it applies to every
endpoint which accepts departed users. `/messages` and `/threads`
returned a 200 with an empty chunk for such a room, and now return the
403 the spec has for a user who isn't a member.
Now, the reason we're not *just* checking `is_outlier()` (aka "we don't
have the room state for this event") but also explicitly
`is_out_of_band_membership()` for this part is that a history purge
(admin API or retention) also leaves outliers behind: it keeps the state
events, but drops the room state at them. A user who left before the
purge really was in the room, so replying with a 403 would be wrong
according to the spec (historical members should be able to see the
state of the room as of their leave). I prefer deferring the
conversation around what we should reply here to another PR later
The second commit is similar, but for `/context` on your own membership
event (the invite, the knock, or the leave). You are allowed to see that
event, but the server has nothing around it, so the request ended in a
500. It now returns a 404, and the event itself is still served by
`/event/{eventId}`. I did a spec clarification PR to explain that we
should return a 404 for events where the server doesn't have context:
https://github.com/matrix-org/matrix-spec/pull/2474
Complement test for `/context`:
https://github.com/matrix-org/complement/pull/965
This one only checks `is_outlier()`, so `/context` on a leave from
before a purge also goes from a 500 to a 404.
<details><summary>Claude's original PR description with more random
details 🤖</summary>
The idea is the same in both commits: your own membership events are
served, but the server has no state or timeline for the room, so it says
so instead of failing.
The easiest example:
- Your local homeserver gets [an invite from a remote
server](https://spec.matrix.org/latest/server-server-api/#inviting-to-a-room)
for a room it is not in, and stores it as an "out of band" event: an
outlier, with no state and no position in the room's timeline.
- You reject it with
[`/leave`](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidleave).
The leave is stored out of band too.
**First commit: `/state`, `/members` and `/initialSync` after the
leave.** [`GET
/rooms/{roomId}/state`](https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidstate),
`/state/{eventType}/{stateKey}`, `/members` and
`/rooms/{roomId}/initialSync` let a user who left a room read its state
as of their leave. Synapse tries to load the state at that out-of-band
leave, there is none, and the request ends in a `KeyError` and a 500.
While the invite was still pending, the same requests got a 403. The
out-of-band leave now gets that same 403: as far as this server knows
the user was never in the room. The spec doesn't really cover a leave
without a join here; its 403 for these endpoints is "You aren't a member
of the room and weren't previously a member of the room".
On matrix.org this is the only cause of 500s on these endpoints, around
a thousand a day. Over three days (Nov 10 to 12) that was about 2000
requests from around 100 users, nearly all from Element X and
matrix-rust-sdk on `/members` and `/state/m.room.encryption/`, retried
again and again for the same rooms.
The check is in `Auth.check_user_in_room`, so it applies to every
endpoint which accepts departed users. That means `/messages`,
`/relations` and `/threads`, which returned a 200 with an empty chunk
for such a room, now return the 403 as well.
**Second commit: `/context` on the membership event.** You are allowed
to see your own membership events, so [`GET
/rooms/{roomId}/context/{eventId}`](https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomidcontexteventid)
on the invite, the knock or the leave passes the visibility check. It
then fails when looking up what is around the event, and returns a 500.
It now returns a 404 `M_NOT_FOUND`, as it already does for an event the
server doesn't know. The event itself stays available from [`GET
/rooms/{roomId}/event/{eventId}`](https://spec.matrix.org/latest/client-server-api/#get_matrixclientv3roomsroomideventeventid),
which returns a 200.
#19959 and #20440 returned a 200 with the event alone and no
`start`/`end` tokens. I dropped that: it needs spec text to say what
missing tokens mean, and no client I looked at needs the response.
Element X does call `/context` on such events (30 to 100 times a day on
matrix.org, all ending in this 500), but only as the fallback of
matrix-rust-sdk's notification client when sliding sync doesn't return
the event, and it already copes with an error there. In those logs the
users had all joined the room since, so this is most likely the invite,
which stays an outlier after the join.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
</details>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
This enables guest access on `/rtc/transports` and `/rtc/livekit/*`
(which is only proxied through application services) as per the
MatrixRTC MSCs.
This pull request can be reviewed by commit.
Follow-up to https://github.com/element-hq/synapse/pull/19972
### Dev notes
MSC4512
---------
Co-authored-by: Eric Eastwood <madlittlemods@gmail.com>
[More internal context
here](https://claude.ai/artifact/2BcZgjUcvHJjV1jdsuPHLv#dbe58feb-2677),
this is part of a series of PRs to try and fix many buggy membership
transitions.
This PR fixes a 500 error when trying to update the membership in rooms
where the server has no forward extremities.
To understand what this concretely means, the easiest example to
understand is when you try to reject a remote invite *twice*. This
means:
- Your local homeserver got [an invite from a remote
server](https://spec.matrix.org/latest/server-server-api/#inviting-to-a-room)
for a room it doesn't know anything about.
- In this case, it is storing the invitation as an "out of band" event,
and doesn't have any forward extremities for this room
- The spec then gives us special
[`/make_join`](https://spec.matrix.org/latest/server-server-api/#joining-rooms)
and
[`/make_leave`](https://spec.matrix.org/latest/server-server-api/#leaving-rooms-rejecting-invites)
dances that will let our homeserver craft proper join or leave events
without yet being in the room
- That's what the [`/leave` C-S
API](https://spec.matrix.org/latest/client-server-api/#post_matrixclientv3roomsroomidleave)
uses, allowing a client to leave an invited room. Problem is when you
call this API twice:
- On the first `/leave`, our current local membership is "invite", so it
will do the `/make_leave` dance (or generate the leave itself if the
remote can't be reached), and then update our current local membership
to "leave" and store that leave event also out of band
- On the second `/leave`, our current local membership is "leave", so it
will try to build that event regularly, but is missing forward
extremities to do so
The reason clients call `/leave` twice is that they miss the leave event
in some circumstances, which will be addressed in other PRs.
But the "double leave" issue was always a problem. This *technically*
addresses https://github.com/element-hq/synapse/issues/18473 and
https://github.com/element-hq/synapse/issues/19485 by not making those
`/leave` return a 500, but the real problem is the leave event not going
down to clients.
This does two things, in two separate commits:
- first a safeguard: in a room we are not in and have no forward
extremities for, any membership change that isn't one of the special
cases gets a 403 because you're "not in the room" instead of a 500
- then replicate what we do normally which is to deduplicate the event
for identical `/leave` when the leave is stored OOB
#20503 is stacked on top of this PR because it makes a new case
reachable (a local user banned in a room we are not in), where `/leave`
would hit the same 500 without the safeguard here.
<details>
<summary>Original PR description from Claude Code 🤖</summary>
A user rejects a remote invite while the inviting server can't be
reached, or rescinds a knock. Synapse generates a local out-of-band
leave, stores it as an outlier and records it in
`local_current_membership`. If the user then calls `/leave` again
(clients do when they did not see the first leave; #20438 is one such
case), `update_membership_locked` finds no prev events for the room, the
LEAVE branch has no arm for a current membership of `leave`, and
`create_new_client_event` fails its "no prev_events" assertion with a
500. `/invite`, `/ban` and `/kick` in such a room hit the same
assertion. This is a few hundred 500s a day on matrix.org, mostly people
rejecting spam invites from servers that no longer answer. Reported as
#18473, #19485 and #18003.
When the server is not in the room and the room has no forward
extremities, an identical leave (same sender, same content) now returns
the existing event, as `deduplicate_state_event` does in a room the
server is in. Any other membership change there gets a 403
(`M_FORBIDDEN`, or `M_NOT_JOINED` with MSC3848) before an event is
built: a leave with different content, a leave by a banned user, and
`/invite`, `/ban` or `/kick`. That is the error the auth rules give a
sender who is not in the room. A room the server has left but still
holds forward extremities for keeps taking the existing path, which
already answers through the deduplication and the auth rules. Rooms
whose extremities `delete_old_current_state_events` removed are covered
too.
The leave is still not sent to the remote server, and it is still
invisible to clients; #20438 is for the latter.
Tests in `tests/handlers/test_room_member.py`: a repeat leave after a
failed invite rejection (the same event comes back, different content
gets a 403), and an invite, ban and kick in that room. All of them fail
with the assertion on develop.
#20503 is stacked on this. #20444 adds a `BAN` arm to the same branch
and will need a rebase.
https://claude.ai/code/session_01Usuxv8JofVGciXVtxbdTtr
</details>
---------
Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
Spawning from making a commit to the changelog while waiting for the CI
actions to finish and then when the upload step came up, it failed
because it expected the tag commit to be the `HEAD` commit.
```shell
$ poetry run ./scripts-dev/release.py full --gh-token $(pass show element.io/synapse_release_process_github_personal_access_token | head -n 1)
...
*** wait for actions ***
Workflows successful. You can now continue the release.
*** publish ***
Publish release v1.165.0 on GitHub? [Y/n]:
*** upload ***
Tag v1.165.0 (0adca7d1f7) is not currently checked out!
Aborted!
```
This check doesn't seem to protect us from anything as we don't interact
with the repo at this stage. This step simply gets the current version
from the current local package metadata, downloads from the associated
GitHub release, and uploads to the associated PyPI version.
Fixes the portdb CI job.
The portdb job fails since the `postgres:14` and `postgres:17` images
moved to the November minor releases. Those servers set a `pg_attver`
option on every column. An older `pg_dump` writes these out, and the
values differ between the two databases. The final diff in
test_synapse_port_db.sh is then never empty.
Newer versions of `pg_dump` skip these.
e.g. (from
https://github.com/element-hq/synapse/actions/runs/43429570465/job/131901164169):
```
-ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN lock_name SET (pg_attver=90372280);
-ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN lock_key SET (pg_attver=90372280);
-ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN write_lock SET (pg_attver=90372280);
-ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN token SET (pg_attver=90372280);
+ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN lock_name SET (pg_attver=81324360);
+ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN lock_key SET (pg_attver=81324360);
+ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN write_lock SET (pg_attver=81324360);
+ALTER TABLE ONLY public.worker_read_write_locks_mode ALTER COLUMN token SET (pg_attver=81324360);
```
Fixes#19561
`GET /_synapse/admin/v1/statistics/database/rooms` returns a 500 when
`pg_stats` has no common `room_id` values for one of the tables it
checks. This happens in two cases:
- The table is empty or not yet analyzed, so `pg_stats` has no row for
it.
- No value is more common than the others, so `most_common_vals` is
`NULL`. `event_edges.room_id` hits this on servers where all rows were
written after schema 72 stopped filling the column.
The change skips the table in both cases, since it adds nothing to the
estimate.
Thanks to @christianarielli for finding the cause and suggesting the
fix. They're credited as co-author on the commit.
The new test runs only on Postgres, as the endpoint doesn't support
SQLite. It creates a room, runs `ANALYZE` while `event_push_actions` is
empty and `event_edges.room_id` is all `NULL`, and checks for a 200 with
the room listed. I ran it against Postgres 17.
`event_edges.room_id` isn't written any more, so dropping that table
from the list might make sense. I left that out to keep this PR small.
### Pull Request Checklist
<!-- Please read
https://element-hq.github.io/synapse/latest/development/contributing_guide.html
before submitting your pull request -->
* [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:
- Be a short description of your change which makes sense to users.
"Fixed a bug that prevented receiving messages from other servers."
instead of "Moved X method from `EventStore` to `EventWorkerStore`.".
- Use markdown where necessary, mostly for `code blocks`.
- End with either a period (.) or an exclamation mark (!).
- Start with a capital letter.
- Feel free to credit yourself, by adding a sentence "Contributed by
@github_username." or "Contributed by [Your Name]." to the end of the
entry.
* [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: Christian Arielli <903609+christianarielli@users.noreply.github.com>
Co-authored-by: Eric Eastwood <erice@element.io>
This is something that came up during the Rust spike, where running lots
of unit tests in parallel used lots of memory.
This is primarily due to a) `HomeServer` object having circular
references during tests, and b) us not doing full GC all the time.
The fix is to ensure that we drop references to the `HomeServer` at the
end of each test (or only keep weakrefs around), so that the GC-0
collection we run at the end of each test correctly cleans it up.
Requires https://github.com/element-hq/synapse/pull/20512 to fully clean
everything up.
This fixes the test `ThreadedMemoryReactorClock` to support
`removeSystemEventTrigger`, which in turn allows the shutdown triggers
to run when `HomeServer.shutdown()` is called in the tests. Previously,
`ThreadedMemoryReactorClock.removeSystemEventTrigger` raised a
`NotImplementedError`,
`cleanup_test_reactor_system_event_triggers` cleared the triggers by
hand so that a homeserver could be garbage collected. `shutdown()` now
removes them itself, so the helper goes.
We can also remove all the `tearDown` implementations that tried to
manually trigger the shutdown as its not longer necessary to do so
manually. They also didn't work, as they indexed `reactor.triggers` as
`[eventType][phase]` when the keys are `[phase][eventType]`
The default statistics for `device_lists_changes_in_room` were often
wrong, underestimating the number of distinct values of `room_id` and
`stream_id` columns. This meant in Postgres 18 that it used the wrong
index, leading to large amounts of IO.
In Postgres 18 the query planner now supports "skip scans", which means
more of the indexes are available to be used, and thus makes it more
important to have accurate statistics.
The problematic query was operating on an array of room IDs and a range
of stream IDs. Previously, it would use the index on `(room_id,
stream_id)`. After upgrade, it started using `(stream_id, room_id)` on
the assumption that we were matching the majority of all rooms and thus
may as well pull out all rows matching the stream ID range.
Fixes#20035
`_MultipartParserProtocol` assigned each `on_header_field` /
`on_header_value` / `on_part_data` value instead of accumulating it.
python-multipart calls these once per `dataReceived` chunk, so any
header name, header value or JSON part split across two chunks kept only
its last piece. A long `Location` in a federated media redirect was the
visible case: the truncated URL had no host and `get_file` failed with
`TypeError`.
The protocol now buffers header names, header values and the JSON part
in `bytearray`s and acts on them in `on_header_end` / `on_part_end`,
with a part counter replacing the `in_json` / `json_done` / `in_*`
flags. The file part still streams straight to the output stream, and
the existing `max_length` check still bounds everything that gets
buffered.
The new tests parse a file response and a redirect response split at
every byte offset, and byte by byte, and check the result matches the
unsplit parse. Before the fix, 100 and 115 split offsets respectively
produced a wrong result.
### Pull Request Checklist
<!-- Please read
https://element-hq.github.io/synapse/latest/development/contributing_guide.html
before submitting your pull request -->
* [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:
- Be a short description of your change which makes sense to users.
"Fixed a bug that prevented receiving messages from other servers."
instead of "Moved X method from `EventStore` to `EventWorkerStore`.".
- Use markdown where necessary, mostly for `code blocks`.
- End with either a period (.) or an exclamation mark (!).
- Start with a capital letter.
- Feel free to credit yourself, by adding a sentence "Contributed by
@github_username." or "Contributed by [Your Name]." to the end of the
entry.
* [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))
---------
Signed-off-by: Ankit Jha <ankit.jha@tradomate.one>
Signed-off-by: Ankit Jha <jhaankit373@gmail.com>
`DeviceHandler.get_user_ids_changed`, which the sliding sync e2ee
extension and `GET /keys/changes` use, adds a member to
`newly_joined_or_invited_or_knocked_users` only when the previous
membership was none of join, invite or knock. A user going from invite
to join is skipped, so other members are never told to refresh the
devices of a user whose device list changed while they were only
invited. Classic sync does report them.
A change to join from any membership other than join is now counted.
join -> join (a profile change) is still ignored.
`test_extension_e2ee.py` covers invite -> join, invite -> join -> leave
in one window and a profile change, `test_keys.py` covers invite -> join
through `/keys/changes`. Not covered: device list changes made while a
user is only invited (#3504), which are still not announced until the
user joins.
Fixes#20486
Follows on from #20289 and #20433. Properly fixes handling of concurrent
requests (on single workers).
This tries to fix two cases:
1. We are *computing* responses for multiple syncs at the same time,
which currently causes the cache to get cross-contaminated.
2. Two syncs concurrent syncs on the wire (but don't overlap during
processing). When the second request is processed we correctly forget
any entries from the first request, however we currently still update
the cache with members returned on the second request. However, there is
no guarantee that the second request is what the client actually reads.
We use three rules to handle concurrent requests:
1. A response only uses cached members recorded at or before the
request's `since`. Members recorded after it cannot be from an ancestor
sync response.
2. Once a response has been built, we forget all already cached members
recorded after its `since`. This handles the client reusing an older
`since` token. Doing it at the end of the build rather than the start
also forgets members recorded by responses built at the same time.
3. We track the highest position seen for the device (`_newest`), from
the `since` of each request and the `next_batch` of each built response.
A response only records its members if its `next_batch` is after that
position. This handles responses that end at the same position, or that
finish out of order.
With these rules, when concurrent requests happen we throw away all
existing cached members and don't record any further members until one
sync has advanced sufficiently such that there are no longer any
concurrent sync requests.
Note that ideally we'd have some sort of per-connection identity so that
we can track this properly (like in sliding sync). However, that is a
bigger change. Instead, we note that we just need to detect concurrent
requests, and not update the cache in those cases.
Also note, can only detect concurrent requests that go to the same
worker.
Fixes#17480
Once `RemoteHandler` is connected, `whenConnected` returns a Deferred
that has already fired, so `writer` runs synchronously inside
`addCallbacks` and clears `_connection_waiter`. The next line then set
the waiter to that fired Deferred, so every later `_connect` call
returned early and logs stopped after the first line or two.
This sets the waiter before adding the callbacks, so a callback that
runs right away can still clear it. The new test logs a few more lines
over an existing connection and checks that they all arrive.
The bug came in with #9591, hence v1.30.0 in the changelog.
Thanks to @haarp for tracking this down and for the detailed
reproduction steps.
### Pull Request Checklist
<!-- Please read
https://element-hq.github.io/synapse/latest/development/contributing_guide.html
before submitting your pull request -->
* [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:
- Be a short description of your change which makes sense to users.
"Fixed a bug that prevented receiving messages from other servers."
instead of "Moved X method from `EventStore` to `EventWorkerStore`.".
- Use markdown where necessary, mostly for `code blocks`.
- End with either a period (.) or an exclamation mark (!).
- Start with a capital letter.
- Feel free to credit yourself, by adding a sentence "Contributed by
@github_username." or "Contributed by [Your Name]." to the end of the
entry.
* [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))
`refresh_certificate` used to build a new `ServerContextFactory` on
every SIGHUP and then replace the factory on each listening port with a
fresh `TLSMemoryBIOFactory` wrapping the new one, reaching into the
port's `factory` attribute to do so.
Twisted asks the context factory for a context on every new connection,
so rebuilding the `SSL.Context` inside the existing factory is enough
for new connections to pick up the new certificate. `start()` now builds
the factory once, and `refresh_certificate` is only the SIGHUP handler.
This is spawning of #20452: Twisted 26.10 annotates `tcp.Port.factory`
as `Factory | None`, and mypy does not accept a `TLSMemoryBIOFactory`
there because its protocol type parameter does not match, so the old
assignment no longer type-checks. The change removes the assignment
rather than suppressing the error.
Verified with trial against Twisted 23.8.0 (our minimum declared dep),
26.4.0 (the current version in the lockfile) and 26.10.0 (the next
version), and with mypy against 26.4.0 and 26.10.0.
Bumps [pyasn1](https://github.com/pyasn1/pyasn1) from 0.6.4 to 0.6.5.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/pyasn1/pyasn1/releases">pyasn1's
releases</a>.</em></p>
<blockquote>
<h2>Release 0.6.5</h2>
<h2>Revision 0.6.5, released 26-10-2026</h2>
<ul>
<li>GHSA-mm57-4v3p-rchx: Decoded binary REAL mantissas in linear time
instead of repeatedly shifting a growing integer and slicing the
remaining bytes (thanks for reporting, manus-use, manus-pi, ucsurf,
adriank31)</li>
<li>GHSA-2qm8-x737-gmw5: Reassembled constructed BIT STRING fragments
in linear time while preserving their decoded bit values, including
intermediate fragment padding (thanks for reporting, manus-use)</li>
<li>GHSA-9m75-vc3g-4x39: Reassembled constructed OCTET STRING and
character-string fragments and indefinite-length ANY content in
linear time. Nested constructed OCTET STRING fragments now contribute
their decoded octets (thanks for reporting, alimony, manus-pi,
adriank31)</li>
<li>GHSA-fm9c-5rcf-2q5p: Bounded schemaless container type tracking
after two distinct tag sets to prevent quadratic CPU use from
colliding long tag IDs (thanks for reporting, droideck)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/pyasn1/pyasn1/blob/main/CHANGES.rst">pyasn1's
changelog</a>.</em></p>
<blockquote>
<h2>Revision 0.6.5, released 26-10-2026</h2>
<ul>
<li>GHSA-mm57-4v3p-rchx: Decoded binary REAL mantissas in linear time
instead of repeatedly shifting a growing integer and slicing the
remaining bytes (thanks for reporting, manus-use, manus-pi, ucsurf,
adriank31)</li>
<li>GHSA-2qm8-x737-gmw5: Reassembled constructed BIT STRING fragments
in linear time while preserving their decoded bit values, including
intermediate fragment padding (thanks for reporting, manus-use)</li>
<li>GHSA-9m75-vc3g-4x39: Reassembled constructed OCTET STRING and
character-string fragments and indefinite-length ANY content in
linear time. Nested constructed OCTET STRING fragments now contribute
their decoded octets (thanks for reporting, alimony, manus-pi,
adriank31)</li>
<li>GHSA-fm9c-5rcf-2q5p: Bounded schemaless container type tracking
after two distinct tag sets to prevent quadratic CPU use from
colliding long tag IDs (thanks for reporting, droideck)</li>
</ul>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/pyasn1/pyasn1/commit/5d1673657b729fb580467e2cf4875856bbca5e59"><code>5d16736</code></a>
Prepare release 0.6.5</li>
<li><a
href="https://github.com/pyasn1/pyasn1/commit/a36e3a3d067148d26197a6b7221fd0e2cde9cc86"><code>a36e3a3</code></a>
Fix quadratic CPU use in schemaless container decoding</li>
<li><a
href="https://github.com/pyasn1/pyasn1/commit/4ce00797c594b59c1fd6b86d9ebc3ba87b7ec9f9"><code>4ce0079</code></a>
Remove quadratic constructed OCTET STRING and ANY reassembly</li>
<li><a
href="https://github.com/pyasn1/pyasn1/commit/73ba7b043cc7e92cb37f16f2c955bff93b0e6f6c"><code>73ba7b0</code></a>
Remove quadratic constructed BIT STRING reassembly</li>
<li><a
href="https://github.com/pyasn1/pyasn1/commit/ce3ec3390784780a530047e0e77be5ff457636a4"><code>ce3ec33</code></a>
Remove quadratic binary REAL mantissa decoding</li>
<li>See full diff in <a
href="https://github.com/pyasn1/pyasn1/compare/v0.6.4...v0.6.5">compare
view</a></li>
</ul>
</details>
<br />
[](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores)
Dependabot will resolve any conflicts with this PR as long as you don't
alter it yourself. You can also trigger a rebase manually by commenting
`@dependabot rebase`.
[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)
---
<details>
<summary>Dependabot commands and options</summary>
<br />
You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)
You can disable automated security fix PRs for this repo from the
[Security Alerts
page](https://github.com/element-hq/synapse/network/alerts).
</details>
Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Reloading the log config on SIGHUP writes every record back into
Twisted's logging. `redirect_stdio_to_logs()` replaces `sys.stderr` with
a `LoggingFile` after startup, and `_load_logging_config` then rebuilds
`StreamHandler`s on it, so records hit the `logging during logging`
guard in `one_time_logging_setup` and JSON lines get wrapped a second
time.
`dictConfig` now runs with `sys.__stdout__` and `sys.__stderr__` swapped
in, and the redirected streams are put back afterwards, including when
the config is invalid. `tests/config/test_logger.py` covers both. Not
covered: Windows and configs that use a `FileHandler`.
Fixes#20091
### 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).
* [x] [Code
style](https://element-hq.github.io/synapse/latest/code_style.html) is
correct (ruff check, ruff format and mypy run on the changed files)
Adds a `synapse_thread_cpu_seconds_total{thread_type, mode}` metric,
grouping threads into:
1. the `main` thread
2. each registered threadpool (`threadpool_*`)
3. `tokio`
4. `other`
The kernel only reports CPU time for live threads, so the collector sums
per-thread deltas between scrapes. A thread that exits loses the CPU it
used since the last scrape.
This is primarily useful for seeing how busy the main thread is vs other
ones.
Fixes#18885.
The "Override ratelimiting for users" section of the user admin API docs
described `messages_per_second` as "the number of actions that can be
performed in a second", which suggests the override applies to every
ratelimiter. In the code (`synapse/api/ratelimiting.py`) the override's
rate/burst values are only used by the event-sending ratelimiter
(`RequestRatelimiter.ratelimit`, i.e. `rc_message`); the generic
`Ratelimiter.can_do_action` only reads the override to check whether
`messages_per_second` is `0` and, if so, disables ratelimiting entirely
for that user.
Changes (docs only):
- State up front that the override replaces only the message-sending
limits (`rc_message`), not `rc_invites`/`rc_joins`/`rc_login` etc., and
that `messages_per_second = 0` disables all ratelimiting.
- Rename the sub-headings to "Get status of / Set / Delete ratelimit
**override**" and describe the fields as messages rather than actions.
- Explain that "Delete ratelimit override" restores the global config
limits rather than disabling ratelimiting.
The `#override-ratelimiting-for-users` anchor referenced elsewhere in
the page is unchanged.
Verified with `mdbook build` (mdbook 0.5.2, same as `docs-pr.yaml`):
renders cleanly, new anchors `#get-status-of-ratelimit-override`,
`#set-ratelimit-override`, `#delete-ratelimit-override` present.
### Pull Request Checklist
A notary key query that leaves out minimum_valid_until_ts is rejected
with errcode M_MISSING_PARAM and an error naming that field as required.
Callers that follow the server-server API, where the timestamp is
optional and the server is supposed to use the current time, cannot
complete the query. The criteria model typed minimum_valid_until_ts as
an integer or null but gave it no default, so validation treated the
field as required and failed before the query ran.
An explicit null was already a separate accepted value, used for
half-lifetime cache behaviour, and was not the same as omitting the
field.
The field now defaults to null, so an omitted timestamp validates. After
parsing, each key whose criteria did not include the field is replaced
with a copy that sets minimum_valid_until_ts to the current time in
milliseconds. Explicit null is left unchanged, and an empty key-id map
is left unchanged so a request for every cached key still ignores
validity. Tests cover the omitted timestamp against cache lifetime,
mixed criteria including zero and null, non-integer timestamps, and a
body without server_keys, and a bugfix newsfragment records the default.
Ran `python3 -m pytest -q tests/rest/key/v2/test_remote_key_resource.py`
in a Linux container (`python:3.12`) for the synapse RemoteKey change; 7
tests passed.
The tests in `tests/rest/key/v2/test_remote_key_resource.py` fail
without the fix in the synapse RemoteKey change (checked by reverting
the source changes).
Fixes#20466
---------
Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com>
This PR should be reviewable on a commit-by-commit basis. If you would
prefer that it is broken down into multiple PRs then I can do so.
Fixes to match latest MSC4388:
- Return `200` with `create_available=false` for `GET` when configured
in `authenticated` mode and no access token presented
- Return `401` for a `GET` where an invalid/expired token is presented
- Return `404` for `DELETE` where session has expired but not yet
evicted
Features:
- Rate limiting which is configurable via
`experimental_features.msc4388_rc_create` (for `POST` and is per
requester for authenticated requests or per client IP for
unauthenticated requests) and
`experimental_features.msc4388_rc_requests` (for `GET`/`PUT`/`DELETE`).
- Allow the session TTL to be configured via the
`experimental_features.msc4388_session_ttl`. As per spec this is between
2 and 5 minutes.
- Concurrent sessions are unlimited for authenticated requesters
(subject to the rate limits).
- Unauthenticated requesters have a maximum concurrent sessions limit
(default 1,000) which is configurable by
`experimental_features.msc4388_max_unauthenticated_sessions`.
Misc:
- Code and comment cleanup
The experimental feature is tracked by
https://github.com/element-hq/synapse/issues/19433 and I will update it
with the new config options when this PR merges.
Fix a bug introduced in Synapse v1.146.0 where failed remote media
downloads and URL previews would leave behind empty files in the media
store.
Regressed in #19204 which restructured
`MediaStorage.store_into_file(...)` to support running without a local
media store. As part of that, the `yield` (where the caller writes into
the file) was moved outside of the `try`/`except` that cleans up the
file on failure. Since `store_into_file(...)` is an
`asynccontextmanager`, an exception raised by the caller is thrown back
in at the `yield`, so it now bypasses the cleanup entirely.
This means any failed remote media download leaves a zero-byte file in
`remote_content/` (and similarly `url_cache/` for URL previews) without
a corresponding database row. Most of these fail before a single byte is
written, for example `NotRetryingDestination` while a remote server is
backed off, which fails instantly without any network request. Media
retention works from the database so it never cleans these up, and
because each attempt uses a fresh `filesystem_id`, clients repeatedly
requesting media (e.g. avatars of members on dead servers) keep
accumulating new ones. On a small homeserver, this added up to ~6000
orphaned files (and ~36000 directories) since upgrading to v1.146.0.
This PR moves the `yield` back inside the `try` (as it was before
#19204) so the file is removed again on failure. This applies to both
the local media store and the temporary file used when
`enable_local_media_storage` is disabled.
### Dev notes
To find orphaned files on an affected homeserver (zero-byte files with
no matching `remote_media_cache` row):
```shell
find /path/to/media_store/remote_content /path/to/media_store/url_cache -type f -size 0
```
Any of these without a matching row in `remote_media_cache` (or
`local_media_repository` for `url_cache/`) are orphans and safe to
delete, along with any empty directories left behind.