perf: narrow sync-settled unread recompute to dirty rooms only (#1253)

<!-- Please read
https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before
submitting your pull request -->

### Description

PushProcessor: Use mx.pushProcessor instead of new PushProcessor(mx) in
five places. The unread fallback path allocated one per room per sync
cycle.
Dirty rooms: Recompute unread only for rooms that received data in the
sync response instead of all joined rooms.

#### Type of change

- [ ] Bug fix (non-breaking change which fixes an issue)
- [ ] New feature (non-breaking change which adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to not work as expected)
- [ ] This change requires a documentation update

### Checklist:

- [x] My code follows the style guidelines of this project
- [x] I have performed a self-review of my own code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings

### AI disclosure:

- [ ] Partially AI assisted (clarify which code was AI assisted and
briefly explain what it does).
- [ ] Fully AI generated (explain what all the generated code does in
moderate detail).
<!-- Write any explanation required here, but do not generate the
explanation using AI!! You must prove you understand what the code in
this PR does. -->
This commit is contained in:
7w1 authored and GitHub committed 2026-07-23 16:54:21 +00:00
commit 2ffe1e4cf4
8 files changed
+127 -22

No files matched your search

+2 -2
View File
@@ -12,7 +12,7 @@ import {
import type { Editor } from 'slate';
import { useAtomValue, useSetAtom, useStore } from 'jotai';
import type { Room } from '$types/matrix-sdk';
import { PushProcessor, Direction, EventType } from '$types/matrix-sdk';
import { Direction, EventType } from '$types/matrix-sdk';
import classNames from 'classnames';
import type { VListHandle } from 'virtua';
import { VList } from 'virtua';
@@ -428,7 +428,7 @@ export function RoomTimeline({
const optionalSpace = useSpaceOptionally();
const roomParents = useAtomValue(roomToParentsAtom);
const imagePackRooms = useImagePackRooms(room.roomId, roomParents);
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
const pushProcessor = mx.pushProcessor;
const parseMemberEvent = useMemberEventParser();
const replyDraftAtom = useMemo(() => roomIdToReplyDraftAtomFamily(room.roomId), [room.roomId]);
+1 -2
View File
@@ -7,7 +7,6 @@ import {
Direction,
MatrixEvent,
MatrixEventEvent,
PushProcessor,
ReceiptType,
RelationType,
RoomEvent,
@@ -137,7 +136,7 @@ export function ThreadDrawer({ room, threadRootId, onClose, overlay }: ThreadDra
(userId: string) => jotaiStore.get(profilesCacheAtom)[userId],
[jotaiStore]
);
const pushProcessor = useMemo(() => new PushProcessor(mx), [mx]);
const pushProcessor = mx.pushProcessor;
const useAuthentication = useMediaAuthentication();
const mentionClickHandler = useMentionClickHandler(room.roomId);
const settingsLinkBaseUrl = useSettingsLinkBaseUrl();
@@ -7,7 +7,6 @@ import {
MatrixEventEvent,
RoomEvent,
SyncState,
PushProcessor,
EventType,
} from '$types/matrix-sdk';
@@ -323,7 +322,7 @@ export function BackgroundNotifications() {
});
}
const pushProcessor = new PushProcessor(mx);
const pushProcessor = mx.pushProcessor;
const handleAccountData = (event: MatrixEvent) => {
if (event.getType() === (EventType.Direct as string)) {
+1 -2
View File
@@ -11,7 +11,6 @@ import { getPresenceSyncManager } from '$client/initMatrix';
import {
MatrixEvent,
MatrixEventEvent,
PushProcessor,
RoomEvent,
SetPresence,
SyncState,
@@ -339,7 +338,7 @@ function MessageNotifications() {
}, []);
useEffect(() => {
const pushProcessor = new PushProcessor(mx);
const pushProcessor = mx.pushProcessor;
// Track encrypted events that should skip focus check when decrypted (because we
// already checked focus when the encrypted event arrived, and want to use that
// original state rather than re-checking after decryption completes).
+13 -8
View File
@@ -17,6 +17,7 @@ import {
getNotificationType,
getUnreadInfo,
getUnreadInfos,
getUnreadInfosForRooms,
isNotificationEvent,
} from '$utils/room';
import { useSyncState } from '$hooks/useSyncState';
@@ -198,16 +199,20 @@ export const useBindRoomToUnreadAtom = (mx: MatrixClient, unreadAtom: typeof roo
useEffect(() => {
const manager = getSlidingSyncManager(mx);
if (!manager) return undefined;
return manager.subscribeToResponseSettled(() => {
setUnreadAtom({
type: 'RESET',
unreadInfos: getUnreadInfos(mx, {
applyFixup: true,
mDirects,
}),
return manager.subscribeToResponseSettled((dirtyRoomIds) => {
if (dirtyRoomIds.size === 0) return;
const { unread, deleted } = getUnreadInfosForRooms(mx, dirtyRoomIds, {
applyFixup: true,
mDirects,
});
for (const roomId of deleted) {
publishUnreadAction({ type: 'DELETE', roomId });
}
for (const unreadInfo of unread) {
publishUnreadAction({ type: 'PUT', unreadInfo });
}
});
}, [mx, setUnreadAtom, mDirects]);
}, [mx, setUnreadAtom, publishUnreadAction, mDirects]);
useEffect(() => {
publishUnreadAction({
+39 -2
View File
@@ -16,7 +16,6 @@ import {
EventTimeline,
EventType,
NotificationCountType,
PushProcessor,
PushRuleActionName,
RelationType,
MsgType,
@@ -427,7 +426,7 @@ export const getUnreadInfo = (room: Room, options?: UnreadInfoOptions): UnreadIn
const liveEvents = room.getLiveTimeline().getEvents();
let fallbackTotal = 0;
let fallbackHighlight = 0;
const pushProcessor = new PushProcessor(room.client);
const pushProcessor = room.client.pushProcessor;
for (let i = liveEvents.length - 1; i >= 0; i -= 1) {
const event = liveEvents[i];
if (!event) break;
@@ -517,6 +516,44 @@ export const getUnreadInfos = (mx: MatrixClient, options?: UnreadInfoOptions): U
return unreadInfos;
};
export const getUnreadInfosForRooms = (
mx: MatrixClient,
roomIds: Iterable<string>,
options?: UnreadInfoOptions
): { unread: UnreadInfo[]; deleted: string[] } => {
const unread: UnreadInfo[] = [];
const deleted: string[] = [];
for (const roomId of roomIds) {
const room = mx.getRoom(roomId);
if (!room) {
deleted.push(roomId);
continue;
}
if (room.isSpaceRoom()) {
deleted.push(roomId);
continue;
}
if (room.getMyMembership() !== 'join') {
deleted.push(roomId);
continue;
}
if (getNotificationType(mx, room.roomId) === NotificationType.Mute) {
deleted.push(roomId);
continue;
}
const unreadInfo = getUnreadInfo(room, options);
if (unreadInfo.total > 0 || unreadInfo.highlight > 0) {
unread.push(unreadInfo);
} else {
deleted.push(roomId);
}
}
return { unread, deleted };
};
export const getRoomAvatarUrl = (
mx: MatrixClient,
room: Room,
+41 -1
View File
@@ -137,7 +137,7 @@ describe('SlidingSyncManager initial request', () => {
it('settles response processing after post-response work can finish', async () => {
const manager = makeManager(makeMockMx());
const settled = vi.fn<() => void>();
const settled = vi.fn<(dirtyRoomIds: ReadonlySet<string>) => void>();
manager.subscribeToResponseSettled(settled);
manager.attach();
@@ -153,6 +153,46 @@ describe('SlidingSyncManager initial request', () => {
expect(settled).toHaveBeenCalledOnce();
});
it('includes receipt-only and account-data-only rooms in the settled unread delta', async () => {
const manager = makeManager(makeMockMx());
const settled = vi.fn<(dirtyRoomIds: ReadonlySet<string>) => void>();
manager.subscribeToResponseSettled(settled);
manager.attach();
fireLifecycle(SlidingSyncState.RequestFinished, {});
fireLifecycle(SlidingSyncState.Complete, {
rooms: {},
extensions: {
receipts: {
rooms: {
'!receipt:example.com': {
type: 'm.receipt',
content: {},
},
},
},
account_data: {
rooms: {
'!account-data:example.com': [
{
type: EventType.FullyRead,
content: { event_id: '$event' },
},
],
},
},
},
});
await Promise.resolve();
expect(settled).toHaveBeenCalledOnce();
expect([...settled.mock.calls[0]![0]]).toEqual([
'!receipt:example.com',
'!account-data:example.com',
]);
});
it('does not fan out member requests for users referenced by startup sync', async () => {
const getStateEvent = vi.fn<() => Promise<Record<string, unknown>>>().mockResolvedValue({
membership: KnownMembership.Join,
+29 -3
View File
@@ -60,6 +60,10 @@ type SlidingSyncOptions = {
initialRoomIds?: Iterable<string>;
};
type RoomScopedExtensionResponse = {
rooms?: Record<string, unknown>;
};
export type SlidingSyncListDiagnostics = {
key: string;
knownCount: number;
@@ -245,6 +249,13 @@ export class SlidingSyncManager {
private deferredImagePackSubscriptions: Set<string> | null = null;
/**
* Room IDs that received data in the current sync cycle. Used to narrow the
* sync-settled unread recompute to only changed rooms instead of all rooms.
* Populated by onCacheRoomData, cleared after the settled listeners fire.
*/
private readonly dirtyRoomIds = new Set<string>();
private roomSubscriptionSyncQueued = false;
private readonly roomTimelineLimit: number;
@@ -294,7 +305,9 @@ export class SlidingSyncManager {
private responseProcessing = false;
private readonly responseSettledListeners = new Set<() => void>();
private readonly responseSettledListeners = new Set<
(dirtyRoomIds: ReadonlySet<string>) => void
>();
private previousListCounts: Map<string, number> = new Map();
@@ -493,10 +506,19 @@ export class SlidingSyncManager {
});
}
['receipts', 'account_data'].forEach((extensionName) => {
const extension = resp.extensions?.[extensionName] as
| RoomScopedExtensionResponse
| undefined;
Object.keys(extension?.rooms ?? {}).forEach((roomId) => this.dirtyRoomIds.add(roomId));
});
globalThis.queueMicrotask(() => {
if (this.disposed) return;
this.responseProcessing = false;
this.responseSettledListeners.forEach((listener) => listener());
const dirtyRoomIds = new Set(this.dirtyRoomIds);
this.dirtyRoomIds.clear();
this.responseSettledListeners.forEach((listener) => listener(dirtyRoomIds));
});
};
@@ -515,6 +537,7 @@ export class SlidingSyncManager {
};
this.onCacheRoomData = (roomId, data) => {
this.dirtyRoomIds.add(roomId);
this.sidebarCache.cacheRoom(roomId, data);
if (!this.initialListHydrationCompleted || this.hydratingSidebarCache) return;
@@ -577,6 +600,7 @@ export class SlidingSyncManager {
this.pendingRoomDataListeners.clear();
this.responseProcessing = false;
this.responseSettledListeners.clear();
this.dirtyRoomIds.clear();
this.roomDataAwaitingSyncCompletion.clear();
this.roomSubscriptionStatusListeners.forEach((listeners) =>
listeners.forEach((listener) => listener(false))
@@ -982,7 +1006,9 @@ export class SlidingSyncManager {
return this.responseProcessing;
}
public subscribeToResponseSettled(listener: () => void): () => void {
public subscribeToResponseSettled(
listener: (dirtyRoomIds: ReadonlySet<string>) => void
): () => void {
this.responseSettledListeners.add(listener);
return () => this.responseSettledListeners.delete(listener);
}