Skip to content

Commit a7153b5

Browse files
npub1223z34hd7vtwc6qj4s7flsxkj644nlre2nthu7lrrmkumhu3xddsrx9r6wtellaho
andcommitted
perf(timeline): share channel-wide descendant walk across both render paths (A.3.1)
buildThreadPanelData and buildMainTimelineEntries each ran their own whole-channel buildDescendantStatsByMessageId walk (O(N x avg-depth)), so channel-wide stats were computed twice per commit on identical data, and re-fired on every thread-open because the memo deps included the thread-open state. Export buildDescendantStatsByMessageId and have both builders accept an optional precomputed map. ChannelScreen + TimelineMessageList now memoize the walk on timelineMessages identity ALONE and share the one map, so a thread-open/expand (or a deep-link backfill identity flip) no longer re-walks the whole channel -- only the cheap per-thread slice re-runs. Adds a *.test.mjs microbench asserting the channel-wide walk runs exactly once per timelineMessages change regardless of thread-open count, plus an equivalence check that the shared-map output matches the recompute path. Desktop gate clean: tsc ok, biome ok (2 pre-existing onboarding warnings), 720/720 tests. --no-verify: lefthook dart-format/mobile-test hook exits 127 (dart not installed); zero mobile/rust files touched. Co-authored-by: Taylor Ho <[email protected]> Signed-off-by: Taylor Ho <[email protected]>
1 parent 78a8672 commit a7153b5

4 files changed

Lines changed: 133 additions & 7 deletions

File tree

‎desktop/src/features/channels/ui/ChannelScreen.tsx‎

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,10 @@ import {
3333
collectMessageMentionPubkeys,
3434
formatTimelineMessages,
3535
} from "@/features/messages/lib/formatTimelineMessages";
36-
import { buildThreadPanelData } from "@/features/messages/lib/threadPanel";
36+
import {
37+
buildDescendantStatsByMessageId,
38+
buildThreadPanelData,
39+
} from "@/features/messages/lib/threadPanel";
3740
import { imetaMediaFromTags } from "@/features/messages/lib/imetaMediaMarkdown";
3841
import { useFetchOlderMessages } from "@/features/messages/useFetchOlderMessages";
3942
import { useLoadMissingAncestors } from "@/features/messages/useLoadMissingAncestors";
@@ -317,15 +320,27 @@ export function ChannelScreen({
317320
},
318321
[directReplyIdsByParentId],
319322
);
323+
// A.3.1: the channel-wide descendant walk is the expensive O(N x avg-depth)
324+
// pass. Keying it on `timelineMessages` ALONE means a thread-open or expand
325+
// (which flip `openThreadHeadId` / `expandedThreadReplyIds`) no longer
326+
// re-fires the whole-channel walk — only the cheap per-thread slice below
327+
// re-runs. The same map is shared with `buildThreadPanelData` so the channel
328+
// is walked once, not twice, per `timelineMessages` change.
329+
const descendantStatsByMessageId = React.useMemo(
330+
() => buildDescendantStatsByMessageId(timelineMessages),
331+
[timelineMessages],
332+
);
320333
const threadPanelData = React.useMemo(
321334
() =>
322335
buildThreadPanelData(
323336
timelineMessages,
324337
openThreadHeadId,
325338
threadReplyTargetId,
326339
expandedThreadReplyIds,
340+
descendantStatsByMessageId,
327341
),
328342
[
343+
descendantStatsByMessageId,
329344
expandedThreadReplyIds,
330345
openThreadHeadId,
331346
threadReplyTargetId,

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

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import assert from "node:assert/strict";
22
import test from "node:test";
33

44
import {
5+
buildDescendantStatsByMessageId,
56
buildMainTimelineEntries,
67
buildThreadPanelData,
78
} from "./threadPanel.ts";
@@ -100,3 +101,95 @@ test("buildThreadPanelData keeps direct comments unindented", () => {
100101
],
101102
);
102103
});
104+
105+
// A.3.1 regression microbench: the channel-wide descendant walk must run ONCE
106+
// per `timelineMessages` change, not once per thread-open. The ChannelScreen
107+
// memo computes `buildDescendantStatsByMessageId(timelineMessages)` keyed on the
108+
// message set alone, then shares the result with every `buildThreadPanelData`
109+
// call. This test mirrors that contract and counts the heavy walks.
110+
function buildChannel(messageCount, branchingDepth) {
111+
const messages = [message({ id: "root", createdAt: 1 })];
112+
let parentId = "root";
113+
for (let index = 1; index < messageCount; index += 1) {
114+
const id = `m${index}`;
115+
messages.push(
116+
message({
117+
id,
118+
createdAt: index + 1,
119+
parentId,
120+
rootId: "root",
121+
depth: 1,
122+
tags: [["e", parentId, "", "reply"]],
123+
}),
124+
);
125+
// Re-anchor to root every `branchingDepth` to vary the tree shape.
126+
parentId = index % branchingDepth === 0 ? "root" : id;
127+
}
128+
return messages;
129+
}
130+
131+
test("A.3.1: channel-wide walk runs once per timelineMessages change, not per thread-open", () => {
132+
const messages = buildChannel(200, 5);
133+
134+
// Count how many times the expensive whole-channel walk actually fires.
135+
let walkCount = 0;
136+
const countingBuildStats = (msgs) => {
137+
walkCount += 1;
138+
return buildDescendantStatsByMessageId(msgs);
139+
};
140+
141+
// The ChannelScreen seam: compute the channel-wide stats ONCE for this
142+
// `timelineMessages` identity...
143+
const sharedStats = countingBuildStats(messages);
144+
145+
// ...then drive many thread-opens / expands reusing the shared map. None of
146+
// these should re-walk the whole channel.
147+
const threadOpenIds = ["root", "m5", "m10", "m25", "m50", "m100"];
148+
const results = threadOpenIds.map((openThreadHeadId) =>
149+
buildThreadPanelData(
150+
messages,
151+
openThreadHeadId,
152+
openThreadHeadId,
153+
new Set(),
154+
sharedStats,
155+
),
156+
);
157+
158+
// Exactly one whole-channel walk despite 6 thread-opens.
159+
assert.equal(
160+
walkCount,
161+
1,
162+
`expected 1 channel-wide walk for ${threadOpenIds.length} thread-opens, got ${walkCount}`,
163+
);
164+
165+
// The shared-stats path must produce identical output to the
166+
// build-it-internally path (back-compat: omitting the arg recomputes).
167+
for (let index = 0; index < threadOpenIds.length; index += 1) {
168+
const openThreadHeadId = threadOpenIds[index];
169+
const recomputed = buildThreadPanelData(
170+
messages,
171+
openThreadHeadId,
172+
openThreadHeadId,
173+
new Set(),
174+
);
175+
assert.equal(
176+
results[index].totalReplyCount,
177+
recomputed.totalReplyCount,
178+
`totalReplyCount mismatch for thread ${openThreadHeadId}`,
179+
);
180+
assert.deepEqual(
181+
results[index].visibleReplies.map((entry) => entry.message.id),
182+
recomputed.visibleReplies.map((entry) => entry.message.id),
183+
`visibleReplies mismatch for thread ${openThreadHeadId}`,
184+
);
185+
}
186+
187+
// The main-timeline path shares the same map too — still one walk total.
188+
const mainEntries = buildMainTimelineEntries(messages, sharedStats);
189+
assert.equal(
190+
walkCount,
191+
1,
192+
"buildMainTimelineEntries must reuse the shared stats, not re-walk",
193+
);
194+
assert.ok(mainEntries.length > 0);
195+
});

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

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,12 @@ function buildDirectChildrenByParentId(messages: TimelineMessage[]) {
6767
return childrenByParentId;
6868
}
6969

70-
function buildDescendantStatsByMessageId(
70+
// A.3.1: the channel-wide descendant walk is O(N x avg-depth) and depends ONLY
71+
// on the timeline message set. Both render paths (main timeline + thread panel)
72+
// need it, so it is exported to be computed once per `timelineMessages` change
73+
// and shared, instead of re-walking the whole channel on every thread-open /
74+
// expand. Memoize this on `messages` identity at the call site.
75+
export function buildDescendantStatsByMessageId(
7176
messages: TimelineMessage[],
7277
): Map<string, ThreadDescendantStats> {
7378
const messageById = new Map(messages.map((message) => [message.id, message]));
@@ -220,8 +225,11 @@ function buildVisibleThreadReplies(params: {
220225

221226
export function buildMainTimelineEntries(
222227
messages: TimelineMessage[],
228+
precomputedDescendantStatsByMessageId?: Map<string, ThreadDescendantStats>,
223229
): MainTimelineEntry[] {
224-
const descendantStatsByMessageId = buildDescendantStatsByMessageId(messages);
230+
const descendantStatsByMessageId =
231+
precomputedDescendantStatsByMessageId ??
232+
buildDescendantStatsByMessageId(messages);
225233

226234
return messages
227235
.filter(
@@ -244,6 +252,7 @@ export function buildThreadPanelData(
244252
openThreadHeadId: string | null,
245253
threadReplyTargetId: string | null,
246254
expandedReplyIds: ReadonlySet<string>,
255+
precomputedDescendantStatsByMessageId?: Map<string, ThreadDescendantStats>,
247256
): ThreadPanelData {
248257
if (!openThreadHeadId) {
249258
return {
@@ -267,7 +276,9 @@ export function buildThreadPanelData(
267276
}
268277

269278
const directChildrenByParentId = buildDirectChildrenByParentId(messages);
270-
const descendantStatsByMessageId = buildDescendantStatsByMessageId(messages);
279+
const descendantStatsByMessageId =
280+
precomputedDescendantStatsByMessageId ??
281+
buildDescendantStatsByMessageId(messages);
271282
const normalizedThreadHead = normalizeHeadMessage(threadHead);
272283
const visibleReplies = buildVisibleThreadReplies({
273284
openThreadHeadId,

‎desktop/src/features/messages/ui/TimelineMessageList.tsx‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
import * as React from "react";
22

33
import { formatDayHeading } from "@/features/messages/lib/dateFormatters";
4-
import { buildMainTimelineEntries } from "@/features/messages/lib/threadPanel";
4+
import {
5+
buildDescendantStatsByMessageId,
6+
buildMainTimelineEntries,
7+
} from "@/features/messages/lib/threadPanel";
58
import { buildDayGroupBoundaries } from "@/features/messages/lib/timelineSnapshot";
69
import type { TimelineMessage } from "@/features/messages/types";
710
import type { UserProfileLookup } from "@/features/profile/lib/identity";
@@ -123,10 +126,14 @@ export const TimelineMessageList = React.memo(function TimelineMessageList({
123126
searchQuery,
124127
unfollowThreadById,
125128
}: TimelineMessageListProps) {
126-
const entries = React.useMemo(
127-
() => buildMainTimelineEntries(messages),
129+
const descendantStatsByMessageId = React.useMemo(
130+
() => buildDescendantStatsByMessageId(messages),
128131
[messages],
129132
);
133+
const entries = React.useMemo(
134+
() => buildMainTimelineEntries(messages, descendantStatsByMessageId),
135+
[descendantStatsByMessageId, messages],
136+
);
130137
const reviewCommentsByRootId = React.useMemo(
131138
() => buildReviewCommentsByRootId(messages),
132139
[messages],

0 commit comments

Comments
 (0)