From 034435d2b13c5f4d5dcd2c9868d2e8602c399157 Mon Sep 17 00:00:00 2001 From: Jade Ellis Date: Sat, 28 Nov 2026 16:18:20 +0000 Subject: [PATCH] fix(state-res): Order no-ancestor events before oldest mainline power level Assigning depth 0 to the oldest mainline power-levels event collided with the 0 sentinel for events with no mainline ancestor, breaking ties by timestamp instead of sorting no-ancestor events strictly earlier as required by the Matrix spec. --- src/core/matrix/state_res/mod.rs | 46 +++++++++++++++++++++++++++++++- 1 file changed, 45 insertions(+), 1 deletion(-) diff --git a/src/core/matrix/state_res/mod.rs b/src/core/matrix/state_res/mod.rs index 4421cb6de..04e9f0a4d 100644 --- a/src/core/matrix/state_res/mod.rs +++ b/src/core/matrix/state_res/mod.rs @@ -966,11 +966,14 @@ where } } + // Reserve depth 0 for events with no mainline power-levels ancestor (spec + // position ∞) so they always sort strictly before the oldest mainline + // power-levels event (depth 1). let mainline_map: HashMap<_, _> = mainline .iter() .rev() .enumerate() - .map(|(idx, eid)| ((*eid).clone(), idx)) + .map(|(idx, eid)| ((*eid).clone(), idx.saturating_add(1))) .collect(); let order_map: HashMap<_, _> = to_sort @@ -1386,6 +1389,47 @@ mod tests { ); } + #[tokio::test] + async fn mainline_sort_orders_no_ancestor_before_oldest_power_level() { + let mut events = INITIAL_EVENTS(); + let mut with_pl = to_pdu_event( + "WITH_PL", + alice(), + TimelineEventType::RoomTopic, + Some(""), + to_raw_json_value(&json!({ "topic": "with pl" })).unwrap(), + &["CREATE", "IPOWER", "IMA"], + &["IMA"], + ); + with_pl.origin_server_ts = uint!(50); + + let mut no_pl = to_pdu_event( + "NO_PL", + alice(), + TimelineEventType::RoomTopic, + Some(""), + to_raw_json_value(&json!({ "topic": "no pl" })).unwrap(), + &["CREATE", "IMA"], + &["IMA"], + ); + no_pl.origin_server_ts = uint!(100); + + let to_sort = [with_pl.event_id.clone(), no_pl.event_id.clone()]; + for event in [with_pl, no_pl] { + events.insert(event.event_id.clone(), event); + } + let fetcher = |id: OwnedEventId| { + let events = &events; + async move { events.get(&id).cloned() } + }; + + let sorted = super::mainline_sort(&to_sort, Some(event_id("IPOWER")), &fetcher) + .await + .unwrap(); + + assert_eq!(sorted, vec![event_id("NO_PL"), event_id("WITH_PL")]); + } + /// Events at the start of a room have no `m.room.power_levels` in their /// auth events, so the sender's power for sort ordering comes from the /// create event instead.