diff --git a/src/app/utils/notifications.test.ts b/src/app/utils/notifications.test.ts index 905320001..ded5ab1be 100644 --- a/src/app/utils/notifications.test.ts +++ b/src/app/utils/notifications.test.ts @@ -45,8 +45,8 @@ const makeMx = (events: MatrixEvent[], readUpTo: string | null) => { }; }; -// The live timeline is in timeline order by contract, so the newest event is last. -// Ordering defects belong in markExpandedTimelinesLimited, not here. +// The live timeline is in timeline order, so the newest event is last. Ordering +// defects belong in the sliding-sync layer, not here. describe('markAsRead', () => { it('marks read up to the last event in the timeline', async () => { const { mx, setRoomReadMarkers, sendReadReceipt } = makeMx( diff --git a/src/client/initMatrix.test.ts b/src/client/initMatrix.test.ts index a73c3ac83..4c0aca6d3 100644 --- a/src/client/initMatrix.test.ts +++ b/src/client/initMatrix.test.ts @@ -63,7 +63,10 @@ describe('supportsSlidingSync', () => { it('reports support when the homeserver advertises simplified sliding sync', async () => { const check = vi.fn<(feature: string) => Promise>().mockResolvedValue(true); - await expect(supportsSlidingSync(makeMx(check), baseUrl)).resolves.toBe(true); + await expect(supportsSlidingSync(makeMx(check), baseUrl)).resolves.toEqual({ + supported: true, + reason: 'advertised', + }); expect(check).toHaveBeenCalledWith('org.matrix.simplified_msc3575'); }); @@ -73,17 +76,18 @@ describe('supportsSlidingSync', () => { makeMx(() => Promise.resolve(false)), baseUrl ) - ).resolves.toBe(false); + ).resolves.toEqual({ supported: false, reason: 'unadvertised' }); }); // Classic sync still works; opting in against a server that cannot serve it does not. + // The reason must stay distinguishable: we never established the server's answer. it('falls back to classic sync when the capability was never confirmed', async () => { await expect( supportsSlidingSync( makeMx(() => Promise.reject(new Error('offline'))), baseUrl ) - ).resolves.toBe(false); + ).resolves.toEqual({ supported: false, reason: 'unknown' }); }); it('keeps sliding sync when a previously confirmed capability is cached', async () => { @@ -94,7 +98,7 @@ describe('supportsSlidingSync', () => { makeMx(() => Promise.reject(new Error('offline'))), baseUrl ) - ).resolves.toBe(true); + ).resolves.toEqual({ supported: true, reason: 'cached' }); }); it('does not resurrect sliding sync from a cached negative', async () => { @@ -105,6 +109,6 @@ describe('supportsSlidingSync', () => { makeMx(() => Promise.reject(new Error('offline'))), baseUrl ) - ).resolves.toBe(false); + ).resolves.toEqual({ supported: false, reason: 'unknown' }); }); }); diff --git a/src/client/initMatrix.ts b/src/client/initMatrix.ts index d363bf3d4..470812056 100644 --- a/src/client/initMatrix.ts +++ b/src/client/initMatrix.ts @@ -164,10 +164,18 @@ function installSlidingSyncRequestPatch(mx: MatrixClient, manager: SlidingSyncMa const roomIds = manager.getActiveRoomSubscriptionIds(); scopeTypingExtension(req.extensions, roomIds); - // Must run before the SDK processes the response. const response = await original(reqBody, baseUrl, abortSignal); - markExpandedTimelinesLimited(response); - manager.sanitizeOptimisticJoinResponse(response); + // Must run before the SDK processes the response. A throw would reach the SDK's + // loop, which drops the response and retries the same `pos` forever. + try { + markExpandedTimelinesLimited(response); + manager.sanitizeOptimisticJoinResponse(response); + } catch (error) { + Sentry.captureException(error, { tags: { area: 'sliding_sync_response' } }); + debugLog.error('sync', 'Failed to prepare sliding sync response', { + error: error instanceof Error ? error.message : String(error), + }); + } return response; }; @@ -379,12 +387,19 @@ const SLIDING_SYNC_UNSTABLE_FEATURE = 'org.matrix.simplified_msc3575'; const SLIDING_SYNC_CAPABILITY_TIMEOUT_MS = 5000; -// The SDK retries an unsupported sync endpoint forever instead of erroring, so an -// unconfirmed capability falls back to classic sync. A cached confirmation keeps -// sliding sync through one bad lookup. /versions has no timeout of its own. -export const supportsSlidingSync = async (mx: MatrixClient, baseUrl: string): Promise => { +// The SDK retries an unsupported endpoint forever instead of erroring, so anything +// short of a confirmation falls back to classic sync. /versions has no timeout of +// its own, hence the race. +export const supportsSlidingSync = async ( + mx: MatrixClient, + baseUrl: string +): Promise<{ + supported: boolean; + reason: 'advertised' | 'unadvertised' | 'cached' | 'unknown'; +}> => { + let timer: ReturnType | undefined; const timeout = new Promise((resolve) => { - globalThis.setTimeout(() => resolve(undefined), SLIDING_SYNC_CAPABILITY_TIMEOUT_MS); + timer = globalThis.setTimeout(() => resolve(undefined), SLIDING_SYNC_CAPABILITY_TIMEOUT_MS); }); let confirmed: boolean | undefined; @@ -395,12 +410,20 @@ export const supportsSlidingSync = async (mx: MatrixClient, baseUrl: string): Pr ]); } catch { confirmed = undefined; + } finally { + globalThis.clearTimeout(timer); } - return ( - confirmed ?? - wasUnstableFeatureCached(baseUrl, mx.getSafeUserId(), SLIDING_SYNC_UNSTABLE_FEATURE) + if (confirmed !== undefined) { + return { supported: confirmed, reason: confirmed ? 'advertised' : 'unadvertised' }; + } + // We never reached /versions, so a previous confirmation is all we have to go on. + const cached = wasUnstableFeatureCached( + baseUrl, + mx.getSafeUserId(), + SLIDING_SYNC_UNSTABLE_FEATURE ); + return { supported: cached, reason: cached ? 'cached' : 'unknown' }; }; const disposeSlidingSync = (mx: MatrixClient): void => { @@ -467,12 +490,19 @@ export const startClient = async (mx: MatrixClient, config?: StartClientConfig): const baseUrl = config?.baseUrl ?? mx.baseUrl; const optedIntoSliding = config?.sessionSlidingSyncOptIn === true; - const useSliding = optedIntoSliding && (await supportsSlidingSync(mx, baseUrl)); + const slidingSupport = optedIntoSliding + ? await supportsSlidingSync(mx, baseUrl) + : { supported: false, reason: 'unadvertised' as const }; + const useSliding = optedIntoSliding && slidingSupport.supported; if (optedIntoSliding && !useSliding) { - debugLog.warn('sync', 'Homeserver does not support sliding sync; using classic sync', { + debugLog.warn('sync', 'Falling back to classic sync', { userId: mx.getUserId(), baseUrl, + reason: slidingSupport.reason, + }); + Sentry.metrics.count('sable.sync.transport_downgrade', 1, { + attributes: { reason: slidingSupport.reason }, }); } diff --git a/src/client/slidingSync.ts b/src/client/slidingSync.ts index cb1c437b8..9e927424b 100644 --- a/src/client/slidingSync.ts +++ b/src/client/slidingSync.ts @@ -282,8 +282,7 @@ type ExpandedTimelineRoomData = MSC3575RoomData & { unstable_expanded_timeline?: // Synapse flags history re-sent for a raised timeline_limit only as // `unstable_expanded_timeline`, but the SDK reconciles a gap on `limited`/`initial`, -// so without this it appends that history after the newest event. Drop once the SDK -// reads the flag. +// so without this it lands after the newest event. Drop once the SDK reads the flag. export const markExpandedTimelinesLimited = (resp: MSC3575SlidingSyncResponse | null): void => { if (!resp?.rooms) return; @@ -973,9 +972,8 @@ export class SlidingSyncManager { } } - // Paging stops once every list is covered, but the counts keep growing. A state - // change does not bump a room, so a room joined mid-session would otherwise sit - // outside the window and stop receiving state deltas until the next restart. + // Paging stops once every list is covered, but the counts keep growing, and a state + // change does not bump a room back into the window. private ensureListCoverage(): void { if (!this.initialListHydrationCompleted) return; diff --git a/src/client/slidingSyncExpandedTimeline.test.ts b/src/client/slidingSyncExpandedTimeline.test.ts index 15f61ba57..5f699e8d3 100644 --- a/src/client/slidingSyncExpandedTimeline.test.ts +++ b/src/client/slidingSyncExpandedTimeline.test.ts @@ -5,8 +5,8 @@ import type { Logger } from 'matrix-js-sdk/lib/logger'; import { createClient, EventTimeline } from '$types/matrix-sdk'; import { markExpandedTimelinesLimited } from './slidingSync'; -// Drives the real matrix-js-sdk room-data path, so this pins the SDK's actual gap -// reconciliation rather than our assumptions about it. +// Drives the real matrix-js-sdk room-data path, pinning the SDK's actual behaviour +// rather than our assumptions about it. const userId = '@me:example.com'; const roomId = '!dm:example.com'; diff --git a/src/client/versionsCache.ts b/src/client/versionsCache.ts index 9726f57ec..ba0a3084d 100644 --- a/src/client/versionsCache.ts +++ b/src/client/versionsCache.ts @@ -113,7 +113,7 @@ export const revalidateVersionsCache = async ( } }; -/** Separates "the server does not support this" from "we could not ask". */ +/** True only when a cached /versions payload advertised the feature. */ export const wasUnstableFeatureCached = ( baseUrl: string, userId: string, diff --git a/tests/e2e/sliding-sync-room-state.spec.ts b/tests/e2e/sliding-sync-room-state.spec.ts index 05a1793e0..eeb3eba48 100644 --- a/tests/e2e/sliding-sync-room-state.spec.ts +++ b/tests/e2e/sliding-sync-room-state.spec.ts @@ -46,7 +46,8 @@ async function loginAsFreshUser( } test.describe('sliding sync room state', () => { - // Regression guard for #1161 / #1389. + // Regression guard for #1389: reintroducing the post-hydration narrowing of the + // joined list fails this. Rooms outside the server's own window are not covered. test('applies a rename to a room that is neither open nor recently active', async ({ page, }, testInfo) => { @@ -81,7 +82,15 @@ test.describe('sliding sync room state', () => { await sendText(hsBaseUrl, user.accessToken, active[i]!, `${tag}-bump-${i}`, i + 1); } + // Proves the client chose sliding sync and the homeserver accepted the request. + const slidingSyncAccepted = page.waitForResponse( + (response) => + response.url().includes('/org.matrix.simplified_msc3575/sync') && response.status() === 200, + { timeout: CLIENT_READY_TIMEOUT } + ); + await page.goto('/'); + await slidingSyncAccepted; await expect(app.room(staleName)).toBeVisible({ timeout: CLIENT_READY_TIMEOUT }); // An active subscription would fetch state regardless of the list config.