diff --git a/browser-host/relay-broker-api.test.mjs b/browser-host/relay-broker-api.test.mjs index af91dc32c3..95e59ed1a9 100644 --- a/browser-host/relay-broker-api.test.mjs +++ b/browser-host/relay-broker-api.test.mjs @@ -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" }], @@ -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); @@ -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({ @@ -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(); @@ -1483,7 +1488,7 @@ 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(); @@ -1491,7 +1496,7 @@ test("a queued request's community refusal marks its own response", async () => 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) => @@ -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; diff --git a/browser-host/relay-broker.mjs b/browser-host/relay-broker.mjs index d1c72f4cbc..bfa4294cac 100644 --- a/browser-host/relay-broker.mjs +++ b/browser-host/relay-broker.mjs @@ -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; diff --git a/docs/performance.md b/docs/performance.md index 362b05e146..e931e091b9 100644 --- a/docs/performance.md +++ b/docs/performance.md @@ -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 | @@ -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 | diff --git a/src/bundled/channels/ChannelsPage.context.test.tsx b/src/bundled/channels/ChannelsPage.context.test.tsx index 886f718df5..b4d3b36474 100644 --- a/src/bundled/channels/ChannelsPage.context.test.tsx +++ b/src/bundled/channels/ChannelsPage.context.test.tsx @@ -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((resolve, reject) => held.push((error) => (error ? reject(error) : resolve())), ); diff --git a/src/features/messages/ChannelTimeline.test.tsx b/src/features/messages/ChannelTimeline.test.tsx index eb266118dd..b18e30d20e 100644 --- a/src/features/messages/ChannelTimeline.test.tsx +++ b/src/features/messages/ChannelTimeline.test.tsx @@ -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, @@ -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>(); vi.stubGlobal( "ResizeObserver", @@ -258,6 +265,7 @@ function setup({ freshness, rows, hasMore, + ...(hasNewer ? { hasNewer } : {}), loadingOlder: loadingOlder || accepted, historyLimited, error, @@ -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. @@ -325,6 +335,7 @@ function setup({ error, rows, hasMore, + ...(hasNewer ? { hasNewer } : {}), loadingOlder, historyLimited, }, @@ -398,6 +409,8 @@ function setup({ return virtualizer.props.keepMounted; }, loadOlder, + loadNewer, + attach, olderReads, flush, render, @@ -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(); }, @@ -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?.(); }, @@ -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; @@ -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(); }); @@ -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" }); @@ -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, diff --git a/src/features/messages/ChannelTimeline.tsx b/src/features/messages/ChannelTimeline.tsx index 60a87809eb..bdf0275c0d 100644 --- a/src/features/messages/ChannelTimeline.tsx +++ b/src/features/messages/ChannelTimeline.tsx @@ -56,6 +56,7 @@ import { geometryFor, geometrySignature } from "./geometry"; import { readView, writeView } from "../../shared/view-state"; import styles from "./Messages.module.css"; import { correctScrollTop } from "./scroll-correction"; +import { rowsSettled } from "./rows-settled"; import { contentSelector } from "./useFloatingActionBar"; import { readingDocumentActive, @@ -68,6 +69,13 @@ import { messageViewKey } from "./view-key"; import { useKnownAgentPubkeys } from "../agents/use-known"; import { JumpToLatestButton } from "./JumpToLatestButton"; import { moveMessageSelection } from "./message-selection"; +import { + MAX_PAGE, + historyAhead, + historyPace, + observePace, + observeRoundTrip, +} from "./history-prefetch"; import { useMessageSelection } from "./use-message-selection"; import { useMessageVisit } from "./MessageManagement"; @@ -155,8 +163,20 @@ function subscribeDocumentActive(listener: () => void) { }; } const TIMELINE_PLACE = "timeline"; -// Older pages a visit reads unasked to fill a screen its head leaves empty. +/** Run `callback` once the main thread is idle: within 500ms, or after 50ms + * without idle callbacks. Returns a cancel. */ +function afterIdle(callback: () => void) { + if (typeof requestIdleCallback === "function") { + const id = requestIdleCallback(callback, { timeout: 500 }); + return () => cancelIdleCallback(id); + } + const id = setTimeout(callback, 50); + return () => clearTimeout(id); +} +// Older pages a visit reads unasked, and the screens of history they keep +// above the reader so a fling on open stays inside loaded rows. const FILL_PAGES = 5; +const READ_AHEAD_SCREENS = 6; // A row's content sits below its day divider and byline, and its virtual item // adds group spacing. All depend on the row before it, so older rows landing // above can remove them. Offsets of the content from the row and item tops. @@ -964,12 +984,15 @@ function Timeline({ ids: ReadonlySet; floor: number; paging: boolean; + /** Detached from the head: rows it reads in are history. */ + detached: boolean; }>({ order: [], containedOwners: new Map(), ids: new Set(), floor: 0, paging: false, + detached: false, }); // The reader's anchor row and its offset before this render's rows. const reader = useRef<{ @@ -993,6 +1016,11 @@ function Timeline({ viewport: number; } | null>(null); const olderDemand = useRef(false); + const pace = useRef(historyPace()); + // The read loadNearTop started: when, and the history height it started from. + const olderRequested = useRef<{ at: number; height: number } | undefined>( + undefined, + ); // A page read to fill the opening screen lands as part of that opening: the // follower's bottom positioning owns it, not prepend anchoring. const fillLanding = useRef(false); @@ -1010,6 +1038,10 @@ function Timeline({ const inputEnded = useRef(undefined); const [showJumpToLatest, setShowJumpToLatest] = useState(false); const [newMessageCount, setNewMessageCount] = useState(0); + // A detached window ends before the latest message: its end is not the + // bottom a reader follows, until the head read that replaces it. + const detached = useRef(false); + detached.current = !!window.hasNewer && !window.refreshing; const recordPosition = useCallback( (element: HTMLElement, layoutOwned = false) => { // A delayed membership event can replace a group's rendered representative. @@ -1079,7 +1111,7 @@ function Timeline({ position.bottom = true; // Restoration can scroll before Virtua measures rows beneath the anchor, // briefly reaching the estimated bottom. Only reader input may follow. - if (restoredAnchor.current) position.bottom = false; + if (restoredAnchor.current || detached.current) position.bottom = false; if (pendingRestore.current !== intent.current) savedPosition.current = position; follow.current = position.bottom; @@ -1100,6 +1132,11 @@ function Timeline({ }, []); const jumpToLatest = useCallback(() => { if (!handle.current || !rows.length) return; + // The latest rows replace a detached window, and the reader follows them. + if (window.hasNewer) { + queries.channels.attach?.(channelId); + detached.current = false; + } intent.current++; follow.current = true; restoredAnchor.current = undefined; @@ -1115,7 +1152,7 @@ function Timeline({ align: "end", ...(tailHeight ? { offset: tailHeight } : {}), }); - }, [rows.length]); + }, [rows.length, window.hasNewer, queries, channelId]); const inlineSignal = inlineTarget?.signal; const targetIndex = rows.findIndex( (row) => row.id === (containedOwners.get(targetId ?? "") ?? targetId), @@ -1467,10 +1504,24 @@ function Timeline({ heldReader.current.ended), }; heldReader.current = anchor; - const top = () => - element - .querySelector(`[data-message-id="${CSS.escape(anchor.id)}"]`) - ?.getBoundingClientRect().top; + // A row the range had not mounted shows its new inset when it mounts, + // and its real offset once it measures: hold it until then. + let inset = now; + let mounted = !!row; + const top = () => { + const row = element.querySelector( + `[data-message-id="${CSS.escape(anchor.id)}"]`, + ); + if (!row) return undefined; + if (!mounted) { + mounted = true; + measure(); + } + const current = contentInset(row); + anchor.y += (inset?.row ?? current.row) - current.row; + inset = current; + return row.getBoundingClientRect().top; + }; const logicalTop = () => { const index = rows.findIndex((row) => row.id === anchor.id); const virtualizer = handle.current; @@ -1521,7 +1572,10 @@ function Timeline({ // consumeMovement keeps the ideal Y through scrollTop rounding. Only a // handover to another row adopts rendered geometry. if (position) { - if (position.id !== anchor.id) Object.assign(anchor, position); + if (position.id !== anchor.id) { + Object.assign(anchor, position); + inset = undefined; + } readerMoved = false; } logical = logicalTop(); @@ -1530,15 +1584,39 @@ function Timeline({ const since = intent.current; // Virtua re-observes moved rows and applies their sizes in the next frame, // or the one after for a row it mounted during observer delivery, whether - // or not their height changed. Input that ended before then releases the - // frame after. + // or not their height changed. Rows those sizes bring into range measure + // the same way, so each height change waits again. Input that ended + // before then releases the frame after. let measured = false; - let frame = requestAnimationFrame(() => { + let frame = 0; + // Virtua keeps rows wholly above the viewport in place itself; rows from + // the one across its top edge down to the held row are the hold's. They + // can mount, or keep the size of the row that held their index before a + // slide, after the frames above. Wait for them, a bounded number of times. + let waits = 0; + const heldSettled = () => { + const virtualizer = handle.current; + const held = rows.findIndex((row) => row.id === anchor.id); + return ( + !virtualizer || + held < 0 || + rowsSettled(virtualizer, element, list, held) + ); + }; + const measure = () => { + cancelAnimationFrame(frame); + measured = false; frame = requestAnimationFrame(() => { - measured = true; - if (anchor.ended) frame = requestAnimationFrame(() => release()); + frame = requestAnimationFrame(() => { + measured = true; + if (anchor.ended && mounted) + frame = requestAnimationFrame(() => + heldSettled() || ++waits > 15 ? release() : measure(), + ); + }); }); - }); + }; + measure(); const hold = new MutationObserver((mutations) => { consumeMovement(); // Ignore list-only pointer-events changes during input. A row's offsets @@ -1549,6 +1627,7 @@ function Timeline({ ) return; height = list.style.height; + measure(); const row = top(); const next = logicalTop(); if (settled.current && !follow.current) { @@ -1576,9 +1655,11 @@ function Timeline({ element.ownerDocument.removeEventListener("pointerup", done); element.ownerDocument.removeEventListener("pointercancel", done); }; + // Input ending is a release point only once the rows are settled too. const done = () => { - if (measured) release(); - else anchor.ended = true; + if (measured && heldSettled()) return release(); + anchor.ended = true; + if (measured) measure(); }; // A held pointer can drag across more moved rows; it ends when released. const end = () => { @@ -1713,8 +1794,13 @@ function Timeline({ const { floor, order } = edges.current; const paged = edges.current.paging && !loadingOlder.current; const tail = rows.findIndex((row) => row.id === order.at(-1)); + // Live rows never enter a detached window: the rows a newer page reads + // into it, up to and including the page that reaches the head, are not + // new messages. + const history = edges.current.detached || detached.current; const arrivals = rows.filter( (row, index) => + !history && !previousIds.has(row.id) && (!paged || index > tail) && (row.createdAt > floor || (row.createdAt === floor && !paged)), @@ -1725,6 +1811,7 @@ function Timeline({ ids: new Set(rows.map((row) => row.id)), floor: rows[0]?.createdAt ?? 0, paging: loadingOlder.current, + detached: detached.current, }; if ( arrivals > 0 && @@ -1748,6 +1835,9 @@ function Timeline({ !fillLanding.current))) ) return; + // A read-ahead page never returns the reader to a pending saved row: only + // the opening head can, before the reader sees the latest messages. + const filled = prepend && fillLanding.current; if (prepend) fillLanding.current = false; // A send supersedes saved reading intent. if (revealIndex >= 0 && revealMessageId) { @@ -1764,7 +1854,8 @@ function Timeline({ // A new gesture wins over restoration queued before that gesture. let scheduledIntent = intent.current; const saved = - (!settled.current || pendingRestore.current === scheduledIntent) && + (!settled.current || + (pendingRestore.current === scheduledIntent && !filled)) && savedPosition.current && !savedPosition.current.bottom ? savedPosition.current @@ -1777,6 +1868,19 @@ function Timeline({ containedOwners.get(anchor.id) ?? anchor.id, ) : -1; + // The read-ahead page that loads a pending saved row retires it. + const pending = savedPosition.current?.anchor; + if ( + filled && + pending && + pendingRestore.current === scheduledIntent && + renderedRowIndex( + rows, + visibleRows, + containedOwners.get(pending.id) ?? pending.id, + ) >= 0 + ) + pendingRestore.current = undefined; // Only a loaded row is a place to return to. Until it loads, an opening // reader follows the latest message and the saved row stays pending; a // place without a row to wait for is forgotten. A placed reader stays put. @@ -1945,11 +2049,34 @@ function Timeline({ ]); // After positioning reads it: a load that ends without rows lands no page. useLayoutEffect(() => { - if (!window.loadingOlder) edges.current.paging = false; + if (window.loadingOlder) return; + fillReading.current = false; + edges.current.paging = false; + // Rows this commit lands end the round trip that sizes the next page; a + // read that ended without adding height times nothing. + const requested = olderRequested.current; + olderRequested.current = undefined; + if (requested && (scroller.current?.scrollHeight ?? 0) > requested.height) + observeRoundTrip(pace.current, performance.now() - requested.at); }, [window.loadingOlder]); const loadNearTop = useCallback( (element: HTMLElement, resume = false) => { olderDemand.current = false; + const ahead = historyAhead( + pace.current, + performance.now(), + element.scrollTop, + element.clientHeight, + element.scrollHeight / Math.max(1, window.rows.length), + ); + // A read-ahead the reader scrolls into reach of is theirs now, and + // survives leaving the channel as their own reads do. + if ( + window.loadingOlder && + userScrolled.current && + element.scrollTop < ahead.distance + ) + fillReading.current = false; if ( !handle.current || !userScrolled.current || @@ -1958,7 +2085,7 @@ function Timeline({ window.historyLimited || window.loadingOlder || window.error || - element.scrollTop >= Math.max(3000, element.clientHeight * 4) + element.scrollTop >= ahead.distance ) return; // Cached does not mean blocked: disconnected windows can still page over @@ -1968,8 +2095,13 @@ function Timeline({ olderDemand.current = true; return; } - queries.channels.loadOlder(channelId); + queries.channels.loadOlder(channelId, ahead.rows); const after = queries.channels.window(channelId); + if (after.loadingOlder) + olderRequested.current = { + at: performance.now(), + height: element.scrollHeight, + }; olderDemand.current = window.freshness === "cached" && after.status === "ready" && @@ -1984,19 +2116,55 @@ function Timeline({ if (olderDemand.current && scroller.current) loadNearTop(scroller.current, true); }, [loadNearTop]); - // A head of folded agent activity can paint less than a screen, leaving no - // range to scroll: no reader input would ask for older history. A settled - // reader at the bottom fills it from verified history, a few pages a visit. - // Past that, or after a failed read, the edge control and gestures page. + // A detached window reads the rows above it as the reader nears its end. + const loadNearBottom = (element: HTMLElement) => { + if ( + !window.hasNewer || + window.loadingNewer || + window.error || + window.status !== "ready" + ) + return; + const { distance } = historyAhead( + pace.current, + performance.now(), + 0, + element.clientHeight, + element.scrollHeight / Math.max(1, window.rows.length), + ); + if ( + element.scrollHeight - element.clientHeight - element.scrollTop < + distance + ) + queries.channels.loadNewer?.(channelId); + }; + // A settled reader at the bottom reads verified history ahead in full + // pages, a few a visit, until READ_AHEAD_SCREENS of it sit above, so a first + // upward fling starts with rows in hand. That includes a head of folded + // agent activity that paints less than a screen, where no reader input could + // ask for more. Past that, or after a failed read, the edge control and + // gestures page. const fillPages = useRef(0); const fillFrame = useRef(undefined); + // A read-ahead still in flight ends with the visit, so channels clicked + // through leave no reads for the next one to wait behind. + const fillReading = useRef(false); + useEffect( + () => () => { + if ( + fillReading.current && + queries.channels.window(channelId).loadingOlder + ) + queries.channels.cancelOlder?.(channelId); + fillReading.current = false; + }, + [queries, channelId], + ); const fillViewport = useCallback(() => { const element = scroller.current; if ( !element || !settled.current || - !follow.current || - pendingRestore.current === intent.current || pendingReveal.current || (targetId && revealedSignal !== targetSignal) || fillPages.current >= FILL_PAGES || @@ -2008,13 +2176,36 @@ function Timeline({ window.historyLimited || window.loadingOlder || window.error || - element.scrollHeight > element.clientHeight + element.scrollHeight - element.clientHeight - element.scrollTop >= 80 ) return; - queries.channels.loadOlder(channelId); + const { distance, rows } = historyAhead( + pace.current, + performance.now(), + element.scrollTop, + element.clientHeight, + element.scrollHeight / Math.max(1, window.rows.length), + ); + if ( + element.scrollTop >= + Math.max(distance, READ_AHEAD_SCREENS * element.clientHeight) + ) + return; + // The first page fills the prefetch distance and lands light beside the + // opening paint; later ones are full. + queries.channels.loadOlder( + channelId, + fillPages.current ? MAX_PAGE : rows, + true, + ); if (!queries.channels.window(channelId).loadingOlder) return; + olderRequested.current = { + at: performance.now(), + height: element.scrollHeight, + }; fillPages.current++; fillLanding.current = true; + fillReading.current = true; }, [ window, queries, @@ -2025,12 +2216,16 @@ function Timeline({ revealedSignal, ]); // After positioning's frame, and again once Virtua measures estimated rows. + // The first read waits until the opening paint's work is done. + const fillIdle = useRef<(() => void) | undefined>(undefined); const scheduleFill = useCallback(() => { if (fillFrame.current !== undefined) cancelAnimationFrame(fillFrame.current); + fillIdle.current?.(); fillFrame.current = requestAnimationFrame(() => { fillFrame.current = undefined; - fillViewport(); + if (fillPages.current) fillViewport(); + else fillIdle.current = afterIdle(fillViewport); }); }, [fillViewport]); // Window updates carry each page; positioning settles once the viewport is @@ -2042,6 +2237,8 @@ function Timeline({ if (fillFrame.current !== undefined) cancelAnimationFrame(fillFrame.current); fillFrame.current = undefined; + fillIdle.current?.(); + fillIdle.current = undefined; }; }, [scheduleFill, size]); const gesture = (upward = false) => { @@ -2074,6 +2271,8 @@ function Timeline({ if (scroller.current && scroller.current.scrollTop <= 0) loadNearTop(scroller.current); }; + // A detached window always leads to the latest rows. + const jumpVisible = showJumpToLatest || !!window.hasNewer; const feed = (
gesture(event.deltaY < 0 && !event.ctrlKey)} onTouchStart={(event) => { touchY.current = event.touches[0]?.clientY; @@ -2172,7 +2371,10 @@ function Timeline({ ); updateJumpToLatest(element); } + if (upwardGesture.current) + observePace(pace.current, element.scrollTop, performance.now()); loadNearTop(element); + loadNearBottom(element); }} >
diff --git a/src/features/messages/ChannelTimeline.viewport.test.tsx b/src/features/messages/ChannelTimeline.viewport.test.tsx index 0f4cdda2ab..01b8249b6b 100644 --- a/src/features/messages/ChannelTimeline.viewport.test.tsx +++ b/src/features/messages/ChannelTimeline.viewport.test.tsx @@ -1268,6 +1268,7 @@ function fillFixture({ cachedOnly = false, recovering = false, intro = undefined as ReactNode, + restore = undefined as "latest" | "older" | undefined, } = {}) { vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockReturnValue(800); vi.spyOn(HTMLElement.prototype, "clientHeight", "get").mockReturnValue(600); @@ -1289,6 +1290,12 @@ function fillFixture({ 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 flush = () => act(() => { for (let round = 0; round < 5 && frames.size; round++) @@ -1309,7 +1316,17 @@ function fillFixture({ }, cachedOnly ? { cachedOnly: true } : undefined, ); - let events = [message(viewer, "alpha", "Latest public message", 100)]; + const latest = message(viewer, "alpha", "Latest public message", 100); + let events = [latest]; + // A revisit restores its saved reading place: the latest message, or the + // first older one, which the head lacks and the first page lands. + let older: (typeof events)[number] | undefined = + restore === "older" ? message(viewer, "alpha", "Older 1", 99) : undefined; + if (restore) + writeView("fill", "scroll:alpha", { + bottom: false, + anchor: { id: (older ?? latest).id, y: 0 }, + }); let window: ChannelWindow = { channelId: "alpha", rows: foldMessages("alpha", relay.pubkey, events), @@ -1325,9 +1342,15 @@ function fillFixture({ const loadOlder = vi.fn(() => { if (!window.loadingOlder) window = { ...window, loadingOlder: true }; }); + const cancelOlder = vi.fn(); const queries = { ...owner.session, - channels: { ...owner.session.channels, loadOlder, window: () => window }, + channels: { + ...owner.session.channels, + loadOlder, + cancelOlder, + window: () => window, + }, recovery: { snapshot: () => recovery, subscribe: () => () => {}, @@ -1348,12 +1371,20 @@ function fillFixture({ return { geometry, loadOlder, + cancelOlder, /** An older page lands, or a read ends with the given patch. */ land(next: Partial = {}) { events = [ - message(viewer, "alpha", `Older ${events.length}`, 100 - events.length), + older ?? + message( + viewer, + "alpha", + `Older ${events.length}`, + 100 - events.length, + ), ...events, ]; + older = undefined; window = { ...window, rows: foldMessages("alpha", relay.pubkey, events), @@ -1363,6 +1394,13 @@ function fillFixture({ view.rerender(content()); flush(); }, + /** A live message arrives below. */ + live() { + events = [...events, message(viewer, "alpha", "Live", 101)]; + window = { ...window, rows: foldMessages("alpha", relay.pubkey, events) }; + view.rerender(content()); + flush(); + }, dispose() { view.unmount(); owner.dispose(); @@ -1374,7 +1412,11 @@ function fillFixture({ it("a settled reader at the bottom fills a screen with nothing to scroll", () => { const h = fillFixture(); try { - expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("alpha"); + expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Number), + true, + ); } finally { h.dispose(); } @@ -1385,7 +1427,11 @@ it("fills past a pending intro and shows it only when verified history reaches i intro:
Welcome
, }); try { - expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith("alpha"); + expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Number), + true, + ); expect( screen.queryByRole("article", { name: "Local introduction" }), ).toBeNull(); @@ -1406,15 +1452,36 @@ it("filling reads at most five pages a visit", () => { try { for (let page = 0; page < 6; page++) h.land(); expect(h.loadOlder).toHaveBeenCalledTimes(5); + // Pages after the first are full. + for (const call of h.loadOlder.mock.calls.slice(1)) + expect(call).toEqual(["alpha", 200, true]); } finally { h.dispose(); } }); -it("filling stops once the history can scroll", () => { +it("leaving a channel cancels its read-ahead in flight", () => { + const h = fillFixture(); + expect(h.loadOlder).toHaveBeenCalledOnce(); + h.dispose(); + expect(h.cancelOlder).toHaveBeenCalledExactlyOnceWith("alpha"); +}); + +it("leaving after the read-ahead lands cancels nothing", () => { + const h = fillFixture(); + h.land({ hasMore: false }); + h.dispose(); + expect(h.cancelOlder).not.toHaveBeenCalled(); +}); + +it("filling stops once the reader has the prefetch distance above", () => { const h = fillFixture(); try { - h.geometry.scrollHeight = 601; + // 6 screens above a reader at the bottom of a 600px viewport. + h.geometry.scrollHeight = 4200; + screen.getByRole("region", { + name: "Channel message history", + }).scrollTop = 3600; h.land(); expect(h.loadOlder).toHaveBeenCalledOnce(); } finally { @@ -1449,14 +1516,52 @@ it.each([ } }); -it("does not fill while a saved reading place is restored", () => { - writeView("fill", "scroll:alpha", { - bottom: false, - anchor: { id: "missing", y: 0 }, - }); - const h = fillFixture(); +it("reads ahead past a pending saved row without returning the reader to it", () => { + const h = fillFixture({ restore: "older" }); try { - expect(h.loadOlder).not.toHaveBeenCalled(); + expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Number), + true, + ); + h.geometry.scrollHeight = 2000; + viewport.scrollToIndex.mockClear(); + h.land(); + // The saved row landed; the reader still follows the latest message. + expect(screen.getByText("Older 1")).toBeVisible(); + expect(viewport.scrollToIndex).toHaveBeenCalledWith(1, { align: "end" }); + expect(viewport.scrollToIndex).not.toHaveBeenCalledWith( + 0, + expect.objectContaining({ align: "start" }), + ); + // Nor does a later update: the landing retired it. + viewport.scrollToIndex.mockClear(); + h.live(); + expect(viewport.scrollToIndex).not.toHaveBeenCalledWith( + 0, + expect.objectContaining({ align: "start" }), + ); + } finally { + h.dispose(); + } +}); + +it("reads ahead for a revisit restored at the bottom, keeping its place", () => { + const h = fillFixture({ restore: "latest" }); + try { + expect(h.loadOlder).toHaveBeenCalledExactlyOnceWith( + "alpha", + expect.any(Number), + true, + ); + viewport.scrollToIndex.mockClear(); + h.land(); + // The saved message, now behind the landed row, keeps its place. + expect(viewport.scrollToIndex).toHaveBeenCalledExactlyOnceWith(1, { + align: "start", + offset: 0, + }); + expect(h.loadOlder).toHaveBeenCalledTimes(2); } finally { h.dispose(); } diff --git a/src/features/messages/history-prefetch.test.ts b/src/features/messages/history-prefetch.test.ts new file mode 100644 index 0000000000..4e17ff5183 --- /dev/null +++ b/src/features/messages/history-prefetch.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, it } from "vitest"; +import { + historyAhead, + historyPace, + observePace, + observeRoundTrip, +} from "./history-prefetch"; + +// An upward scroll of `px` over `ms`, sampled at its start and end. +function scrolled(px: number, ms: number, at = 1000) { + const pace = historyPace(); + observePace(pace, 20_000, at); + observePace(pace, 20_000 - px, at + ms); + return pace; +} + +describe("history prefetch", () => { + it("refills the base distance for a reader who is not scrolling up", () => { + const pace = historyPace(); + observePace(pace, 1000, 1000); + observePace(pace, 1400, 1100); + // 4 × 900px viewport, 2600px of it missing above a reader at 1000px. + expect(historyAhead(pace, 1100, 1000, 900, 40)).toEqual({ + distance: 3600, + rows: 65, + }); + // A reader past the distance with its rows above needs only the base page. + expect(historyAhead(pace, 1100, 3600, 900, 40).rows).toBe(20); + }); + + it("covers twice the distance scrolled during a smoothed round trip", () => { + // 5000px/s upward. + const pace = scrolled(500, 100); + observeRoundTrip(pace, 300); + expect(pace.roundTripMs).toBe(400); + // 2 × 5px/ms × 400ms = 4000px ahead, plus 4000px of reach. + expect(historyAhead(pace, 1100, 4000, 900, 40)).toEqual({ + distance: 4000, + rows: 100, + }); + }); + + it("decays the pace while a reader waits at the top edge without scrolling", () => { + const pace = scrolled(1000, 100); + expect(historyAhead(pace, 1100, 3600, 900, 40).rows).toBe(200); + // Two seconds later, with no scroll event between, the pace is a quarter. + expect(historyAhead(pace, 3100, 3600, 900, 40).rows).toBe(63); + }); + + it("measures no speed across a gap between scroll events", () => { + // A jump of 10,000px between samples a second apart is not movement. + expect(historyAhead(scrolled(10_000, 1000), 2000, 3600, 900, 40).rows).toBe( + 20, + ); + }); + + it("bounds a round trip that waited out retries", () => { + const pace = historyPace(); + observeRoundTrip(pace, 7000); + expect(pace.roundTripMs).toBe(1000); + }); + + it("stays within one capped page", () => { + const pace = scrolled(50_000, 16); + // The distance is what one 200-row page of 20px rows supplies. + expect(historyAhead(pace, 1016, 0, 900, 20)).toEqual({ + distance: 4000, + rows: 200, + }); + }); +}); diff --git a/src/features/messages/history-prefetch.ts b/src/features/messages/history-prefetch.ts new file mode 100644 index 0000000000..4ddde2a94e --- /dev/null +++ b/src/features/messages/history-prefetch.ts @@ -0,0 +1,80 @@ +import { WINDOW_PAGE_SIZE } from "../relay/window"; + +// The relay serves at most 200 rows a read. +export const MAX_PAGE = 200; +// Until a page has been timed, assume a slow round trip. +const FIRST_ROUND_TRIP_MS = 500; +// A retried read's backoff is not page latency. +const MAX_ROUND_TRIP_MS = 1500; +// Upward speed halves each second without faster movement, so a reader held +// at the top edge still asks for pages sized to their last pace. +const SPEED_HALF_LIFE_MS = 1000; +// Scroll events this far apart start a new movement rather than measure one. +const MAX_SAMPLE_GAP_MS = 250; + +/** An upward reader's pace: `speed` in px/ms, and older pages' smoothed round + * trip from request to rendered rows. */ +export type HistoryPace = { + top: number; + at: number; + speed: number; + roundTripMs: number; +}; + +export const historyPace = (): HistoryPace => ({ + top: 0, + at: 0, + speed: 0, + roundTripMs: FIRST_ROUND_TRIP_MS, +}); + +const speedAt = (pace: HistoryPace, at: number) => + pace.speed * 0.5 ** (Math.max(0, at - pace.at) / SPEED_HALF_LIFE_MS); + +/** Record a scroll offset at time `at` (ms). */ +export function observePace(pace: HistoryPace, top: number, at: number) { + const elapsed = at - pace.at; + const upward = + pace.at && elapsed > 0 && elapsed <= MAX_SAMPLE_GAP_MS + ? (pace.top - top) / elapsed + : 0; + pace.speed = Math.max(upward, speedAt(pace, at)); + pace.top = top; + pace.at = at; +} + +/** Record a page's round trip; one slow or fast page moves the estimate halfway. */ +export function observeRoundTrip(pace: HistoryPace, ms: number) { + pace.roundTripMs = + (pace.roundTripMs + Math.min(Math.max(0, ms), MAX_ROUND_TRIP_MS)) / 2; +} + +/** Read older history ahead of the reader. Within `distance` of the top, read + * `rows`: enough to refill that distance plus twice what the reader scrolls + * during one round trip. A slow reader keeps the base distance. */ +export function historyAhead( + pace: HistoryPace, + at: number, + top: number, + viewport: number, + rowPx: number, +) { + const row = Math.max(1, rowPx); + const reach = 2 * speedAt(pace, at) * pace.roundTripMs; + // Never ahead of what one page can supply, which would chain reads. + const distance = Math.max( + 3000, + viewport * 4, + Math.min(reach, MAX_PAGE * row), + ); + return { + distance, + rows: Math.min( + MAX_PAGE, + Math.max( + WINDOW_PAGE_SIZE, + Math.ceil((distance - Math.max(0, top) + reach) / row), + ), + ), + }; +} diff --git a/src/features/messages/rows-settled.test.ts b/src/features/messages/rows-settled.test.ts new file mode 100644 index 0000000000..0c8e0a85e5 --- /dev/null +++ b/src/features/messages/rows-settled.test.ts @@ -0,0 +1,75 @@ +// @vitest-environment jsdom +import { expect, it } from "vitest"; +import { rowsSettled } from "./rows-settled"; + +// Virtua's layout: each mounted item at its offset from its own sizes, in +// index order; findItemIndex gives the last index starting at or above an +// offset. `rendered` is each row's height in the DOM, `undefined` unmounted. +function layout( + sizes: number[], + rendered: (number | undefined)[], + scrollOffset: number, +) { + const starts = sizes.map((_, index) => + sizes.slice(0, index).reduce((sum, size) => sum + size, 0), + ); + const virtualizer = { + scrollOffset, + getItemSize: (index: number) => sizes[index] ?? 0, + findItemIndex: (offset: number) => { + let found = 0; + starts.forEach((start, index) => { + if (start <= offset) found = index; + }); + return found; + }, + }; + const rect = (top: number, height: number) => ({ top, height }) as DOMRect; + const element = document.createElement("section"); + element.getBoundingClientRect = () => rect(100, 600); + const list = document.createElement("ol"); + rendered.forEach((height, index) => { + if (height === undefined) return; + const item = document.createElement("li"); + item.getBoundingClientRect = () => + rect(100 + (starts[index] ?? 0) - scrollOffset, height); + list.append(item); + }); + return (held: number) => rowsSettled(virtualizer, element, list, held); +} + +it("settles when every row from the top edge to the held row is measured", () => { + expect(layout([40, 40, 40, 40], [40, 40, 40, 40], 50)(3)).toBe(true); +}); + +it("waits for a row below the edge row that renders at another size", () => { + expect(layout([40, 40, 40, 40, 40], [40, 40, 104, 40, 40], 50)(4)).toBe( + false, + ); +}); + +it("waits for a row in the interval that is not mounted", () => { + expect(layout([40, 40, 40, 40, 40], [40, 40, undefined, 40, 40], 50)(4)).toBe( + false, + ); +}); + +it("leaves rows wholly above the viewport and from the held row down to Virtua", () => { + expect(layout([40, 40, 40, 40, 40], [64, 40, 40, 40, 64], 50)(3)).toBe(true); +}); + +it("settles over folded rows of no height", () => { + expect(layout([40, 40, 0, 0, 40, 40], [40, 40, 0, 0, 40, 40], 50)(5)).toBe( + true, + ); + expect(layout([40, 40, 40, 0, 40], [40, 40, 40, 0, 40], 50)(4)).toBe(true); +}); + +it("waits for a row Virtua still sizes at zero", () => { + expect(layout([40, 40, 0, 40, 40], [40, 40, 40, 40, 40], 50)(4)).toBe(false); +}); + +it("checks from the first row at the channel start", () => { + expect(layout([40, 40, 40], [40, 64, 40], 0)(2)).toBe(false); + expect(layout([40, 40, 40], [40, 40, 40], 0)(2)).toBe(true); +}); diff --git a/src/features/messages/rows-settled.ts b/src/features/messages/rows-settled.ts new file mode 100644 index 0000000000..ab2a201ac7 --- /dev/null +++ b/src/features/messages/rows-settled.ts @@ -0,0 +1,46 @@ +import type { VirtualizerHandle } from "virtua"; + +/** + * Whether Virtua holds the rendered size of every row from the one across the + * viewport's top edge down to, not including, the held row. Rows wholly above + * the viewport are Virtua's to keep in place. + */ +export function rowsSettled( + virtualizer: Pick< + VirtualizerHandle, + "findItemIndex" | "getItemSize" | "scrollOffset" + >, + element: Element, + list: Element, + held: number, +) { + // Virtua places each item at its offset, whatever its height, and in index + // order. A row of no height shares the next row's offset, so walk up from + // the last item and never reuse an index. + const viewport = element.getBoundingClientRect().top; + const items = new Map(); + let next = Number.POSITIVE_INFINITY; + for (const child of Array.from(list.children).reverse()) { + const { top, height } = child.getBoundingClientRect(); + next = Math.min( + next - 1, + virtualizer.findItemIndex( + top - viewport + virtualizer.scrollOffset + 0.5, + ), + ); + items.set(next, height); + } + for ( + let index = virtualizer.findItemIndex(virtualizer.scrollOffset); + index < held; + index++ + ) { + const height = items.get(index); + if ( + height === undefined || + Math.abs(height - virtualizer.getItemSize(index)) >= 0.5 + ) + return false; + } + return true; +} diff --git a/src/features/relay/contracts.ts b/src/features/relay/contracts.ts index fc5b6fcc04..68f879adaa 100644 --- a/src/features/relay/contracts.ts +++ b/src/features/relay/contracts.ts @@ -417,7 +417,13 @@ export interface ChannelQueries { subscribeWindow(channelId: string, listener: () => void): () => void; ensureList(): void; ensure(channelId: string): void; - loadOlder(channelId: string): void; + /** Read the next older page of `rows` top-level rows (default 20, at most + * 200). A page past the history budget slides the window down to it, + * detached from the head. A read `ahead` of the reader never slides: past + * the budget it is dropped, and read-ahead stops until the reader pages. */ + loadOlder(channelId: string, rows?: number, ahead?: boolean): void; + /** Cancel the window's older read in flight. */ + cancelOlder?(channelId: string): void; /** Detach the window to history at `from` (unix seconds; 0 is the channel * start). Resolves the first message at or after `from`, else the newest. */ seek?( diff --git a/src/features/relay/http-admission.test.ts b/src/features/relay/http-admission.test.ts index c0a7fdac20..281c5d7de8 100644 --- a/src/features/relay/http-admission.test.ts +++ b/src/features/relay/http-admission.test.ts @@ -1,5 +1,6 @@ import { afterEach, expect, it, vi } from "vitest"; import { + API_ACTIVE_LIMIT, apiFailure, admittedApiRequest, ApiPaused, @@ -9,7 +10,7 @@ import { } from "./http-admission"; afterEach(() => vi.useRealTimers()); -it("starts six background reads immediately and refills by foreground priority", async () => { +it("starts background reads immediately up to the request ceiling and refills by foreground priority", async () => { vi.useFakeTimers(); const lane = createApiAdmission(); const calls: string[] = []; @@ -18,13 +19,13 @@ it("starts six background reads immediately and refills by foreground priority", calls.push(name); return new Promise((resolve) => release.push(resolve)); }; - const active = Array.from({ length: 6 }, (_, i) => + const active = Array.from({ length: API_ACTIVE_LIMIT }, (_, i) => lane.run(work(`${i}`), undefined, "background"), ); - expect(calls).toEqual(["0", "1", "2", "3", "4", "5"]); + expect(calls).toEqual(active.map((_, i) => `${i}`)); const background = lane.run(work("background"), undefined, "background"); const foreground = lane.run(work("foreground")); - expect(calls).toHaveLength(6); + expect(calls).toHaveLength(API_ACTIVE_LIMIT); release.shift()?.(); await active[0]; await Promise.resolve(); @@ -83,7 +84,7 @@ it("pauses queued consumers, cancels before dispatch, and never retries admitted release = resolve; }); const work = vi.fn(() => held); - const active = Array.from({ length: 6 }, () => lane.run(work)); + const active = Array.from({ length: API_ACTIVE_LIMIT }, () => lane.run(work)); const controller = new AbortController(); const cancelled = expect( lane.run(work, controller.signal), @@ -100,7 +101,7 @@ it("pauses queued consumers, cancels before dispatch, and never retries admitted await expect(lane.run(work)).rejects.toBeInstanceOf(ApiPaused); await vi.advanceTimersByTimeAsync(1); await lane.run(async () => {}); - expect(work).toHaveBeenCalledTimes(6); + expect(work).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); expect(vi.getTimerCount()).toBe(0); }); it("normalizes only upstream quota hints and bounds streaming error bodies", async () => { diff --git a/src/features/relay/http-admission.ts b/src/features/relay/http-admission.ts index a122d2cf7f..27310f09a7 100644 --- a/src/features/relay/http-admission.ts +++ b/src/features/relay/http-admission.ts @@ -247,11 +247,13 @@ type Ticket = { reject(error: Error): void; abort(): void; }; -/** One host/principal API lane, bounded like the broker's six-request ceiling. +/** Requests one API lane runs at once, like the browser broker's ceiling. */ +export const API_ACTIVE_LIMIT = 10; +/** One host/principal API lane, bounded like the broker's ten-request ceiling. * Available capacity dispatches immediately; only server cooldowns pause starts. * Cooldowns reject queued work rather than spending a read's 10s deadline. */ export function createApiAdmission() { - const activeLimit = 6; + const activeLimit = API_ACTIVE_LIMIT; const artifactActiveLimit = 4; const queuedLimit = 128; const artifactQueuedLimit = 120; diff --git a/src/features/relay/live-session.test.ts b/src/features/relay/live-session.test.ts index ad11e8b1cd..8e1305c5c0 100644 --- a/src/features/relay/live-session.test.ts +++ b/src/features/relay/live-session.test.ts @@ -1188,6 +1188,33 @@ it("a fill whose last page lands in the tick the stream drops reports the window } }); +it("a stream drop that cancels an older page's aux read reads it again after the catch-up", async () => { + const h = reconnectHarness(); + try { + const seen = message(h.alice, "c", "seen", 10), + old = message(h.alice, "c", "old", 5); + await h.reconnect(seen); + h.read().respond(h.page("head", [seen], seen)); + await flush(); + h.owner.session.channels.loadOlder("c"); + h.read().respond(h.page(h.cursor(seen), [old], null)); + await flush(); + const aux = h.read(); + expect(aux.filters[0]).toMatchObject({ until: 10, include_aux: true }); + // The history has no older page left to read it with. + await h.dropAndReplay([]); + expect(aux.signal?.aborted).toBe(true); + h.read().respond(h.page("head", [seen], seen)); + await flush(); + expect(h.read().filters[0]).toMatchObject({ + until: 10, + include_aux: true, + }); + } finally { + h.owner.dispose(); + } +}); + it("an older page read while the stream is down waits below a settled fill until paging reaches it", async () => { // Those rows are not in the drop-time snapshot, so a fill that gives up on // the snapshot does not drop them; the settle's cursor hides them below the @@ -1212,6 +1239,14 @@ it("an older page read while the stream is down waits below a settled fill until older.respond(h.page(h.cursor(seen), [old], old)); await flush(); expect(h.rows()).toEqual([old.id, seen.id]); + // The page's aux closure follows its rows. + const aux = h.read(); + expect(aux.filters[0]).toMatchObject({ + until: seen.created_at, + include_aux: true, + }); + aux.respond(h.page(h.cursor(seen), [old], old)); + await flush(); await h.dropAndReplay([]); let previous: (typeof missed)[number] | undefined; for (const row of missed) { diff --git a/src/features/relay/membership.test.ts b/src/features/relay/membership.test.ts index 95a9c61918..63c9b8ab88 100644 --- a/src/features/relay/membership.test.ts +++ b/src/features/relay/membership.test.ts @@ -355,8 +355,10 @@ it("live activity obeys the same retained row budget as messages", async () => { addition(pinky.pubkey, 2), addition(brain.pubkey, 3), ]); + // The oldest goes, and an older page can read it again. expect(owner.session.channels.window("a")).toMatchObject({ - historyLimited: true, + historyLimited: false, + hasMore: true, }); expect( owner.session.channels.window("a").rows.map((r) => r.createdAt), diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index 6ad2cbc854..11dc7fe797 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -21,6 +21,7 @@ import { nativeWriteKinds, verifyNativeStored, } from "./native"; +import { API_ACTIVE_LIMIT } from "./http-admission"; import { keypair, message, nativeSignatureChecks, signed } from "./testing"; import { createOutbox, type OutgoingEvent, PublishRejected } from "./outbox"; import { createMessages } from "./messages"; @@ -655,7 +656,7 @@ it("cancellation fences a late native response and prevents undispatched work", await expect(request).rejects.toMatchObject({ name: "AbortError" }); }); -it("cancelled native reads retain the six-request admission bound until IPC settles", async () => { +it("cancelled native reads retain the request admission bound until IPC settles", async () => { vi.useFakeTimers(); const transport = await connectNativeTransport( "https://cancelled-native.test", @@ -672,7 +673,10 @@ it("cancelled native reads retain the six-request admission bound until IPC sett active--; } }; - const controllers = Array.from({ length: 12 }, () => new AbortController()); + const controllers = Array.from( + { length: API_ACTIVE_LIMIT * 2 }, + () => new AbortController(), + ); const reads = controllers.map((controller) => transport .query([{ kinds: [0], limit: 5 }], controller.signal) @@ -680,19 +684,25 @@ it("cancelled native reads retain the six-request admission bound until IPC sett ); try { await vi.waitFor(() => - expect(requests.filter((r) => r.path === "/query")).toHaveLength(6), + expect(requests.filter((r) => r.path === "/query")).toHaveLength( + API_ACTIVE_LIMIT, + ), ); for (const controller of controllers) controller.abort(); // A further request has entered the same lane, but cannot dispatch past cancelled native work. const last = transport.query([{ kinds: [0], limit: 5 }]); await vi.advanceTimersByTimeAsync(0); - expect(requests.filter((r) => r.path === "/query")).toHaveLength(6); + expect(requests.filter((r) => r.path === "/query")).toHaveLength( + API_ACTIVE_LIMIT, + ); gate.resolve({ body: [] }); await last; - expect(requests.filter((r) => r.path === "/query")).toHaveLength(7); + expect(requests.filter((r) => r.path === "/query")).toHaveLength( + API_ACTIVE_LIMIT + 1, + ); for (const error of await Promise.all(reads)) expect(error).toMatchObject({ name: "AbortError" }); - expect(maximum).toBe(6); + expect(maximum).toBe(API_ACTIVE_LIMIT); } finally { gate.resolve({ body: [] }); await Promise.all(reads); @@ -1042,7 +1052,7 @@ it("holds the shared admission lease until a cancelled native history request se const workflows = transport.workflows; assert.exists(workflows); const id = "11111111-1111-4111-8111-111111111111"; - const pending = Array.from({ length: 6 }, () => + const pending = Array.from({ length: API_ACTIVE_LIMIT }, () => deferred<{ status: number; headers: Record; @@ -1068,12 +1078,12 @@ it("holds the shared admission lease until a cancelled native history request se const reads = controllers.map((controller) => workflows.runs(id, undefined, controller.signal), ); - await vi.waitFor(() => expect(historyCalls).toHaveLength(6)); + await vi.waitFor(() => expect(historyCalls).toHaveLength(API_ACTIVE_LIMIT)); const outcomes = reads.map((read) => expect(read).rejects.toThrow()); for (const controller of controllers) controller.abort(); const query = transport.query([{ kinds: [9], limit: 1 }]); await Promise.resolve(); - expect(requests).toHaveLength(1); // Discovery only; all six IPC requests still hold slots. + expect(requests).toHaveLength(1); // Discovery only; all IPC requests at the ceiling still hold slots. for (const request of pending) { request.resolve({ status: 200, @@ -1931,7 +1941,7 @@ it("holds native publication admission until cancelled IPC settles", async () => ], content: "ciphertext", }); - const gates = Array.from({ length: 6 }, () => + const gates = Array.from({ length: API_ACTIVE_LIMIT }, () => deferred<{ status: number; headers: Record; @@ -1958,7 +1968,7 @@ it("holds native publication admission until cancelled IPC settles", async () => .mock.calls.filter( ([command]) => command === "relay_publish_read_state", ), - ).toHaveLength(6), + ).toHaveLength(API_ACTIVE_LIMIT), ); controllers[0]?.abort(); const queued = readState.publish?.(event, new AbortController().signal); @@ -1968,7 +1978,7 @@ it("holds native publication admission until cancelled IPC settles", async () => .mock.calls.filter( ([command]) => command === "relay_publish_read_state", ), - ).toHaveLength(6); + ).toHaveLength(API_ACTIVE_LIMIT); gates[0]?.resolve({ status: 200, headers: {}, @@ -1981,7 +1991,7 @@ it("holds native publication admission until cancelled IPC settles", async () => .mock.calls.filter( ([command]) => command === "relay_publish_read_state", ), - ).toHaveLength(7), + ).toHaveLength(API_ACTIVE_LIMIT + 1), ); await expect(queued).resolves.toBeUndefined(); } finally { diff --git a/src/features/relay/prepared.test.ts b/src/features/relay/prepared.test.ts index a47743eef5..8c4013967e 100644 --- a/src/features/relay/prepared.test.ts +++ b/src/features/relay/prepared.test.ts @@ -234,7 +234,7 @@ describe("prepared channel working sets", () => { expect(store.diagnostics().heads.entries).toBe(0); store.dispose(); }); - it("enforces a history budget without pretending it reached EOF or evicting the reading rows", async () => { + it("an older page past the history budget slides the window down, detached from the newer rows", async () => { const { queries, next, store } = setup({ prepared: false, maxHistoryRows: 1, @@ -261,10 +261,11 @@ describe("prepared channel working sets", () => { ]); await flush(); expect(queries.window("a")).toMatchObject({ - historyLimited: true, - hasMore: true, - rows: [{ content: "new" }], + hasMore: false, + hasNewer: true, + rows: [{ content: "old" }], }); + expect(queries.window("a").historyLimited).toBeFalsy(); store.dispose(); }); it("clear rejects in-flight results and clears the persistent identity partition", async () => { diff --git a/src/features/relay/reader-recovery.test.ts b/src/features/relay/reader-recovery.test.ts index 45c47f6f2c..22a5fbcf02 100644 --- a/src/features/relay/reader-recovery.test.ts +++ b/src/features/relay/reader-recovery.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, it, vi } from "vitest"; -import { createRelayReader } from "./reader"; +import { ACTIVE_READS, createRelayReader } from "./reader"; import { scriptedTransport } from "./testing"; import { yieldToHost } from "./yield"; @@ -110,10 +110,10 @@ it("retains queued deadlines during recovery and ignores late transport rejectio it("coalesces simultaneous failures into one turn and recovers normal capacity", async () => { const h = setup(); - const reads = ["one", "two", "three", "four"].map((id) => - h.read(filter(id)).catch((e) => e), + const reads = Array.from({ length: ACTIVE_READS + 1 }, (_, i) => + h.read(filter(`r${i}`)).catch((e) => e), ); - const active = [h.next(), h.next(), h.next()]; + const active = Array.from({ length: ACTIVE_READS }, () => h.next()); for (const request of active) request.fail(new Error("offline")); await flush(); expect(h.pending).toHaveLength(0); @@ -122,11 +122,13 @@ it("coalesces simultaneous failures into one turn and recovers normal capacity", h.next().respond([]); await Promise.all(reads); // Success still releases queued capacity without imposing a task boundary. - const more = ["a", "b", "c", "d"].map((id) => h.read(filter(id))); + const more = Array.from({ length: ACTIVE_READS + 1 }, (_, i) => + h.read(filter(`m${i}`)), + ); h.next().respond([]); await flush(); - expect(h.pending).toHaveLength(3); - for (let i = 0; i < 3; i++) h.next().respond([]); + expect(h.pending).toHaveLength(ACTIVE_READS); + for (let i = 0; i < ACTIVE_READS; i++) h.next().respond([]); await Promise.all(more); expect(turns).toHaveLength(0); }); diff --git a/src/features/relay/reader.test.ts b/src/features/relay/reader.test.ts index 5df1f8e027..dd716430b3 100644 --- a/src/features/relay/reader.test.ts +++ b/src/features/relay/reader.test.ts @@ -1,5 +1,5 @@ import { afterEach, expect, it, vi } from "vitest"; -import { createRelayReader } from "./reader"; +import { ACTIVE_READS, createRelayReader } from "./reader"; import { flush, scriptedTransport } from "./testing"; const owners: ReturnType[] = []; @@ -174,17 +174,18 @@ it("preserves ordered bridge extensions and distinguishes their request identity it("fresh reads retain scheduler bounds but never join older or simultaneous equal work", async () => { const h = setup(); const old = h.read(filter("c")); - const one = h.read(filter("c"), { fresh: true }); - const two = h.read(filter("c"), { fresh: true }); - const three = h.read(filter("c"), { fresh: true }); - expect(h.pending).toHaveLength(3); + const fresh = Array.from({ length: ACTIVE_READS }, () => + h.read(filter("c"), { fresh: true }), + ); + expect(h.pending).toHaveLength(ACTIVE_READS); h.next().respond([]); await flush(); - expect(h.pending).toHaveLength(3); - h.next().respond([]); - h.next().respond([]); - h.next().respond([]); - await Promise.all([old, one, two, three]); + expect(h.pending).toHaveLength(ACTIVE_READS); + while (h.pending.length) { + h.next().respond([]); + await flush(); + } + await Promise.all([old, ...fresh]); }); /** Real owner wiring; tests dispatch lifecycle events, never toggle a private gate. */ diff --git a/src/features/relay/reader.ts b/src/features/relay/reader.ts index 785c63ffcb..fedd48c1c7 100644 --- a/src/features/relay/reader.ts +++ b/src/features/relay/reader.ts @@ -9,6 +9,9 @@ import { byteSize } from "./budget"; import { ReadError } from "./errors"; import type { AgentLibrary } from "../agents/library"; +/** Reads running at once; at most one of them is background. Below the API + * lane's `API_ACTIVE_LIMIT` of ten, so writes keep three slots. */ +export const ACTIVE_READS = 7; export type Priority = "foreground" | "background"; export type ReadOptions = { signal?: AbortSignal; @@ -159,7 +162,7 @@ export function createRelayReader( if (closed || suspended || recovering || !transport) return; while (!closed && !suspended && !recovering) { const active = [...jobs.values()].filter((job) => job.running); - if (active.length >= 3) return; + if (active.length >= ACTIVE_READS) return; const background = active.some((job) => job.priority === "background"); const queued = [...jobs.values()].filter((job) => !job.running); const job = diff --git a/src/features/relay/signed-boundary.test.ts b/src/features/relay/signed-boundary.test.ts index a399775e3d..56915a3844 100644 --- a/src/features/relay/signed-boundary.test.ts +++ b/src/features/relay/signed-boundary.test.ts @@ -2,7 +2,7 @@ import { assert, afterEach, expect, it, vi } from "vitest"; import { connectSignedTransport } from "./transport"; -import { ApiCapacity, ApiPaused } from "./http-admission"; +import { API_ACTIVE_LIMIT, ApiCapacity, ApiPaused } from "./http-admission"; import { PublishRejected } from "./outbox"; import { hostSigner, signed } from "./testing"; const tick = async () => { @@ -72,7 +72,7 @@ it("work queued for dispatch cannot bypass a newly learned shared cooldown; refu ); assert.exists(t.writer); const paused = t.query([{ kinds: [0], limit: 1 }]).catch((error) => error); - const active = Array.from({ length: 5 }, () => + const active = Array.from({ length: API_ACTIVE_LIMIT - 1 }, () => t.query([{ kinds: [0], limit: 1 }]), ); const queuedRead = t.query([{ kinds: [0], limit: 2 }]); @@ -89,11 +89,11 @@ it("work queued for dispatch cannot bypass a newly learned shared cooldown; refu await publishRejected; host.release(); await Promise.all(active); - expect(host.request).toHaveBeenCalledTimes(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); await vi.advanceTimersByTimeAsync(60000); - expect(host.request).toHaveBeenCalledTimes(6); // No automatic resend. + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); // No automatic resend. await t.writer.publish(event, new AbortController().signal); - expect(host.request).toHaveBeenCalledTimes(7); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT + 1); expect(host.bodies.at(-1)).toBe(JSON.stringify(event)); }); @@ -105,11 +105,11 @@ it("cancelled while queued for dispatch never reaches the host or blocks the nex "https://cancel-sign.test", "relay", ); - const active = Array.from({ length: 6 }, () => + const active = Array.from({ length: API_ACTIVE_LIMIT }, () => t.query([{ kinds: [0], limit: 1 }]), ); await tick(); - expect(host.request).toHaveBeenCalledTimes(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); const controller = new AbortController(); const cancelled = t.query([{ kinds: [0], limit: 2 }], controller.signal); const rejected = expect(cancelled).rejects.toMatchObject({ @@ -120,9 +120,9 @@ it("cancelled while queued for dispatch never reaches the host or blocks the nex await rejected; host.release(); await Promise.all(active); - expect(host.request).toHaveBeenCalledTimes(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); await t.query([{ kinds: [0], limit: 3 }]); - expect(host.request).toHaveBeenCalledTimes(7); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT + 1); expect(host.bodies.at(-1)).toBe(JSON.stringify([{ kinds: [0], limit: 3 }])); expect(vi.getTimerCount()).toBe(0); }); @@ -142,7 +142,7 @@ it("host request ownership is bounded across signed constructor recreation", asy .catch((error) => error), ); await tick(); - expect(host.request).toHaveBeenCalledTimes(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); const replacement = await connectSignedTransport( { ...host.signer }, "https://bounded-sign.test/", @@ -157,11 +157,11 @@ it("host request ownership is bounded across signed constructor recreation", asy // slots until they settle. const next = replacement.query([{ kinds: [0], limit: 1 }]); await tick(); - expect(host.request).toHaveBeenCalledTimes(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT); host.release(); await next; - expect(host.request).toHaveBeenCalledTimes(7); - // Queued reads never reached the host; the six in flight settled through it. - const queued = (await Promise.all(reads)).slice(6); + expect(host.request).toHaveBeenCalledTimes(API_ACTIVE_LIMIT + 1); + // Queued reads never reached the host; the in-flight ones settled through it. + const queued = (await Promise.all(reads)).slice(API_ACTIVE_LIMIT); expect(queued.every((error) => error.name === "AbortError")).toBe(true); }); diff --git a/src/features/relay/signed-priority.test.ts b/src/features/relay/signed-priority.test.ts index 800617c47c..819f4fbabd 100644 --- a/src/features/relay/signed-priority.test.ts +++ b/src/features/relay/signed-priority.test.ts @@ -2,7 +2,8 @@ import { afterEach, expect, it, vi } from "vitest"; import { connectSignedTransport } from "./transport"; -import { createRelayReader } from "./reader"; +import { ACTIVE_READS, createRelayReader } from "./reader"; +import { API_ACTIVE_LIMIT } from "./http-admission"; import { hostSigner } from "./testing"; afterEach(() => { vi.useRealTimers(); @@ -23,22 +24,22 @@ it("production reader prioritizes queued work at real capacity, not a clock inte ); const r = createRelayReader(t); try { - const active = [1, 2, 3].map((limit) => - r.reader.read([{ kinds: [0], limit }]), + const active = Array.from({ length: ACTIVE_READS }, (_, i) => + r.reader.read([{ kinds: [0], limit: i + 1 }]), ); - await vi.waitFor(() => expect(calls).toHaveLength(3)); - const b = r.reader.read([{ kinds: [0], limit: 4 }], { + await vi.waitFor(() => expect(calls).toHaveLength(ACTIVE_READS)); + const b = r.reader.read([{ kinds: [0], limit: ACTIVE_READS + 1 }], { priority: "background", }); - const f = r.reader.read([{ kinds: [0], limit: 5 }], { + const f = r.reader.read([{ kinds: [0], limit: ACTIVE_READS + 2 }], { priority: "foreground", }); release.shift()?.(); - await vi.waitFor(() => expect(calls).toHaveLength(4)); - expect(calls.at(-1)).toBe(5); + await vi.waitFor(() => expect(calls).toHaveLength(ACTIVE_READS + 1)); + expect(calls.at(-1)).toBe(ACTIVE_READS + 2); release.shift()?.(); - await vi.waitFor(() => expect(calls).toHaveLength(5)); - expect(calls.at(-1)).toBe(4); + await vi.waitFor(() => expect(calls).toHaveLength(ACTIVE_READS + 2)); + expect(calls.at(-1)).toBe(ACTIVE_READS + 1); for (const finish of release) finish(); await Promise.all([...active, b, f]); } finally { @@ -58,28 +59,28 @@ it("signed transport forwards query priority to host request admission", async ( "https://priority-forwarding.test", "relay", ); - const active = [1, 2, 3, 4, 5, 6].map((limit) => - t.query([{ kinds: [0], limit }]), + const active = Array.from({ length: API_ACTIVE_LIMIT }, (_, i) => + t.query([{ kinds: [0], limit: i + 1 }]), ); - await vi.waitFor(() => expect(calls).toHaveLength(6)); + await vi.waitFor(() => expect(calls).toHaveLength(API_ACTIVE_LIMIT)); const background = t.query( - [{ kinds: [0], limit: 7 }], + [{ kinds: [0], limit: API_ACTIVE_LIMIT + 1 }], undefined, "read", "background", ); const foreground = t.query( - [{ kinds: [0], limit: 8 }], + [{ kinds: [0], limit: API_ACTIVE_LIMIT + 2 }], undefined, "read", "foreground", ); release.shift()?.(); - await vi.waitFor(() => expect(calls).toHaveLength(7)); - expect(calls.at(-1)).toBe(8); + await vi.waitFor(() => expect(calls).toHaveLength(API_ACTIVE_LIMIT + 1)); + expect(calls.at(-1)).toBe(API_ACTIVE_LIMIT + 2); release.shift()?.(); - await vi.waitFor(() => expect(calls).toHaveLength(8)); - expect(calls.at(-1)).toBe(7); + await vi.waitFor(() => expect(calls).toHaveLength(API_ACTIVE_LIMIT + 2)); + expect(calls.at(-1)).toBe(API_ACTIVE_LIMIT + 1); for (const finish of release) finish(); await Promise.all([...active, background, foreground]); }); diff --git a/src/features/relay/store.test.ts b/src/features/relay/store.test.ts index 08b0a9e9d6..643dc34e00 100644 --- a/src/features/relay/store.test.ts +++ b/src/features/relay/store.test.ts @@ -1,6 +1,7 @@ import { assert, describe, expect, it, vi } from "vitest"; import { huddleDescription } from "../huddle/lifecycle"; import { ReadError } from "./errors"; +import { listByteSize } from "./budget"; import { createRelaySession } from "./session"; import type { LiveCallbacks } from "./live"; import type { HeadPersistence, SavedStartup } from "./persistence"; @@ -8,6 +9,7 @@ import type { RelayEvent } from "./events"; import { bounds, flush, + isNoticeRead, keypair, message, metadata, @@ -203,6 +205,1070 @@ describe("channel store", () => { owner.dispose(); } }); + it("reads an older page of the asked size", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + const queries = createRelaySession(scripted.transport).session.channels; + queries.ensure("c"); + const newer = message(alice, "c", "newer", 20); + scripted.next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + const limits = []; + let cursor = newer; + for (const rows of [5, 120, 900]) { + queries.loadOlder("c", rows); + const page = scripted.pending.find( + (read) => read.filters[0]?.until && !read.filters[0]?.include_aux, + ); + assert(page); + scripted.pending.splice(scripted.pending.indexOf(page), 1); + limits.push(page.filters[0]?.limit); + const older = message(alice, "c", `older ${rows}`, cursor.created_at - 1); + page.respond([ + older, + bounds(relay, "c", `${cursor.created_at}:${cursor.id}`, { + has_more: true, + next_cursor: { created_at: older.created_at, id: older.id }, + }), + ]); + cursor = older; + await flush(); + } + // The asked size, within the relay's read limit. + expect(limits).toEqual([5, 120, 200]); + }); + it("pages again after an older read is cancelled under the window", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + const queries = createRelaySession(scripted.transport).session.channels; + queries.ensure("c"); + const newer = message(alice, "c", "newer", 20); + scripted.next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + const older = () => + scripted.pending.find((read) => read.filters[0]?.until === 20); + queries.loadOlder("c"); + const first = older(); + assert(first); + scripted.pending.splice(scripted.pending.indexOf(first), 1); + // A stream drop cancels every relay read, this page's included. + first.fail(new DOMException("Relay read cancelled", "AbortError")); + await flush(); + expect(queries.window("c").loadingOlder).toBe(false); + queries.loadOlder("c"); + expect(older()).toBeDefined(); + }); + describe("an older page's aux closure", () => { + const newer = message(alice, "c", "newer", 20); + const row = (at: number) => message(alice, "c", `row ${at}`, at); + const on = (kind: number, target: RelayEvent, content = "") => + signed(alice, { + kind, + content, + created_at: 30, + tags: [ + ["e", target.id], + ["h", "c"], + ], + }); + const below = (cursor: RelayEvent, last?: RelayEvent) => + bounds(relay, "c", `${cursor.created_at}:${cursor.id}`, { + has_more: !!last, + next_cursor: last ? { created_at: last.created_at, id: last.id } : null, + }); + async function opened(budget = {}, whileHeadReads?: RelayEvent) { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const store = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + budget, + ); + const queries = store.session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + if (whileHeadReads) live.receive([whileHeadReads]); + scripted.next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + const take = (aux: boolean) => { + const read = scripted.pending.find( + (entry) => + !!entry.filters[0]?.until && + !!entry.filters[0]?.include_aux === aux, + ); + assert(read); + scripted.pending.splice(scripted.pending.indexOf(read), 1); + return read; + }; + /** Page once, below `cursor`, to `rows` shown bare. */ + const page = async (cursor: RelayEvent, ...rows: RelayEvent[]) => { + queries.loadOlder("c"); + take(false).respond([...rows, below(cursor, rows[0])]); + await flush(); + }; + return { queries, take, page, scripted, store, live }; + } + it("withdraws a held edit its aux read deletes", async () => { + const { queries, take, page } = await opened(); + const target = row(10); + const edit = on(40003, target, "edited"); + await page(newer, target, edit); + expect(queries.window("c").rows[0]?.content).toBe("edited"); + take(true).respond([target, edit, on(5, edit), below(newer)]); + await flush(); + expect(queries.window("c").rows[0]?.content).toBe("row 10"); + }); + it("reads a page's aux only once its channel is open again", async () => { + const { queries, take, scripted } = await opened(); + const first = row(10); + queries.loadOlder("c"); + queries.ensure("d"); + take(false).respond([first, below(newer, first)]); + await flush(); + expect( + scripted.pending.some( + (read) => read.filters[0]?.until && read.filters[0]?.include_aux, + ), + ).toBe(false); + queries.ensure("c"); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + }); + it("reads a page too large for a response again in default pages", async () => { + const { queries, take } = await opened(); + queries.loadOlder("c", 200); + const large = take(false); + expect(large.filters[0]).toMatchObject({ limit: 200, until: 20 }); + large.fail( + new ReadError( + "invalid-response", + "Relay response exceeds the read budget", + ), + ); + await flush(); + expect(take(false).filters[0]).toMatchObject({ limit: 20, until: 20 }); + expect(queries.window("c")).toMatchObject({ + loadingOlder: true, + error: undefined, + }); + }); + it("ends a newer page a stream drop cancels", async () => { + const { queries, page, scripted } = await opened({ maxHistoryRows: 2 }); + const [a, b, c] = [row(10), row(8), row(6)]; + await page(newer, a); + await page(a, b); + await page(b, c); + expect(queries.window("c").hasNewer).toBe(true); + const before = new Set(scripted.pending); + queries.loadNewer?.("c"); + expect(queries.window("c").loadingNewer).toBe(true); + const read = scripted.pending.find((entry) => !before.has(entry)); + assert(read); + read.fail(new DOMException("Relay read cancelled", "AbortError")); + await flush(); + expect(queries.window("c").loadingNewer).toBeFalsy(); + }); + it("reads a closure too large for a response again in smaller parts", async () => { + const { take, page } = await opened(); + await page(newer, row(10), row(9), row(8)); + const large = take(true); + expect(large.filters[0]).toMatchObject({ limit: 3, until: 20 }); + large.fail( + new ReadError( + "invalid-response", + "Relay response exceeds the read budget", + ), + ); + await flush(); + expect(take(true).filters[0]).toMatchObject({ limit: 2, until: 20 }); + }); + it("reads past a failing aux page to the pages behind it", async () => { + const { take, page } = await opened(); + const [a, b] = [row(10), row(8)]; + await page(newer, a); + const failing = take(true); + await page(a, b); + // One row's closure past the response budget: it reads no smaller. + failing.fail( + new ReadError( + "invalid-response", + "Relay response exceeds the read budget", + ), + ); + await flush(); + // The same fill reads the page behind it. + expect(take(true).filters[0]).toMatchObject({ until: a.created_at }); + }); + it("an aux slide forgets the live rows it drops", async () => { + const late = message(alice, "c", "late", 25); + const target = row(10); + const edit = on(40003, target, "edited"); + const { queries, take, page, scripted, live } = await opened({ + maxHistoryBytes: listByteSize([newer, late, target, edit]) - 1, + }); + live.receive([late]); + await flush(); + await page(newer, target); + take(true).respond([target, edit, below(newer)]); + await flush(); + // The slide drops the live row for the rows paged to. + expect(queries.window("c").hasNewer).toBe(true); + expect(queries.window("c").rows.map((row) => row.content)).toEqual([ + "edited", + "newer", + ]); + // A head without the live row (deleted meanwhile) shows only its own. + queries.attach?.("c"); + const head = scripted.pending.find( + (read) => read.filters[0]?.top_level && !read.filters[0]?.until, + ); + head?.respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).toEqual([newer.id]); + }); + it("drops a read-ahead page past the budget and stays at the head", async () => { + const target = row(10); + const { queries, take, scripted } = await opened({ + maxHistoryBytes: listByteSize([newer, target]) - 1, + }); + queries.loadOlder("c", 20, true); + take(false).respond([target, below(newer, target)]); + await flush(); + expect(queries.window("c")).toMatchObject({ + loadingOlder: false, + rows: [{ id: newer.id }], + }); + expect(queries.window("c").hasNewer).toBeFalsy(); + // Read-ahead stops; the reader's own paging still reads. + queries.loadOlder("c", 20, true); + expect(scripted.pending.some((read) => read.filters[0]?.until)).toBe( + false, + ); + queries.loadOlder("c"); + expect(take(false).filters[0]).toMatchObject({ until: 20 }); + }); + it("trims a read-ahead page's closure past the budget at the head", async () => { + const target = row(10); + const edit = on(40003, target, "edited"); + const { queries, take } = await opened({ + maxHistoryBytes: listByteSize([newer, target, edit]) - 1, + }); + queries.loadOlder("c", 20, true); + take(false).respond([target, below(newer, target)]); + await flush(); + take(true).respond([target, edit, below(newer)]); + await flush(); + expect(queries.window("c").hasNewer).toBeFalsy(); + expect(queries.window("c").rows.map((row) => row.id)).toEqual([newer.id]); + }); + it("a read-ahead closure trim forgets the live rows it drops", async () => { + const target = row(10); + const edit = on(40003, target, "edited"); + // A late send in the oldest second, sorting below the row paged to. + let late = message(alice, "c", "late", 10); + for (let n = 0; late.id < target.id; n++) + late = message(alice, "c", `late ${n}`, 10); + const { queries, take, live, scripted } = await opened({ + maxHistoryBytes: listByteSize([newer, late, target, edit]) - 1, + }); + queries.loadOlder("c", 20, true); + take(false).respond([target, below(newer, target)]); + await flush(); + live.receive([late]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).toContain(late.id); + take(true).respond([target, edit, below(newer)]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).not.toContain( + late.id, + ); + // Nor does a head that meets the rows held. + queries.refresh?.("c"); + for (const read of scripted.pending.filter( + (entry) => entry.filters[0]?.top_level && !entry.filters[0]?.until, + )) + read.respond([ + newer, + target, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 10, id: target.id }, + }), + ]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).not.toContain( + late.id, + ); + }); + it("keeps a live row from the head read when aux merges", async () => { + const late = message(alice, "c", "late", 25); + const { queries, take, page } = await opened({}, late); + const target = row(10); + await page(newer, target); + take(true).respond([target, on(7, target, "+"), below(newer)]); + await flush(); + expect(queries.window("c").rows.map((row) => row.content)).toEqual([ + "row 10", + "newer", + "late", + ]); + }); + it("reads a cancelled aux read again with the next fill", async () => { + const { take, page } = await opened(); + const first = row(10); + await page(newer, first); + // A stream drop cancels every relay read, this aux read's included. + take(true).fail(new DOMException("Relay read cancelled", "AbortError")); + await flush(); + await page(first, row(8)); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + }); + it("slides an aux closure past the budget down to the rows paged to", async () => { + const target = row(10); + const edit = on(40003, target, "edited"); + const { queries, take, page } = await opened({ + maxHistoryBytes: listByteSize([newer, target, edit]) - 1, + }); + await page(newer, target); + take(true).respond([target, edit, below(newer)]); + await flush(); + const window = queries.window("c"); + expect(window).toMatchObject({ + hasNewer: true, + rows: [{ id: target.id, content: "edited" }], + }); + expect(window?.historyLimited).toBeFalsy(); + // The next older page slides on within the budget. + const older = row(8); + await page(target, older); + expect(queries.window("c")).toMatchObject({ + hasNewer: true, + rows: [{ id: older.id }, { id: target.id, content: "edited" }], + }); + }); + it("applies an aux closure larger than the whole budget", async () => { + const target = row(10); + const edit = on(40003, target, "edited"); + const { queries, take, page } = await opened({ + maxHistoryBytes: listByteSize([target, edit]) - 1, + }); + await page(newer, target); + expect(queries.window("c").historyLimited).toBeFalsy(); + take(true).respond([target, edit, below(newer)]); + await flush(); + expect(queries.window("c")).toMatchObject({ + rows: [{ id: target.id, content: "edited" }, { id: newer.id }], + }); + }); + it("does not slide to rows an aux closure deletes", async () => { + const [a, b] = [row(10), row(8)]; + const edit = on(40003, a, "edited ".repeat(200)); + const { queries, take, page } = await opened({ + maxHistoryBytes: listByteSize([newer, a, b]) + 400, + }); + await page(newer, a, b); + take(true).respond([a, b, edit, on(5, b), below(newer)]); + await flush(); + expect(queries.window("c")).toMatchObject({ + rows: [{ id: a.id, content: edit.content }, { id: newer.id }], + }); + }); + it("skips the aux read of a page the window has slid past", async () => { + const { queries, take, page, scripted } = await opened({ + maxHistoryRows: 2, + }); + const [a, b, c, d] = [row(10), row(8), row(6), row(4)]; + await page(newer, a); + const held = take(true); + await page(a, b); + await page(b, c); + await page(c, d); + // The window holds c and d: b's page is gone, c's is next. + held.respond([a, below(newer)]); + await flush(); + // The dropped row stays dropped. + expect(queries.window("c")).toMatchObject({ + hasNewer: true, + rows: [{ id: d.id }, { id: c.id }], + }); + expect(take(true).filters[0]).toMatchObject({ until: b.created_at }); + // Newer history reads up from b, the newest row slid past: a day above + // the ceiling (history-seek), not above the row the late aux held. + queries.loadNewer?.("c"); + const newerRead = scripted.pending.find((read) => + read.filters[0]?.["#h"]?.includes("c"), + ); + expect(newerRead?.filters[0]?.until).toBe(b.created_at + 86_400); + }); + it("keeps a row live traffic drops out while its aux read is in flight", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { maxHistoryRows: 3 }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + scripted.next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + const [a, b] = [row(10), row(8)]; + queries.loadOlder("c"); + const bare = scripted.pending.find((read) => read.filters[0]?.until); + assert(bare); + bare.respond([a, b, below(newer, b)]); + await flush(); + const held = scripted.pending.find( + (read) => read.filters[0]?.include_aux, + ); + assert(held); + const fresh = message(alice, "c", "fresh", 25); + live.receive([fresh]); + held.respond([a, b, below(newer)]); + await flush(); + // The window stays at the head, without the dropped row. + expect(queries.window("c").hasNewer).toBeFalsy(); + expect(queries.window("c").rows.map((row) => row.id)).toEqual([ + a.id, + newer.id, + fresh.id, + ]); + }); + it.each([false, true])( + "reads an aux read an access purge cancels again (resolved first: %s)", + async (resolved) => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + const queries = createRelaySession(scripted.transport).session.channels; + queries.ensure("c"); + scripted.next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + queries.loadOlder("c"); + const bare = scripted.pending.find((read) => read.filters[0]?.until); + assert(bare); + bare.respond([row(10), below(newer)]); + await flush(); + const auxRead = () => + scripted.pending.find( + (read) => read.filters[0]?.include_aux && read.filters[0]?.until, + ); + const held = auxRead(); + assert(held); + scripted.pending.splice(scripted.pending.indexOf(held), 1); + if (resolved) held.respond([below(newer)]); + // Another channel's denied head read purges access everywhere. + queries.ensure("x"); + const other = scripted.pending.find((read) => + read.filters[0]?.["#h"]?.includes("x"), + ); + assert(other); + other.fail(new ReadError("denied", "Forbidden", 403)); + await flush(); + // Opening the other channel paused the aux work; returning resumes it. + queries.ensure("c"); + expect(auxRead()?.filters[0]).toMatchObject({ until: 20 }); + }, + ); + it("reads a refused aux read again when its retry hint expires", async () => { + const { queries, take, page } = await opened(); + await page(newer, row(10)); + vi.useFakeTimers({ + toFake: ["performance", "setTimeout", "clearTimeout"], + }); + try { + // A fractional hint: the timer fires at whole milliseconds. + take(true).fail(new ReadError("unavailable", "Quota", 429, 60_000.6)); + await vi.advanceTimersByTimeAsync(0); + queries.ensure("c"); + expect(() => take(true), "no aux read inside the hint").toThrow(); + await vi.advanceTimersByTimeAsync(60_000); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + } finally { + vi.useRealTimers(); + } + }); + it("cancels a refused aux read's retry when the session is disposed", async () => { + const { take, page, store } = await opened(); + await page(newer, row(10)); + vi.useFakeTimers({ + toFake: ["performance", "setTimeout", "clearTimeout"], + }); + try { + take(true).fail(new ReadError("unavailable", "Quota", 429, 60_000)); + await vi.advanceTimersByTimeAsync(0); + store.dispose(); + await vi.advanceTimersByTimeAsync(60_000); + expect(() => take(true), "no aux read after disposal").toThrow(); + } finally { + vi.useRealTimers(); + } + }); + it("reads a failed aux read again when the channel is revisited", async () => { + const { queries, take, page } = await opened(); + await page(newer, row(10)); + take(true).fail(new Error("denied")); + await flush(); + queries.ensure("c"); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + }); + it("cancels an aux read when another channel opens and reads it again on return", async () => { + const { queries, take, page, scripted } = await opened(); + await page(newer, row(10)); + const held = take(true); + queries.ensure("d"); + expect(held.signal?.aborted).toBe(true); + await flush(); + scripted.pending.length = 0; + queries.ensure("c"); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + }); + async function revisited(head: RelayEvent[]) { + let clock = 1_000_000; + const { queries, take, page, scripted } = await opened({ + prepared: true, + now: () => clock, + }); + const older = row(10); + await page(newer, older); + take(true).respond([older, below(newer)]); + await flush(); + queries.ensure("d"); + await flush(); + scripted.pending.length = 0; + clock += 61_000; + const query = vi.spyOn(scripted.transport, "query"); + queries.ensure("c"); + const last = head.at(-1); + assert(last); + const read = scripted.next(); + read.respond([ + ...head, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: last.created_at, id: last.id }, + }), + ]); + await flush(); + return { + ids: queries.window("c").rows.map((row) => row.id), + older, + read, + noticeReads: query.mock.calls.filter(([filters]) => + isNoticeRead(filters), + ).length, + }; + } + const latest = message(alice, "c", "latest", 25); + it("merges a newer head into the paged rows on a revisit past the lease", async () => { + const { ids, older, read, noticeReads } = await revisited([ + latest, + newer, + ]); + expect(ids).toEqual([older.id, newer.id, latest.id]); + // The head read its newest notices, so none are read apart from it. + expect(read.filters[1]).toMatchObject({ kinds: [40099] }); + expect(noticeReads).toBe(0); + }); + it("replaces the paged rows with a newer head that does not meet them", async () => { + const after = message(alice, "c", "after", 24); + expect(await revisited([latest, after])).toMatchObject({ + ids: [after.id, latest.id], + }); + }); + it("a failed return to the head keeps the aux work of the rows it shows", async () => { + const { queries, take, page, scripted } = await opened({ + maxHistoryRows: 2, + }); + const [a, b] = [row(10), row(8)]; + await page(newer, a); + const held = take(true); + await page(a, b); + expect(queries.window("c").hasNewer).toBe(true); + queries.attach?.("c"); + expect(held.signal?.aborted).toBe(true); + await flush(); + // No aux read while the head loads. + expect( + scripted.pending.some( + (read) => read.filters[0]?.include_aux && read.filters[0]?.until, + ), + ).toBe(false); + const head = scripted.pending.find( + (read) => !read.filters[0]?.until && read.filters[0]?.["#h"], + ); + assert(head); + scripted.pending.splice(scripted.pending.indexOf(head), 1); + head.fail(new ReadError("unavailable", "Relay is down")); + await flush(); + expect(queries.window("c").hasNewer).toBe(true); + expect(take(true).filters[0]).toMatchObject({ until: 20 }); + }); + it("returning to the head ends the aux work of the rows it replaces", async () => { + const { queries, take, page, scripted } = await opened({ + maxHistoryRows: 2, + }); + const [a, b] = [row(10), row(8)]; + await page(newer, a); + const held = take(true); + await page(a, b); + expect(queries.window("c").hasNewer).toBe(true); + queries.attach?.("c"); + expect(held.signal?.aborted).toBe(true); + // The cancelled read is not read again: paging once reads one aux part. + const head = scripted.pending.find( + (read) => !read.filters[0]?.until && read.filters[0]?.["#h"], + ); + assert(head); + scripted.pending.splice(scripted.pending.indexOf(head), 1); + head.respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + await page(newer, a); + take(true).respond([a, below(newer)]); + await flush(); + expect( + scripted.pending.filter((read) => read.filters[0]?.include_aux), + ).toEqual([]); + }); + }); + // 40 held rows at 1000..961, two of them sharing 981, and an older page of + // 40 rows at 960..921. + const held = Array.from({ length: 40 }, (_, i) => + message(alice, "c", `held ${i}`, i === 18 ? 981 : 1000 - i), + ); + const older = Array.from({ length: 40 }, (_, i) => + message(alice, "c", `older ${i}`, 960 - i), + ); + // A withdrawn edit and a removed reaction on the two newest older rows. + const about = (kind: number, target: RelayEvent, content = "") => + signed(alice, { + kind, + content, + created_at: 999, + tags: [ + ["e", target.id], + ["h", "c"], + ], + }); + const edit = about(40003, older[0] as RelayEvent, "withdrawn edit"); + const reaction = about(7, older[1] as RelayEvent, "👍"); + const aux = [edit, about(5, edit), reaction, about(5, reaction)]; + // The page and the 20 oldest held rows: the 21st shares its second with the + // 22nd, which the budget leaves out. + const kept = [...older, ...held.filter((row) => row.created_at < 981)]; + const notices = Array.from({ length: 150 }, (_, i) => + signed(relay, { + kind: 40099, + content: JSON.stringify({ + type: "member_joined", + actor: alice.pubkey, + target: keypair().pubkey, + }), + created_at: 1001 + i, + tags: [["h", "c"]], + }), + ); + it.each([ + [ + "byte", + 0, + { + maxHistoryBytes: listByteSize([ + ...kept, + ...aux, + held[18] as RelayEvent, + ]), + }, + ], + ["row", 0, { maxHistoryRows: 61 }], + ["row", notices.length, { maxHistoryRows: 61 }], + ])( + "an older page past the %s budget, with %i notices shown, slides the window down to it", + async (_, shown, budget) => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey, { + notices: true, + }); + const queries = createRelaySession(scripted.transport, budget).session + .channels; + queries.ensure("c"); + const last = held[39] as RelayEvent; + scripted.next().respond([ + ...held, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: last.created_at, id: last.id }, + }), + ]); + await flush(); + scripted.next().respond(notices.slice(0, shown)); + await flush(); + expect(queries.window("c").rows).toHaveLength(40 + shown); + queries.loadOlder("c", 200); + const page = scripted.pending.find((read) => read.filters[0]?.until); + assert(page); + const oldest = older[39] as RelayEvent; + page.respond([ + ...older, + ...aux, + bounds(relay, "c", `${last.created_at}:${last.id}`, { + has_more: true, + next_cursor: { created_at: oldest.created_at, id: oldest.id }, + }), + ]); + await flush(); + const window = queries.window("c"); + expect(window).toMatchObject({ + status: "ready", + hasMore: true, + hasNewer: true, + loadingOlder: false, + }); + expect(window.historyLimited).toBeFalsy(); + expect(window.rows.map((row) => row.id)).toEqual( + kept + .sort((a, b) => a.created_at - b.created_at) + .map((event) => event.id), + ); + // The withdrawn edit and removed reaction stay withdrawn. + const row = (event?: RelayEvent) => + window.rows.find((item) => item.id === event?.id); + expect(row(older[0])?.content).toBe("older 0"); + expect(row(older[1])?.reactions).toEqual([]); + }, + ); + it("replaces paged rows with a revisit head that meets only their live tail", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + let clock = 1_000_000; + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { prepared: true, now: () => clock }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + const [older, head, stray, tail, latest] = [5, 10, 20, 30, 40].map((at) => + message(alice, "c", `at ${at}`, at), + ); + assert(older && head && stray && tail && latest); + const take = () => { + const read = scripted.pending.find( + (entry) => + entry.filters[0]?.top_level && !entry.filters[0]?.include_aux, + ); + assert(read); + scripted.pending.splice(scripted.pending.indexOf(read), 1); + return read; + }; + scripted.next().respond([ + head, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 10, id: head.id }, + }), + ]); + await flush(); + queries.loadOlder("c"); + take().respond([ + older, + bounds(relay, "c", `10:${head.id}`, { + has_more: false, + next_cursor: null, + }), + ]); + await flush(); + // The stream delivers a row; what it missed before it is unknown. + live.receive([stray, tail]); + queries.ensure("d"); + await flush(); + scripted.pending.length = 0; + clock += 61_000; + queries.ensure("c"); + const revisit = scripted.pending.find( + (entry) => entry.filters[0]?.top_level && !entry.filters[0]?.until, + ); + assert(revisit); + revisit.respond([ + latest, + tail, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 30, id: tail.id }, + }), + ]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).toEqual([ + tail.id, + latest.id, + ]); + }); + it("a revisit head drops live rows below its cursor in the cursor's second", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + let clock = 1_000_000; + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { prepared: true, now: () => clock }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + const [older, head, latest] = [5, 10, 40].map((at) => + message(alice, "c", `at ${at}`, at), + ); + // Relay order at a tie is ID ascending: `after` sorts below the cursor. + const [tail, after] = ["a", "c"] + .map((name) => message(alice, "c", name, 30)) + .sort((a, b) => a.id.localeCompare(b.id)); + assert(older && head && latest && tail && after); + scripted.next().respond([ + head, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 10, id: head.id }, + }), + ]); + await flush(); + queries.loadOlder("c"); + const page = scripted.pending.find( + (entry) => entry.filters[0]?.until && !entry.filters[0]?.include_aux, + ); + assert(page); + scripted.pending.splice(scripted.pending.indexOf(page), 1); + page.respond([ + older, + bounds(relay, "c", `10:${head.id}`, { + has_more: false, + next_cursor: null, + }), + ]); + await flush(); + live.receive([tail, after]); + queries.ensure("d"); + await flush(); + scripted.pending.length = 0; + clock += 61_000; + queries.ensure("c"); + const revisit = scripted.pending.find( + (entry) => entry.filters[0]?.top_level && !entry.filters[0]?.until, + ); + assert(revisit); + revisit.respond([ + latest, + tail, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 30, id: tail.id }, + }), + ]); + await flush(); + expect(queries.window("c").rows.map((row) => row.id)).toEqual([ + tail.id, + latest.id, + ]); + }); + it("a live trim of late rows below the floor keeps the older cursor", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const head = message(alice, "c", "head", 30); + const [ten, five] = [ + message(alice, "c", "ten", 10), + message(alice, "c", "five", 5), + ]; + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { maxHistoryBytes: listByteSize([head, ten]) }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + scripted.next().respond([ + head, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 30, id: head.id }, + }), + ]); + await flush(); + live.receive([ten, five]); + await flush(); + queries.loadOlder("c"); + expect( + scripted.pending.find((read) => read.filters[0]?.until)?.filters[0], + ).toMatchObject({ until: 30, before_id: head.id }); + }); + it("a live trim keeps the older cursor for rows below it in the cursor's second", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + // The relay orders a second's rows by ID: the head read ends at `head`. + const [head, unseen, liveA, liveB] = ["a", "b", "c", "d"] + .map((name) => message(alice, "c", name, 30)) + .sort((a, b) => a.id.localeCompare(b.id)); + assert(head && unseen && liveA && liveB); + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { maxHistoryBytes: listByteSize([head, liveA]) }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + scripted.next().respond([ + head, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 30, id: head.id }, + }), + ]); + await flush(); + live.receive([liveA, liveB]); + await flush(); + queries.loadOlder("c"); + expect( + scripted.pending.find((read) => read.filters[0]?.until)?.filters[0], + ).toMatchObject({ until: 30, before_id: head.id }); + }); + it("a full window drops its oldest rows for live traffic, but not under an older read", async () => { + const scripted = scriptedTransport(viewer.pubkey, relay.pubkey); + let live!: LiveCallbacks; + const queries = createRelaySession( + { + ...scripted.transport, + subscribe(callbacks) { + live = callbacks; + return { update() {}, retry() {}, dispose() {} }; + }, + }, + { maxHistoryRows: 2 }, + ).session.channels; + live.receive([roster(relay, "c", [viewer.pubkey])]); + queries.ensure("c"); + const one = message(alice, "c", "one", 1); + const two = message(alice, "c", "two", 2); + scripted.next().respond([ + two, + one, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 1, id: one.id }, + }), + ]); + await flush(); + const three = message(alice, "c", "three", 3); + live.receive([three]); + expect(queries.window("c")).toMatchObject({ hasMore: true }); + expect(queries.window("c").rows.map((row) => row.content)).toEqual([ + "two", + "three", + ]); + // The next older page reads the dropped row again; traffic while it is + // in flight does not cancel it. + await flush(); + queries.loadOlder("c"); + const older = scripted.pending.find((read) => read.filters[0]?.until); + expect(older?.filters[0]).toMatchObject({ until: 2, before_id: two.id }); + live.receive([message(alice, "c", "four", 4)]); + expect(older?.signal?.aborted).toBe(false); + older?.respond([ + one, + bounds(relay, "c", `2:${two.id}`, { has_more: false, next_cursor: null }), + ]); + await flush(); + // It lands below the rows held and slides the window within its budget. + expect(queries.window("c")).toMatchObject({ + hasNewer: true, + loadingOlder: false, + }); + expect(queries.window("c").rows.map((row) => row.content)).toEqual([ + "one", + "two", + ]); + // The slide forgets the live row it dropped: a head without it (deleted + // meanwhile) shows only its own rows. + queries.attach?.("c"); + const head = scripted.pending.find( + (read) => read.filters[0]?.top_level && !read.filters[0]?.until, + ); + head?.respond([ + three, + two, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 2, id: two.id }, + }), + ]); + await flush(); + expect(queries.window("c").rows.map((row) => row.content)).toEqual([ + "two", + "three", + ]); + }); it("pages a window by the relay cursor, prepends older rows, and fetches missing profiles once", async () => { const { store, queries, next, pending } = setup(); const listener = vi.fn(); @@ -249,10 +1315,10 @@ describe("channel store", () => { until: 20, before_id: newer.id, top_level: true, - include_aux: true, include_summaries: true, limit: 20, }); + expect(page.filters[0]).not.toHaveProperty("include_aux"); // Older rows prepend; the duplicated `newer` row is deduped; alice is already pending so no second profile query. page.respond([ older, @@ -269,6 +1335,37 @@ describe("channel store", () => { loadingOlder: false, rows: [{ id: older.id }, { id: newer.id }], }); + // The same page then reads in full, adding its aux closure to the rows: + // as many rows as it showed. + const aux = next(); + expect(aux.filters[0]).toMatchObject({ + until: 20, + before_id: newer.id, + include_aux: true, + limit: 2, + }); + expect(aux.filters[0]).not.toHaveProperty("include_summaries"); + aux.respond([ + older, + newer, + signed(viewer, { + kind: 7, + content: "+", + created_at: 11, + tags: [ + ["h", "c"], + ["e", older.id], + ], + }), + bounds(relay, "c", `20:${newer.id}`, { + has_more: false, + next_cursor: null, + }), + ]); + await flush(); + expect(queries.window("c").rows[0]?.reactions).toMatchObject([ + { content: "+" }, + ]); expect(pending.length).toBe(0); profiles.respond([profile(alice, { name: "Alice" })]); await flush(); @@ -279,6 +1376,225 @@ describe("channel store", () => { expect(pending.length).toBe(0); expect(listener.mock.calls.length).toBeGreaterThanOrEqual(4); }); + it("cancelling an older read aborts it and leaves the window to read it again", async () => { + const { queries, next, pending } = setup(); + queries.ensure("c"); + const newer = message(alice, "c", "newer", 20); + next().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + queries.loadOlder("c", 200); + const page = pending.find((read) => read.filters[0]?.until); + assert(page); + queries.cancelOlder?.("c"); + expect(page.signal?.aborted).toBe(true); + expect(queries.window("c")).toMatchObject({ + loadingOlder: false, + hasMore: true, + error: undefined, + rows: [{ id: newer.id }], + }); + await flush(); + queries.loadOlder("c"); + expect(pending.at(-1)?.filters[0]).toMatchObject({ + until: 20, + before_id: newer.id, + }); + }); + it("reads a large page's aux closure in 50-row parts by the relay cursor", async () => { + const { queries, pending } = setup(); + queries.ensure("c"); + const newer = message(alice, "c", "newer", 200); + const take = () => { + const read = pending.find((entry) => entry.filters[0]?.top_level); + assert(read); + pending.splice(pending.indexOf(read), 1); + return read; + }; + take().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 200, id: newer.id }, + }), + ]); + await flush(); + queries.loadOlder("c", 120); + const page = take(); + expect(page.filters[0]).toMatchObject({ limit: 120 }); + expect(page.filters[0]).not.toHaveProperty("include_aux"); + const rows = Array.from({ length: 120 }, (_, n) => + message(alice, "c", `older ${n}`, 199 - n), + ); + const last = rows.at(-1); + assert(last); + page.respond([ + ...rows, + bounds(relay, "c", `200:${newer.id}`, { + has_more: true, + next_cursor: { created_at: last.created_at, id: last.id }, + }), + ]); + await flush(); + const parts = []; + let cursor = newer; + for (const size of [50, 50, 20]) { + const aux = take(); + parts.push(aux.filters[0]); + const part = rows.slice( + rows.indexOf(cursor) + 1, + rows.indexOf(cursor) + 1 + size, + ); + const end = part.at(-1); + assert(end); + aux.respond([ + ...part, + bounds(relay, "c", `${cursor.created_at}:${cursor.id}`, { + has_more: true, + next_cursor: { created_at: end.created_at, id: end.id }, + }), + ]); + cursor = end; + await flush(); + } + expect(parts).toMatchObject([ + { include_aux: true, limit: 50, until: 200 }, + { include_aux: true, limit: 50, until: rows[49]?.created_at }, + { include_aux: true, limit: 20, until: rows[99]?.created_at }, + ]); + expect(pending.filter((entry) => entry.filters[0]?.top_level)).toEqual([]); + }); + it("reads on past a row written into a page's range until its aux covers every row", async () => { + const { queries, pending } = setup(); + queries.ensure("c"); + const newer = message(alice, "c", "newer", 200); + const take = () => { + const read = pending.find((entry) => entry.filters[0]?.top_level); + assert(read); + pending.splice(pending.indexOf(read), 1); + return read; + }; + take().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 200, id: newer.id }, + }), + ]); + await flush(); + queries.loadOlder("c"); + const rows = [190, 180, 170].map((at) => + message(alice, "c", `older ${at}`, at), + ); + const [first, second, last] = rows; + assert(first && second && last); + take().respond([ + ...rows, + bounds(relay, "c", `200:${newer.id}`, { + has_more: true, + next_cursor: { created_at: last.created_at, id: last.id }, + }), + ]); + await flush(); + // A backdated row takes a place in the limited aux read. + const backdated = message(alice, "c", "backdated", 175); + const aux = take(); + expect(aux.filters[0]).toMatchObject({ include_aux: true, limit: 3 }); + aux.respond([ + first, + second, + backdated, + bounds(relay, "c", `200:${newer.id}`, { + has_more: true, + next_cursor: { created_at: backdated.created_at, id: backdated.id }, + }), + ]); + await flush(); + const rest = take(); + expect(rest.filters[0]).toMatchObject({ + include_aux: true, + limit: 1, + until: backdated.created_at, + before_id: backdated.id, + }); + const reaction = signed(viewer, { + kind: 7, + content: "+", + created_at: 171, + tags: [ + ["h", "c"], + ["e", last.id], + ], + }); + rest.respond([ + last, + reaction, + bounds(relay, "c", `175:${backdated.id}`, { + has_more: true, + next_cursor: { created_at: last.created_at, id: last.id }, + }), + ]); + await flush(); + expect( + queries.window("c").rows.find((row) => row.id === last.id)?.reactions, + ).toHaveLength(1); + // Every row of the page is covered: no further aux read. + expect(pending.filter((entry) => entry.filters[0]?.top_level)).toEqual([]); + }); + it("evicting a window aborts its pages' aux read and drops the rest", async () => { + const { queries, pending } = setup(1); + queries.ensure("c"); + const newer = message(alice, "c", "newer", 20), + older = message(alice, "c", "older", 10), + oldest = message(alice, "c", "oldest", 5); + const window = () => pending.filter((read) => read.filters[0]?.top_level); + const take = () => { + const [read] = window(); + assert(read); + pending.splice(pending.indexOf(read), 1); + return read; + }; + take().respond([ + newer, + bounds(relay, "c", "head", { + has_more: true, + next_cursor: { created_at: 20, id: newer.id }, + }), + ]); + await flush(); + for (const [row, cursor] of [ + [older, newer], + [oldest, older], + ] as const) { + queries.loadOlder("c"); + const page = window().find((read) => !read.filters[0]?.include_aux); + assert(page); + pending.splice(pending.indexOf(page), 1); + page.respond([ + row, + bounds(relay, "c", `${cursor.created_at}:${cursor.id}`, { + has_more: true, + next_cursor: { created_at: row.created_at, id: row.id }, + }), + ]); + await flush(); + } + // One aux read at a time: the first page's, with the second queued. + const aux = window(); + expect(aux.map((read) => read.filters[0]?.until)).toEqual([20]); + queries.ensure("d"); + expect(aux[0]?.signal?.aborted).toBe(true); + expect( + window().filter( + (read) => read.filters[0]?.["#h"]?.[0] === "c" && !read.signal?.aborted, + ), + ).toEqual([]); + }); it("keeps rows older than a paged window's history bound out until a page reaches them", async () => { // Agents, search and previews read single old messages through the // session. Merging one into an open window above its loaded history makes diff --git a/src/features/relay/store.ts b/src/features/relay/store.ts index 20c066cd3b..72f8e4a9c2 100644 --- a/src/features/relay/store.ts +++ b/src/features/relay/store.ts @@ -44,6 +44,7 @@ import { noticeFilter, parseWindow, WINDOW_KINDS, + WINDOW_PAGE_SIZE, windowFilter, type WindowCursor, } from "./window"; @@ -121,6 +122,27 @@ type WindowState = { /** A head read asked for the newest notices again. */ noticeHead?: boolean | undefined; noticeRead?: { controller: AbortController; generation: number } | undefined; + /** Older pages shown without their aux closure: the rows each still needs + * it for, read down from `cursor` to no older than `floor` (unix seconds). */ + auxPages: { + cursor: WindowCursor; + floor: number; + rows: ReadonlySet; + /** Rows a read takes, below `AUX_PAGE` once a response ran too large. */ + limit?: number; + /** Read ahead of the reader: its closure trims, never slides. */ + ahead?: boolean; + }[]; + /** A read-ahead page met the budget: no more until the reader pages. */ + aheadFull?: boolean | undefined; + auxRead?: + | { controller: AbortController; generation: number; dropped?: boolean } + | undefined; + /** Aux work waits while a head read may replace its rows (`reattach`). */ + auxPaused?: boolean | undefined; + /** A refused aux read's retry hint: no aux read before it, one at it. */ + auxRetryAt?: number; + auxRetry?: ReturnType; }; type Head = { rows: readonly ChannelMessage[]; @@ -225,6 +247,9 @@ const UNAVAILABLE: ChannelList = Object.freeze({ }); const describe = (error: unknown) => error instanceof Error ? error.message : String(error); +/** Rows per aux read: the relay's aux closure costs about a tenth of a second + * a row, so a larger read risks its read timeout. */ +const AUX_PAGE = 50; const isAbort = (error: unknown) => readErrorKind(error) === "cancelled"; /** An open channel name's match rank: the joined-channel rule (`matchRank`), * so "buzz community" finds "buzz-community"; an exact lookup names one. */ @@ -242,9 +267,30 @@ const CATCH_UP_PAGES = 5; /** Membership notices a window reads below its head. Past it, older pages show * without their notices. */ const MAX_NOTICES = 2000; +/** `events` with an id in `ids`, and the non-row events about them: edits and + * reactions of kept rows, and the deletions of those. */ +function retainAbout(events: readonly RelayEvent[], ids: ReadonlySet) { + const about = new Map(); + for (const event of events) + if (!channelRowKind(event.kind)) + for (const [name, id] of event.tags) + if (name === "e" && id) { + const list = about.get(id); + if (list) list.push(event); + else about.set(id, [event]); + } + const kept = new Set(ids); + for (const id of kept) + for (const event of about.get(id) ?? []) kept.add(event.id); + return events.filter((event) => kept.has(event.id)); +} /** Relay query order: time descending, then ID ascending at ties. */ const newestFirst = (a: RelayEvent, b: RelayEvent) => b.created_at - a.created_at || a.id.localeCompare(b.id); +/** Whether `event` sorts below `cursor` in relay order: unread by its page. */ +const belowCursor = (event: RelayEvent, cursor: WindowCursor) => + event.created_at < cursor.createdAt || + (event.created_at === cursor.createdAt && event.id > cursor.eventId); /** Where the read after a page of notices starts: null when it was the last. */ const noticeCursor = (events: readonly RelayEvent[]): WindowCursor | null => { const last = [...events].sort(newestFirst).at(-1); @@ -693,9 +739,11 @@ export function createChannelStore( } function evict(state: WindowState) { windows.delete(state.channelId); + clearTimeout(state.auxRetry); state.generation++; state.controller?.abort(); state.noticeRead?.controller.abort(); + dropAux(state); state.events = []; state.notices.clear(); state.floor = undefined; @@ -735,6 +783,7 @@ export function createChannelStore( cursor: null, events: [], notices: new Map(), + auxPages: [], atHead: true, sent: new Set(), generation: 0, @@ -813,6 +862,7 @@ export function createChannelStore( * `noticeHead` is false when its newest notices are already being read. */ function adoptHead(state: WindowState, head: Head, noticeHead = true) { state.events = head.events; + state.aheadFull = undefined; // A head read with its newest notices needs no second read of them. if (head.noticesRead && state.ceiling === undefined) { takeNotices(state, head.notices ?? [], null); @@ -984,6 +1034,185 @@ export function createChannelStore( if (state.noticeRead === current) state.noticeRead = undefined; } } + /** End aux work for rows the window is replacing or dropping. */ + function dropAux(state: WindowState) { + if (state.auxRead) { + state.auxRead.dropped = true; + state.auxRead.controller.abort(); + } + state.auxPages = []; + } + /** Add the aux closure to older pages shown without it, one read at a time. */ + async function fillAux(state: WindowState) { + const reading = state.auxRead; + if ( + reading?.generation === state.generation && + !reading.controller.signal.aborted + ) + return; + if (!transport || !state.auxPages.length || state.auxPaused) return; + // Only the open channel reads aux; another channel's wait for its + // revisit (see `ensure`). + if (current !== state.channelId) return; + if (performance.now() < (state.auxRetryAt ?? 0)) return; + const source = transport; + const { channelId, generation } = state; + const controller = new AbortController(); + const mine: NonNullable = { + controller, + generation, + }; + state.auxRead = mine; + // A read lost to anything but dropAux is read again with the next fill. + const keep = (page: WindowState["auxPages"][number]) => { + if (!mine.dropped) state.auxPages.unshift(page); + }; + controllers.add(controller); + // Pages that failed in this fill: the drain reads each other page once + // before it stops on them. + const failed = new Set(); + let failure: unknown; + try { + while (live(state, generation) && canReadRemote(channelId)) { + const next = state.auxPages.shift(); + if (!next) break; + if (failed.has(next)) { + state.auxPages.unshift(next); + break; + } + // A page whose rows the window has since dropped needs no aux. + const held = rowIds(state); + if (![...next.rows].some((id) => held.has(id))) continue; + const page = next; + const { cursor } = page; + const chunk = Math.min(page.rows.size, page.limit ?? AUX_PAGE); + let events: readonly RelayEvent[]; + try { + // Foreground on purpose: a window reads one aux part and one older + // page at a time, and only the open window starts them. A read the + // reader scrolled into survives a switch, so read-ahead can hold a + // few of the reader's slots, which its cap leaves room for. The + // rows' thread summaries came with them. + events = await retryRead( + (signal) => + source.read( + [windowFilter(channelId, cursor, chunk, true, false)], + { signal }, + ), + controller.signal, + ); + } catch (error) { + // A closure past the response budget reads again in smaller parts. + if ( + readErrorKind(error) === "invalid-response" && + chunk > 1 && + live(state, generation) + ) { + keep({ ...page, limit: Math.ceil(chunk / 2) }); + continue; + } + // A failure with no retry hint goes behind the other pages, so it + // does not hold their aux back. + if ( + isAbort(error) || + (error instanceof ReadError && error.retryAfterMs !== undefined) + ) { + keep(page); + throw error; + } + if (mine.dropped) throw error; + failed.add(page); + state.auxPages.push(page); + failure = error; + continue; + } + if (!live(state, generation) || controller.signal.aborted) + return keep(page); + const read = parseWindow(channelId, cursor, source.relayAuthor, events); + // A row written into the range since the page was read takes a place + // in this limited read: continue until every row of the page is read. + const seen = new Set(read.events.map((event) => event.id)); + const rest = new Set([...page.rows].filter((id) => !seen.has(id))); + if (read.cursor && rest.size && read.cursor.createdAt >= page.floor) + state.auxPages.unshift({ ...page, cursor: read.cursor, rows: rest }); + // Only aux about rows the window still holds: a row it has since + // dropped stays dropped. The closure spans the events held too, so a + // held edit's deletion arrives. + const ids = new Set(state.events.map((event) => event.id)); + const added = retainAbout(read.events, rowIds(state)).filter( + (event) => !ids.has(event.id), + ); + if (!added.length) continue; + const fold = (events: readonly RelayEvent[]) => + Object.freeze( + foldChannelMessages(channelId, source.relayAuthor, events), + ); + let merged: readonly RelayEvent[] = [...state.events, ...added]; + let rows = fold(merged); + let slide = false; + // A read-ahead page's closure keeps the window at the head: past the + // budget it drops the oldest rows instead. + if (page.ahead && state.ceiling === undefined) { + // As the live trim: the viewer's own sends are not counted. + const own = new Set( + (local?.snapshot() ?? []).map((item) => item.event.id), + ); + const trimmed = trimOldest(state, merged, own); + if (trimmed !== merged) { + merged = trimmed; + rows = fold(merged); + slide = true; + } + } + // Past the byte budget the closure slides the window down to the + // rows paged to, as an older page does. One that leaves no row to + // show, or is larger than the whole budget, applies as is. + else if (listByteSize(merged) > maxHistoryBytes) { + const slid = slideOlder( + state, + added, + (events) => listByteSize(events) <= maxHistoryBytes, + ); + const floor = state.floor ?? -Infinity; + const slidRows = slid && fold(slid.events); + if (slid && slidRows?.some((row) => row.createdAt >= floor)) { + merged = slid.events; + rows = slidRows; + state.ceiling = slid.ceiling; + state.atHead = false; + slide = true; + } + } + state.events = merged; + if (slide) dropStrayTraffic(state); + setWindow(state, { rows }); + } + if (failure !== undefined) throw failure; + } catch (error) { + if (error instanceof ReadError && error.retryAfterMs !== undefined) { + state.auxRetryAt = performance.now() + error.retryAfterMs; + clearTimeout(state.auxRetry); + state.auxRetry = setTimeout(() => { + // Timers can fire a fraction of a millisecond before the hint. + delete state.auxRetryAt; + if (windows.get(channelId) === state) void fillAux(state); + }, error.retryAfterMs); + } + if (!isAbort(error)) + relayDebug("aux failed", channelId.slice(0, 8), readErrorKind(error)); + } finally { + controllers.delete(controller); + if (state.auxRead === mine) state.auxRead = undefined; + // A generation change the window survives (an access purge) ends this + // fill but not its work. + if ( + !mine.dropped && + state.generation !== generation && + windows.get(channelId) === state + ) + void fillAux(state); + } + } /** The known profiles of a head's row and notice authors. */ function headProfiles(channelId: string, head: Head) { const notices = @@ -1063,6 +1292,7 @@ export function createChannelStore( state.generation++; state.controller?.abort(); state.noticeRead?.controller.abort(); + dropAux(state); state.events = []; state.notices.clear(); state.noticeCursor = undefined; @@ -1121,10 +1351,12 @@ export function createChannelStore( cursor: WindowCursor | null, settings: ReadOptions, withNotices = false, + limit?: number, + full = true, ) { if (!transport) throw new Error("Relay is unavailable"); const source = transport; - const filters = [windowFilter(channelId, cursor)]; + const filters = [windowFilter(channelId, cursor, limit, full, true)]; if (withNotices && !cursor) filters.push(noticeFilter(channelId, source.relayAuthor, null)); const read = (signal?: AbortSignal) => @@ -1246,7 +1478,12 @@ export function createChannelStore( if (intent === channelId) prepareMedia(channelId); return head; } - async function loadPage(state: WindowState, cursor: WindowCursor | null) { + async function loadPage( + state: WindowState, + cursor: WindowCursor | null, + limit?: number, + ahead = false, + ) { if (!transport || !canReadRemote(state.channelId)) return; const generation = state.generation; const controller = new AbortController(); @@ -1260,12 +1497,50 @@ export function createChannelStore( if (prepared && !cursor) { const head = await requestHead(state.channelId, "foreground"); if (!live(state, generation)) return; + // A reader paged back from the head keeps its older rows when the + // newer head meets them; past a gap the head replaces them. Only rows + // read prove continuity: the stream may have missed rows before one + // it delivered. + const ids = rowIds(state); + if ( + !state.atHead && + besideHead && + (!head.hasMore || + head.events.some( + (event) => ids.has(event.id) && !state.traffic.has(event.id), + )) + ) { + accept(head.events); + // Its newest notices came with it, or need their own read. + if (head.noticesRead) { + takeNotices(state, head.notices ?? [], null); + state.noticeHead = false; + } else void fillNotices(state, true); + state.restored = false; + state.readAt = head.readAt; + setWindow(state, { freshness: head.cached ? "cached" : "verified" }); + return; + } + // The head replaces the window: the paged floor and live rows below + // the head go with the rows they belonged to. + const below = head.cursor; + state.floor = undefined; + if (below) + for (const [id, event] of state.traffic) + if (belowCursor(event, below)) state.traffic.delete(id); adoptHead(state, head); return; } - const reading = readPage(state.channelId, cursor, { - signal: controller.signal, - }); + // An older page's aux closure costs the relay far more than its rows + // (seconds against a tenth of one): rows show first, aux follows. + const reading = readPage( + state.channelId, + cursor, + { signal: controller.signal }, + false, + limit, + !cursor, + ); if (besideHead) void fillNotices(state, true); const { page } = await reading; // A settled catch-up aborts an older read that has already resolved. @@ -1274,14 +1549,38 @@ export function createChannelStore( (cursor ? state.events : []).map((event) => [event.id, event]), ); for (const event of page.events) combined.set(event.id, event); - const retained = [...combined.values()]; - const rows = Object.freeze( - foldChannelMessages(state.channelId, transport.relayAuthor, retained), - ); + let retained = [...combined.values()]; + const fold = (events: readonly RelayEvent[]) => + Object.freeze( + foldChannelMessages(state.channelId, transport.relayAuthor, events), + ); + const over = (events: readonly RelayEvent[], folded = fold(events)) => + folded.length > maxHistoryRows || + listByteSize(events) > maxHistoryBytes; + let rows = fold(retained); + // An older page past the budget slides the window down to it. + let ceiling: number | undefined; + // A read-ahead page past the budget is dropped: the reader at the head + // keeps its rows, and read-ahead stops until the reader pages. if ( - rows.length > maxHistoryRows || - listByteSize(retained) > maxHistoryBytes + cursor && + ahead && + state.ceiling === undefined && + over(retained, rows) ) { + state.aheadFull = true; + setWindow(state, { loadingOlder: false }); + return; + } + if (cursor && over(retained, rows)) { + const slid = slideOlder(state, page.events, (events) => !over(events)); + if (slid) { + retained = slid.events; + rows = fold(retained); + ceiling = slid.ceiling; + } + } + if (over(retained, rows)) { setWindow(state, { loadingOlder: false, historyLimited: true, @@ -1290,6 +1589,11 @@ export function createChannelStore( return; } state.events = retained; + if (!ahead) state.aheadFull = undefined; + if (ceiling !== undefined) { + state.ceiling = ceiling; + dropStrayTraffic(state); + } state.atHead = !cursor; if (!cursor) attached(state); moveCursor(state, page.cursor); @@ -1308,15 +1612,43 @@ export function createChannelStore( freshness: "verified", }); void fillNotices(state, !cursor && !besideHead); + if (cursor) { + const pageRows = page.events.filter((event) => + WINDOW_KINDS.includes(event.kind), + ); + if (pageRows.length) + state.auxPages.push({ + cursor, + floor: Math.min(...pageRows.map((event) => event.created_at)), + rows: new Set(pageRows.map((event) => event.id)), + ...(ahead ? { ahead } : {}), + }); + void fillAux(state); + } void fetchProfiles(rows); } catch (error) { - if (isAbort(error) || !live(state, generation)) return; + if (!live(state, generation)) return; + if (isAbort(error)) { + // A read cancelled under the window (a stream drop) ends its page. + if (cursor && !controller.signal.aborted) + setWindow(state, { loadingOlder: false }); + return; + } // A denied revalidation must not keep exposing a cached head. const denied = readErrorKind(error) === "denied"; if (denied) { denyChannel(state.channelId, error); return; } + // A large page can pass the reader's response budget where the same + // range in default pages fits. + if ( + cursor && + limit !== undefined && + limit > WINDOW_PAGE_SIZE && + readErrorKind(error) === "invalid-response" + ) + return loadPage(state, cursor, WINDOW_PAGE_SIZE); setWindow( state, cursor || state.snapshot.rows.length @@ -1366,6 +1698,10 @@ export function createChannelStore( function reattach(state: WindowState) { state.controller?.abort(); state.controller = undefined; + // The segment's aux work waits for the head: it ends with the rows the + // head replaces, or continues past a failed read. + state.auxPaused = true; + state.auxRead?.controller.abort(); const above = new Map(); state.above = above; state.generation++; @@ -1373,6 +1709,9 @@ export function createChannelStore( // A failed read leaves the segment; the next head read has these rows. return loadPage(state, null).finally(() => { if (state.above === above) state.above = undefined; + state.auxPaused = undefined; + if (state.ceiling === undefined) dropAux(state); + else if (windows.get(state.channelId) === state) void fillAux(state); }); } /** Replace the window with a seek page; a null ceiling is the head page. */ @@ -1382,6 +1721,7 @@ export function createChannelStore( ceiling: number | null, ) { state.controller?.abort(); + dropAux(state); state.controller = undefined; state.generation++; state.events = page.events; @@ -1404,34 +1744,84 @@ export function createChannelStore( }); void fetchProfiles(state.snapshot.rows); } - /** Keep a detached window within the history budget by dropping its oldest - * rows: the next older page continues from the oldest row kept. */ - function trimOldest(state: WindowState, events: readonly RelayEvent[]) { + /** An older page past the history budget: keep its rows and the oldest + * held rows that `fit` with them, and detach below the newest rows dropped. + * No kept row shares the ceiling's second, so a newer read resumes there + * without a gap or a repeat. Undefined when no rows fit. */ + function slideOlder( + state: WindowState, + page: readonly RelayEvent[], + fits: (events: readonly RelayEvent[]) => boolean, + ) { + const held = new Set(state.events.map((event) => event.id)); + const events = [ + ...state.events, + ...page.filter((event) => !held.has(event.id)), + ]; const rows = events .filter((event) => channelRowKind(event.kind)) + .sort(newestFirst) + .reverse(); + const take = (count: number) => + retainAbout(events, new Set(rows.slice(0, count).map((row) => row.id))); + // The most rows that fit: binary search, as more rows never fit better. + let low = 0; + let high = rows.length; + while (low < high) { + const mid = Math.ceil((low + high) / 2); + if (fits(take(mid))) low = mid; + else high = mid - 1; + } + const above = rows[low]; + while (low && rows[low - 1]?.created_at === above?.created_at) low--; + if (!low || !above) return undefined; + return { events: take(low), ceiling: above.created_at }; + } + /** Forget live rows a slide dropped from the window: kept, they would + * outlive both budgets and show again once it returns to the head. */ + function dropStrayTraffic(state: WindowState) { + const ids = new Set(state.events.map((event) => event.id)); + for (const id of state.traffic.keys()) + if (!ids.has(id)) state.traffic.delete(id); + } + /** Keep a window within the history budget by dropping its oldest rows, + * besides the uncounted `own` ones: the next older page continues from the + * oldest row kept. */ + function trimOldest( + state: WindowState, + events: readonly RelayEvent[], + own: ReadonlySet = new Set(), + ) { + const rows = events + .filter((event) => channelRowKind(event.kind) && !own.has(event.id)) .sort(newestFirst); if ( rows.length <= maxHistoryRows && listByteSize(events) <= maxHistoryBytes ) return events; + const retain = (kept: readonly RelayEvent[]) => + retainAbout(events, new Set([...own, ...kept.map((event) => event.id)])); let kept = rows.slice(0, maxHistoryRows); - const retain = (ids: ReadonlySet) => - events.filter( - (event) => - ids.has(event.id) || - (!channelRowKind(event.kind) && - event.tags.some((tag) => tag[0] === "e" && ids.has(tag[1] ?? ""))), - ); - let retained = retain(new Set(kept.map((event) => event.id))); + let retained = retain(kept); while (kept.length > 1 && listByteSize(retained) > maxHistoryBytes) { kept = kept.slice(0, -Math.max(1, Math.ceil(kept.length / 4))); - retained = retain(new Set(kept.map((event) => event.id))); + retained = retain(kept); } + // Only dropping rows paging read moves the next older read; a kept live + // row below the cursor (a late send) must not skip the rows under it. + // Paged rows sit at or above the cursor in the relay's order. + const { cursor } = state; + const paged = (event: RelayEvent) => !cursor || !belowCursor(event, cursor); + const keptIds = new Set(kept.map((event) => event.id)); const oldest = kept.at(-1); - state.floor = undefined; - if (oldest) + if ( + oldest && + rows.some((event) => paged(event) && !keptIds.has(event.id)) + ) { + state.floor = undefined; moveCursor(state, { createdAt: oldest.created_at, eventId: oldest.id }); + } return retained; } async function hydrate() { @@ -3933,6 +4323,10 @@ export function createChannelStore( if (disposed || !transport || !authorized(channelId)) return; intent = channelId; current = channelId; + // Another channel's aux reads wait for its revisit; the opened channel + // reads first. + for (const other of windows.values()) + if (other.channelId !== channelId) other.auxRead?.controller.abort(); const state = touch(channelId); const retained = prepared ? heads.peek(channelId) : undefined; if (retained && ["idle", "error"].includes(state.snapshot.status)) @@ -3960,14 +4354,16 @@ export function createChannelStore( state.snapshot.status !== "idle" && state.snapshot.status !== "error" ) { + // Aux work a failed read left over resumes on revisit. + void fillAux(state); if (prepared) { prepareMedia(channelId); const previous = heads.peek(channelId); - // Revalidate a retained head on revisit after its freshness lease. Do not - // replace a paged history reader with a new head merely because time passed. + // Revalidate a retained head on revisit after its freshness lease. A + // detached segment is old history, not what the head refreshes. if ( previous && - state.atHead && + state.ceiling === undefined && !state.controller && (previous.cached || now() - previous.savedAt >= FRESH_FOR) ) @@ -4044,7 +4440,7 @@ export function createChannelStore( setWindow(state, { status: "loading", error: undefined }); void loadPage(state, null); }, - loadOlder(channelId: string) { + loadOlder(channelId: string, rows = WINDOW_PAGE_SIZE, ahead = false) { if (disposed || !transport) return; if (!canReadRemote(channelId)) { revalidateCached(channelId); @@ -4057,11 +4453,19 @@ export function createChannelStore( state.snapshot.loadingOlder || state.snapshot.historyLimited || !state.cursor || - state.controller + state.controller || + (ahead && state.aheadFull) ) return; setWindow(state, { loadingOlder: true, error: undefined }); - void loadPage(state, state.cursor); + void loadPage(state, state.cursor, rows, ahead); + }, + cancelOlder(channelId: string) { + const state = windows.get(channelId); + if (!state?.snapshot.loadingOlder) return; + state.controller?.abort(); + state.controller = undefined; + setWindow(state, { loadingOlder: false }); }, async seek(channelId: string, from: number, signal: AbortSignal) { const state = windows.get(channelId); @@ -4162,6 +4566,14 @@ export function createChannelStore( state.controller = undefined; state.above = undefined; } + // A read cancelled under the window (a stream drop) ends its page. + if ( + !state.controller && + state.snapshot.loadingNewer && + !disposed && + windows.get(channelId) === state + ) + setWindow(state, { loadingNewer: undefined }); } })(); }, @@ -4359,43 +4771,28 @@ export function createChannelStore( const localIds = new Set( (local?.snapshot() ?? []).map((item) => item.event.id), ); - let retained = [...state.events, ...incoming]; - let limited = false; - if ( - listByteSize(retained) > maxHistoryBytes || - retained.filter( - (event) => channelRowKind(event.kind) && !localIds.has(event.id), - ).length > maxHistoryRows - ) { - limited = true; - const newest = retained - .filter( - (event) => channelRowKind(event.kind) && !localIds.has(event.id), - ) - .sort( - (a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id), - ) - .slice(0, maxHistoryRows); - const keep = new Set([...newest.map((event) => event.id), ...localIds]); - retained = retained.filter( - (event) => - keep.has(event.id) || - (!channelRowKind(event.kind) && - event.tags.some( - (tag) => tag[0] === "e" && keep.has(tag[1] ?? ""), - )), - ); - while (retained.length && listByteSize(retained) > maxHistoryBytes) - retained.splice(0, Math.max(1, Math.ceil(retained.length / 4))); - const retainedIds = new Set(retained.map((event) => event.id)); + const merged = [...state.events, ...incoming]; + // A full window drops its oldest rows; older pages read them again. An + // older page in flight lands below the rows held and slides the window + // within its budget then: trimming under it would cancel it each time. + const retained = state.snapshot.loadingOlder + ? merged + : trimOldest(state, merged, localIds); + const trimmed = retained.length < merged.length; + const retainedIds = new Set(retained.map((event) => event.id)); + if (trimmed) { for (const id of state.traffic.keys()) if (!retainedIds.has(id)) state.traffic.delete(id); } - const retainedIds = new Set(retained.map((event) => event.id)); for (const event of incoming) if (retainedIds.has(event.id)) state.traffic.set(event.id, event); state.events = retained; - setWindow(state, limited ? { historyLimited: true } : {}); + setWindow( + state, + trimmed + ? { hasMore: true, historyLimited: false, loadingOlder: false } + : {}, + ); if (disposed || generation !== epoch) return; void fetchProfiles(state.snapshot.rows.slice(-12)); } @@ -4531,6 +4928,7 @@ export function createChannelStore( for (const state of windows.values()) { state.generation++; state.controller?.abort(); + clearTimeout(state.auxRetry); } windows.clear(); heads.clear(); @@ -4799,6 +5197,7 @@ export function createChannelStore( retained.kept = keptAfter(); // The descent below the newest notices waits for the floor set here. void fillNotices(retained, false); + void fillAux(retained); // A drop mid-fill has marked the window cached; the stream is retrying. setWindow(retained, { ...(retained.atHead ? { hasMore: page.hasMore } : {}), @@ -4867,7 +5266,9 @@ export function createChannelStore( setWindow(state, { freshness: "verified", error: undefined }); // The replay holds only the outage's notices: finish a notice read that // failed or was cut before the drop. It reads nothing when none is owed. + // So for an aux read. void fillNotices(state, false); + void fillAux(state); return true; }, /** A grant for the channel reached the session. The relay may have left diff --git a/src/features/relay/traffic.integration.test.ts b/src/features/relay/traffic.integration.test.ts index 5a4a6f6c32..b2321476ad 100644 --- a/src/features/relay/traffic.integration.test.ts +++ b/src/features/relay/traffic.integration.test.ts @@ -710,7 +710,10 @@ it("continues incoming traffic at the history budget and applies live membership expect(h.session.channels.window("c").rows.map((row) => row.content)).toEqual( ["two", "three"], ); - expect(h.session.channels.window("c").historyLimited).toBe(true); + expect(h.session.channels.window("c")).toMatchObject({ + historyLimited: false, + hasMore: true, + }); h.emit([roster(relay, "c", [], 1800000000)]); expect(h.session.channels.window("c").rows).toHaveLength(0); h.emit([message(other, "c", "late revoked traffic", 4)]); diff --git a/src/features/relay/unread.test.ts b/src/features/relay/unread.test.ts index d6ff825cc3..41a62db70d 100644 --- a/src/features/relay/unread.test.ts +++ b/src/features/relay/unread.test.ts @@ -310,8 +310,11 @@ it("unread repair observes history without seeding the channel window or consumi expect(h.session.channels.window("room").rows.map(({ id }) => id)).toEqual( rows.slice(20).map(({ id }) => id), ); + // The page's aux closure follows its rows by the same cursor. const cursorReads = h.query.mock.calls.flatMap(([filters]) => - filters.filter((filter) => filter.until !== undefined), + filters.filter( + (filter) => filter.until !== undefined && !filter.include_aux, + ), ); expect(cursorReads).toHaveLength(1); expect(cursorReads[0]).toMatchObject({ diff --git a/src/features/relay/window.test.ts b/src/features/relay/window.test.ts index 20afcd200f..b605b9be39 100644 --- a/src/features/relay/window.test.ts +++ b/src/features/relay/window.test.ts @@ -28,6 +28,9 @@ describe("channel window bounds", () => { expect(bare).toMatchObject({ top_level: true, limit: 200 }); expect(bare).not.toHaveProperty("include_aux"); expect(bare).not.toHaveProperty("include_summaries"); + const rows = windowFilter(channel, null, 50, false, true); + expect(rows).toMatchObject({ include_summaries: true, limit: 50 }); + expect(rows).not.toHaveProperty("include_aux"); }); it("reads the relay's membership notices apart, by the same composite cursor", () => { expect(noticeFilter(channel, relay.pubkey, null)).toEqual({ diff --git a/src/features/relay/window.ts b/src/features/relay/window.ts index bfb819fdaf..41f9ece953 100644 --- a/src/features/relay/window.ts +++ b/src/features/relay/window.ts @@ -18,19 +18,22 @@ export const WINDOW_KINDS: readonly number[] = CHANNEL_ROW_KINDS.filter( export const NOTICE_PAGE_SIZE = 500; /** NIP-CW window request: top-level rows plus aux closure and thread summaries, paged by the relay's composite cursor. - * A bare (`full: false`) request reads rows only, for a seek's probes. */ + * A bare (`full: false`) request reads rows only, for a seek's probes, or rows + * and their summaries with `summaries`. */ export function windowFilter( channelId: string, cursor: WindowCursor | null, limit = WINDOW_PAGE_SIZE, full = true, + summaries = full, ): ReadFilter { return { kinds: [...WINDOW_KINDS], "#h": [channelId], limit: Math.max(1, Math.min(200, limit)), top_level: true, - ...(full ? { include_aux: true, include_summaries: true } : {}), + ...(full ? { include_aux: true } : {}), + ...(summaries ? { include_summaries: true } : {}), ...(cursor ? { until: cursor.createdAt, before_id: cursor.eventId } : {}), }; } diff --git a/tests/browser/fixture.mjs b/tests/browser/fixture.mjs index 9491dc359e..3959beb176 100644 --- a/tests/browser/fixture.mjs +++ b/tests/browser/fixture.mjs @@ -107,6 +107,8 @@ export const test = base.extend({ // Opt-in perf workload: chat-like Markdown (code, links, lists, mentions) // in most corpus rows instead of inert prose. markdownMessages: [false, { option: true }], + // Opt-in perf workload: chat-like one-line rows, every fifth one two lines. + shortMessages: [false, { option: true }], // Opt-in perf workload: newer activity in another joined channel fills the // startup unread read, so corpus history reaches the app first-seen. firstSeenHistory: [false, { option: true }], @@ -199,6 +201,7 @@ export const test = base.extend({ inboxSoloAgent, tallMessages, markdownMessages, + shortMessages, firstSeenHistory, olderPageDelayMs, membershipActivity, @@ -561,7 +564,7 @@ export const test = base.extend({ ] : []), ], - `${community} ${channel} message ${i}\n${"Mixed height message content. ".repeat((1 + (i % 7) * 3) * (tallMessages ? 5 : 1))}${syntax ? `\n${syntax}` : ""}`, + `${community} ${channel} message ${i}\n${"Mixed height message content. ".repeat(shortMessages ? Number(i % 5 === 0) : (1 + (i % 7) * 3) * (tallMessages ? 5 : 1))}${syntax ? `\n${syntax}` : ""}`, readState ? peerKey : userKey, 1700000100 + Math.floor(i / historyRowsPerSecond), ); @@ -1016,6 +1019,7 @@ export const test = base.extend({ agentPeers, tallMessages, markdownMessages, + shortMessages, firstSeenHistory, olderPageDelayMs, browserVersion: browser.version(), @@ -1958,10 +1962,12 @@ export const test = base.extend({ filter.until === undefined ? "head" : `${filter.until}:${filter.before_id}`; - return filter.include_aux + // As the relay: a window read is always bounded; aux and summaries + // come only when asked for. + return filter.top_level ? [ ...events, - ...(actionProfile + ...(actionProfile && filter.include_aux ? targetEvents.filter((aux) => aux.tags.some( ([k, id]) => @@ -1969,13 +1975,15 @@ export const test = base.extend({ ), ) : []), - ...threadSummaries.filter((summary) => - events.some((event) => - summary.tags.some( - ([key, value]) => key === "e" && value === event.id, - ), - ), - ), + ...(filter.include_summaries + ? threadSummaries.filter((summary) => + events.some((event) => + summary.tags.some( + ([key, value]) => key === "e" && value === event.id, + ), + ), + ) + : []), sign( 39006, [ @@ -2564,10 +2572,12 @@ export const test = base.extend({ ).values(), ]; for (const { id } of result) served.add(id); + // An older page's aux closure, read apart from its rows, is not held. if ( filter.search === undefined && filter.until !== undefined && - filter["#h"]?.length + filter["#h"]?.length && + !(filter.include_aux && !filter.include_summaries) ) { const queuedAt = performance.now(); const receipt = { @@ -2582,6 +2592,12 @@ export const test = base.extend({ }, }; pending.push(receipt); + // A read the app cancels is no longer pending. + response.on("close", () => { + if (response.writableEnded) return; + const index = pending.indexOf(receipt); + if (index >= 0) pending.splice(index, 1); + }); if (olderPageDelayMs !== null) { const timer = setTimeout(() => { olderPageTimers.delete(timer); diff --git a/tests/browser/history-loading.spec.mjs b/tests/browser/history-loading.spec.mjs index 4cb6dd77da..bf93570ebe 100644 --- a/tests/browser/history-loading.spec.mjs +++ b/tests/browser/history-loading.spec.mjs @@ -1,8 +1,11 @@ import { openPage } from "./navigation.mjs"; -import { test, expect } from "./fixture.mjs"; +import { test, expect, historySize } from "./fixture.mjs"; import { anchor, + edge, + toOlder, expectAnchor, + frames, open, settle, upper, @@ -30,16 +33,18 @@ tall( }), ).toHaveCount(0); await history(page).hover(); + // Distance from the bottom: rows above that measure taller raise + // scrollTop by their growth while the reader's row stays put. + const fromBottom = () => + history(page).evaluate((e) => e.scrollHeight - e.scrollTop); for (let i = 0; i < 100 && !app.pending.length; i++) { - const before = await history(page).evaluate((e) => e.scrollTop); + const before = await fromBottom(); await page.mouse.wheel(0, -450); // Each wheel step must land (scroll moves or the older page is // requested) before the next one. await expect .poll( - async () => - app.pending.length > 0 || - (await history(page).evaluate((e) => e.scrollTop)) < before, + async () => app.pending.length > 0 || (await fromBottom()) > before, ) .toBe(true); if ( @@ -58,7 +63,7 @@ tall( }, ); -test("returning to the top continues history loading on wheel without a button", async ({ +test("landed pages keep reading ahead of a reader who stops at the top", async ({ page, app, }) => { @@ -69,9 +74,141 @@ test("returning to the top continues history loading on wheel without a button", exact: true, }), ).toHaveCount(0); + await toOlder(page, app); + // No more input: each landed page asks for the next while the reader is + // still within reach of the top, then reading stops. + const reads = []; + for (;;) { + reads.push(app.pending.shift()); + reads.at(-1).release(); + await settle(page); + if (!(await history(page).getByText("Loading older…").count())) break; + await expect.poll(() => app.pending.length).toBe(1); + } + // One full page can already put the reader past reach; either way reading + // stops only with the prefetch distance above them. + expect(reads.length).toBeGreaterThanOrEqual(1); + expect(app.pending).toHaveLength(0); + const { top, viewport } = await history(page).evaluate((e) => ({ + top: e.scrollTop, + viewport: e.clientHeight, + })); + expect(top).toBeGreaterThanOrEqual(Math.max(3000, viewport * 4)); + expect( + new Set(reads.flatMap(({ events }) => events.map(({ id }) => id))).size, + "history is read ahead, not downloaded whole", + ).toBeLessThan(620); +}); + +test("a fast upward scroll reads larger pages than a slow one", async ({ + page, + app, +}) => { + await open(page, app); await history(page).hover(); - await page.mouse.wheel(0, -100000); - await expect.poll(() => app.pending.length).toBe(1); + // Scrolls that land close together, which are what the app reads a pace from. + const close = await history(page).evaluateHandle((element) => { + const scrolls = { last: 0, close: 0 }; + element.addEventListener("scroll", () => { + const at = performance.now(); + if (at - scrolls.last < 125) scrolls.close++; + scrolls.last = at; + }); + return scrolls; + }); + // Keep wheeling up while every read lands at once, until history is exhausted. + const limits = []; + let loaded = 20; + for (let step = 0; step < 200 && loaded < historySize; step++) { + // Back-to-back notches: scrolls far apart measure no pace. + for (let notch = 0; notch < 3; notch++) await page.mouse.wheel(0, -500); + const pending = app.pending.shift(); + if (pending) { + limits.push(pending.filter.limit); + loaded += pending.events.length; + pending.release(); + } + } + // A runner too slow to land notches inside the app's 250 ms sample gap + // gives it no pace to read, so base-size pages are correct there. + test.skip( + (await close.evaluate((scrolls) => scrolls.close)) < 5, + "this runner spaced every wheel notch past the pace sample gap", + ); + expect(Math.max(...limits)).toBeGreaterThan(20); + expect(limits.length, "fewer reads than base-size pages").toBeLessThan(31); +}); + +test.describe("past the history budget", () => { + // More rows than one window keeps (2,400). + test.use({ historyCounts: { alpha: 2700, beta: 20 } }); + test("paging older slides the window to the channel start, and Jump to latest returns", async ({ + page, + app, + }) => { + test.setTimeout(240_000); + await open(page, app); + const latestId = await history(page) + .locator("[data-message-id]") + .last() + .getAttribute("data-message-id"); + const [first] = app.histories.get("primary/alpha"); + const seen = new Set(); + while (!seen.has(first.id)) { + // A landed page reads ahead while the reader is within the app's reach + // of the top; past it, reaching the top reads the next page. + await toOlder(page, app, { top: false }); + const before = await anchor(page); + const pending = app.pending.shift(); + for (const { id } of pending.events) seen.add(id); + pending.release(); + // The page landed: its aux closure is read next. Its rows can be + // mounted far above a reader who did not reach the top. + await expect + .poll(() => + app.report.queries.some( + ({ filter }) => + filter.include_aux && + !filter.include_summaries && + filter.until === pending.filter.until, + ), + ) + .toBe(true); + await settle(page); + // Dropping the newest rows below the reader does not move them. + await expectAnchor(page, before); + await expect( + history(page).getByText("History window limit reached"), + ).toHaveCount(0); + } + expect(seen.size, "paged past the window budget").toBeGreaterThan(2400); + await edge(page, -1); + await expect( + history(page).locator(`[data-message-id="${first.id}"]`), + ).toBeAttached(); + // The newest rows went to make room; the reader returns to them. + await expect( + history(page).locator(`[data-message-id="${latestId}"]`), + ).toHaveCount(0); + await page.getByRole("button", { name: "Jump to latest" }).click(); + await expect( + history(page).locator(`[data-message-id="${latestId}"]`), + ).toBeInViewport(); + }); +}); + +test("returning to the top continues history loading on wheel without a button", async ({ + page, + app, +}) => { + await open(page, app); + await expect( + page.getByRole("dialog", { + name: "Buzz is having trouble connecting", + exact: true, + }), + ).toHaveCount(0); + await toOlder(page, app); await settle(page); // Navigate away while a real cursor request is in flight, then return to the // saved top before releasing it; this must remain an ordinary scroll journey. @@ -85,17 +222,36 @@ test("returning to the top continues history loading on wheel without a button", ).toBeVisible(); app.pending.shift().release(); await settle(page); - await history(page).hover(); - await page.mouse.wheel(0, -100000); - await expect.poll(() => app.pending.length).toBe(1); + await toOlder(page, app); + app.pending.shift().release(); +}); + +test("a read-ahead the reader scrolls up to survives leaving the channel", async ({ + page, + app, +}) => { + await open(page, app, { hold: true }); + const [ahead] = app.pending; + await toOlder(page, app); + await page.getByRole("button", { name: "Beta", exact: true }).click(); + await expect( + page.getByRole("textbox", { name: "Message #Beta", exact: true }), + ).toBeVisible(); + await page.getByRole("button", { name: "Alpha", exact: true }).click(); + await expect( + page.getByRole("textbox", { name: "Message #Alpha", exact: true }), + ).toBeVisible(); + expect(app.pending, "the reader's read is still in flight").toEqual([ahead]); app.pending.shift().release(); + await settle(page); }); test("saved top resumes automatic history on an upward gesture after remount", async ({ page, app, }) => { - await open(page, app); + // The saved top stays in the head the reload reads. + await open(page, app, { hold: true }); await expect( page.getByRole("dialog", { name: "Buzz is having trouble connecting", @@ -121,7 +277,8 @@ test("saved top resumes automatic history on an upward gesture after remount", a // Remounting Channels captures the normal reading anchor in localStorage. // Reload gives a new session/finite head but preserves that user-owned anchor. await page.reload(); - app.pending.shift().release(); + // The reload cancelled the older read in flight. + await expect.poll(() => app.pending.length).toBe(0); await openPage(page, "Messages"); await expect(history(page)).toBeVisible(); await expect( @@ -152,10 +309,12 @@ test.describe("quota retry without threshold-driven continuation", () => { exact: true, }), ).toHaveCount(0); + // An older page's aux closure, read apart from its rows, is not a page. const olderAlpha = (filter) => filter.until !== undefined && filter["#h"]?.includes("alpha") && - filter.kinds?.some((kind) => kind === 9 || kind === 40002); + filter.kinds?.some((kind) => kind === 9 || kind === 40002) && + !(filter.include_aux && !filter.include_summaries); // Observe before broker admission: a bad retry may be rejected locally. // Unrelated background reads (including unread repair) must not count. const browserCursors = []; @@ -172,18 +331,19 @@ test.describe("quota retry without threshold-driven continuation", () => { app.relay.quotaNextOlder("alpha"); const cursors = () => app.report.queries.filter(({ filter }) => olderAlpha(filter)); - await history(page).hover(); - await page.mouse.wheel(0, -100000); + // Opening already read ahead. + const opened = cursors().length; + await edge(page, -1); await expect(history(page).getByRole("alert")).toContainText( "rate-limited", ); const count = cursors().length; - expect(count).toBe(1); + expect(count).toBe(opened + 1); expect(browserCursors).toHaveLength(1); for (let i = 0; i < 3; i++) await page.mouse.wheel(0, -500); await settle(page); expect(cursors()).toHaveLength(count); - expect(browserCursors).toHaveLength(count); + expect(browserCursors).toHaveLength(count - opened); // Only the broker lane holds older-page retries; it reopens at this bound. await expect.poll(() => app.relay.brokerCooldownOver()).toBe(true); await history(page) @@ -191,18 +351,48 @@ test.describe("quota retry without threshold-driven continuation", () => { .click(); await expect.poll(() => app.pending.length).toBe(1); expect(cursors()).toHaveLength(count + 1); - expect(browserCursors).toHaveLength(count + 1); - app.pending.shift().release(); + expect(browserCursors).toHaveLength(count - opened + 1); + const retry = app.pending.shift(); + retry.release(); await expect(history(page).getByRole("alert")).toHaveCount(0); + // The landed page reads ahead while the reader is within the app's reach + // of the top, as any landed page does: each read older than the last. The + // retry enqueues nothing more. + const older = (read, than) => + read.filter.until < than.filter.until || + (read.filter.until === than.filter.until && + read.filter.before_id < than.filter.before_id); + let last = retry; + let ahead = 0; + for (;;) { + await settle(page); + await expect + .poll(() => app.pending.length, { timeout: 1000 }) + .toBeGreaterThan(0) + .catch(() => {}); + const read = app.pending.shift(); + if (!read) break; + expect(older(read, last), "read ahead is older than the last read").toBe( + true, + ); + last = read; + read.release(); + ahead++; + } + // At most the visit's five fill pages, stopping with the prefetch + // distance above the reader. + expect(ahead).toBeLessThanOrEqual(5); + expect( + await history(page).evaluate((e) => e.scrollTop), + ).toBeGreaterThanOrEqual(3000); await expect( history(page).getByRole("button", { name: "Load older messages", exact: true, }), - ).toBeEnabled(); // Still more history: retry success must not enqueue it. - await settle(page); - expect(cursors()).toHaveLength(count + 1); - expect(browserCursors).toHaveLength(count + 1); + ).toBeEnabled(); // Still more history. + expect(cursors()).toHaveLength(count + 1 + ahead); + expect(browserCursors).toHaveLength(count - opened + 1 + ahead); expect(app.pending).toHaveLength(0); }); }); @@ -211,19 +401,15 @@ test.describe("pages inside one second", () => { // More rows share a second than a page holds. Relay pages break ties by id, // rows by send time, so the next page lands among the loaded rows of that second. test.use({ historyRowsPerSecond: 30 }); - // Hold the next older page while reading `depth` px above the newest rows. + // Hold the read ahead on open while reading `depth` px above the newest rows. async function reading(page, app, depth) { - await open(page, app); + await open(page, app, { hold: true }); await history(page).hover(); - await wheel(page, -250); - await expect.poll(() => app.pending.length).toBe(1); - if (depth > 250) await wheel(page, 250 - depth); + await wheel(page, -depth); + expect(app.pending).toHaveLength(1); const pending = app.pending.shift(); - expect( - pending.events.every( - (event) => event.created_at === pending.filter.until, - ), - ).toBe(true); + // The page starts among the loaded rows of that second. + expect(pending.events[0].created_at).toBe(pending.filter.until); return pending; } const latest = (page) => @@ -290,6 +476,64 @@ test.describe("pages inside one second", () => { "a wheel ended before the first render that holds its row ends the hold", endedBeforeHold("wheel"), ); + // Rows measure after the hold's own frames; a press released then waits + // for them rather than releasing the hold. + test("a press released while rows measure keeps the reader's row", async ({ + page, + app, + }) => { + await page.addInitScript(() => { + const Native = window.ResizeObserver; + const held = []; + window.ResizeObserver = class extends Native { + constructor(callback) { + super((entries, observer) => { + const rows = window.holdRowSizes + ? entries.filter(({ target }) => target.tagName === "LI") + : []; + const rest = entries.filter((entry) => !rows.includes(entry)); + if (rows.length) held.push(() => callback(rows, observer)); + if (rest.length) callback(rest, observer); + }); + } + }; + window.releaseRowSizes = () => { + window.holdRowSizes = false; + const delivered = held.length; + for (const deliver of held.splice(0)) deliver(); + return delivered; + }; + }); + const pending = await reading(page, app, 3000); + const before = await anchor(page); + const box = await history(page).boundingBox(); + await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2); + await page.mouse.down(); + const height = await history(page).evaluate((e) => e.scrollHeight); + await page.evaluate(() => (window.holdRowSizes = true)); + let delivered = 0; + try { + pending.release(); + await expect + .poll(() => history(page).evaluate((e) => e.scrollHeight)) + .toBeGreaterThan(height); + // Past the hold's own frames, with the page's row sizes still held. + await frames(page, 4); + await page.mouse.up(); + // Virtua corrects every row in view until its shift ends, when it + // restores the list's pointer events; past that, the rows below the + // edge are the hold's alone. + await expect(history(page).locator("ol")).toHaveCSS( + "pointer-events", + "auto", + ); + } finally { + delivered = await page.evaluate(() => window.releaseRowSizes()); + } + expect(delivered, "row sizes held through the press").toBeGreaterThan(0); + await settle(page); + await expectAnchor(page, before); + }); }); test("input after the page lands starts from the reader's row", async ({ @@ -558,13 +802,9 @@ test.describe("pages inside one second", () => { }), ), ); - await open(page, app); + await open(page, app, { hold: true }); await history(page).hover(); - for (let step = 0; step < 20 && !app.pending.length; step++) - await wheel(page, -500); - await expect.poll(() => app.pending.length).toBe(1); - if (await history(page).evaluate((e) => e.scrollTop)) - await wheel(page, -100000); + await wheel(page, -100000); await wheel(page, 600); await grows(page, app.pending.shift(), 600); }); @@ -647,14 +887,16 @@ test.describe("pages inside one second", () => { const start = e.scrollTop; let corrected = 0; e.dataset.scrollEnded = ""; - e.addEventListener("virtua-scroll-correction", ({ detail }) => { - corrected += detail.after - detail.before; - }); const ended = () => { if (start + corrected - e.scrollTop < 150) return; delete e.dataset.scrollEnded; e.removeEventListener("scrollend", ended); }; + // A correction can be dispatched after the input's scrollend. + e.addEventListener("virtua-scroll-correction", ({ detail }) => { + corrected += detail.after - detail.before; + ended(); + }); e.addEventListener("scrollend", ended); }); if (input === "drag") @@ -796,14 +1038,14 @@ test.describe("pages inside one second", () => { page, app, }) => { - await open(page, app); + // The read ahead on open fails, so the alert does not prove the reader + // left the bottom. upper() does. app.relay.quotaNextOlder("alpha"); - // The failed load starts within the first pixels of upward scroll, so the - // alert does not prove the reader left the bottom. upper() does. - await upper(page); + await open(page, app); await expect(history(page).getByRole("alert")).toContainText( "rate-limited", ); + await upper(page); await settle(page); const { filter } = app.report.queries.find( ({ filter }) => diff --git a/tests/browser/inbox-tabs.spec.mjs b/tests/browser/inbox-tabs.spec.mjs index bf45bb7020..11c11aca62 100644 --- a/tests/browser/inbox-tabs.spec.mjs +++ b/tests/browser/inbox-tabs.spec.mjs @@ -148,7 +148,8 @@ test.describe("with the thread's root beyond the channel's newest page", () => { app, }) => { await page.setViewportSize({ width: 1280, height: 900 }); - await open(page, app); + // Straight to Activity: #Alpha has read nothing beyond its head. + await page.goto(app.origin); await openPage(page, "Activity"); const inbox = page.getByRole("region", { name: "Activity", exact: true }); await expect(inbox.getByText("Checking recent activity…")).toHaveCount(0); @@ -211,7 +212,15 @@ test.describe("with the thread's root beyond the channel's newest page", () => { await expect(tab).toBeFocused(); // Beside it, the channel waits to show its list at the thread's root, // reading the older page the fixture holds. - await expect.poll(() => app.pending.length).toBe(1); + // Reopening the channel at the root cancels its read-ahead. + await expect + .poll(() => app.pending.filter((read) => !read.closed).length) + .toBe(1); + app.pending.splice( + 0, + app.pending.length, + ...app.pending.filter((read) => !read.closed), + ); expect(app.pending[0].channel).toBe("alpha"); await expect(channel.getByRole("status")).toHaveText("Loading messages…"); await expect(tab).toBeFocused(); diff --git a/tests/browser/initial-position.spec.mjs b/tests/browser/initial-position.spec.mjs index 321e168815..f383c7ab6b 100644 --- a/tests/browser/initial-position.spec.mjs +++ b/tests/browser/initial-position.spec.mjs @@ -7,6 +7,7 @@ import { settle, anchor, expectAnchor, + readAhead, } from "./timeline.mjs"; test.use({ @@ -258,12 +259,14 @@ activityHead( ); app.append("primary", "alpha", "Latest public message", false); const latest = history(page).getByText("Latest public message"); - const filled = async (visit) => { + const filled = async (visit, ahead = true) => { await expect .poll(() => history(page).evaluate((e) => e.scrollHeight - e.clientHeight), ) .toBeGreaterThan(0); + // The settled reader reads on to the prefetch distance. + if (ahead) await readAhead(page, app); await bottom(page, app, `${visit} filled activity head`); await expect(latest).toBeInViewport(); expect( @@ -272,7 +275,7 @@ activityHead( ).toHaveLength(0); }; for (const visit of ["cold", "reloaded"]) { - if (visit === "cold") await open(page, app); + if (visit === "cold") await open(page, app, { hold: true }); else { await page.reload(); await openPage(page, "Messages"); @@ -294,7 +297,7 @@ activityHead( // A return in the same session keeps the filled rows: no page is reread. await select(page, "Beta"); await select(page, "Alpha"); - await filled(`${visit} returned`); + await filled(`${visit} returned`, false); } }, ); diff --git a/tests/browser/layout.spec.mjs b/tests/browser/layout.spec.mjs index b2bf91b065..5f6dba60c9 100644 --- a/tests/browser/layout.spec.mjs +++ b/tests/browser/layout.spec.mjs @@ -25,6 +25,7 @@ import { upper, expectAnchor, keyScroll, + readAhead, } from "./timeline.mjs"; // These layout/navigation journeys exercise opt-in page surfaces. @@ -40,7 +41,9 @@ const readingTest = test.extend({ // Keep the old restored row visible when wheel input selects another row. historyCounts: { alpha: 24, beta: 1 }, }); -async function expectNonPaging(page, app) { +/** `ahead`: the reads released to read ahead on opening, which are not paging, + * nor is the aux closure read for a page's rows. */ +async function expectNonPaging(page, app, ahead = []) { expect( await page .getByRole("region", { name: "Channel message history" }) @@ -48,7 +51,12 @@ async function expectNonPaging(page, app) { "resize reading position stays outside older-page prefetch", ).toBeGreaterThan(0); expect( - app.report.queries.filter(({ filter }) => filter.until !== undefined), + app.report.queries.filter( + ({ filter }) => + filter.until !== undefined && + !(filter.include_aux && !filter.include_summaries) && + !ahead.some((read) => read.filter === filter), + ), ).toHaveLength(0); } @@ -668,6 +676,7 @@ readingTest( async ({ page, app }) => { await open(page, app); await settle(page); + const ahead = await readAhead(page, app); await link(page, app, "https://github.com/block/buzz/pull/4"); const history = page.getByRole("region", { name: "Channel message history", @@ -720,7 +729,7 @@ readingTest( await history.hover(); await wheel(page, -200); const saved = await anchor(page); - await expectNonPaging(page, app); + await expectNonPaging(page, app, ahead); await opener(page, target).evaluate((el) => el.focus({ preventScroll: true }), ); @@ -775,7 +784,7 @@ readingTest( await page.setViewportSize({ width: 1200, height: 700 }); await settle(page); await expectAnchor(page, saved); - await expectNonPaging(page, app); + await expectNonPaging(page, app, ahead); }, ); @@ -1197,14 +1206,17 @@ companionReadingTest( async ({ page, app }) => { await open(page, app); await settle(page); + await readAhead(page, app); const saved = await upper(page); - await expectNonPaging(page, app); + // The reader's own wheel can read ahead at its pace; the panel must not. + const read = [...app.report.queries]; await companionLauncher(page, "Companion fixture").click(); await settle(page); await expectAnchor(page, saved); await button(page, "Close Companion fixture panel").click(); await settle(page); await expectAnchor(page, saved); + await expectNonPaging(page, app, read); await link(page, app, "https://github.com/block/buzz/pull/6"); await companionLauncher(page, "Companion fixture").click(); for (const [width, height] of [ @@ -1268,6 +1280,7 @@ companionReadingTest( async ({ page, app }) => { await open(page, app); await settle(page); + await readAhead(page, app); const original = await upper(page); await companionLauncher(page, "Companion fixture").click(); await settle(page); @@ -1311,10 +1324,12 @@ companionReadingTest( await expect( history.locator(`[data-message-id="${original.id}"]`), ).toBeInViewport(); + // The wheel can read ahead at its pace; restoring the panel must not. + const read = [...app.report.queries]; await button(page, "Close Companion fixture panel").click(); await settle(page); await expectAnchor(page, reading); - await expectNonPaging(page, app); + await expectNonPaging(page, app, read); }, ); diff --git a/tests/browser/live.spec.mjs b/tests/browser/live.spec.mjs index 072f047959..06396c2e1f 100644 --- a/tests/browser/live.spec.mjs +++ b/tests/browser/live.spec.mjs @@ -7,7 +7,7 @@ import { upper, expectAnchor, end, - edge, + toOlder, anchor, } from "./timeline.mjs"; @@ -202,15 +202,24 @@ test("production WS → broker → mounted UI delivers messages and retries a pa * reconnect must keep both the paged range and the reading position. */ async function pagedReader(page, app) { await ready(page, app); - await edge(page, -1); - await expect.poll(() => app.pending.length).toBe(1); + // Read ahead fills screens above the reader: take its read where it starts, + // so the held read does not wait out a Linux scroll to the top. + await toOlder(page, app, { top: false }); await settle(page); const before = await anchor(page); const pageOne = app.pending.shift(); pageOne.release(); - await expect( - history(page).locator(`[data-message-id="${pageOne.events[0].id}"]`), - ).toBeAttached(); + // The page landed: its aux closure is read next. + await expect + .poll(() => + app.report.queries.some( + ({ filter }) => + filter.include_aux && + !filter.include_summaries && + filter.until === pageOne.filter.until, + ), + ) + .toBe(true); await settle(page); await expectAnchor(page, before); return { pageOne, reading: await upper(page) }; @@ -218,8 +227,7 @@ async function pagedReader(page, app) { /** The paged cursor survived: the next older page continues below page one. */ async function pageOnward(page, app, pageOne) { - await edge(page, -1); - await expect.poll(() => app.pending.length).toBe(1); + await toOlder(page, app, { top: false }); const pageTwo = app.pending.shift(); expect(pageTwo.filter.until).toBeLessThan(pageOne.filter.until); pageTwo.release(); diff --git a/tests/browser/membership.spec.mjs b/tests/browser/membership.spec.mjs index 3037f1770f..b79d84f951 100644 --- a/tests/browser/membership.spec.mjs +++ b/tests/browser/membership.spec.mjs @@ -1,6 +1,12 @@ import { openPage } from "./navigation.mjs"; import { test, expect } from "./fixture.mjs"; -import { anchor, expectAnchor, keyScroll, settle } from "./timeline.mjs"; +import { + anchor, + expectAnchor, + keyScroll, + readAhead, + settle, +} from "./timeline.mjs"; test.use({ membershipActivity: true, @@ -419,14 +425,17 @@ burstTest( ).toBeVisible(); await expect(groups).toHaveCount(1); await expect(groups).toContainText("and 499 others were added"); - // The second notice read pages below the first by the composite cursor. - await expect.poll(() => app.pending.length).toBe(1); - const notices = app.pending.shift(); + // The second notice read pages below the first by the composite cursor, + // beside the older messages read ahead. + const isNotices = (read) => read.filter.kinds?.includes(40099); + await expect.poll(() => app.pending.some(isNotices)).toBe(true); + const [notices] = app.pending.splice(app.pending.findIndex(isNotices), 1); expect(notices.filter).toMatchObject({ kinds: [40099], "#h": ["alpha"] }); expect(notices.filter.until).toEqual(expect.any(Number)); notices.release(); await expect(groups).toContainText("Pinky and 601 others were added"); await expect(groups).toHaveCount(1); + await readAhead(page, app); await settle(page); expect(app.pending).toHaveLength(0); // A real hover surface must remain reachable and expose every member, diff --git a/tests/browser/message-navigation.spec.mjs b/tests/browser/message-navigation.spec.mjs index 85fb29e77b..c16162ab95 100644 --- a/tests/browser/message-navigation.spec.mjs +++ b/tests/browser/message-navigation.spec.mjs @@ -37,7 +37,9 @@ test("old root and reply beyond the first thread page open exactly; reclick and page, app, }) => { - await open(page, app); + // The read ahead stays pending: the old root is not in the loaded window. + await open(page, app, { hold: true }); + const [ahead] = app.pending; const initialHeadQueries = app.report.queries.filter( (q) => q.filter.top_level, ).length; @@ -101,7 +103,11 @@ test("old root and reply beyond the first thread page open exactly; reclick and app.report.queries.some((q) => q.filter.thread_cursor !== undefined), "the exact reply requires a second thread page", ).toBe(true); - expect(app.report.queries.filter((q) => q.filter.until)).toHaveLength(0); + expect( + app.report.queries.filter( + (q) => q.filter.until && q.filter !== ahead?.filter, + ), + ).toHaveLength(0); // Settings temporarily takes the rail without disposing the routed thread. const threadElement = page.locator('[aria-label="Thread"]'); await threadElement.evaluate((element) => { @@ -542,7 +548,8 @@ for (const selected of ["reply", "root"]) { page, app, }) => { - await open(page, app); + // The read ahead stays pending: the old root is not in the loaded window. + await open(page, app, { hold: true }); const id = selected === "root" ? app.exact.root.id : app.exact.target.id; const destination = { ...target(app, id), diff --git a/tests/browser/navigation-channel-history.spec.mjs b/tests/browser/navigation-channel-history.spec.mjs index 828d967039..9498de75b7 100644 --- a/tests/browser/navigation-channel-history.spec.mjs +++ b/tests/browser/navigation-channel-history.spec.mjs @@ -222,10 +222,10 @@ test("Back between two links in one channel returns to the reader's place; the s await follow(page, link(0)); await expectRevealed(page, first.id); // Enter on the link is reading input in #Alpha's own timeline, so the - // reveal's scroll asks for the one older page beyond its 20-row head. Answer - // it, so no held read can time out under a later opening. - await expect.poll(() => app.pending.length).toBe(1); - app.pending.shift().release(); + // reveal's scroll can ask for older history beyond what opening read ahead. + // Answer it, so no held read can time out under a later opening. + await settle(page); + for (const read of app.pending.splice(0)) read.release(); await expectVerifiedAlpha(page, app); await settle(page); await end(page); diff --git a/tests/browser/new-message-boundary.spec.mjs b/tests/browser/new-message-boundary.spec.mjs index b1937d821e..f436713f49 100644 --- a/tests/browser/new-message-boundary.spec.mjs +++ b/tests/browser/new-message-boundary.spec.mjs @@ -603,7 +603,8 @@ appTest.describe("history longer than one page", () => { hasMore: history.hasMore, }; }); - await open(page, app); + // Reading ahead would load the rest; it stays pending. + await open(page, app, { hold: true }); await expect.poll(entryWindow).toEqual({ status: "ready", freshness: "verified", diff --git a/tests/browser/perf/run.mjs b/tests/browser/perf/run.mjs index 7f820be6c3..69ca446e6a 100644 --- a/tests/browser/perf/run.mjs +++ b/tests/browser/perf/run.mjs @@ -14,6 +14,7 @@ const cases = [ "scroll-long", "scroll-paging-fast", "scroll-paging-delayed", + "scroll-paging-delayed-short", "scroll-paging-fast-keyboard", "scroll-paging-fast-markdown", "scroll-paging-fast-first-seen", diff --git a/tests/browser/perf/scroll-paging.perf.mjs b/tests/browser/perf/scroll-paging.perf.mjs index 6284be4627..4c6ca5cc6e 100644 --- a/tests/browser/perf/scroll-paging.perf.mjs +++ b/tests/browser/perf/scroll-paging.perf.mjs @@ -2,10 +2,11 @@ import { test, expect, repeats, timeline } from "./runner.mjs"; import { scrollCadence } from "./cadence.mjs"; const count = 640; -// Each variant changes one condition of scroll-paging-fast. +// Each variant changes one condition of scroll-paging-fast or -delayed. for (const [name, olderPageDelayMs, modality, options] of [ ["scroll-paging-fast", 100, "pointer", {}], ["scroll-paging-delayed", 500, "pointer", {}], + ["scroll-paging-delayed-short", 500, "pointer", { shortMessages: true }], ["scroll-paging-fast-keyboard", 100, "keyboard", {}], ["scroll-paging-fast-markdown", 100, "pointer", { markdownMessages: true }], ["scroll-paging-fast-first-seen", 100, "pointer", { firstSeenHistory: true }], @@ -23,7 +24,9 @@ for (const [name, olderPageDelayMs, modality, options] of [ const oldestId = app.histories.get("primary/alpha")[0].id; const point = await perf.gutter("alpha", modality); await perf.settle("alpha"); - expect(app.pending, "history is not preloaded").toHaveLength(0); + // Input starts as soon as the opening settles, with any read-ahead + // still in flight: a reader scrolling back at once. + const olderReadsBefore = app.pending.length; const head = app.report.queries.find( ({ filter }) => filter.top_level && @@ -35,8 +38,12 @@ for (const [name, olderPageDelayMs, modality, options] of [ .slice(0, -head.limit) .map(({ id }) => id); // Served events are in the app's proof memo; first-seen ones verify. - const olderRowsServedBefore = expectedOlderIds.filter((id) => - app.served.has(id), + // The visit's own older pages, read ahead, verify as they arrive. + const paged = new Set( + app.pending.flatMap(({ events }) => events.map(({ id }) => id)), + ); + const olderRowsServedBefore = expectedOlderIds.filter( + (id) => app.served.has(id) && !paged.has(id), ).length; if (options.firstSeenHistory) expect(olderRowsServedBefore, "older history is first-seen").toBe(0); @@ -77,6 +84,19 @@ for (const [name, olderPageDelayMs, modality, options] of [ }, }); Object.assign(sample.metrics, scrollCadence(sample.recording)); + // Time the reader spent held at the top edge, waiting for history. + const { frames, gestureStartMs, gestureEndMs } = sample.recording; + sample.metrics.edgeWaitMs = frames + .slice(1) + .reduce( + (sum, { t }, i) => + frames[i].top <= 1 && + frames[i].t >= gestureStartMs && + t <= gestureEndMs + ? sum + t - frames[i].t + : sum, + 0, + ); const received = new Set( app.pending .filter(({ releaseDelayMs }) => releaseDelayMs !== undefined) @@ -85,7 +105,8 @@ for (const [name, olderPageDelayMs, modality, options] of [ Object.assign(sample.work, { gestures, wheels: sample.recording.wheels, - olderReadsDuring: app.pending.length, + olderReadsBefore, + olderReadsDuring: app.pending.length - olderReadsBefore, olderReleaseDelaysMs: app.pending.map( ({ releaseDelayMs }) => releaseDelayMs, ), @@ -99,10 +120,9 @@ for (const [name, olderPageDelayMs, modality, options] of [ expect.arrayContaining(expectedOlderIds), ); expect(sample.work.wheels, "real wheel input").toBeGreaterThan(0); - expect( - sample.work.olderReadsDuring, - "multiple pages arrive during input", - ).toBeGreaterThan(1); + expect(app.pending.length, "history arrives in pages").toBeGreaterThan( + 1, + ); expect( sample.recording.frames.at(-1).rows.map(([id]) => id), "oldest message remains visible after settling", diff --git a/tests/browser/policy-relay.mjs b/tests/browser/policy-relay.mjs index cfcc888cff..690a3845a3 100644 --- a/tests/browser/policy-relay.mjs +++ b/tests/browser/policy-relay.mjs @@ -280,7 +280,9 @@ export function policyRelay({ filters[1].kinds[0] === 40099 ) { expect(filters[1]["#h"]).toEqual(filters[0]["#h"]); - const parts = await Promise.all( + // Returned, not awaited: a part held and then cancelled by the app + // is consumer cancellation, not a fault (see the presence hold). + return Promise.all( filters.map((filter) => api.fetch(url, { ...init, @@ -288,14 +290,15 @@ export function policyRelay({ [REQUEST_PART]: true, }), ), - ); - const failed = parts.find((response) => !response.ok); - if (failed) return failed; - return Response.json( - ( - await Promise.all(parts.map((response) => response.json())) - ).flat(), - ); + ).then(async (parts) => { + const failed = parts.find((response) => !response.ok); + if (failed) return failed; + return Response.json( + ( + await Promise.all(parts.map((response) => response.json())) + ).flat(), + ); + }); } if (filters.length === 2 && filters[1].depth_limit) { const [root, replies] = filters; @@ -643,19 +646,30 @@ export function policyRelay({ filter.authors?.some((id) => heldAuthors.has(id)) ) return holdProfile(result); + // An older page's aux closure, read apart from its rows, is not held. if ( filter.search === undefined && filter.until !== undefined && + !(filter.include_aux && !filter.include_summaries) && holdOlder ) return new Promise((resolve, reject) => { - const abort = () => reject(init.signal.reason); + const abort = () => { + // A read the app cancels is no longer pending. + const index = pending.indexOf(receipt); + if (index >= 0) pending.splice(index, 1); + reject(init.signal.reason); + }; init.signal.addEventListener("abort", abort, { once: true }); const receipt = { community, channel, filter, events: result.filter((event) => event.kind === 9), + // The app abandoned the read, such as a cancelled read-ahead. + get closed() { + return init.signal.aborted; + }, release() { init.signal.removeEventListener("abort", abort); resolve(Response.json(result)); diff --git a/tests/browser/scroll.spec.mjs b/tests/browser/scroll.spec.mjs index 2f541f8e29..fccf1d9bfb 100644 --- a/tests/browser/scroll.spec.mjs +++ b/tests/browser/scroll.spec.mjs @@ -234,7 +234,13 @@ readingTest( scenario: "live-appends", ...(await workSample(page)), }); - expect(app.pending).toHaveLength(0); + // Visits left read-ahead reads cancelled; only the reader now at the + // latest message may still be reading ahead. + expect( + app.pending.filter( + (read) => !(read.community === "primary" && read.channel === "alpha"), + ), + ).toEqual([]); }, ); @@ -335,10 +341,12 @@ readingTest( test("cursor paging preserves visible anchors and keeps a large history virtualized", { tag: "@local-webkit", }, async ({ page, app, browserName }) => { - await open(page, app); + const ahead = await open(page, app); await observeWork(page); - let loaded = 20; - const cursors = new Set(); + let loaded = 20 + ahead.reduce((rows, read) => rows + read.events.length, 0); + const cursors = new Set( + ahead.map(({ filter }) => `${filter.until}:${filter.before_id}`), + ); while (loaded < historySize) { // A small prepend can leave us inside the prefetch zone and automatically // request the next page. A new gesture must not duplicate that pending read. @@ -362,13 +370,17 @@ test("cursor paging preserves visible anchors and keeps a large history virtuali expect(pending.channel).toBe("alpha"); expect(pending.filter.until).toBeDefined(); expect(pending.filter.before_id).toMatch(/^[a-f0-9]{64}$/); - expect(pending.filter.limit).toBe(20); + // Pages are sized to the reader's pace, within the relay's read limit. + expect(pending.filter.limit).toBeGreaterThanOrEqual(20); + expect(pending.filter.limit).toBeLessThanOrEqual(200); const cursor = `${pending.filter.until}:${pending.filter.before_id}`; expect(cursors.has(cursor), "each older cursor is requested once").toBe( false, ); cursors.add(cursor); - expect(pending.events).toHaveLength(20); + expect(pending.events).toHaveLength( + Math.min(pending.filter.limit, historySize - loaded), + ); pending.release(); loaded += pending.events.length; await expect @@ -387,10 +399,15 @@ test("cursor paging preserves visible anchors and keeps a large history virtuali await settle(page); expect(app.pending.length).toBeLessThanOrEqual(1); } - expect(cursors.size).toBe(31); + expect(loaded).toBe(historySize); + // Each page's aux closure is read apart from its rows. expect( - app.report.queries.filter(({ filter }) => filter.until !== undefined), - ).toHaveLength(31); + app.report.queries.filter( + ({ filter }) => + filter.until !== undefined && + !(filter.include_aux && !filter.include_summaries), + ), + ).toHaveLength(cursors.size); expect(app.pending).toHaveLength(0); await edge(page, -1); @@ -476,6 +493,7 @@ test("cursor paging preserves visible anchors and keeps a large history virtuali true, ); expect(primaryQueries(app)).toBe(queriesBeforeTraversal); + // Each Beta visit's read-ahead was cancelled when the reader left. expect(app.pending).toHaveLength(0); const sample = await workSample(page); expect(sample.frameSamples).toBeGreaterThan(0); diff --git a/tests/browser/shortcuts.spec.mjs b/tests/browser/shortcuts.spec.mjs index 575be024fb..7480a4f8f4 100644 --- a/tests/browser/shortcuts.spec.mjs +++ b/tests/browser/shortcuts.spec.mjs @@ -352,8 +352,8 @@ async function wheelToScaledHistoryTop(page, history, messageIds) { } test.describe("scaled history", () => { - test.use({ historyCounts: { alpha: 21, beta: 0 } }); - // Twenty rows fill one page; the extra row proves the virtualized paging edge. + test.use({ historyCounts: { alpha: 300, beta: 0 } }); + // History remains past the read ahead on open, for the virtualized paging edge. // Real layout and pointer coordinates cannot be established by a DOM emulator. test("interface zoom keeps timeline paging and sidebar resizing usable", async ({ page, @@ -433,6 +433,7 @@ test.describe("scaled history", () => { deferred.clear(); }; }); + let pageRows = []; try { await wheelToScaledHistoryTop( page, @@ -440,6 +441,7 @@ test.describe("scaled history", () => { messages.map(({ id }) => id), ); await expect.poll(() => app.pending.length).toBe(1); + pageRows = app.pending[0].events; const loading = history.getByRole("button", { name: "Loading older…", exact: true, @@ -457,12 +459,24 @@ test.describe("scaled history", () => { await readDeadlines.evaluate((resume) => resume()); await readDeadlines.dispose(); } + // The page's newest row lands just above the reader. + const newest = pageRows.reduce((a, b) => + b.created_at > a.created_at ? b : a, + ); await expect( - history.getByRole("button", { name: "Loading older…", exact: true }), - ).toHaveCount(0); - await expect( - history.locator(`[data-message-id="${messages[0].id}"]`), + history.locator(`[data-message-id="${newest.id}"]`), ).toBeVisible(); + // A reader at the top reads on to the channel start. + const loading = history.getByRole("button", { + name: "Loading older…", + exact: true, + }); + for (let read = 0; read < 5 && (await loading.count()); read++) { + await expect.poll(() => app.pending.length).toBe(1); + app.pending.shift().release(); + await settle(page); + } + await expect(loading).toHaveCount(0); }); }); diff --git a/tests/browser/startup.spec.mjs b/tests/browser/startup.spec.mjs index 378f45e82e..2efd7df81f 100644 --- a/tests/browser/startup.spec.mjs +++ b/tests/browser/startup.spec.mjs @@ -69,6 +69,10 @@ test("reload restores the selected conversation/groups before handshake and upda const history = page.getByRole("region", { name: "Channel message history" }); await expect(history).toContainText("primary beta message 39"); await expect(page.getByText("Work", { exact: true })).toBeVisible(); + // Beta reads ahead; the reload leaves that read unanswered. + await expect.poll(() => app.pending.length).toBe(1); + const [unanswered] = app.pending.splice(0); + expect(unanswered.channel).toBe("beta"); const composer = page.getByRole("textbox", { name: "Message #Beta", exact: true, @@ -166,13 +170,8 @@ test("reload restores the selected conversation/groups before handshake and upda // Visible appended content can precede Virtua's final follow-to-bottom // measurement. Establish that layout before measuring a wheel distance. await settle(page); - const olderReads = () => - app.report.queries.filter( - ({ filter }) => filter["#h"]?.includes("beta") && filter.before_id, - ); - const beforeOlder = olderReads().length; + // The reloaded session reads ahead, or the top edge asks. await edge(page, -1); - await expect.poll(() => olderReads().length).toBeGreaterThan(beforeOlder); await expect.poll(() => app.pending.length).toBe(1); const older = app.pending.shift(); expect(older.channel).toBe("beta"); diff --git a/tests/browser/timeline.mjs b/tests/browser/timeline.mjs index ff277e88ed..40d7947be3 100644 --- a/tests/browser/timeline.mjs +++ b/tests/browser/timeline.mjs @@ -181,17 +181,21 @@ export async function edge(page, direction, scroller = history(page)) { let remaining = await distance(); if (remaining < 4) await page.mouse.wheel(0, direction * Math.max(1, remaining)); - // A gesture can end short of the edge, as one did 199px from the top in - // Linux WebKit (see upper). Each further gesture must make real progress, - // so an immobile timeline still fails. - for (let gesture = 0; remaining >= 4 && gesture < 4; gesture++) { - await wheel(page, direction * remaining, scroller); + // A gesture can end short of the edge: Linux WebKit moves one about 1.5k px + // at most. Each further gesture must make real progress, so an immobile + // timeline still fails. + // A page landing beyond the edge adds height, not lost progress. + const height = () => scroller.evaluate((element) => element.scrollHeight); + for (let gesture = 0; remaining >= 4 && gesture < 40; gesture++) { const before = remaining; + const grown = await height(); + await wheel(page, direction * remaining, scroller); remaining = await distance(); if (remaining >= 4) - expect(remaining, "edge gesture moves toward the edge").toBeLessThan( - before, - ); + expect( + remaining - Math.max(0, (await height()) - grown), + "edge gesture moves toward the edge", + ).toBeLessThan(before); } await expect .poll(distance, { message: "wheel reaches timeline edge" }) @@ -201,12 +205,32 @@ export async function edge(page, direction, scroller = history(page)) { 4, ); } +/** Scroll to the top for the next older read. Gestures stop once the app's + * reach starts that read, and the rest of the way is short: a held read waits + * only for that, not for a whole Linux scroll past its deadline. With `top` + * false, a read the app's read-ahead starts, before the call or during a + * gesture, is the next read where the reader is. */ +export async function toOlder( + page, + app, + { top = true } = {}, + scroller = history(page), +) { + await scroller.hover(); + for (let gesture = 0; !app.pending.length && gesture < 40; gesture++) { + const offset = await scroller.evaluate((element) => element.scrollTop); + if (offset < 4) break; + await wheel(page, -offset, scroller); + } + if (top || !app.pending.length) await edge(page, -1, scroller); + await expect.poll(() => app.pending.length).toBe(1); +} export async function end(page) { await edge(page, 1); } // `cold` reaches Messages by its tab, for journeys that need conversations // unread by the app: search previews the results it highlights on the way. -export async function open(page, app, { cold = false } = {}) { +export async function open(page, app, { cold = false, hold = false } = {}) { await page.goto(app.origin); if (cold) await page.getByRole("tab", { name: "Messages", exact: true }).click(); @@ -214,6 +238,68 @@ export async function open(page, app, { cold = false } = {}) { await composer(page, "Alpha").waitFor(); await expect(history(page).locator(rowSelector).first()).toBeVisible(); await settle(page); + return readAhead(page, app, { hold }); +} +/** Opening reads older history ahead of a reader at the bottom. Release it + * until the reader has the prefetch distance or the channel's first message + * above them, or a read fails, so a journey's baseline starts after it. + * `hold` leaves the first read pending for a journey that lands it itself. + * Returns the reads it released. */ +export async function readAhead(page, app, { hold = false } = {}) { + const channel = await history(page).evaluate( + (element) => + element.closest("[data-channel-timeline]").dataset.channelTimeline, + ); + const rows = app.histories + .get(`primary/${channel}`) + .filter((event) => event.kind === 9); + const first = Math.min(...rows.map((event) => event.created_at)); + const start = rows + .filter((event) => event.created_at === first) + .map((event) => event.id); + const done = () => + history(page).evaluate( + (element, start) => + element.scrollTop >= Math.max(3000, element.clientHeight * 6) || + start.every((id) => + element.querySelector(`[data-message-id="${id}"]`), + ) || + !!element.querySelector('[role="alert"]'), + start, + ); + const released = []; + // At most the visit's five fill pages. + for (let read = 0; read < 5; read++) { + if (hold) { + await expect + .poll(async () => app.pending.length > 0 || (await done()), { + message: "opening reads ahead or has history above the reader", + }) + .toBe(true); + return released; + } + // A read-ahead starts once the opening is idle, within 500ms; none starts + // when the loaded history is all there is. + await expect + .poll(async () => app.pending.length > 0 || (await done()), { + timeout: 2000, + }) + .toBe(true) + .catch(() => {}); + // The app's own reach can take one page more than `done` (Linux WebKit + // did): give that read its start window too, so none is left held. + if (!app.pending.length) + await expect + .poll(() => app.pending.length, { timeout: 1000 }) + .toBeGreaterThan(0) + .catch(() => {}); + const pending = app.pending.shift(); + if (!pending) return released; + pending.release(); + released.push(pending); + await settle(page); + } + return released; } export async function upper(page) { await end(page);