fix: prune inactive room timelines (#1466)

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

### Description

Prune inactive room history to reduce memory use while preserving
pagination.

Fixes #

#### Type of change

- [x] 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
- [ ] I have made corresponding changes to the documentation
- [ ] 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-29 02:55:12 +00:00
commit c6cb6fb126
3 files changed
+162 -6

No files matched your search

@@ -0,0 +1,5 @@
---
default: patch
---
Reduce memory use by pruning inactive room history while keeping it available for pagination.
+132 -6
View File
@@ -78,6 +78,25 @@ function makeManager(mx: ReturnType<typeof makeMockMx>): SlidingSyncManager {
return new SlidingSyncManager(mx, 'https://sliding.example.com');
}
function makeRoomWithTimeline(
eventCount: number,
statuses: Array<string | null> = [],
backwardPaginationToken: string | null = 'back-token'
) {
const events = Array.from({ length: eventCount }, (_, i) => ({
status: statuses[i] ?? null,
}));
return {
getLiveTimeline: vi.fn<
() => { getEvents: () => typeof events; getPaginationToken: () => string | null }
>(() => ({
getEvents: () => events,
getPaginationToken: () => backwardPaginationToken,
})),
resetLiveTimeline: vi.fn<() => void>(),
};
}
beforeEach(() => {
vi.clearAllMocks();
localStorage.clear();
@@ -761,9 +780,14 @@ describe('SlidingSyncManager local membership reconciliation', () => {
const updateMyMembership = vi.fn<() => void>();
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => { updateMyMembership: typeof updateMyMembership }>().mockReturnValue({
updateMyMembership,
}),
getRoom: vi
.fn<() => { updateMyMembership: typeof updateMyMembership; getLiveTimeline: unknown }>()
.mockReturnValue({
updateMyMembership,
getLiveTimeline: vi.fn<() => { getEvents: () => unknown[] }>(() => ({
getEvents: () => [],
})),
}),
})
);
manager.subscribeToRoom('!room:example.com');
@@ -958,9 +982,14 @@ describe('SlidingSyncManager local membership reconciliation', () => {
const updateMyMembership = vi.fn<() => void>();
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => { updateMyMembership: typeof updateMyMembership }>().mockReturnValue({
updateMyMembership,
}),
getRoom: vi
.fn<() => { updateMyMembership: typeof updateMyMembership; getLiveTimeline: unknown }>()
.mockReturnValue({
updateMyMembership,
getLiveTimeline: vi.fn<() => { getEvents: () => unknown[] }>(() => ({
getEvents: () => [],
})),
}),
})
);
manager.subscribeToRoom('!room:example.com');
@@ -973,6 +1002,103 @@ describe('SlidingSyncManager local membership reconciliation', () => {
});
});
describe('SlidingSyncManager timeline pruning on room deactivation', () => {
it('prunes the live timeline when it exceeds the threshold, preserving the backward pagination token', () => {
const roomId = '!over:example.com';
const room = makeRoomWithTimeline(151);
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => typeof room>().mockReturnValue(room),
})
);
manager.subscribeToRoom(roomId);
manager.unsubscribeFromRoom(roomId);
expect(room.resetLiveTimeline).toHaveBeenCalledOnce();
expect(room.resetLiveTimeline).toHaveBeenCalledWith('back-token');
});
it('keeps the live timeline at the threshold exactly', () => {
const roomId = '!at:example.com';
const room = makeRoomWithTimeline(150);
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => typeof room>().mockReturnValue(room),
})
);
manager.subscribeToRoom(roomId);
manager.unsubscribeFromRoom(roomId);
expect(room.resetLiveTimeline).not.toHaveBeenCalled();
});
it('never prunes while a local echo is pending send', () => {
const roomId = '!pending:example.com';
const statuses = Array<string | null>(151).fill(null);
statuses[100] = 'sending';
const room = makeRoomWithTimeline(151, statuses);
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => typeof room>().mockReturnValue(room),
})
);
manager.subscribeToRoom(roomId);
manager.unsubscribeFromRoom(roomId);
expect(room.resetLiveTimeline).not.toHaveBeenCalled();
});
it('prunes the room left behind on a route switch', () => {
const oldRoomId = '!old-route:example.com';
const newRoomId = '!new-route:example.com';
const oldRoom = makeRoomWithTimeline(200);
const newRoom = makeRoomWithTimeline(200);
const manager = makeManager(
makeMockMx({
getRoom: vi
.fn<(id: string) => typeof oldRoom | null>()
.mockImplementation((id) =>
id === oldRoomId ? oldRoom : id === newRoomId ? newRoom : null
),
})
);
manager.setActiveRoomSubscriptions([oldRoomId]);
manager.setActiveRoomSubscriptions([newRoomId]);
expect(oldRoom.resetLiveTimeline).toHaveBeenCalledOnce();
expect(newRoom.resetLiveTimeline).not.toHaveBeenCalled();
});
it('does not prune a room that is still active after a route change', () => {
const roomId = '!still-active:example.com';
const room = makeRoomWithTimeline(200);
const manager = makeManager(
makeMockMx({
getRoom: vi.fn<() => typeof room>().mockReturnValue(room),
})
);
manager.setActiveRoomSubscriptions([roomId]);
manager.setActiveRoomSubscriptions([roomId]);
expect(manager.isRoomActive(roomId)).toBe(true);
expect(room.resetLiveTimeline).not.toHaveBeenCalled();
});
it('skips pruning when the room is unknown', () => {
const manager = makeManager(makeMockMx());
manager.subscribeToRoom('!unknown:example.com');
expect(() => manager.unsubscribeFromRoom('!unknown:example.com')).not.toThrow();
expect(manager.isRoomActive('!unknown:example.com')).toBe(false);
});
});
// ── dispose() ────────────────────────────────────────────────────────────────
describe('SlidingSyncManager.dispose()', () => {
+25
View File
@@ -16,6 +16,7 @@ import {
MSC3575_STATE_KEY_LAZY,
MSC3575_STATE_KEY_ME,
EventType,
EventTimeline,
EventEmitterEvents,
ClientEvent,
} from '$types/matrix-sdk';
@@ -44,6 +45,7 @@ const SPACE_SUBSCRIPTION_KEY = 'space';
const IMAGE_PACK_SUBSCRIPTION_KEY = 'image_packs';
const SPACE_IMAGE_PACK_SUBSCRIPTION_KEY = 'space_image_packs';
const ACTIVE_ROOM_TIMELINE_LIMIT = 50;
const PRUNE_TIMELINE_THRESHOLD = 150;
export type PartialSlidingSyncRequest = {
filters?: MSC3575List['filters'];
@@ -1237,6 +1239,28 @@ export class SlidingSyncManager {
return true;
}
// Skips rooms with pending local echoes so unsent messages are never discarded.
private maybePruneRoomTimeline(roomId: string): void {
if (this.disposed || this.activeRoomSubscriptions.has(roomId)) return;
const room = this.mx.getRoom(roomId);
if (!room) return;
const timeline = room.getLiveTimeline();
const events = timeline.getEvents();
if (events.length <= PRUNE_TIMELINE_THRESHOLD) return;
if (events.some((event) => event.status !== null)) return;
// Preserve the backward pagination token so a quiet room can still
// back-paginate if sliding sync does not resend one on reactivation.
const backwardPaginationToken = timeline.getPaginationToken(EventTimeline.BACKWARDS);
room.resetLiveTimeline(backwardPaginationToken);
debugLog.info('sync', 'Pruned inactive room live timeline', {
roomId,
previousEventCount: events.length,
syncCycle: this.syncCount,
});
}
private removeActiveRoomSubscription(roomId: string): boolean {
if (!this.activeRoomSubscriptions.has(roomId)) return false;
const pendingListener = this.pendingRoomDataListeners.get(roomId);
@@ -1247,6 +1271,7 @@ export class SlidingSyncManager {
this.roomDataAwaitingSyncCompletion.delete(roomId);
this.notifyRoomSubscriptionStatus(roomId, false);
this.activeRoomSubscriptions.delete(roomId);
this.maybePruneRoomTimeline(roomId);
log.log(`Sliding Sync active room subscription removed: ${roomId}`);
debugLog.info('sync', 'Room subscription removed (sliding)', {
remainingSubscriptions: this.activeRoomSubscriptions.size,