Commit Graph
25915 Commits
Author SHA1 Message Date
3f032ebb1a Map Postgres errors onto a DBAPI2 exception hierarchy
Previously every `tokio_postgres` error became a bare `RuntimeError`. Synapse's
transaction driver, though, branches on the *type* of a database error and on
its `pgcode`: `new_transaction` retries `OperationalError`, retries deadlocks it
recognises via `is_deadlock` (which reads `pgcode`) on a `DatabaseError`, and
`simple_upsert` retries `IntegrityError`. With everything collapsed to
`RuntimeError` none of that fired.

Add just the distinctions Synapse acts on, rather than psycopg2's full PEP-249
hierarchy: `Error` -> `DatabaseError` -> {`OperationalError`, `IntegrityError`},
exposed on the `postgres` submodule, each instance tagged with `pgcode` (the
SQLSTATE string, or `None`). A small classifier maps the SQLSTATE class:
constraint violations (`23`) to `IntegrityError`, connection/resource classes
(`08`/`53`/`57`/`58`) to `OperationalError`, everything else (incl. `40*`
deadlocks, which retry via `pgcode`) to `DatabaseError`. Codeless errors are
split with `is_closed()`: a lost connection is operational, any other (a bad
parameter, a failed connect) is a plain `DatabaseError` so it isn't retried.

Errors surfacing while a result stream is drained (the usual case for an
`INSERT` constraint violation) now route through the same mapping, so they carry
the right class and `pgcode` too.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
Erik Johnston a2a994e0fd Newsfile 2026-07-24 12:42:05 +01:00
82841cb702 Add integration tests for the Rust Postgres backend
Add the end-to-end test suite for the Rust DBAPI2 backend, driving the real
tokio-postgres client against a live Postgres server. It is skipped unless
the suite is configured for Postgres (SYNAPSE_POSTGRES), the same switch the
rest of the suite uses.

These cover the behaviours that need a real server rather than the
in-memory fakes the Rust unit tests use: connect (good and bad DSN),
run_interaction (return value, arg/kwarg forwarding, commit on success,
rollback on a Python exception, and recovery after both a Python-raised and
a server-rejected statement, including a constraint violation), cursor
reuse across queries, the fetch_one/fetch_all/fetch_next_batch/rowcount
surface (including batching across a 1000-row result set and the
exhausted-vs-no-active-query error distinction), and value round-trips for
every supported type (NULL, bytea with NUL/high bytes, float4 lossiness,
and an out-of-range int bound to a real int4 column).

A separately-guarded case exercises the libpq default-host fixup by
connecting with a DSN that omits the host.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
Erik Johnston 6db431c358 Newsfile 2026-07-24 12:42:05 +01:00
9d55966082 Use libpq's default host when the DSN omits one
`tokio_postgres` and libpq disagree on the default host when a DSN gives
no `host=`: tokio-postgres falls back to localhost, whereas libpq (which
`psql` and the rest of Synapse use) applies its configurable compiled-in
default — typically the Unix socket directory — and honours `PGHOST`.

To keep Synapse's existing connection behaviour, `connect()` now runs the
DSN through `fixup_default_host`: if the parsed config has neither a host
nor a hostaddr, it asks libpq what its default would be (via
`PQconnectStart` on an empty conninfo, which applies libpq's defaults/env
without opening a socket) and sets that on the tokio-postgres config.

The libpq call lives in a small hand-written safe wrapper
(`database::postgres::libpq`) over the `pq-sys` crate. pq-sys ships
pre-generated bindings and links the system libpq itself, so — unlike a
bindgen-based binding crate — this needs no libclang to build. The
behaviour is exercised by the Python integration tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
17fe3d25c1 Add Postgres Connection/Cursor types and connect()
Add the Python-facing `Connection` / `Cursor` pair and the `connect`
factory, implementing enough of the PEP-249 (DBAPI2) shape for Synapse's
needs.

A `Connection` owns a single `tokio_postgres::Client`. The client *moves*
between the connection and an in-flight cursor rather than being shared:
it lives in the connection between interactions, is taken out for the
duration of a cursor, and is handed back when the cursor finishes. That
single-owner baton (an `Option<Client>` slot on each side) makes it
structurally impossible to use the connection mid-transaction or to run
two overlapping transactions on one socket — both become a clean "already
closed" error.

The transaction lifecycle (`cursor` opens with `BEGIN`; `finish`
COMMIT/ROLLBACKs and hands the client back; `CursorGuard` rolls back an
abandoned transaction on drop) is included here. On any
transaction-control error the client is dropped rather than returned,
closing the socket — safer than handing a possibly-broken connection back
to what will become a connection pool.

`connect()` parses a libpq-style DSN, blocks until connected, and spawns
the long-lived connection task onto the shared runtime (the libpq
default-host fixup is a follow-up). The cursor query methods
(`execute` / `fetch_one` / `fetch_all` / `fetch_next_batch` / `rowcount`)
delegate to the `CursorQueryState` machine.

`run_interaction` — the high-level glue that opens a cursor, runs the
callback, and commits/rolls back — follows in the next change, so
`cursor`/`finish`/`CursorGuard` carry a transitional `#[allow(dead_code)]`
until then. Now that the value/helpers/cursor_state modules are consumed
internally, their visibility is tightened from `pub` back to private.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
Erik Johnston 348608f068 Newsfile 2026-07-24 12:42:05 +01:00
70aad71c4a Add fetch_next_batch to the cursor state machine
Add a batched fetch alongside `fetch_one`/`fetch_all`: it blocks for the
first row, then scoops up any further rows that are already buffered
without blocking again, returning them as one batch. This lets Python
iterate large result sets without the per-row overhead of `fetch_one`,
while still not blocking on the whole result set like `fetch_all`.

Exhaustion is reported by an empty batch, and deliberately deferred: a
batch that runs into the end of the stream still returns the rows it has
and leaves the empty-batch report (and the move to `Closed`) to the next
call. The fused stream makes that re-poll safe.

Unit tests use the in-memory fakes from the previous change, plus a new
`SteppedStream` that can report "not ready yet" mid-stream, so the partial
-batch boundary, the deferred empty report, the capacity-is-a-hint
behaviour, interleaving with `fetch_one`, and the mid-batch error path are
all covered without a live database.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
d72a30ccab Add CursorQueryState result-set state machine
Model the lifecycle of a cursor's most recent query as an explicit state
machine (Idle / Active / Closed) so that illegal field combinations are
unrepresentable and fetching past the end of a result set is a clean,
specific error rather than the spurious "connection closed" you get from
re-polling a finished stream. The row stream is fused so an
exhausted-but-not-yet-reported stream can sit safely in `Active`.

This change adds `fetch_one`, `fetch_all` and `rowcount` (the batched
`fetch_next_batch` follows separately). On a stream error a cursor resets
to `Idle`; on normal exhaustion it moves to `Closed`, retaining the
PEP-249 rowcount from the command tag.

The state machine is generic over the stream type, defaulting to
`RowStream`, via a small `CursorRowStream` trait that abstracts the three
things the logic needs (the affected-row count, row->PyTuple conversion,
and error rendering). This is what lets the state transitions, exhaustion
handling and error recovery be unit-tested against an in-memory fake
stream, with no live Postgres server.

`cursor_state` is `pub` for now so its not-yet-consumed items don't trip
clippy's dead_code lint; the connection code wires it up and tightens that
later.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 12:42:05 +01:00
Erik Johnston 32f2c9e22c Newsfile 2026-07-24 12:23:57 +01:00
f5496f47e1 Add GIL-releasing block_on helpers on the shared tokio runtime
Add the `block_on`/`block_on_result`/`block_on_next` helpers the Postgres
backend uses to drive its async `tokio-postgres` futures to completion from
sync, GIL-holding Python methods, releasing the GIL for the wait. They take
a `tokio::runtime::Handle` and block on it from the calling (Python) thread.

Rather than give the DB backend a runtime of its own, they use the
extension's existing shared runtime (`tokio_runtime::PyTokioRuntime`, stored
on the reactor). `start` is made idempotent and a `runtime_handle` accessor
starts it on demand, so a caller that needs a connection before the reactor
is running still gets a handle; once the reactor runs, its
`callWhenRunning(start)` hook is a no-op.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RPEeXx2fAG67o6u4CnmC8W
2026-07-24 12:21:55 +01:00
f54233a526 Add Postgres value mapping for the Rust database backend
Introduce the Python<->Postgres value-mapping layer that the forthcoming
Rust DBAPI2 backend will build on, plus the module scaffolding to hang it
off (`synapse_rust.database.postgres`).

`PgValue` is an owned representation of a bound parameter that implements
`tokio_postgres::types::ToSql`, encoding into Postgres' binary wire format
according to the column type from the prepared statement (so a single
Python `int` becomes INT2/INT4/INT8 as appropriate, with range checks).
`PythonPgFromSql` is the decode counterpart, turning a column's wire bytes
back into the natural Python object (and SQL NULL into `None`). The two
`accepts` lists are kept in sync via tests.

The `value` submodule is exposed as `pub` for now so its
not-yet-consumed public items don't trip clippy's `dead_code` lint; later
changes that wire it into the cursor/connection code tighten that back up.

Covers int / float / bool / str / bytes / None; lists and richer types
(json, decimal, timestamps) are left to a follow-up.

The unit tests exercise the whole mapping without a live Postgres server,
including the float4 lossy narrowing, integer width boundaries, the
WrongType and out-of-range paths, and the unsupported/non-UTF-8 decode
errors.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-24 11:54:28 +01:00
dependabot[bot]andGitHub a58ad44eb0 Bump the minor-and-patches group with 5 updates (#19982)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 09:23:18 +00:00
dependabot[bot]andGitHub eaba03b577 Bump pillow from 12.2.0 to 12.3.0 (#19983)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 09:21:30 +00:00
dependabot[bot]andGitHub c39c92e9c9 Bump setuptools from 82.0.0 to 83.0.0 (#19988)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 09:20:15 +00:00
dependabot[bot]andGitHub bdd53836ef Bump gitpython from 3.1.50 to 3.1.52 (#19990)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 09:19:25 +00:00
dependabot[bot]andGitHub 444564f0be Bump pyasn1 from 0.6.3 to 0.6.4 (#19989)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-24 09:10:04 +00:00
343581a1a0 fixes related to room v12 and sytest (#19898)
Co-authored-by: Andrew Morgan <1342360+anoadragon453@users.noreply.github.com>
2026-07-23 11:13:21 +00:00
Eric Eastwood 01ef46f95d Merge branch 'master' into develop 2026-07-22 13:57:25 -05:00
Eric Eastwood 2b5a0623ba 1.157.1 v1.157.1 2026-07-22 09:31:47 -05:00
Eric EastwoodandGitHub 7cb94ab266 Fix config regression around falsy experimental_features (None) (#19987)
Fix https://github.com/element-hq/synapse/issues/19986

Regressed in https://github.com/element-hq/synapse/pull/19539
2026-07-22 09:07:29 -05:00
Eric Eastwood 3622579e7b Merge branch 'master' into develop 2026-07-21 10:52:42 -05:00
Eric Eastwood e0f251ce2c 1.157.0 v1.157.0 2026-07-21 10:21:37 -05:00
夜坂雅andGitHub 5ed830b3b4 Change default room version to 11 (MSC4239) (#18680)
Fix #18530

Complement test changes: https://github.com/matrix-org/complement/pull/858

SyTest changes: https://github.com/matrix-org/sytest/pull/1422
2026-07-16 12:33:13 -05:00
Eric Eastwood 837d687977 Merge branch 'release-v1.157' into develop
Conflicts:
	scripts-dev/release.py
2026-07-15 12:02:47 -05:00
Eric EastwoodandGitHub d930ac615b Update release script JSON schema find/replace to be compatible with macOS (#19962)
BSD vs GNU `sed` problems:
```shell
$ sed -i '0,/^\$id: .*/s||$id: https://element-hq.github.io/synapse/schema/synapse/v1.157/synapse-config.schema.json|' schema/synapse-config.schema.yaml
sed: 1: "schema/synapse-config.s ...": bad flag in substitute command: 'h'
```
2026-07-15 12:01:09 -05:00
Eric EastwoodandGitHub 4679ed4b06 Silencing alerts is no longer necessary during a deploy (release script instructions) (#19968)
As discussed in
[`#element-backend-internal:matrix.org`](https://matrix.to/#/!SGNQGPGUwtcPBUotTL:matrix.org/$29ZzRe7gg62UZmT0bgeseMs320Kb-Ub6DyaQE20-3ng?via=jki.re&via=element.io&via=matrix.org)

Our assumptions on why this was done previously: in the olden days you'd
get paged doing the redeploy even if everything was actually fine
(probably before we started doing rolling restarts?)
2026-07-15 11:45:52 -05:00
catfromplan9andGitHub 30088f38c0 Implement support for generating animated thumbnails in the media thumbnailer (#18831)
Signed-off-by: cat <cat@plan9.rocks>
2026-07-15 15:37:09 +00:00
Eric Eastwood e1420becdd Linkify 'Redact events of a user' docs v1.157.0rc1 2026-07-15 09:56:19 -05:00
dependabot[bot]andGitHub 0512511f87 Bump anyhow from 1.0.102 to 1.0.103 in the patches group (#19952)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 11:25:46 +00:00
dependabot[bot]andGitHub ff4e9ec7a7 Bump the minor-and-patches group with 2 updates (#19953)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 11:24:15 +00:00
jakobrssandGitHub 243983e193 Clarified documentation for "List accounts" guests parameter (#19963) 2026-07-15 11:18:55 +00:00
Eric Eastwood 11b48cdbad Fix title case 2026-07-14 16:37:50 -05:00
Eric Eastwood f8c913c1c0 Call out upgrade notes 2026-07-14 16:32:17 -05:00
Eric Eastwood 72be9b5e17 1.157.0rc1 2026-07-14 16:20:56 -05:00
Eric Eastwood 651b44e0fc Update release script to be compatible with macOS
BSD vs GNU `sed` problems:
```
sed -i '0,/^\$id: .*/s||$id: https://element-hq.github.io/synapse/schema/synapse/v1.157/synapse-config.schema.json|' schema/synapse-config.schema.yaml
sed: 1: "schema/synapse-config.s ...": bad flag in substitute command: 'h'
```
2026-07-14 16:14:35 -05:00
dependabot[bot]andGitHub 1979fcca52 Bump actions/checkout from 6.0.3 to 7.0.0 (#19921)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 11:19:15 +00:00
Andrew MorganandGitHub 6bfec47c47 Revert "Fix flaky 3PID inhibit error unit tests" (#19916) 2026-07-14 09:46:28 +00:00
dependabot[bot]andGitHub ff7c3b9418 Bump actions/cache from 5.0.5 to 6.1.0 (#19920)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 09:25:28 +00:00
dependabot[bot]andGitHub 60aa4466c8 Bump the minor-and-patches group with 2 updates (#19919)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 09:25:07 +00:00
dependabot[bot]andGitHub 10f6370daf Bump bytes from 1.11.1 to 1.12.0 (#19918)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 09:24:39 +00:00
dependabot[bot]andGitHub 1b181ee813 Bump log from 0.4.32 to 0.4.33 in the patches group (#19917)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 09:24:11 +00:00
dependabot[bot]andGitHub aafb1fabcf Bump golang.org/x/crypto from 0.51.0 to 0.52.0 in /complement (#19925)
Signed-off-by: dependabot[bot] <support@github.com>
2026-07-14 09:04:15 +00:00
bf0f4f6a9d Support MSC4446: allow moving fully read markers backwards (#19663)
Co-authored-by: Andrew Morgan <1342360+anoadragon453@users.noreply.github.com>
2026-07-13 16:12:26 +00:00
WesselandGitHub c93d5230c0 Honor de.sorunome.msc2409.push_ephemeral flag in appservice handler (#19928) 2026-07-13 16:06:17 +00:00
Olivier 'reivilibreandGitHub 292bbb8f30 Fix a bug causing device list pruning to skip some rows when the transaction gets retried. (#19947)
Introduced in: #19473

Noticed in:
https://github.com/element-hq/synapse/pull/19556#discussion_r3505783541

I have not experienced the bug in the real world, it's just something I
noticed by reading.

--

Fix bug in `_prune_device_lists_changes_in_room` when transaction is
retried
The `nonlocal` variable is a footgun as it increments the counter even
though the transaction did not commit yet and may still be retried.

---------

Signed-off-by: Olivier 'reivilibre <oliverw@matrix.org>
2026-07-13 13:32:09 +01:00
SandroandGitHub 733620acd7 Fix SYNAPSE_ASYNC_IO_REACTOR=1 on Python 3.14 (#19949) 2026-07-13 09:39:56 +00:00
Erik JohnstonandGitHub be511b22a2 Send offline presence for stale states when presence is disabled (#19948)
If presence is disabled after having been enabled, the presence states
in the database (and hence on clients) are frozen at whatever they were
when presence was last enabled: nothing writes to the presence stream
any more and /sync omits the presence section entirely, so clients show
the old presence states forever.

Fix this in two parts:

1. At startup, if presence is disabled but the database still contains
non-offline presence states, the presence writer sends out one final
round of updates marking those users as offline.

2. /sync no longer unconditionally omits presence when presence is
disabled: incremental syncs whose since token is behind the presence
stream still get the straggling updates. As the stream doesn't advance
while presence is disabled, clients catch up once and the check then
short-circuits to a token comparison.

Remote servers already handle this themselves by timing out our users
([`FEDERATION_TIMEOUT`](https://github.com/element-hq/synapse/blob/4d8905a15a417ed0054ec2533d243932d890bbbd/synapse/handlers/presence.py#L194-L198)),
so no federation changes are needed.

Note that this only fixes the issue if presence is fully disabled. If
set to `untracked` we still have the same issue, however since modules
would still write to presence we can't just clobber everything like we
do in this patch.
2026-07-13 10:08:57 +01:00
0bd28389b1 Improve caching for presence (#19939)
This does two things, first it adds a config flag to ignore rooms for
the purposes of presence routing.

Secondly, it changes the caching behaviour to try and improve the cache
hit ratio. Previously, the size of the `do_users_share_a_room` cache
(which stores pairs of users) needs to `O(n²)` for the number of online
users, which is infeasible for large servers.

Instead, we call `get_users_in_room` for both the syncing and updated
users. This sounds more expensive, but a) we will already have cached
the syncing user's rooms, and b) we will only calculate the updated
user's rooms once (rather than once per syncing user).

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-13 09:34:07 +01:00
c0c2b37d5e MSC4140: update error responses (#19539)
- Impose limit of scheduled delayed events
- Update error codes to match latest draft of MSC4140 

---------

Co-authored-by: Eric Eastwood <madlittlemods@gmail.com>
2026-07-11 01:23:33 +00:00