Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6305af0
perf: read channel history ahead of the reader and slide past the budget
kalvinnchau Nov 21, 2026
eace668
fix: keep a read-ahead the reader scrolls up to across a channel switch
kalvinnchau Nov 21, 2026
bf31e42
test: recheck the reader's move when a scroll correction lands late
kalvinnchau Nov 21, 2026
86e2aca
test: wheel the fast-scroll pages test in back-to-back notches
kalvinnchau Nov 21, 2026
d9039e7
test: return a held head-with-notices read instead of awaiting it
kalvinnchau Nov 21, 2026
58c822c
test: check a merged revisit head reads its notices with it
kalvinnchau Nov 22, 2026
fee36cb
test: skip the fast-scroll page size check where no pace can be read
kalvinnchau Nov 22, 2026
5e62c9e
fix: read an older page's aux until it covers every row
kalvinnchau Nov 22, 2026
3e82543
fix: read aux only for the open channel
kalvinnchau Nov 22, 2026
7ff8357
fix: slide a window an aux closure takes past its byte budget
kalvinnchau Nov 22, 2026
6dbe70f
fix: let an older page land through live traffic at the row cap
kalvinnchau Nov 22, 2026
bbe7bf3
fix: read a page too large for a response again in default pages
kalvinnchau Nov 22, 2026
2df4d9a
fix: end a newer page a stream drop cancels
kalvinnchau Nov 22, 2026
73ba105
fix: merge a revisit head only where it meets rows read
kalvinnchau Nov 22, 2026
169e530
fix: keep a segment's aux work through a failed return to the head
kalvinnchau Nov 22, 2026
9b53e31
chore: satisfy types and format in the history paging fixes
kalvinnchau Nov 22, 2026
2dbe2f8
fix: keep the older cursor when a live trim keeps late rows below the…
kalvinnchau Nov 23, 2026
9183529
perf: read ahead six screens of history instead of twelve
kalvinnchau Nov 23, 2026
a522cb9
fix: drop the paged floor and stray live rows when a revisit head rep…
kalvinnchau Nov 23, 2026
3bccaa0
fix: keep the aux queue moving past a failing page
kalvinnchau Nov 23, 2026
59c22e9
fix: forget live rows a slide drops from the window
kalvinnchau Nov 23, 2026
f57fc28
fix: do not count rows read into a detached window as new messages
kalvinnchau Nov 23, 2026
1b55e27
chore: note why read-ahead reads stay at foreground priority
kalvinnchau Nov 23, 2026
2d73aed
fix: keep live rows, the tie cursor and the aux drain intact
kalvinnchau Nov 23, 2026
d94dd61
fix: leave writes three api slots and baseline reader-paced reads
kalvinnchau Nov 23, 2026
445787c
fix: keep read-ahead at the head and drop stray live rows after slides
kalvinnchau Nov 23, 2026
2c66db3
fix: forget live rows a read-ahead closure trim drops
kalvinnchau Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 19 additions & 14 deletions browser-host/relay-broker-api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,9 @@ async function harness(
/** Native media URLs name one sha256 blob; the broker enforces the same shape. */
const blob = "c".repeat(64);
const filters = [{ kinds: [0], limit: 1 }];
// Mirrors MAX_INFLIGHT in relay-broker.mjs (not exported).
const MAX_INFLIGHT = 10;
const QUEUED_LIMIT = 99;

test.each([
[202, { status: "aborted" }],
Expand Down Expand Up @@ -1321,11 +1324,13 @@ test("each community has its own query capacity", async () => {
return h.post(route, filters, controller.signal);
};
try {
const primary = Array.from({ length: 6 }, () => post("primary/query"));
await vi.waitFor(() => expect(h.calls).toHaveLength(6));
const primary = Array.from({ length: MAX_INFLIGHT }, () =>
post("primary/query"),
);
await vi.waitFor(() => expect(h.calls).toHaveLength(MAX_INFLIGHT));
expect((await h.post("primary/query", filters)).status).toBe(429);
const secondary = post("secondary/query");
await vi.waitFor(() => expect(h.calls).toHaveLength(7));
await vi.waitFor(() => expect(h.calls).toHaveLength(MAX_INFLIGHT + 1));
release();
for (const response of [...primary, secondary])
expect((await response).status).toBe(200);
Expand All @@ -1347,12 +1352,12 @@ test("local capacity is explicitly unsent, not relay quota; unknown upstream pub
});
const controllers = [];
try {
const requests = Array.from({ length: 6 }, () => {
const requests = Array.from({ length: MAX_INFLIGHT }, () => {
const controller = new AbortController();
controllers.push(controller);
return h.post("query", filters, controller.signal);
});
await vi.waitFor(() => expect(h.calls).toHaveLength(6));
await vi.waitFor(() => expect(h.calls).toHaveLength(MAX_INFLIGHT));
const refused = await h.post("profile", { name: "Fixture", picture: "" });
expect(refused.status).toBe(429);
expect(await refused.json()).toEqual({
Expand All @@ -1363,11 +1368,11 @@ test("local capacity is explicitly unsent, not relay quota; unknown upstream pub
await Promise.all(
requests.map(async (response) => (await response).text()),
);
expect(h.calls).toHaveLength(6);
expect(h.calls).toHaveLength(MAX_INFLIGHT);
const transport = await connectBrokerTransport(h.base);
// Generic upstream 503 is not proof of non-delivery (separate fixture below).
await transport.query(filters);
expect(h.calls).toHaveLength(7); // Local capacity did not introduce a relay cooldown.
expect(h.calls).toHaveLength(MAX_INFLIGHT + 1); // Local capacity did not introduce a relay cooldown.
} finally {
release();
for (const c of controllers) c.abort();
Expand Down Expand Up @@ -1483,15 +1488,15 @@ test("query keeps relay 403 refusals but turns an edge 403 page into a gateway f
});

test("a queued request's community refusal marks its own response", async () => {
// A held sidebar write and five held queries fill the community's six-slot
// A held sidebar write and nine held queries fill the community's ten-slot
// lane. The next query waits and starts from whichever finishes first, so
// its refusal must mark its own response, not that one's.
const releases = new Map();
let holding = true;
const h = await harness(async (call, count, event) => {
const filter = call.body?.[0];
const sidebar = filter?.kinds?.[0] === 30078;
if (filter?.limit === 7)
if (filter?.limit === QUEUED_LIMIT)
return new Response("authorization denied\n", { status: 403 });
if (holding && call.url.endsWith("/query"))
await new Promise((resolve) =>
Expand All @@ -1513,13 +1518,13 @@ test("a queued request's community refusal marks its own response", async () =>
sectionIds: [],
});
await vi.waitFor(() => expect(releases.has("sidebar")).toBe(true));
const held = [1, 2, 3, 4, 5].map((limit) =>
h.post("query", [{ kinds: [0], limit }]),
const held = Array.from({ length: MAX_INFLIGHT - 1 }, (_, i) =>
h.post("query", [{ kinds: [0], limit: i + 1 }]),
);
await vi.waitFor(() => expect(releases.size).toBe(6));
const queued = h.post("query", [{ kinds: [0], limit: 7 }]);
await vi.waitFor(() => expect(releases.size).toBe(MAX_INFLIGHT));
const queued = h.post("query", [{ kinds: [0], limit: QUEUED_LIMIT }]);
await delay(20);
expect(h.calls).toHaveLength(6);
expect(h.calls).toHaveLength(MAX_INFLIGHT);
releases.get(1)();
const first = await held[0];
const refused = await queued;
Expand Down
2 changes: 1 addition & 1 deletion browser-host/relay-broker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ function validProfilePicture(value) {

const MAX_FILTERS = 4,
MAX_LIMIT = 500,
MAX_INFLIGHT = 6,
MAX_INFLIGHT = 10,
UPSTREAM_TIMEOUT_MS = 20000,
KEEPALIVE_MS = 60000;

Expand Down
2 changes: 2 additions & 0 deletions docs/performance.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ errors before trusting a number.
| `scroll-long` | 12,000px upward through 360 fully loaded messages |
| `scroll-paging-fast` | Scrolling to the oldest of 640 messages while older pages arrive after 100ms |
| `scroll-paging-delayed` | The same with 500ms page delays |
| `scroll-paging-delayed-short` | The delayed case with one- and two-line messages |
| `scroll-paging-fast-keyboard`, `-markdown`, `-first-seen` | The fast case in keyboard modality, with Markdown messages, or with older pages the app hasn't verified yet |
| `thread-open-rich`, `-close-rich`, `-reopen-rich` | A 120-reply thread with media, tables and code |
| `thread-unread-open-60`, `-200` | Opening a thread whose 60 or 200 replies are all unread |
Expand All @@ -59,6 +60,7 @@ never arrive) fails instead of reporting a fast time.
| `scriptMs`, `layoutMs`, `styleMs`, `taskMs` | Chromium's JavaScript, layout, style and main-thread task time |
| `loafBlockingMs` | Long-animation-frame blocking time, from every frame that overlaps the action |
| `rafP95GapMs`, `rafMaxGapMs`, `rafGapsOver33`, `rafGapsOver50` | Animation-frame spacing during a scroll gesture |
| `edgeWaitMs` | Paging time spent held at the top edge, waiting for older history |
| `domGapFrames` | Thread scroll frames with no loaded reply in view |
| `idleTaskMsPerSec`, `trafficTaskMsPerSec`, `taskMsPerMessage` (and script, style and layout per message) | Background traffic cost |
| `heapGrowthKBPerMessage`, `nodesDelta`, `listenersDelta` | Background traffic growth, measured after a forced GC |
Expand Down
7 changes: 6 additions & 1 deletion src/bundled/channels/ChannelsPage.context.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,12 @@ async function channelsPage({ root = true, cached = false } = {}) {
filters.some((filter) => matchesEvent(event, filter)),
);
const channelId = window["#h"]?.[0];
if (channelId === "alpha" && window.until !== undefined)
// An older page's background aux read is served without waiting.
if (
channelId === "alpha" &&
window.until !== undefined &&
!window.include_aux
)
await new Promise<void>((resolve, reject) =>
held.push((error) => (error ? reject(error) : resolve())),
);
Expand Down
167 changes: 162 additions & 5 deletions src/features/messages/ChannelTimeline.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ function setup({
continuityKey = undefined as string | undefined,
historyControl = "button" as "button" | "scroll",
hasMore = false,
hasNewer = false,
loadingOlder = false,
historyLimited = false,
error = undefined as string | undefined,
Expand Down Expand Up @@ -169,6 +170,12 @@ function setup({
return frameId;
});
vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
// Idle callbacks run with the frames.
vi.stubGlobal("requestIdleCallback", (callback: () => void) => {
frames.set(++frameId, callback);
return frameId;
});
vi.stubGlobal("cancelIdleCallback", (id: number) => frames.delete(id));
const observers = new Map<() => void, Set<unknown>>();
vi.stubGlobal(
"ResizeObserver",
Expand Down Expand Up @@ -258,6 +265,7 @@ function setup({
freshness,
rows,
hasMore,
...(hasNewer ? { hasNewer } : {}),
loadingOlder: loadingOlder || accepted,
historyLimited,
error,
Expand All @@ -268,10 +276,12 @@ function setup({
olderReads();
}
});
const loadNewer = vi.fn();
const attach = vi.fn();
let queries =
session ??
({
channels: { loadOlder, window: snapshot },
channels: { loadOlder, loadNewer, attach, window: snapshot },
profiles: {},
agentChoices: createAgentLibrary(undefined).queries,
// Geometry fixtures are read-only; reading behavior has its own boundary tests.
Expand Down Expand Up @@ -325,6 +335,7 @@ function setup({
error,
rows,
hasMore,
...(hasNewer ? { hasNewer } : {}),
loadingOlder,
historyLimited,
},
Expand Down Expand Up @@ -398,6 +409,8 @@ function setup({
return virtualizer.props.keepMounted;
},
loadOlder,
loadNewer,
attach,
olderReads,
flush,
render,
Expand All @@ -421,6 +434,7 @@ function setup({
if ("error" in patch) error = patch.error;
if ("loadingOlder" in patch) loadingOlder = !!patch.loadingOlder;
if ("hasMore" in patch) hasMore = !!patch.hasMore;
if ("hasNewer" in patch) hasNewer = !!patch.hasNewer;
if ("historyLimited" in patch) historyLimited = !!patch.historyLimited;
render();
},
Expand Down Expand Up @@ -544,6 +558,17 @@ function setup({
expect(section.props["data-jump-visible"]).toBe(visible || undefined);
return visible;
},
/** The new-message count Jump to latest shows. */
jumpCount() {
const button = section.props.children.find(
(child) =>
!!child &&
typeof child === "object" &&
"type" in child &&
child.type === JumpToLatestButton,
) as ReactElement<{ newMessageCount: number }> | undefined;
return button?.props.newMessageCount;
},
unmount() {
for (const effect of hooks.effects) effect.cleanup?.();
},
Expand Down Expand Up @@ -685,13 +710,138 @@ it("reader input retires a pending jump so a live append cannot pull the reader
expect(h.hasJumpToLatest()).toBe(true);
h.unmount();
});
it("a detached window's end is not followed, and Jump to latest attaches it", () => {
const h = setup({ hasNewer: true });
// The reader at the window's end reads the rows above it.
h.element.scrollTop = 3038;
h.scroll();
expect(h.loadNewer).toHaveBeenCalledExactlyOnceWith("channel");
h.handle.scrollToIndex.mockClear();
h.append();
h.render();
expect(h.handle.scrollToIndex).not.toHaveBeenCalled();
expect(h.hasJumpToLatest()).toBe(true);
// The rows read in are history, not new messages.
expect(h.jumpCount()).toBe(0);
h.jumpToLatest();
expect(h.attach).toHaveBeenCalledExactlyOnceWith("channel");
h.unmount();
});
it("a detached window reads newer rows only near its end", () => {
const h = setup({ hasNewer: true });
h.element.scrollHeight = 20_000;
h.element.scrollTop = 10_000;
h.scroll();
expect(h.loadNewer).not.toHaveBeenCalled();
h.element.scrollTop = 17_000;
h.scroll();
expect(h.loadNewer).toHaveBeenCalledExactlyOnceWith("channel");
h.unmount();
});
it("loads older rows at the current DOM threshold despite a stale far-away virtualizer offset", () => {
const h = setup({ hasMore: true });
h.handle.scrollOffset = 3300;
h.scroll();
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("channel");
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith(
"channel",
expect.any(Number),
);
h.unmount();
});
it.each([
{ height: 2000, rows: 34 },
{ height: 4675, rows: 20 },
{ height: 4676, rows: undefined },
])(
"reads ahead for a reader settled at the bottom of $height px",
({ height, rows }) => {
const h = setup({ hasMore: true });
// 40 rows of `height / 40` px, at the bottom of a 668px viewport.
Object.assign(h.element, { scrollHeight: height, scrollTop: height - 668 });
h.setRows(
Array.from({ length: 40 }, (_, i) => timelineMessage(`row ${i}`)),
);
// A first page sized to the prefetch distance until 6 screens (4008px)
// sit above the reader, then no more.
if (rows)
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith(
"channel",
rows,
true,
);
else expect(h.loadOlder).not.toHaveBeenCalled();
h.unmount();
},
);
it("sizes the older page to a fast upward scroll", () => {
const now = vi.spyOn(performance, "now").mockReturnValue(10_000);
try {
const h = setup({ hasMore: true });
// 400 rows of 100px.
h.setRows(
Array.from({ length: 400 }, (_, i) => timelineMessage(`row ${i}`)),
);
h.element.scrollHeight = 40_000;
h.element.scrollTop = 30_000;
h.dispatchScroll();
h.gesture(true);
h.element.scrollTop = 20_000;
h.dispatchScroll();
expect(h.loadOlder).not.toHaveBeenCalled();
// 18,000px upward in 100ms reaches the top within one round trip.
now.mockReturnValue(10_100);
h.element.scrollTop = 2000;
h.dispatchScroll();
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("channel", 200);
h.unmount();
} finally {
now.mockRestore();
}
});
it("sizes the next older page to the last page's round trip", () => {
const now = vi.spyOn(performance, "now");
// After a page that took `ms` to land, the same scroll asks for `rows`.
const nextRead = (ms: number, rows: number) => {
now.mockReturnValue(10_000);
const h = setup({ hasMore: true });
// 400 rows of 100px; a slow reader near the top reads the base page.
h.setRows(
Array.from({ length: 400 }, (_, i) => timelineMessage(`row ${i}`)),
);
h.element.scrollHeight = 40_000;
h.element.scrollTop = 30_000;
h.dispatchScroll();
h.gesture(true);
h.element.scrollTop = 2000;
h.dispatchScroll();
expect(h.loadOlder).toHaveBeenLastCalledWith("channel", 20);
h.update({ loadingOlder: true });
now.mockReturnValue(10_000 + ms);
h.setRows(
Array.from({ length: 600 }, (_, i) => timelineMessage(`row ${i}`)),
);
h.element.scrollHeight = 60_000;
h.element.scrollTop = 22_000;
h.update({ loadingOlder: false });
// Then 1000px upward in 100ms.
now.mockReturnValue(20_000);
h.element.scrollTop = 4000;
h.dispatchScroll();
now.mockReturnValue(20_100);
h.element.scrollTop = 3000;
h.dispatchScroll();
expect(h.loadOlder).toHaveBeenCalledTimes(2);
expect(h.loadOlder).toHaveBeenLastCalledWith("channel", rows);
h.unmount();
};
try {
// Smoothed round trips of 260ms and 1000ms: 2 × 10px/ms of reach each.
nextRead(20, 74);
nextRead(1500, 200);
} finally {
now.mockRestore();
}
});
it("does not load older rows when only the old virtualizer position is inside the threshold", () => {
const h = setup({ hasMore: true });
h.element.scrollHeight = 8000;
Expand Down Expand Up @@ -1011,7 +1161,10 @@ it("a user gesture at a restored top pages without needing a DOM scroll event",
h.element.scrollTop = 0;
expect(h.loadOlder).not.toHaveBeenCalled();
h.gesture();
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("channel");
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith(
"channel",
expect.any(Number),
);
h.unmount();
});

Expand Down Expand Up @@ -1279,7 +1432,8 @@ it("rechecks current geometry before honoring the cached gesture", () => {
const h = setup({ hasMore: true, freshness: "cached" });
h.element.scrollTop = 0;
h.gesture();
h.element.scrollTop = 4000;
// Past the read-ahead's reach as well as the paging boundary.
h.element.scrollTop = 9000;
h.update({ freshness: "verified" });
h.element.scrollTop = 0;
h.update({ freshness: "verified" });
Expand Down Expand Up @@ -2098,7 +2252,10 @@ it("pages Solo chat history on scroll without an initial button and keeps error
const h = setup({ hasMore: true, historyControl: "scroll" });
expect(h.hasHistoryButton()).toBe(false);
h.scroll();
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("channel");
expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith(
"channel",
expect.any(Number),
);
h.unmount();
const failed = setup({
hasMore: true,
Expand Down
Loading
Loading