One emitter now sends both Python's and Rust's spans to the Jaeger
agent. `init_tracer` sets the tracer up as before, with
`initialize_tracer` (its sampler, remote or not, its throttler, its
logging reporter, and the first-homeserver-wins guard), then swaps
jaeger-client's reporter for one whose `report_span` converts the
finished span into the Rust reporter's form, with the GIL held (a few
attribute reads), and queues it. The encoding and the UDP send happen
on the reporter thread, as for Rust's spans. Support for the external
`rust_python_jaeger_reporter` package is removed. If tracing in Rust
cannot start, jaeger-client's reporter stays.
The conversion follows jaeger-client's `make_jaeger_batch`, so the
datagrams are what jaeger-client sent, trace IDs from a remote context
wider than 128 bits included: a test encodes spans of every shape (all
tag types, logs, follows-from references, IDs at or above 2^63) both
ways and compares the bytes. A failure to convert is logged with its
traceback once, then at debug level.
One jaeger `PrometheusMetricsFactory` serves the process, as each
registers its metrics globally. jaeger-client's `reporter_*` options
and metrics no longer apply: the docs say what the Rust reporter does
instead. Tests run `init_tracer` and check that a Python span and a
Rust span under it arrive in one datagram, and that `logging: true`
keeps jaeger-client's logging reporter.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
Sliding sync requests computed in Rust now report spans under the
request's Python span, one per step the handler calls:
`sliding_sync.load_connection_state`, `sliding_sync.interested_rooms`,
`sliding_sync.room_entries` (with the room count), and
`sliding_sync.finish_request`. Inside the room entries, a
`sliding_sync.room` per room is tagged `room_id` and its `outcome`
(`entry`, `fallback` or `error`, marked with the `error` tag), with
that room's reads under it. `sliding_sync.encode` covers encoding the
rooms, which runs on a threadpool thread whose logcontext carries the
request's Python span (`encode_json_response`).
A trial test makes a sliding sync request over two rooms with tracing
on and checks that each step is under the servlet's Python span, that
each room is under `sliding_sync.room_entries`, and that the rooms'
reads are under them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
- `state.resolve` around a state resolution on the database, tagged
`room_id`, `state_sets` and, once done, the resolution's database and
auth chain time. It covers the handler's resolutions and the
persister's, under `persist.state_res`. A room without a chain cover
index is tagged `fallback`, not an error: the caller resolves its
state in Python.
- `events.load` around an event load, tagged with the number of events
asked for, `reload`, and on success how many this load read from the
database (`fetched`) and how many it did not (`cached`, which counts
events another load was already reading). Its `db.*` spans nest
under it.
- `outgoing-client-request` around a request of the Rust HTTP client
(MAS introspection), with the tags Python's `SimpleHttpClient` span
has: `span.kind`, `http.method`, `http.url` (without credentials or
query) and `http.status_code`. As in Python, an error status is the
caller's to judge, so only a failure to get a response is marked as
an error, before the conversion to a Python exception.
A trial test loads an uncached event with tracing on and checks that
`events.load` is under the caller's Python span, with the event fetched
and its reads under it. Rust tests check `state.resolve` on a failed
resolution and the HTTP client span against a local server.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
The legacy /sync work done in Rust now reports spans under the
request's Python span:
- `sync.room_changes`, working out which rooms changed;
- `sync.room_entries` (with the room count), and inside it a
`sync.room` per room, tagged `room_id` and its `outcome` (`entry`,
`fallback` to Python, or `error`, with the error as a log);
- `sync.encode` (with the room count), encoding the entries on the
reactor thread under the request's span.
The room spans are created in the task, so the per-room loop's ten
concurrent rooms each nest under `sync.room_entries`, and their
`db.*` spans under them.
A trial test syncs two rooms with tracing on and checks the tree that
reaches the agent: `sync.room_entries` under the servlet's Python span,
a `sync.room` per room with its reads under it, and `sync.encode` in
the same trace. The tracing set-up of the persist test moves to a base
class both share.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
The persister's entry points and stages now have spans, so the `db.*`
spans of the earlier commits nest under the step that made them:
- `persist.prepare_chunk` and `persist.write_chunk` (with `room_id`
and `events`), created in the functions both the chunk entry points
and the batch call, so they have them at every
`rust_event_persistence` level; `persist.batch_next`,
`persist.batch_abort` and `persist.update_current_state`;
- inside a prepare: `persist.state_delta` (which includes the
extremities), `persist.state_res` (with the resolution's total and
database time), `persist.chain_cover`, `persist.sliding_sync` and
`persist.sticky`;
- inside the write transaction: `persist.txn.read`,
`persist.txn.store_events`, `persist.txn.auth_chain`,
`persist.txn.metadata`, `persist.txn.current_state` and
`persist.txn.sliding_sync`. Most steps only queue their writes, so
their spans time the step's own work, and the writes are timed in
the next round trip's `db.query`.
The spans are created inside the task, so their parent is the Python
span active when the persist was started. `TxnTimings` stay as they
are: Python still needs them for its metrics, which are not sampled.
A trial test makes the test tracer the global one, as `init_tracer`
does, persists a message through the Rust persister and checks what
reaches the agent's UDP port: `persist.batch_next` under the persist
queue's Python span and in its trace, the chunk's steps under it, and
`persist.write_chunk` → `db.persist_events` → `db.connection` →
`db.txn`, with the transaction's steps and `db.query` round trips
carrying queued writes and the COMMIT under it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
Rust code now creates spans with the `tracing` crate.
`JaegerLayer` gives each span Jaeger IDs and reports sampled ones
through the homeserver's UDP reporter when they close.
A span's parent is its `tracing` parent, else (for a span with no
explicit parent) the Python span that was active when its task was
spawned, from the task's logcontext handle, else the Python span set
for the thread by `with_py_parent`. With no parent, the configured
`const` or `probabilistic` sampler decides, and a sampled root gets
jaeger-client's `sampler.type` and `sampler.param` tags. A child
copies its parent's trace ID, flags and baggage, so sampling is
decided once per trace and `force_tracing` carries over.
A span ends when it is last exited, or when it closes if it was never
entered. The registry keeps a parent open until its children close, so
its duration must not be taken at close. Work that outlives its parent
should start a trace with `parent: None` and `follows_from`.
Span fields become tags (strings cut to 1024 bytes, as jaeger-client
does), `otel.name` sets the operation name, and events inside a span
become logs. Only Synapse's own spans and events are recorded, not
those of hyper, h2 and other dependencies.
The layer is the process-wide subscriber. It reports to the first
homeserver that enables tracing until that homeserver shuts down or is
dropped. Spans are disabled while no reporter is attached, so they
cost almost nothing with tracing off.
`is_sampled`, `span_context`, `inject_headers` (`uber-trace-id` plus
`uberctx-*` baggage, as jaeger-client's HTTP codec writes them) and
`follows_from` are there for the instrumentation that follows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
`enable_tracing` now starts a reporter for the homeserver. A finished
span is queued on a bounded channel and dropped if the queue is full,
so reporting never blocks. A `jaeger-reporter` std thread encodes the
spans and sends them as `emitBatch` datagrams to the agent the Python
tracer uses. A batch goes when the next span would not fit in a 65000
byte datagram, at 100 spans, or a second after its first span. Every
batch carries the Python tracer's service name and process tags.
Like jaeger-client, the reporter sends from an unconnected socket and
resolves the agent's host name when it sends: again every 30 seconds
and after a failed send. A name that does not resolve at startup, or an
agent that moves, does not lose Rust spans for good, and an ICMP error
from a down agent cannot fail a later send.
Homeserver shutdown sends the queued spans, waiting up to a second.
The counters are exported as `synapse_rust_tracing_*` metrics, and a
changed send error is logged.
Nothing reports spans yet: the span API comes next.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
Rust work spawned from Python needs the caller's span as the parent of
the spans it will report. `LogContextHandle::capture` now reads the
active span's context (trace ID, span ID, flags, baggage) off the
logcontext's scope, but only once a homeserver has enabled tracing.
Otherwise a capture costs one relaxed atomic load. A capture inside a
task copies the task's handle, so the span stays the one the task was
spawned under.
The `_blocking` entry points ran their futures on the reactor thread
with no handle at all. They now go through
`RustRuntime.block_on_scoped`, which spawns the future with a captured
handle and blocks on the join, the same as `create_deferred`.
`init_tracer` hands the Jaeger tracer's service name, process tags,
agent address and sampler to `RustRuntime.enable_tracing`, which stores
them for the reporter that follows.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W4zxygfJC93SsugxskhoJG
A worker sending a new room's events to an event persister got the
persister's RoomIdCollisionError back as a plain 500. So createRoom did
not retry under a fresh ID, and did not move an alias it had created
off the room that owned the ID. The error now has the M_ROOM_IN_USE
errcode, and the sender raises RoomIdCollisionError again when it sees
it, as it does PartialStateConflictError for a 409.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Before the write: the sliding sync step's three reads of the room go
out together on one connection, and the relevant state is read once,
not twice; the chain cover step pairs its two input reads, and the
chains' sequence numbers with their links, which are read for the
chains known before allocation since new chains have none; the read of
rejected and soft failed prev events leaves out the chunk's accepted
events, which it could not have found; and a room with no forward
extremities has no current state to read.
After it: get_current_state_deltas groups and budgets the deltas in one
statement, with window functions, so each handler's read is one round
trip in autocommit, and the stream_positions upsert runs in autocommit
too, from both persist paths. The twin test's fake background runner
passes keyword arguments on.
The write transaction read six times between its writes, each read a
round trip: the room's depth, which events it already had, their
redactions, whether the prev events were persisted, the cache prefill's
rejections and redactions, and a cache stream ID. Now the rooms row of a
new room and the depth update are queued writes (the depth update
conditional, as Python's read made it), the three reads it still needs
go out together with eight cache stream IDs in one round trip behind
them, through the new WriteTxn::query_many, and the rest is known: the
cache prefill from the contexts and the redactions already read, and a
prev event the chunk itself persists needs no check. A chunk that
creates a room is written in two round trips instead of eight.
The createRoom bench gets a sane event cache, as the test default of one
entry made every read after persisting a fetch, which no server does.
The rooms row for a new room is inserted by the persist transaction,
Rust or Python, when the create event's context is flagged, instead of
by a store_room transaction of its own beforehand. The insert also
claims the room ID: a row already there fails the batch with
RoomIdCollisionError, and create_room runs the whole creation again
under a fresh ID, perturbing the create event's timestamp for v12+
rooms as the old loop did. The room version is prefilled on the upgrade
path too, as the row is no longer there to read.
The chain cover check skips its rooms read when the create event is
among the events, since the row may not be stored yet, and the
createRoom bench advances the fake clock per room so that rooms do not
collide.
The push rule evaluator wrote each event's push actions to the staging
table, a round trip, for the persister to move into `event_push_actions`
in its transaction. It now leaves them on the event's context, as
`push_actions`, and the Rust persister writes them into
`event_push_actions` in the write transaction, queued behind the other
writes. The staging table stays for the persisters that read from it:
`stage_push_actions` writes the rows there before the Python persister
runs, and before a batch is sent to another worker.
The persist queue's read lock against purges was dropped with a round
trip the request waited for. Its row is now deleted in the background.
Waiters for the write lock retry on their own, so they lose nothing but
a few milliseconds.
The proxy's round trips per room for a room with an invite fall from 81
to 80, and the Python interactions from 14 to 13. The purge lock's two
round trips remain, one of them off the request now; so does
`store_room`, whose insert is also the room ID collision check.
Creating a room read the database from Python for things the request
already knows, each a round trip of its own:
- The creator's and each invitee's profile, for the membership events.
`get_profileinfo` is now cached by user ID, invalidated where the
profile is written: setting the displayname or avatar, registering
with a displayname, and deleting the profile.
- Whether a joining user is already joined, in
`persist_and_notify_client_events`, and whether a membership event's
target is joined, in the push rule evaluator. A membership event that
replaces no membership in the room state, which `replaces_state` in its
unsigned data records, is of a user who is not joined, so there is
nothing to read.
- The new room's version, when the invite is built in Python. The room
handler prefills `get_room_version_id` once the room is stored.
On the native driver with the Rust persister the bench's Python
interactions per room fall from 13 to 11 for a plain room and from 19 to
14 for a room with an invite, and the Postgres round trips the proxy
counts from 72 to 70 and from 86 to 81. `SYNAPSE_BENCH_TRACE` prints a
stack for each interaction with a given description.
`store_state_group_chain` inserted the new groups, their edges and their
state one statement at a time, then committed: five round trips for a
new room, with the ID allocation. The inserts, and the bump of the prev
group's pending deletion, are now queued, so a new room's chain takes
two: the IDs, then the rows with the COMMIT.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
A join without profile data read the user's display name and then their
avatar URL, two transactions. For a local user with neither in the
content, `get_profileinfo` now reads both at once. A remote user, or
content that has one of the two, takes the same path as before.
If the user has no profile row, the first read used to fail with a 404,
logged, and leave both out. Now both are left out without the log line.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
The sync store's transactions (`SyncReader::begin` and `begin_write`),
which the Rust sync and sliding sync handlers and the persister's reader
use, still sent `BEGIN` on its own and waited for it.
As for `WriteTxn`, the `BEGIN` now goes out with the first statement:
with its execution when the connection has it cached, otherwise with its
prepare. If the `BEGIN` fails, the connection is discarded. A
transaction that runs nothing sends neither `BEGIN` nor `COMMIT`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Each connection of the native pool caches its prepared statements, and
a statement it has not prepared costs an extra round trip. Two things
made those misses common:
- The pool handed out connections in rotation (deadpool's default FIFO
queue), so each statement was prepared on every connection in turn,
and idle connections were as likely to be picked as busy ones.
- A full cache was emptied whole, so one burst of one-off SQL re-cost
the whole hot set.
The pool now hands out the most recently returned connection first
(LIFO), so the connections that do the work keep warm caches, and a full
cache drops its least recently used statement. The clear counter becomes
`synapse_rust_db_pool_statement_cache_evictions_total`.
With five warm-up rooms, the E2EE monitor's room goes from 135 to 102
round trips.
With LIFO, connections at the back of the pool can sit idle for long
stretches. A server-side close is caught at checkout by the liveness
check, but a firewall that silently drops an idle flow is only noticed
through TCP keepalives, which tokio-postgres enables by default, as
libpq does for psycopg2.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Every transaction on the native driver sent `BEGIN` on its own and
waited for it before the first statement: one round trip per
transaction that did nothing but open it.
The `BEGIN` now goes out in front of the first statement's first
request: its execution if the connection has the statement cached, its
prepare otherwise. tokio-postgres queues a request when its future is
first polled, so joining the two puts them on the wire in order, and
Postgres runs the statement inside the transaction. This applies to
Python's transactions (`Connection::with_client`, through a
`PendingBegin` each statement method gets) and to Rust's write
interactions (`WriteTxn`, whose first statement claims the `BEGIN`).
If the `BEGIN` fails, the statement behind it may have run outside a
transaction, so the connection is discarded rather than reused. A retry
could then apply that statement twice, but `BEGIN ISOLATION LEVEL ...`
has no realistic way to fail on the server while the next statement
succeeds: a broken connection fails both. A
`WriteTxn` that runs no statement now sends neither `BEGIN` nor
`COMMIT`.
The E2EE monitor's room on jki.re goes from 150 to 135 round trips, a
plain room from 104 to 93.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Each connection of the native Postgres pool caches its prepared
statements. A miss costs a round trip to prepare, and the cache is
emptied whole when it reaches 512 statements. Nothing showed how often
either happens, or how often `txn_limit` replaces a connection and loses
its cache.
The pool now counts cache hits, prepares, cache clears, and connections
opened and retired. Python reports them per pool as
`synapse_rust_db_pool_statement_cache_hits_total`,
`..._statement_prepares_total`, `..._statement_cache_clears_total`,
`..._connections_opened_total` and `..._connections_retired_total`,
carried over when the native pool is closed.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Behind `experimental_features.rust_room_creation: on`, the room handler
collects the events that follow the create event (the creator's join,
power levels, join rules, history visibility, the initial state, name,
topic) as `(type, state_key, content)`, and `LocalEventSigner` builds,
hashes and signs them all in one call. Each event's prev event, depth
and auth events follow from the one before, as `create_event` gives
them for a batch.
Python keeps every check: the requester checks ran when the create
event was built, and each built event still goes through
`validate_builder`, `validate_new` and the relation check before
joining the batch, which persists through `handle_new_client_event` as
before. Invites are still built by `create_event`.
Rooms the Rust builder does not cover are built in Python and counted
as fallbacks: v1 and v2 rooms, MSC4242 state DAG rooms, appservice
senders, modules with `check_event_allowed`, initial `m.room.aliases`
events, and `m.call.invite` or `m.room.create` in the initial state. If
Rust fails, the events are built in Python. If Python rejects them too,
the request was bad and gets Python's error. Otherwise it counts as a
Rust error. In tests,
`SYNAPSE_TEST_RUST_ROOM_CREATION=on` turns the builder on and makes a
failure fail the test.
Python orders auth events by iterating a set, so the order changes with
the process's hash seed. Rust keeps the order of the auth types. A test
creates rooms of several configurations and room versions in Python,
rebuilds their events in Rust from the same inputs, and compares them
with the auth events taken as a set.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Rust could read state groups but not write them. A new
`store_state_group_chain` on the `RustStore` writes the chain
`store_state_deltas_for_batched` stores: an optional full group for the
state before the first event, then one delta group per state event. It
runs in one native transaction, allocating from `state_group_id_seq` as
Python does. A `prev_group` is locked against deletion and its pending
deletion pushed back, and a missing one fails with Python's message.
When the state groups share the main database and that uses the native
driver, `store_state_deltas_for_batched` calls it instead of running a
Python transaction. The context bookkeeping and the cache prefill are
shared by both paths. Room creation, and anything else sending a batch,
saves one Python transaction.
A twin test stores the same batches through both writers and compares
the rows and the groups the contexts get.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Validating a power levels event against its JSON schema took 250 us
even with the validator compiled once, ten times the rest of
`validate_new`.
Rust now answers "certainly valid" or "not sure" for the power levels
schema, the mentions schema and the canonical JSON check. Python runs
its own check only when Rust is not sure, so Python still decides every
rejection and its error message. Rust only accepts integers it parsed as
`i64` in range, so floats such as `50.0`, which the schema accepts, are
left to Python.
`_check_size_limits` takes the canonical JSON length from Rust instead
of building the dict and encoding it. Rust keeps each number's source
text, which can differ from how Python prints a float, so an event with
any number other than a plain integer is still measured in Python.
`validate_new` on a default power levels event: 305 us before, 43 us
after.
Tests generate random contents and check that whatever Rust accepts,
Python accepts too. They found that the strict canonical serializer in
`canonical_json.rs` does not range-check numbers inside arrays, so the
canonical check walks the JSON itself. Nothing else uses strict mode.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`create_local_event_from_event_dict` encoded the event as canonical JSON
three times: once for the content hash, once to sign the redacted event,
and once to parse it as an `Event`, which then hashed it again for the
event ID.
A Rust `LocalEventSigner`, one per homeserver, now takes the canonical
JSON once, adds the content hash and the signature, and builds the
`Event`. The signed bytes are the redacted event without its signatures,
which is also what the reference hash covers, so the event ID comes from
them without another pass. Hashes and signatures already on the event
(a make_join template) are kept, as before.
Numbers keep the text Python's encoder gave them, so floats and large
integers in old room versions hash and sign as they did. An event the
room version cannot parse is still a 400. A make_join template with a
non-object `hashes` or `signatures` entry, or no `content`, is now a
400 too, where it used to raise a 500.
Saves about 45 us per event on this host. ed25519 signing is 25 us of
what is left.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
With `require_membership_for_aliases` (the default), `create_event`
checks that the sender of an `m.room.aliases` event has joined, by
loading their membership event from the database. Since the initial
events of a room are persisted in one batch, the creator's join is not
there yet, so a `/createRoom` with `m.room.aliases` in its initial
state failed with 403 "You must be in the room to create an alias for
it".
Persist the create event and the join on their own first in that case,
as for v1 rooms.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`/createRoom` sent each invite with `update_membership_locked` after the
room's initial events, one persist round per invitee.
Invites to local users now go into the batch with the rest of the room, in
`invite` order, until the first invite that has to be sent on its own:
- an invite to a remote user, which needs a federation request first;
- an invite that would be refused (server notices user, non-admin invites
blocked, the invitee's invite rules). It is sent the old way once the room
exists and fails the request as before.
`RoomMemberHandler.build_new_room_invite_content` makes those checks and
builds the content, with the invitee's profile where the server includes
it in invites. A repeated invitee is skipped, as `deduplicate_state_event`
dropped the repeat before.
Each batched invite is also checked against the auth rules before it joins
the batch, as one that fails (inviting yourself, or a power level override
that forbids invites) would otherwise abort the whole batch and leave the
room without events. It and the invites after it are sent on their own
instead, and fail the request once the room exists, as before. The
`trusted_private_chat` preset still gives every invitee ops in rooms
without MSC4289 creators.
Modules that check invites (`user_may_invite`) or events
(`check_event_allowed`) are given the room state from the database, so
with any of those registered all invites are sent on their own. So are
invites in v1 and v2 rooms, whose create event and join are already
persisted on their own.
`invite_room_state` (and `knock_room_state`) now take earlier events of the
same batch from the batch, as they are not in the database yet. Invitees
are passed to the notifier as extra users, as `update_membership` did.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
After `batch_persist_unpersisted_contexts`, an event's `EventContext` only
had state group IDs, so every read of the state before the event went to
the state store. For a new room that was eight state-group reads per
`/createRoom`: six from `deduplicate_state_event`, one from the
create-event check in `persist_and_notify_client_events`, and one from the
persister working out the new current state.
Keep the state map the batch was built from on the `EventContext`, as a
private attribute that `get_prev_state_ids` prefers and that is not
serialized, so a context sent to another worker reads the state group as
before. A context that arrives with a state group of its own, which the
batch then replaces, drops its map. `store_state_deltas_for_batched` also prefills the state group
caches with the state after the last event of the batch, through the
helper `store_state_group` now shares.
On the trial harness (SQLite) a plain room drops from 35 to 27 database
interactions, and `/createRoom` from 17 to 10 database transactions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`/createRoom` persisted the create event on its own, then the creator's
join through `update_membership`, then the rest of the initial state as a
batch. Each round paid for the persist queue, the purge lock, forward
extremities, chain cover, a replication notify and a wake-up of the stats
and presence pollers.
Build the create event and the join against the in-memory state map like
the other initial events, and persist all of them in one batch. The join's
content comes from `RoomMemberHandler.build_creator_join_content`, which
shares the suspension and profile handling with `update_membership_locked`
through the new `_prepare_membership_content`. The MSC4291 create event,
built before the room ID is known, now also leaves its context unpersisted
for the batch.
`store_state_deltas_for_batched` accepts a batch that starts the room: it
stores the empty state before the create event as a full state group, then
the delta chain. If the first context already has a group for the state
before it (a module rewrote the event), the chain builds on that instead.
`calculate_context_info` and `UnpersistedEventContext` treat an empty state
map as known empty state. Before, an empty map tripped an assertion. Room
creation never passed one, but federation could (`compute_event_context`
with an empty remote state), and such an event is now stored with an empty
state group and left to the auth checks.
Two cases keep persisting the create event and the join on their own:
v1 and v2 rooms, whose builder reads prev and auth event hashes from the
database, and servers with a `check_event_allowed` module callback, which
is given the room state from the database and may have the event rebuilt.
On the trial harness (SQLite) a plain room drops from 68 to 35 ms and 26
to 17 database transactions.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`jsonschema.validate` checks the schema against the metaschema on every
call. For power levels that cost more than validating the event: about
9 ms per `/createRoom`. Check the power levels and mentions schemas once
at import and validate with bound validator instances, reporting the same
best-match error.
`create_event` also ran `validate_new` a second time on the event that
`create_new_client_event` had just validated. Drop the repeat.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`tests/rest/client/bench_createroom.py` times room creation per room in
the trial harness, with optional cProfile dumps and per-room counts of
database interactions and SQL statements. It skips unless
`SYNAPSE_BENCH_CREATEROOM` is set.
`scripts-dev/createroom_bench.py` times it against a real server, reusing
`persist_bench.Server`. That server now lifts the room-creation rate limit
and can run on psycopg2 instead of the native driver.
The test template database's maintenance connection now always uses
psycopg2, as `setup_test_homeserver` does. The Rust driver's `postgres`
module has no `connect`, so it failed under `SYNAPSE_TEST_RUST_DRIVER=1`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
`twisted.internet.task.Clock` re-sorts its whole list of pending calls on every
`callLater` and after every call it runs. A test homeserver has dozens of
pending calls and the threadless database pool schedules a `callLater(0, ...)`
per transaction, so this showed up as ~10% of a test's time in profiles.
Insert new calls in order with `bisect.insort` and only re-sort after a call
was rescheduled with `reset` or `delay`.
Together with the previous commit, `tests.rest.client.test_rooms` goes from
44.9s to 32.7s and `tests.handlers` from 146s to 114s single-process on
SQLite; a 147-test Postgres subset from 85.9s to 74.4s.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Every test homeserver runs the background updates when it starts, and with a
fresh copy of the template database there are dozens to run: 29ms per test
on SQLite and 99ms on Postgres, against a median test time of ~140ms.
Run them once per process on a throwaway homeserver and copy the result back
over the template (`backup()` for the in-memory SQLite template, `CREATE
DATABASE ... TEMPLATE` for the Postgres base database), so each test's
homeserver finds nothing left to do.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Trial worker memory grew steadily over a run because `HomeServer`s outlived
their test. Each one is a ~10k-object reference cycle; GC is disabled while a
test runs and the tearDown only does a gen-0 collection, which frees the
homeserver only if nothing older still points at it. Four things did:
- `ThreadedMemoryReactorClock.__init__` installs `tls._get_default_clock =
lambda: self` into the `twisted.protocols.tls` module. That held the test
reactor, whose never-removed shutdown triggers hold handlers, and so the
homeserver, until the next test's reactor replaced it. Hold the reactor
weakly instead.
- `synapse.config.cache._CACHES` maps cache names to bound `set_cache_factor`
methods, so an old homeserver lived until a later test registered a cache
with the same name. Hold bound methods through `weakref.WeakMethod`.
- `_CacheContext._cache_context_objects` is a class-level `WeakValueDictionary`
keyed on `(cache, key)`: the key strongly holds the cache, which holds the
homeserver, for as long as any context exists. Key on `id(cache)`; the id
cannot be reused while an entry exists since the context holds the cache.
- trial keeps finished `TestCase` instances around (for example in its list of
skipped tests), and those keep `self.hs`, `self.store`, ... Drop every
attribute a test added from setUp onwards before the gen-0 collection.
The fake reactor's `callWhenRunning` and shutdown hooks are emptied once the
homeserver has shut down: they never fire in tests, and the Rust runtime holds
the reactor through a reference the garbage collector cannot see, so a reactor
that still pointed at the handlers kept the homeserver alive.
With this the homeserver dies in the existing gen-0 collection. A full
collection per test was ruled out: it costs ~100ms per test. RSS over
`tests.rest.client.test_rooms` goes from 148→337 MB to 148→176 MB, and over
`tests.handlers` from 170→498 MB to 170→278 MB.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
Brings Rust sliding sync (erikj/rust-sss-queries) together with Rust
event persistence (erikj/rust-persist-validate). Both branch from
a78b02b55c.
The conflicts were both sides adding parallel entries:
- the Complement and test environment switches
- the `RustHandlers` fields and getters
- the `_BlockingRustCalls` types
These keep both. `RustHandlers` builds the persister and the sliding sync
handler in one pass over the native pool. `SyncReader::begin` keeps the
persist side's flag-before-BEGIN and the sliding sync side's transaction
count and `begin_write`. Both sides had added the `invite_room_state`
and `knock_room_state` accessors to `Unsigned`, so one copy is kept.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PVLsNh6akt4ifEizY4D1ta
The native driver's write path recorded no `sql_txn_count` or
`sql_txn_duration`, nor the log context's transaction counts, so the
`persist_events` panels read near zero at `rust_event_persistence:
transaction` and `full`.
`run_write_interaction` now times each interaction as `new_transaction`
does: every attempt, from when it has its connection, so the wait for
one is left out. The times go into a task-local list that
`with_txn_timings` collects. The persister's entry points carry the list
back on what they already return (`PersistEffects`, `PreparedChunk`,
`PersistedBatch`, `CurrentStateUpdate`), and Python records it where
`new_transaction` would: the two counters, the pool's perf counters and
the current log context, which is the caller's when Python applies what
Rust returned. That costs no GIL hop.
When a persist fails, or Python gives up a batch, no result carries the
times back, so the persister keeps them and `flush_rust_persist_metrics`
counts them at the next scrape, without a log context. In shadow mode
Python's own interactions are the ones used, so Rust's dry run is not
recorded. The stream orderings' `nextval`, which runs outside a write
interaction, is recorded as `_load_next_mult_id`, as Python's is. The
`db.<desc>` tracing span is not recorded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
`_update_current_state`, the queue's `_UpdateCurrentStateTask`, becomes
one call to `Persister.update_current_state`:
- `calculate_current_state` reads the room's forward extremities (its
state DAG extremities in an MSC4242 room) and takes the state of
their one state group, or resolves several, after checking the groups
still exist and putting off their deletion, as `resolve_state_groups`
does.
- The delta from the current state and the sliding sync table changes
are computed as for a chunk, with no events.
- If anything changed, one stream ID is taken from the events stream,
as `get_next` does, and `_update_current_state_txn` runs in Rust.
Python applies the effects, which finishes the ID.
A room on state resolution v1 whose extremities need resolving is handed
back, and Python recalculates its state as before.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
`_after_persisting_events` moves into the batch step, after the write
and before Python applies the chunk and finishes its stream orderings,
as it ran inside `get_next_mult` in Python:
- The persisted events, by type and origin, and the persisted position
go to the Rust metrics that `flush_rust_persist_metrics` reports.
- With MSC4293, a join, or a leave by someone else, ends the redaction
of the target's events. A ban or kick with `redact_events` set, by a
sender who may redact (`_can_sender_redact`, read from the current
state), starts it. Python then drops the room's events from its event
cache, through a new `event_cache_room_invalidations` effect, even if
a later event of the chunk fails, as Python drops them right after
each start.
- The forward extremities prefill moves into the effects.
The MSC4293 flag goes with each batch, as Python reads it per chunk and
tests change it at runtime.
If what follows the write fails, the chunk is still written, so Python
applies its effects and finishes its orderings as a failure, as
`get_next_mult` does when its block raises, then raises the error and
releases the batch's state groups as a failed persist does.
Where Python would raise on odd power levels or memberships, Rust is
more lenient: it reads a level that is a string of an integer as that
number (Python compares two strings, or raises), a null default as 0
and a `users` or `events` that is not an object as missing, and skips a
member event without a membership. Numbers, floats and bools compare as
in Python.
The chunk path, for chunks Rust hands back, keeps the Python block.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
At `full`, `_persist_event_batch` hands the batch to
`Persister.persist_batch` and steps through it with `batch_next`:
- The first step drops the events already persisted under the same
transaction ID (`get_already_persisted_events`).
- Each step prepares the next chunk of up to 100 events, marks the
batch's state groups as being persisted
(`persisting_state_group_references`, two short native
transactions), takes the chunk's stream orderings and writes it.
- Python applies what the chunk asks for, runs
`_after_persisting_events` and finishes the orderings before the next
step, which first releases the state groups. So each chunk is
prepared against current caches.
- If Python cannot apply a chunk, `batch_abort` releases the state
groups as a failed persist does.
A chunk Rust cannot prepare (a state resolution fallback, or an error)
is handed back with the rest of the batch to the chunk-by-chunk path,
which prepares it again and falls back or raises as at lower levels.
Python drives the steps, rather than Rust calling back into Python, so
every step has a `_blocking` twin for tests and nothing waits on the
reactor from Rust. That costs the same hops as a callback: one in and
one out per chunk.
The prepare inputs are now built from `Event`s that share their data
with the Python events, so a chunk's input can be built without the
GIL once the batch has been deduplicated.
The persister's Deferreds already follow the logcontext rules, so they
are awaited directly. Wrapping them in `make_deferred_yieldable` again,
as the `prepare_chunk`, `persist_events_txn` and `persist_chunk` call
sites did, resumed the caller in the sentinel context.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
At `full`, `Persister.persist_chunk` takes the chunk's stream orderings
from the events or backfill stream tracker, which Python's
`_stream_id_gen` and `_backfill_id_gen` share. It runs `nextval` in
autocommit after prepare, as late as `get_next_mult` does, and sets each
event's stream ordering, received time and instance before the write
transaction. Backfilled events take theirs negated.
The orderings come back unfinished in `PersistEffects.stream_ids`.
`_persist_events_and_state_updates` skips `get_next_mult` when Rust takes
them. Its post-transaction block (metrics, MSC4293
`room_ban_redactions`, the extremities prefill) moves to
`_after_persisting_events`, which both paths call. At `full` it runs
after the effects are applied and before the orderings are finished, as
it ran inside `get_next_mult`. So a ban that redacts a user's events is
recorded before other workers see it.
`finish_rust_persist_stream_ids` finishes the orderings as
`get_next_mult` does on exit: it tells replication, and on success moves
`stream_positions` on. If the transaction fails, Rust finishes them. If
the apply or the follow-ups raise, Python finishes them.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The seventh commit of phase 2, which completes it. The Rust transaction
now covers the whole of `_persist_events_txn`, so at the `transaction`
level every chunk Rust prepared is written in Rust, including on a
server with `include_profile_updates_in_sync`.
- `txn/profile.rs` ports `_record_profile_updates_for_state_delta_txn`
and the helpers it calls: the joined room updates of local members
who joined, and the left room updates, both ways, of members who left
or were state reset out of the room, with the deletes of the rows they
replace. It runs at the end of `update_current_state`, as in Python.
- Its rows take IDs from the profile updates stream inside the
transaction, through a third `TxnStream` over the tracker of
`_profile_updates_id_gen`. `PersistEffects.profile_stream_ids` hands
them to the applier, which finishes them as `get_next_mult_txn` does,
as it does the sticky events stream's. The two share
`_finish_txn_stream_ids`.
- The controller no longer falls back to Python on a server that
records profile updates.
- The Python helpers take the members in user ID order where they took
a set's order, so both sides take the stream IDs in the same order.
- `Persister.persist_events_txn` resolves with the effects alone. The
events left and the redacted copies were only for the Python steps
after Rust's in the twin test, which are gone.
The twin test compares the profile updates rows each twin's persists
wrote, and the rows of each twin's own users from outside them, which a
leave deletes. Those are compared without `inserted_ts`, as each twin
writes them at a different time. New scenarios, with members of each
twin's own, cover:
- joins, a change of display name, and leaves
- several members in one chunk
- a member state reset out of the room
- a remote member state reset out of it, which writes nothing, as only
local members have membership snapshots
- a leave while still sharing another room with some members, and with
all of them
- a leave deleting the rows about earlier profile changes
- the last local member leaving
Making the Rust shared room query match nothing, dropping the reverse
left room rows, or skipping the delete of the leaver's rows about the
others, fails the scenarios that cover it. The
prereqs test now checks that a server recording profile updates writes
the rows in Rust and finishes the stream IDs.
These suites pass at `SYNAPSE_TEST_RUST_PERSIST=transaction` on the
native driver: `tests.handlers` (including the profile and sync tests
that record profile updates), `tests.federation`, `tests.replication`,
`tests.rest.client.sliding_sync` (including the profiles extension),
the phase 2 storage suites, and the `tests.rest.client` group but for
the two `test_rooms` tests that count database transactions, which fail
the same way at `prepare`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The sixth commit of phase 2. At the `transaction` level, a chunk Rust
prepared is written by the Rust transaction in place of
`_persist_events_txn`.
- `Persister.persist_events_txn`, with a `_blocking` twin for tests,
runs the transaction over the chunk and resolves with its effects.
The test-only entry it replaces shared its body.
- `_persist_events_and_state_updates` takes a `RustTransaction` (the
persister and the prepared chunk). With one, it calls Rust inside the
same stream ordering allocation, then applies the effects, so the
event stream IDs are finished after them, as before. The call and
the apply run together under `delay_cancellation`, as
`runInteraction` runs its callbacks: a transaction that commits must
have its effects applied, or the cache and sticky events stream IDs it
took are never finished.
- The controller passes one when the level is `transaction` or later
and Rust prepared the chunk. A chunk Python prepared, after a state
resolution fallback, is written in Python. So is every chunk on a
server with `include_profile_updates_in_sync`, as the Rust
transaction leaves the profile updates to Python.
- `_add_to_cache` moves to Rust: the transaction picks the events
neither rejected nor redacted, in
`PersistEffects.event_cache_prefills`, and the applier puts the events
Python holds into the event cache. Of a duplicated event, it puts the
copy that was written, the earliest non-outlier, as `_add_to_cache`
reads the deduplicated chunk.
- The applier is now `apply_rust_persist_effects(store, ...)` in
`synapse/storage/databases/main/rust_persist.py`, as the event
persister may be a worker, whose main store is a `GenericWorkerStore`.
A mixin on both stores cannot be linearised into `DataStore`. If a
step raises, it still finishes the cache and sticky events stream IDs
it has not finished, as `call_on_exception` does in Python.
The twin test compares the events each side puts in the event cache,
and checks which copy of a duplicated event goes in. New prereqs tests
check:
- that Rust writes the chunk, with Python's transaction made to fail,
and the applier fills the event cache
- that a lowered level, or a server that records profile updates,
writes in Python a chunk Rust prepared
- that the transaction takes the GIL at no persist site
- that cancelling the persist mid-transaction waits for it and applies
the effects
- that a worker event persister writes in Rust to the main database
The Rust transaction does not yet record the `sql_txn_*` metrics, the
log context's transaction counts or the `db.persist_events` span, as
the native driver's write path records none of them.
These suites pass at `SYNAPSE_TEST_RUST_PERSIST=transaction` on the
native driver: `tests.handlers`, `tests.federation`, `tests.replication`
(sharded event persisters included), `tests.rest.client.sliding_sync`,
the storage suites in the phase 2 plan, and `test_sync`,
`test_relations`, `test_redactions`, `test_sticky_events`,
`test_profile`, `test_retention` and `test_rooms` in
`tests.rest.client`, but for two `test_rooms` tests that count database
transactions. Those fail the same way at `prepare`: Rust's prepare step
takes one more transaction per room creation.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
A context sent to the event persister over replication holds its state
maps as `immutabledict`s, which Rust's persist context conversion
refused, as it took only a `dict`. So on a deployment with workers,
preparing a chunk in Rust failed for every event another worker sent,
and fell back to Python with an error logged. It now takes any mapping.
Two worker tests with the native driver showed it, and then showed a
test harness problem. `make_worker_hs` points a worker's Python pool at
the master's database once the worker is built, but the worker's Rust
handlers keep the native pool they were built with, on the worker's own
database. It now points that pool at the master's database too.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The fifth commit of phase 2. The Rust transaction now runs the rest of
`_persist_events_txn`, but for the event cache prefill (`_add_to_cache`)
and the profile updates, which stay in Python.
- `txn/sticky.rs`: `insert_sticky_events_txn` for the chunk's new
events, and `un_soft_fail_sticky_events_txn` for the events
`compute_sticky_events_to_un_soft_fail` found in prepare. A
de-outliered sticky event becomes sticky inside `update_outliers`, as
in Python, so the chunk's redactions come after it. As in Python, an
event with a zero sticky duration is not tried there.
- `txn/sliding_sync.rs`: the latest stream ordering and bump stamp of
the room's `sliding_sync_joined_rooms` row.
- `txn/streams.rs`: what was `CacheStream`, now `TxnStream` for any
stream the transaction takes IDs from, several at a time. The sticky
events stream is the second. Its IDs come back unfinished in
`PersistEffects.sticky_stream_ids`. Python finishes them once the
caches are invalidated, notifies replication and, as the stream has
writers, updates `stream_positions`, as `get_next_mult_txn`'s
callbacks do. A failed attempt's IDs are finished as for the cache
stream.
`persist_events_txn` returns the events left. The test entry no longer
returns the de-outliered events.
Python's `un_soft_fail_sticky_events_txn` gave the events their new
stream IDs in a set's order. It now keeps their order in the stream, by
`event_stream_ordering`, with any event without a row last, by event ID.
Rust does the same, which lets the twin test compare several events
lifted at once.
The new scenarios found a Python bug, which Rust keeps. A de-outliered
sticky event's `sticky_events` row has the stream ordering of the chunk
that de-outliered it, but its `events` row keeps the one it was first
persisted with. `delete_sticky_events_txn` looks for the latter, so a
redaction of the event, in that chunk or any later one, leaves it
sticky until it expires.
The twin harness:
- records the stream IDs the applier finishes and the notifiers it
calls, rather than modelling them from the effects
- merges each persist's finished IDs per stream into one call, and
compares its notifiers by whether they were called. Python queues
them per allocation of IDs, and the effects do each once.
- names a background process by what it runs: an ID generator's
`stream_positions` update by its stream, any other by its description
New twin scenarios:
- sticky events in one chunk, one of them expired
- a sticky outlier, de-outliered; de-outliered and redacted in one
chunk; de-outliered with a new sticky event in one chunk
- soft-failed sticky events lifted when their sender joins, one and
three at once
- a rejected sticky event, a backfilled one, and one redacted in its
own chunk
A prereqs test checks that applying the effects finishes the sticky
events stream IDs after the event cache invalidations, then notifies,
and updates `stream_positions`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The fourth commit of phase 2. The Rust transaction now also runs
`_update_current_state_txn`, apart from the profile updates at its end.
- `txn/current_state.rs`: the delta stream rows, read before the current
state changes, then `current_state_events` and the state columns of
`sliding_sync_joined_rooms`. When the server leaves the room, the room
version is recorded and the room's current state goes instead.
`local_current_membership` and the membership snapshots follow either
way. The effects move the current state delta and membership stream
change caches on, and invalidate the state caches. The `cs_cache_fake`
rows name 50 members each. Remote members who share no room with the
server any more have their device lists unsubscribed.
- `txn/caches.rs`: `_send_invalidation_to_replication`, the cache stream
row without the local invalidation.
The profile updates take IDs from the `profile_updates` stream, which
has writers and so a `stream_positions` row. They move to
`_record_profile_updates_for_state_delta_txn` in Python, which the twin
test runs after Rust, and are left for a later commit. The twin test
cannot compare their rows, as the twins share the profile tables. The
profile suites cover the moved code.
Rust differs from Python in these places:
- Rust writes the members of the `cs_cache_fake` rows, and the device
list rows of the remote users who left, in sorted order. Python's
follow a set's.
- A create event whose `room_version` is not a string, null included,
or whose `creator` is neither a string nor null, fails the persist
when the server leaves. Python stores a number cast to text or a
NULL, and fails on an object. Event auth requires a string
`room_version`, so only old or corrupt data can differ.
The room version upsert has a Postgres test on temporary tables. The
twin test cannot see it, as the `rooms` row always holds the version
already.
The twin harness now applies Rust's effects with
`_apply_rust_persist_effects`, as the facade will, so the steps after
Rust's see the caches Rust invalidated. Some of what Python writes from
a set, it compares in any order:
- sets in effects, as sorted tuples
- a run of `cs_cache_fake` rows, as its members and its row sizes
- a run of single-key cache stream rows of one cache, as its keys
- an event's `auth_events`, where the stored JSON matches its content
hash, which covers their order. The hand-built events are rehashed.
It compares `device_lists_remote_extremeties` on each twin's own remote
users.
New twin scenarios:
- the sliding sync state columns (encryption, name, tombstone and a
leave)
- the server leaving the room, with one or two remote members still
joined
- remote members and their device lists
- 60 members changing at once
- a state key, and a local member's invite with its snapshot, removed
by state resolution
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The third commit of phase 2. The Rust transaction now also runs
`_update_metadata_tables_txn`, apart from the event cache prefill at its
end (`_add_to_cache`), which stays in Python:
- `txn/metadata.rs`: push actions move from the staging table, and the
chunk's staging rows go. A redaction removes the push actions and the
relation of the event it redacts, and moves or deletes its thread.
Then search (with the plain text topic from `m.topic`), redactions,
retention, relations and threads, labels, expiry, and room members.
An out-of-band membership of a local user also updates
`local_current_membership` and the user's sliding sync snapshot, with
the stripped state of an invite or knock.
- `txn/edges.rs`: `event_edges` with the backward extremities, and the
MSC4242 state DAG edges.
- `txn/caches.rs`: `_invalidate_cache_and_stream`. The rows go into
`cache_invalidation_stream_by_instance` inside the transaction, with
IDs from the cache stream's tracker. The committed attempt hands its
IDs to Python in `PersistEffects.cache_stream_ids`. Python finishes
them after invalidating the caches, as `get_next_txn` does. A failed
attempt's IDs are finished when its steps fail, or for a failed
commit, by the next attempt or when the persist ends. A fetch of an ID
that is dropped before the sequence answers still ends, so a cancelled
persist cannot hold the stream's position back.
Where Python and Rust differ, the input is malformed:
- Python stores labels from any value it can iterate, and non-string
labels. Rust stores only string labels from a list.
- An integer lifetime or expiry beyond `u64` is a float to serde, so
Rust ignores it where Python's insert fails. Within `u64` but beyond
`bigint`, both fail.
The persister reads `enable_search` and `enable_ephemeral_messages`
from the server config. `persist_events_txn_for_test` takes
`inhibit_local_membership_updates`.
New twin scenarios: each kind of relation and its redaction, which
moves the thread back and then deletes it, a relation redacted in its
own chunk, two thread replies in one chunk, search, retention (also two
policies in one chunk), labels and expiry, member rows, push actions and
their redaction, an out-of-band invite and its rejection, a knock, and a
backfilled invite. The out-of-band ones are skipped in state DAG rooms,
as a hand-built event has no state DAG context. A redaction before its
target is now stored with a recheck still needed.
The test harness compared `event_edges` by its `room_id` column, which
is no longer filled in, so it compared no rows. It now compares by
`event_id`. It also names the cache behind each invalidation, compares
the cache stream rows' times, and finishes the cache stream IDs Rust
hands back. Fifteen mutants of the new steps each fail the comparison.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The second commit of phase 2. The Rust transaction now runs the steps of
`_persist_events_txn` from `_update_room_depths_txn` up to
`_store_rejected_events_txn`:
- `txn/events.rs`: the room's depth and its place in the events stream
cache, de-outliering, redactions that already apply (the event is
stored pruned) and the earlier events the chunk's redactions confirm
(they stop being sticky, and a passed recheck is stored), the
`event_json`, `events` and `state_events` rows, transaction IDs, state
groups and partial state, the chain cover index and `event_auth`, and
rejections.
- `txn/edges.rs`: the forward and state DAG extremities, and the
backward extremities and timeline gaps of a de-outliered event.
`_handle_mult_prev_events` will use the latter for new events.
- `txn/json.rs`: JSON as `json_encoder` writes it, with non-ASCII and
DEL escaped. The event and its internal metadata keep the key order
`get_dict_for_persistence()` and `get_dict()` give, so the `event_json`
text is Python's byte for byte. Only number text from federation can
differ (`1.50` against Python's `1.5`).
An event with partial state in a room that is no longer partial stated
fails with `PartialStateConflictError`, as in Python.
`Persister.persist_events_txn_for_test` takes the chunk Rust prepared,
which `PreparedChunk` now shares through an `Arc`. It returns which
events were stored redacted and which were de-outliered, so the twin
test's Python half can carry on from there. Making a de-outliered event
sticky stays in Python until the sticky commit, as it needs the sticky
stream's ID generator. Python makes those sticky before deleting
redacted events' sticky rows, so the sticky commit has to insert them
inside `update_outliers`.
New twin scenarios: transaction IDs, URLs and non-ASCII text, a
redaction recheck (alone and in a chunk with its target), a partial
state conflict, a redacted sticky event, and a redaction of a later
redaction, which needs censoring again, and an event de-outliered while
its prev event is an outlier (a backward extremity and a timeline gap).
The test checks that room B's transaction takes the chunk prepared for
it. The fork scenario now advances
the clock between its topics, as state resolution otherwise breaks the
tie by event ID, which differs between the rooms. Each ID generator's
stream is ranked separately. Nineteen mutants of the new steps each
fail the comparison. `PersistenceJsonTestCase` compares the `event_json`
text byte for byte.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
The first commit of phase 2 of the event persistence plan
(`transaction` level). `rust/src/persist/txn/` will hold the port of
`_persist_events_txn`. This commit adds its driver: the share lock on
the room's `rooms` row, the cache updates Python queues for every event
up front, and dropping duplicate events. It returns the events left for
the steps still in Python.
`tests/storage/test_rust_persist_txn.py` builds the same DAG in two
rooms. Room A persists in Python. Room B prepares in Rust, runs the
Rust part of the transaction in its own committed transaction through
`Persister.persist_events_txn_for_test`, and then runs the Python steps
after it. The test compares the rows of every table the transaction
writes, after normalising room and event IDs, stream positions, state
groups and chain IDs, and compares the cache updates both rooms asked
for. Each later commit moves more steps from the Python half to the
Rust half, in transaction order, until the facade runs the whole
transaction. Mutating the driver (dropping the redaction
invalidation, the relation, the state key, or the outlier rule for
duplicates) fails the comparison.
Two open items from phase 1:
- Reads before the transaction now retry. Python runs each read in a
`runInteraction` that retries a lost connection or a cancelled
statement. `Persister.prepare_chunk` now prepares the whole chunk
again on such an error, up to five attempts. That is safe because its
only write, bumping the state groups it uses, can be repeated. The
reader and the state resolution store keep the pool's error as the
cause, so `is_retryable_error` can classify it. A `WriteError` does
not count, as its write interaction has already retried, and
`WriteError::from_pg` shares the classification.
- The Rust persister needs the state tables in the main database, as
it reads and writes both in one transaction. `Persister::for_homeserver`
now checks for that, and the persister is off when they are apart.
Also fixed in the dispatch: at `off`, `_prepare_chunk` ran Rust when a
persister existed. That only happens when a test changes the level at
runtime. The twin test does exactly that.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
`Persister.prepare_chunk` runs the steps of the previous commits for a
chunk: the extremities and state delta, then the sliding sync table
changes and sticky events, then the chain cover index. The chain cover
step comes last as the only one that writes, so a failure in an earlier
step leaves nothing for Python to find. Sliding sync and sticky events
now come before the stream orderings are allocated, as nothing there
reads them. Each step reads the clock when it needs the time.
`_persist_event_batch` dispatches on `rust_event_persistence`:
- `shadow`: Rust runs first with its chain cover write rolled back, then
Python. The results are compared and Python's are used. The comparison
ignores orders Python leaves to chance and the IDs of new chains. Both
rejecting the chunk with the same error is a match.
- `prepare` and above: Rust's results are used. A `SynapseError` is
raised as Python would raise it. Python computes the chunk when Rust
cannot resolve state in the room, or on any other Rust error.
Trial runs strict by default (`SYNAPSE_TEST_RUST_PERSIST_STRICT`), so a
mismatch or Rust error fails the test. Rust's counts and state res stats
are recorded by Python once it uses the result.
At `prepare`, the `_calculate_state_and_extrem` and
`calculate_chain_cover_index_for_events` timings give way to
`rust_prepare_chunk`. Python's state resolution and state group caches
are not filled, so creating a room costs one more transaction
(`RoomsCreateTestCase` counts it) and the first local event after a
fork resolves state again.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LXMkcZVkcZhi21augBff4a
Port `compute_sticky_events_to_un_soft_fail` and
`_get_soft_failed_sticky_events_to_recheck` to
`rust/src/persist/sticky.rs`. The reads go through a `StickyReads`
trait over the persist reader. Events to recheck and auth events not in
the chunk come from the Rust event loader, redacted and without
rejected events, as `get_events` returns them.
An auth failure keeps an event soft failed. A malformed event fails the
step, as Python raises it as something other than `AuthError`.
`persist_error_to_py` now raises an `AuthFailure` as the auth rules
raise it.
`StickyTestCase` compares the two over the same database, chunk and
delta.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UHKYPSc37kWqGACn9aKxKL
The phase 6 bench found Rust making 2 to 6 times Python's queries: 8 per
room computed, and 4 on an incremental request where nothing changed.
- Bundled aggregations read the thread summary, edits and references
through Rust caches that mirror Python's `get_thread_summary`,
`get_applicable_edit` and `get_references_for_event`, so Python's
invalidations reach them. The thread summary takes one statement with a
window count, where it took a transaction of up to two. v2 sync in Rust
shares these reads.
- `ignored_users` reads through a mirror of Python's cache.
- The `instance_map` table is cached. It only gains rows, so a stored
token naming a writer the cache lacks drops the cache and reads again.
- The self-leave query is skipped when the membership stream cache says
the user's membership has not changed since the `to_token`, the
shortcut Python's query carries as a TODO.
- On a room's first send, the name and the required state come from one
state read. Rooms with heroes keep a second read for their memberships.
On the bench, initial sync goes from 173 queries to 49, the range
expansion from 662 to 178 (Python makes 335), and a no-op incremental
from 4 to 0.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KETBASkkVomGNnbut9NWQq