feat: Delayed events support #2583

Open
Henry-Hiles wants to merge 3 commits from Henry-Hiles/continuwuity:quad/feat/delayed-events into main
Member

This pull request adds delayed event support. Closes #1840, fixes #903.

Pull request checklist:

  • This pull request targets the main branch, and the branch is named something other than
    main.
  • I have written an appropriate pull request title and my description is clear.
  • I understand I am responsible for the contents of this pull request.
  • I have followed the contributing guidelines:
<!-- In order to help reviewers know what your pull request does at a glance, you should ensure that 1. Your PR title is a short, single sentence describing what you changed 2. You have described in more detail what you have changed, why you have changed it, what the intended effect is, and why you think this will be beneficial to the project. If you have made any potentially strange/questionable design choices, but didn't feel they'd benefit from code comments, please don't mention them here - after opening your pull request, go to "files changed", and click on the "+" symbol in the line number gutter, and attach comments to the lines that you think would benefit from some clarification. --> This pull request adds delayed event support. Closes #1840, fixes #903. <!-- Example: This pull request allows us to warp through time and space ten times faster than before by double-inverting the warp drive with hyperheated jump fluid, both making the drive faster and more efficient. This resolves the common issue where we have to wait more than 10 milliseconds to engage, use, and disengage the warp drive when travelling between galaxies. --> <!-- Closes: #... --> <!-- Fixes: #... --> <!-- Uncomment the above line(s) if your pull request fixes an issue or closes another pull request by superseding it. Replace `#...` with the issue/pr number, such as `#123`. --> **Pull request checklist:** <!-- You need to complete these before your PR can be considered. If you aren't sure about some, feel free to ask for clarification in #dev:continuwuity.org. --> - [x] This pull request targets the `main` branch, and the branch is named something other than `main`. - [x] I have written an appropriate pull request title and my description is clear. - [x] I understand I am responsible for the contents of this pull request. - I have followed the [contributing guidelines][c1]: - [x] My contribution follows the [code style][c2], if applicable. - [ ] I ran [pre-commit checks][c1pc] before opening/drafting this pull request. - [ ] I have [tested my contribution][c1t] (or proof-read it for documentation-only changes) myself, if applicable. This includes ensuring code compiles. - [x] My commit messages follow the [commit message format][c1cm] and are descriptive. <!-- Notes on these requirements: - While not required, we encourage you to sign your commits with GPG or SSH to attest the authenticity of your changes. - While we allow LLM-assisted contributions, we do not appreciate contributions that are low quality, which is typical of machine-generated contributions that have not had a lot of love and care from a human. Please do not open a PR if all you have done is asked ChatGPT to tidy up the codebase with a +-100,000 diff. - In the case of code style violations, reviewers may leave review comments/change requests indicating what the ideal change would look like. For example, a reviewer may suggest you lower a log level, or use `match` instead of `if/else` etc. - In the case of code style violations, pre-commit check failures, minor things like typos/spelling errors, and in some cases commit format violations, reviewers may modify your branch directly, typically by making changes and adding a commit. Particularly in the latter case, a reviewer may rebase your commits to squash "spammy" ones (like "fix", "fix", "actually fix"), and reword commit messages that don't satisfy the format. - Pull requests MUST pass the `Checks` CI workflows to be capable of being merged. This can only be bypassed in exceptional circumstances. If your CI flakes, let us know in matrix:r/dev:continuwuity.org. - Pull requests have to be based on the latest `main` commit before being merged. If the main branch changes while you're making your changes, you should make sure you rebase on main before opening a PR. Your branch will be rebased on main before it is merged if it has fallen behind. - We typically only do fast-forward merges, so your entire commit log will be included. Once in main, it's difficult to get out cleanly, so put on your best dress, smile for the cameras! --> [c1]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md [c2]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/docs/development/code_style.mdx [c1pc]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#pre-commit-checks [c1t]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#running-tests-locally [c1cm]: https://forgejo.ellis.link/continuwuation/continuwuity/src/branch/main/CONTRIBUTING.md#commit-messages
feat: Delayed events support
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Auto Labeler / Apply labels based on changed files (pull_request_target) Successful in 4s
Checks / Prek / Check changed files (pull_request) Successful in 6s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 1m33s
Update flake hashes / update-flake-hashes (pull_request) Successful in 1m32s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 25m21s
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 8s
5a20a66493
Includes stable support.

Co-authored-by: new-years-eve <new-years-evening@proton.me>
Author
Member

Still needs real-world testing.

Still needs real-world testing.
nex requested review from nex 2026-11-23 04:08:48 +00:00
nex requested changes 2026-11-23 04:19:40 +00:00
Dismissed
nex left a comment

Overall looks solid, just a few flags

Overall looks solid, just a few flags
Lines 51-56
@ -48,9 +43,2 @@
let state_lock = services.rooms.state.mutex.lock(body.room_id.as_str()).await;
if body.event_type == MessageLikeEventType::CallInvite
&& services.rooms.directory.is_public_room(&body.room_id).await
{
return Err!(Request(Forbidden("Room call invites are not allowed in public rooms")));
}
Owner

Why was this removed?

Why was this removed?
Author
Member

It's not spec-compliant, I don't know why it existed in the first place. If it's out of scope I can do it in another PR, but I had to move it around anyways, then realized it doesn't exist.

It's not spec-compliant, I don't know why it existed in the first place. If it's out of scope I can do it in another PR, but I had to move it around anyways, then realized it doesn't exist.
Owner

It's annoying (the fact it exists) because it's a check present in every homeserver right now, although I think it's kinda useless. Feel free to keep it removed, it just makes me a bit itchy that we deviate from the common standard (even if it's not the spec)

It's annoying (the fact it exists) because it's a check present in every homeserver right now, although I think it's kinda useless. Feel free to keep it removed, it just makes me a bit itchy that we deviate from the common standard (even if it's not the spec)
Henry-Hiles marked this conversation as resolved
@ -53,1 +53,4 @@
("org.matrix.msc4354".to_owned(), true),
// Delayed events (https://github.com/matrix-org/matrix-spec-proposals/pull/4140)
// Proposal merged, expected for spec v1.20/v2.0
("org.matrix.msc4140".to_owned(), true),
Owner

Is the unstable version of the proposal as merged into the matrix-spec-proposals actually supported? I haven't checked the diff between the proposal and spec but given the implementation is coming after the spec was stabilised I'm not sure we should bother advertising the unstable version

Is the unstable version of the proposal as merged into the matrix-spec-proposals actually supported? I haven't checked the diff between the proposal and spec but given the implementation is coming after the spec was stabilised I'm not sure we should bother advertising the unstable version
Author
Member

Ruma maintains both codepaths (yes this was very painful in my Ruma PR). Applications using the unstable path will use the old unstable behavior, and it should work as-is. Needs testing, though.

Ruma maintains both codepaths (yes this was very painful in my Ruma PR). Applications using the unstable path will use the old unstable behavior, and it should work as-is. Needs testing, though.
Contributor

older clients send ?org.matrix.msc4140.delay= on the normal /send and /state, we ignore it so with this flag their event goes out right away. should we reject that param or not advertise the unstable flag?

older clients send `?org.matrix.msc4140.delay=` on the normal `/send` and `/state`, we ignore it so with this flag their event goes out right away. should we reject that param or not advertise the unstable flag?
Owner

If the unstable and stable behaviours are basically the same then I think it's fine to keep both

If the unstable and stable behaviours are basically the same then I think it's fine to keep both
Author
Member

@eleboucher wrote in #2583 (comment):

older clients send ?org.matrix.msc4140.delay= on the normal /send and /state, we ignore it so with this flag their event goes out right away. should we reject that param or not advertise the unstable flag?

I think it's probably fine as-is. That's a really old version of the MSC, quite old, clients shouldn't be using it now.

@eleboucher wrote in https://forgejo.ellis.link/continuwuation/continuwuity/pulls/2583#issuecomment-40847: > older clients send `?org.matrix.msc4140.delay=` on the normal `/send` and `/state`, we ignore it so with this flag their event goes out right away. should we reject that param or not advertise the unstable flag? I think it's probably fine as-is. That's a really old version of the MSC, quite old, clients shouldn't be using it now.
Henry-Hiles marked this conversation as resolved
@ -542,0 +548,4 @@
..descriptor::RANDOM_SMALL
},
Descriptor {
name: "userid_delayid",
Owner

Column names are usually key_value, so this name implies the key is just a user ID and it consequently maps to explicitly one delay ID value. I think useriddelayid might be more idiomatic?

Column names are usually `key_value`, so this name implies the key is just a user ID and it consequently maps to explicitly one delay ID value. I think `useriddelayid` might be more idiomatic?
Author
Member

Fixed :3

Fixed :3
Henry-Hiles marked this conversation as resolved
@ -0,0 +184,4 @@
}
}
impl Service {
Owner

nit: I think methods of this impl are broadly missing docstrings, I'm having to do too much jumping around to figure out how they piece together.

nit: I think methods of this impl are broadly missing docstrings, I'm having to do too much jumping around to figure out how they piece together.
Author
Member

Added them, lmk if it's good enough.

Added them, lmk if it's good enough.
Henry-Hiles marked this conversation as resolved
@ -0,0 +274,4 @@
let retry_after = Duration::from_secs(
retry_after
.as_secs()
.saturating_add(u64::from(retry_after.subsec_nanos() > 0)),
Owner

I might be oopid but doesn't this u64::from receive a boolean value (X > N)? or does rust do something unintuitive here that I need an IDE to see

I might be oopid but doesn't this `u64::from` receive a boolean value (`X > N`)? or does rust do something unintuitive here that I need an IDE to see
Author
Member

I think it's correct behavior, as it rounds up. But I will make it more clear maybe.

I think it's correct behavior, as it rounds up. But I will make it more clear maybe.
Author
Member

I can replace this with:

		let retry_after = Duration::from_secs(
			retry_after
				.as_millis()
				.div_ceil(1000)
				.try_into()
				.unwrap_or(u64::MAX),
		);

If you think it's clearer?

I can replace this with: ```rs let retry_after = Duration::from_secs( retry_after .as_millis() .div_ceil(1000) .try_into() .unwrap_or(u64::MAX), ); ``` If you think it's clearer?
Author
Member

To clarify, the original behavior is to add 1 if there's any fractional part, which MSC4140 requires for Retry-After.

To clarify, the original behavior is to add 1 if there's any fractional part, which MSC4140 requires for Retry-After.
Author
Member

I can definitely add a comment, but lmk if you want me to also change the code to what I said above ^

I can definitely add a comment, but lmk if you want me to also change the code to what I said above ^
Author
Member

I went ahead and replaced it with the other logic, plus a comment, so it's more clear:

		let retry_after = Duration::from_secs(
			retry_after
				.as_millis()
				// MSC4140 requires rounding up to the nearest second.
				.div_ceil(1000)
				.try_into()
				.unwrap_or(u64::MAX),
		);
I went ahead and replaced it with the other logic, plus a comment, so it's more clear: ```rs let retry_after = Duration::from_secs( retry_after .as_millis() // MSC4140 requires rounding up to the nearest second. .div_ceil(1000) .try_into() .unwrap_or(u64::MAX), ); ```
Owner

That makes sense, I thought it'd be some weird round-up hack since true is technically 1. This looks clearer though, thanks!

That makes sense, I thought it'd be some weird round-up hack since true is technically 1. This looks clearer though, thanks!
nex marked this conversation as resolved
@ -0,0 +362,4 @@
/// Removes a user's scheduled delayed events without keeping them for
/// lookup, for account deactivation.
pub async fn remove_all_for_user(&self, user_id: &UserId) {
let delay_ids: Vec<String> = self.user_delay_ids(user_id).collect().await;
Owner

nit: this iterator doesn't need collecting, you can just pin a stream and poll over it

nit: this iterator doesn't need collecting, you can just pin a stream and poll over it
Author
Member

Fixed :3

Fixed :3
Henry-Hiles marked this conversation as resolved
@ -0,0 +374,4 @@
}
/// Sends the delayed event if it is due, otherwise returns its send time.
async fn send_if_due(&self, delay_id: String) -> Option<(SystemTime, String)> {
Owner

Does delay_id need to be a String? it looks like it could take &str instead

Does `delay_id` need to be a `String`? it looks like it could take `&str` instead
Author
Member

i think you're right and I just don't know rust well enough :3

will change!

i think you're right and I just don't know rust well enough :3 will change!
Author
Member

Fixed :3

Fixed :3
Henry-Hiles marked this conversation as resolved
Lines 403-406
@ -0,0 +400,7 @@
async fn send(&self, delay_id: &str, event: &ScheduledDelayedEvent) -> Result<OwnedEventId> {
let content = event.content.clone().into_json();
let redacts = (event.event_type == TimelineEventType::RoomRedaction)
.then(|| serde_json::from_str::<MaybeRedaction>(content.get()).ok())
.flatten()
.and_then(|redaction| redaction.redacts);
Owner

I don't think this works for redactions in rooms v10 and below?

I don't think this works for redactions in rooms v10 and below?
Author
Member

Uhh I think it does because it's the same as /send, redacts is read from the content into partialPdu.recats, and then timeline/create.rs keeps it top-level for v10 and below, or drops it for v11+ where its just in the content?

Uhh I think it does because it's the same as `/send`, `redacts` is read from the content into `partialPdu.recats`, and then `timeline/create.rs` keeps it top-level for v10 and below, or drops it for v11+ where its just in the content?
Owner

Oh I forgot that's how we did that. Nevermind then!

Oh I forgot that's how we did that. Nevermind then!
nex marked this conversation as resolved
Lines 456-467
@ -0,0 +453,15 @@
return;
};
let expired: Vec<String> = self
.db
.delayid_finalizeddelayedevent
.stream::<'_, &str, FinalizedDelayedEvent>()
.ignore_err()
.ready_filter_map(|(delay_id, event)| {
(event.finalized.finalized_ts < cutoff).then(|| delay_id.to_owned())
})
.collect()
.await;
for delay_id in expired {
Owner

nit: this stream also doesn't need collecting (see earlier comment)

nit: this stream also doesn't need collecting (see earlier comment)
Author
Member

Fixed :3

Fixed :3
Henry-Hiles marked this conversation as resolved
nex added this to the 26.11.0 milestone 2026-11-23 04:21:04 +00:00
nex modified the milestone from 26.11.0 to 27.1.0 2026-11-23 04:21:05 +00:00
chore: Address review comments for #2583
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Prek / Check changed files (pull_request) Successful in 7s
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 8s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 2m4s
Update flake hashes / update-flake-hashes (pull_request) Successful in 2m31s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 10m41s
e4cf3b82d2
eleboucher requested changes 2026-11-23 07:23:35 +00:00
Dismissed
eleboucher left a comment

looks good overall

looks good overall
@ -0,0 +46,4 @@
)));
}
if serde_json::from_str::<JsonMap<String, JsonValue>>(body.content.json().get()).is_err() {
Contributor

no size check here, content can be up to max_request_size (20MB). can we reject anything over the 65536 pdu limit?

no size check here, content can be up to `max_request_size` (20MB). can we reject anything over the 65536 pdu limit?
Owner

It's probably not great for UX but huge events will be rejected at send time by build and append pdu. It's hard to know the final size of the PDU without building it outright (although I think there's create_hash_sign_event or something that can create a pdu without persisting it)

It's probably not great for UX but huge events will be rejected at send time by build and append pdu. It's hard to know the final size of the PDU without building it outright (although I think there's `create_hash_sign_event` or something that can create a pdu without persisting it)
Author
Member

Done based on convo in devel :3

Done based on convo in devel :3
Henry-Hiles marked this conversation as resolved
@ -0,0 +102,4 @@
.rooms
.delayed_events
.update(sender_user, &delay_id, action)
.await?;
Contributor

missing the suspension check that /send and /state have

missing the suspension check that `/send` and `/state` have
Author
Member

Fixed.

Fixed.
Henry-Hiles marked this conversation as resolved
@ -0,0 +437,4 @@
redacts,
};
let state_lock = self.services.state.mutex.lock(&event.room_id).await;
Contributor

same here, events scheduled before a suspension still get sent

same here, events scheduled before a suspension still get sent
Author
Member

Fixed!

Fixed!
Henry-Hiles marked this conversation as resolved
@ -0,0 +454,4 @@
) {
self.db.useriddelayid.del((&event.user_id, delay_id));
self.db.delayid_scheduleddelayedevent.remove(delay_id);
self.db.delayid_finalizeddelayedevent.raw_put(
Contributor

no cap per user on finalized events, schedule + cancel in a loop grows this forever. MSC recommends 1000 per user

no cap per user on finalized events, schedule + cancel in a loop grows this forever. MSC recommends 1000 per user
Author
Member

Added!

Added!
Henry-Hiles marked this conversation as resolved
@ -0,0 +73,4 @@
// All of these are cancellation-safe
select! {
Some(delay_id) = next_due => {
if let Some(time) = service.send_if_due(&delay_id).await {
Contributor

the send is awaited inline, so one slow room delays every other delayed event. could we spawn it?

the send is awaited inline, so one slow room delays every other delayed event. could we spawn it?
Author
Member

Added!

Added!
Henry-Hiles marked this conversation as resolved
chore: Address review comments for #2583
Some checks failed
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Prek / Check changed files (pull_request) Successful in 6s
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 9s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 3m21s
Update flake hashes / update-flake-hashes (pull_request) Successful in 3m33s
Checks / Prek / Clippy and Cargo Tests (pull_request) Has been cancelled
57243198a1
Henry-Hiles force-pushed quad/feat/delayed-events from 57243198a1
Some checks failed
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Prek / Check changed files (pull_request) Successful in 6s
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 9s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 3m21s
Update flake hashes / update-flake-hashes (pull_request) Successful in 3m33s
Checks / Prek / Clippy and Cargo Tests (pull_request) Has been cancelled
to 26118d18b6
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 9s
Checks / Prek / Check changed files (pull_request) Successful in 14s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 2m1s
Update flake hashes / update-flake-hashes (pull_request) Successful in 2m20s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 10m4s
2026-11-23 15:57:35 +00:00
Compare
nex approved these changes 2026-11-23 16:03:07 +00:00
eleboucher approved these changes 2026-11-23 16:07:11 +00:00
Henry-Hiles force-pushed quad/feat/delayed-events from 26118d18b6
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 9s
Checks / Prek / Check changed files (pull_request) Successful in 14s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 2m1s
Update flake hashes / update-flake-hashes (pull_request) Successful in 2m20s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 10m4s
to 3da0497c5c
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Prek / Check changed files (pull_request) Successful in 4s
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 11s
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 1m32s
Update flake hashes / update-flake-hashes (pull_request) Successful in 1m50s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 6m17s
2026-11-23 21:14:49 +00:00
Compare
Author
Member

(force-push was to resolve merge conflicts)

(force-push was to resolve merge conflicts)
All checks were successful
Documentation / Build and Deploy Documentation (pull_request) Has been skipped
Checks / Prek / Check changed files (pull_request) Successful in 4s
Required
Details
Checks / Changelog / Check changelog is added (pull_request_target) Successful in 11s
Required
Details
Checks / Prek / Pre-commit & Formatting (pull_request) Successful in 1m32s
Required
Details
Update flake hashes / update-flake-hashes (pull_request) Successful in 1m50s
Checks / Prek / Clippy and Cargo Tests (pull_request) Successful in 6m17s
Required
Details
This pull request is blocked because it's outdated.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u 'quad/feat/delayed-events:Henry-Hiles-quad/feat/delayed-events'
git switch 'Henry-Hiles-quad/feat/delayed-events'
Sign in to join this conversation.
No reviewers
No milestone
No assignees
3 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
continuwuation/continuwuity!2583
No description provided.