Skip to content

Commit 5a5566c

Browse files
author
Meli
committed
fix(desktop): sequence post-subscribe refresh behind channel head hydration
Carl/#6572 re-review: useChannelMessagesQuery parks on channelHeadHydration() while useChannelSubscription starts concurrently. When subscribeToChannelLive settles before the SQLite head load, refreshAfterSubscribe() invalidates a query that is fetching with no data yet. TanStack dedupes that onto the in-flight fetch (query.fetch only cancels when state.data exists), the seed lands, consumeHydratedChannel() returns the snapshot, and get_channel_window is never called — the channel stays stale until reconnect or remount. refreshChannelWindowMessages now awaits channelHeadHydration() first, and when the query holds seeded data (dataUpdatedAt 0 — only the hydration seed writes that) awaits the snapshot fetch's promise so the mount gate is consumed before invalidating. The refetch is then a distinct authoritative window fetch. Cold and warm channels carry no such marker and dedupe or cancel exactly as before; one call site covers the subscribe-success, subscribe-failure and reconnect paths. Tests (channelHeadCache.test.mjs): - subscribe resolves before a 150 ms cache load → 1 get_channel_window call and the relay row replaces the persisted one. Fails at the previous head with 0 calls. - cold channel with an immediate subscription → still exactly 1 call. Co-authored-by: Meli <5aaa86bce934fc3445fc254aab560a40923f10252f92107e665073dede0e04d3@buzz.block.builderlab.xyz> Signed-off-by: Meli <5aaa86bce934fc3445fc254aab560a40923f10252f92107e665073dede0e04d3@buzz.block.builderlab.xyz>
1 parent db21b05 commit 5a5566c

2 files changed

Lines changed: 93 additions & 1 deletion

File tree

‎desktop/src/features/messages/lib/channelHeadCache.test.mjs‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,81 @@ test("a hydrated channel still revalidates when live subscription setup fails",
302302
),
303303
);
304304
});
305+
306+
test("a live subscription that settles before a slow cache load still revalidates", async () => {
307+
// Carl/#6572 re-review: the query is parked on the hydration gate with no
308+
// data yet, so an invalidation issued now dedupes onto that in-flight fetch
309+
// (cancelRefetch only cancels when data exists). The seed then lands and the
310+
// queryFn returns the persisted snapshot — zero authoritative fetches.
311+
install(
312+
[{ channelId, events: [root, bounds()], savedAt: 1, lastVisitedAt: 1 }],
313+
{ loadDelayMs: 150 },
314+
);
315+
mock.method(relayClient, "subscribeToReconnects", () => () => {});
316+
mock.method(relayClient, "subscribeToChannelLive", () =>
317+
Promise.resolve(async () => {}),
318+
);
319+
try {
320+
const client = new QueryClient({
321+
defaultOptions: { queries: { retry: false } },
322+
});
323+
void hydrateChannelHeads(client, {
324+
pubkey: "f".repeat(64),
325+
relayUrl: "wss://relay",
326+
});
327+
const { renderHook, waitFor } = await import("@testing-library/react");
328+
const view = renderHook(
329+
() => {
330+
useChannelSubscription(channel);
331+
return useChannelMessagesQuery(channel);
332+
},
333+
{
334+
wrapper: ({ children }) =>
335+
React.createElement(QueryClientProvider, { client }, children),
336+
},
337+
);
338+
await waitFor(() => assert.equal(channelWindowCalls, 1));
339+
await waitFor(() =>
340+
assert.deepEqual(view.result.current.data, [replacement]),
341+
);
342+
view.unmount();
343+
client.clear();
344+
} finally {
345+
mock.restoreAll();
346+
}
347+
});
348+
349+
test("a cold channel with an immediate live subscription fetches the window once", async () => {
350+
// The post-subscribe refresh must still dedupe onto a cold relay fetch that
351+
// is already in flight; only the hydration-parked fetch needs sequencing.
352+
install([]);
353+
mock.method(relayClient, "subscribeToReconnects", () => () => {});
354+
mock.method(relayClient, "subscribeToChannelLive", () =>
355+
Promise.resolve(async () => {}),
356+
);
357+
try {
358+
const client = new QueryClient({
359+
defaultOptions: { queries: { retry: false } },
360+
});
361+
const { renderHook, waitFor } = await import("@testing-library/react");
362+
const view = renderHook(
363+
() => {
364+
useChannelSubscription(channel);
365+
return useChannelMessagesQuery(channel);
366+
},
367+
{
368+
wrapper: ({ children }) =>
369+
React.createElement(QueryClientProvider, { client }, children),
370+
},
371+
);
372+
await waitFor(() =>
373+
assert.deepEqual(view.result.current.data, [replacement]),
374+
);
375+
await waitFor(() => assert.equal(view.result.current.isFetching, false));
376+
assert.equal(channelWindowCalls, 1);
377+
view.unmount();
378+
client.clear();
379+
} finally {
380+
mock.restoreAll();
381+
}
382+
});

‎desktop/src/features/messages/lib/projectChannelWindow.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
type ChannelWindowStore,
88
} from "./channelWindowStore";
99
import { reconcileChannelWindowMessages } from "./channelWindowReconciliation";
10+
import { channelHeadHydration } from "./channelHeadCache";
1011

1112
/** Keep the rendered timeline cache aligned with its authoritative window. */
1213
export function projectChannelWindowMessages(
@@ -26,8 +27,21 @@ export async function refreshChannelWindowMessages(
2627
queryClient: QueryClient,
2728
channelId: string,
2829
) {
30+
const queryKey = channelMessagesKey(channelId);
31+
// Sequence behind persisted-head hydration. While the channel query is parked
32+
// on that gate it has no data, so TanStack would dedupe this invalidation
33+
// onto it — and that fetch returns the seeded snapshot, never asking the
34+
// relay. A seeded query is recognisable by data at `dataUpdatedAt` 0; let its
35+
// snapshot fetch settle (consuming the mount gate) before invalidating, so
36+
// the refetch is a distinct authoritative window fetch. Cold and warm
37+
// channels carry no such marker and dedupe/cancel exactly as before.
38+
await channelHeadHydration(queryClient);
39+
const query = queryClient.getQueryCache().find({ queryKey, exact: true });
40+
if (query?.state.data !== undefined && query.state.dataUpdatedAt === 0) {
41+
await query.promise?.catch(() => {});
42+
}
2943
await queryClient.invalidateQueries({
30-
queryKey: channelMessagesKey(channelId),
44+
queryKey,
3145
exact: true,
3246
refetchType: "active",
3347
});

0 commit comments

Comments
 (0)