From 8ace7859b9c6bfa3bcfde9d49d605058e3dbb6c1 Mon Sep 17 00:00:00 2001 From: Micha Mailaender <87228994+mmailaender@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:15:34 +0200 Subject: [PATCH 1/2] Handle failed paginated queries without throwing or resetting forever Fixes #61. - New shared subscribePaginated() used by usePaginatedQuery and the detached paginated query (convexLoadPaginated): errors the Convex client throws from getCurrentValue() or onPaginatedUpdate_experimental() (see get-convex/convex-js#193) go to onError, a cleanup is always returned, and a synchronous first callback no longer hits the TDZ. - PaginatedQueryStateMachine resets once on InvalidCursor; a repeated one before a page arrived is surfaced as the error. A loaded page, changed args or reset() re-arm the reset. - The detached paginated query resubscribes after an InvalidCursor reset instead of staying in LoadingFirstPage. --- .changeset/paginated-query-errors.md | 9 ++ src/lib/shared/paginated_query_state.spec.ts | 48 +++++++ src/lib/shared/paginated_query_state.ts | 16 ++- src/lib/shared/paginated_subscription.spec.ts | 129 ++++++++++++++++++ src/lib/shared/paginated_subscription.ts | 76 +++++++++++ .../paginated-query-detached.svelte.ts | 47 ++++--- src/lib/sveltekit/query-detached.spec.ts | 87 ++++++++++++ src/lib/use_paginated_query.svelte.ts | 50 ++----- 8 files changed, 403 insertions(+), 59 deletions(-) create mode 100644 .changeset/paginated-query-errors.md create mode 100644 src/lib/shared/paginated_subscription.spec.ts create mode 100644 src/lib/shared/paginated_subscription.ts diff --git a/.changeset/paginated-query-errors.md b/.changeset/paginated-query-errors.md new file mode 100644 index 0000000..6c955bf --- /dev/null +++ b/.changeset/paginated-query-errors.md @@ -0,0 +1,9 @@ +--- +'convex-svelte': patch +--- + +### Fixes + +- **Failed paginated queries no longer throw during setup** ([#61](https://github.com/get-convex/convex-svelte/issues/61)) - the Convex client throws from `getCurrentValue()` once a page has failed, and from `onPaginatedUpdate_experimental()` when another subscriber already holds the query in a failed state. `usePaginatedQuery`, `convexLoadPaginated` and `createDetachedPaginatedQuery` now report these errors through `error` instead of throwing, and always clean up their subscription. +- **`InvalidCursor` no longer resets forever** ([#61](https://github.com/get-convex/convex-svelte/issues/61)) - a paginated query resets once on `InvalidCursor`. If the cursor fails again before a page arrived, the error is shown instead of resetting in a loop. A loaded page, changed args or `reset()` allow the next reset. +- **`convexLoadPaginated` recovers from `InvalidCursor`** - it reset its state but never resubscribed, so it stayed in `LoadingFirstPage`. It now starts a fresh subscription, and a load waiting for its first page keeps waiting for it. diff --git a/src/lib/shared/paginated_query_state.spec.ts b/src/lib/shared/paginated_query_state.spec.ts index d30953a..2bff589 100644 --- a/src/lib/shared/paginated_query_state.spec.ts +++ b/src/lib/shared/paginated_query_state.spec.ts @@ -230,3 +230,51 @@ describe('PaginatedQueryStateMachine keepPreviousData', () => { }); }); }); + +describe('PaginatedQueryStateMachine InvalidCursor reset limit (#61)', () => { + const invalidCursor = () => new Error('InvalidCursor: the cursor is no longer valid'); + const loadMore = () => false; + + function machineWithArgs() { + const machine = new PaginatedQueryStateMachine({ initialNumItems: 3 }); + machine.onArgsChange('{}'); + return machine; + } + + it('resets once, then surfaces a repeated InvalidCursor as the error', () => { + const machine = machineWithArgs(); + + expect(machine.onError(invalidCursor())).toBe(true); + const afterReset = machine.getSnapshot(); + expect(afterReset).toMatchObject({ status: 'LoadingFirstPage', error: undefined }); + + // The resubscription only reports its empty loading snapshot, then fails again. + machine.onUpdate({ results: [], status: 'LoadingFirstPage', loadMore }); + expect(machine.onError(invalidCursor())).toBe(false); + + expect(machine.getSnapshot()).toMatchObject({ + isLoading: false, + resetKey: afterReset.resetKey + }); + expect(machine.getSnapshot().error?.message).toContain('InvalidCursor'); + }); + + it('allows another reset once a page arrived', () => { + const machine = machineWithArgs(); + machine.onError(invalidCursor()); + + machine.onUpdate({ results: ['a'], status: 'CanLoadMore', loadMore }); + + expect(machine.onError(invalidCursor())).toBe(true); + }); + + it('allows another reset after the args changed or after reset()', () => { + const machine = machineWithArgs(); + machine.onError(invalidCursor()); + machine.onArgsChange('{"other":true}'); + expect(machine.onError(invalidCursor())).toBe(true); + + machine.reset(); + expect(machine.onError(invalidCursor())).toBe(true); + }); +}); diff --git a/src/lib/shared/paginated_query_state.ts b/src/lib/shared/paginated_query_state.ts index 643ad78..37d9a4e 100644 --- a/src/lib/shared/paginated_query_state.ts +++ b/src/lib/shared/paginated_query_state.ts @@ -111,6 +111,13 @@ export class PaginatedQueryStateMachine { * before the first server update). Flushed by `onUpdate`. */ private pendingLoadMoreNumItems: number | null = null; + /** + * Whether the next InvalidCursor may reset pagination. Disarmed by a reset + * and re-armed by a real result, changed args or `reset()`: if the cursor + * keeps failing (e.g. another subscriber holds the failed query alive), the + * second InvalidCursor is surfaced as an error instead of resetting forever. + */ + private invalidCursorResetArmed = true; constructor(config: PaginatedQueryConfig) { this.config = config; @@ -244,6 +251,7 @@ export class PaginatedQueryStateMachine { this.state.argsKey = newArgsKey; // A queued loadMore belongs to the previous args — drop it. this.pendingLoadMoreNumItems = null; + this.invalidCursorResetArmed = true; // Track when args change from initial if (!this.state.haveArgsEverChanged && this.state.initialArgsKey !== newArgsKey) { @@ -297,6 +305,10 @@ export class PaginatedQueryStateMachine { * "empty loading" snapshot to keep SSR-rendered content visible. */ onUpdate(update: PaginatedQueryUpdate): void { + // A page arrived: the cursor works again. The empty loading snapshot right + // after a reset must not re-arm, or a persistent InvalidCursor loops. + if (update.status !== 'LoadingFirstPage') this.invalidCursorResetArmed = true; + // Hydration guard: if using initial data, ignore empty loading snapshots // This keeps SSR-rendered content visible until real data arrives. // Checked before keepPreviousData: SSR data is not "previous" data, and @@ -353,7 +365,8 @@ export class PaginatedQueryStateMachine { * @returns `true` if we detected and handled an InvalidCursor (framework should resubscribe) */ onError(error: Error): boolean { - if (this.isInvalidCursorError(error)) { + if (this.isInvalidCursorError(error) && this.invalidCursorResetArmed) { + this.invalidCursorResetArmed = false; console.warn('PaginatedQueryStateMachine: InvalidCursor detected, resetting:', error.message); this.pendingLoadMoreNumItems = null; this.state = { @@ -384,6 +397,7 @@ export class PaginatedQueryStateMachine { */ reset(): void { this.pendingLoadMoreNumItems = null; + this.invalidCursorResetArmed = true; this.state = { ...this.state, results: [], diff --git a/src/lib/shared/paginated_subscription.spec.ts b/src/lib/shared/paginated_subscription.spec.ts new file mode 100644 index 0000000..115d8f7 --- /dev/null +++ b/src/lib/shared/paginated_subscription.spec.ts @@ -0,0 +1,129 @@ +import { describe, expect, it, vi } from 'vitest'; +import { makeFunctionReference } from 'convex/server'; +import { subscribePaginated } from './paginated_subscription.js'; + +// The Convex client can throw instead of calling onError (get-convex/convex-js#193): +// from getCurrentValue() for a failed page, and from onPaginatedUpdate_experimental() +// itself. Those errors must reach onError, and a cleanup must always come back. + +const ref = makeFunctionReference<'query'>('messages:paginatedList'); +const page = { results: [1], status: 'CanLoadMore' as const, loadMore: () => true }; + +function clientWith( + impl: (onUpdate: () => void, onError: (e: Error) => void) => ReturnType +) { + return { + onPaginatedUpdate_experimental: vi.fn( + (_q: unknown, _a: unknown, _o: unknown, onUpdate: () => void, onError: (e: Error) => void) => + impl(onUpdate, onError) + ) + } as never; +} + +describe('subscribePaginated', () => { + it('reports a failed cached page instead of throwing, and still returns a cleanup', () => { + const unsubscribe = Object.assign(vi.fn(), { + getCurrentValue: () => { + throw new Error('page failed'); + } + }); + const onSnapshot = vi.fn(); + const onError = vi.fn(); + + const cleanup = subscribePaginated( + clientWith(() => unsubscribe), + ref, + {}, + 10, + onSnapshot, + onError + ); + + expect(onError).toHaveBeenCalledWith(new Error('page failed')); + expect(onSnapshot).not.toHaveBeenCalled(); + cleanup(); + expect(unsubscribe).toHaveBeenCalledOnce(); + }); + + it('reports an error thrown by onPaginatedUpdate_experimental itself', () => { + const onError = vi.fn(); + const client = { + onPaginatedUpdate_experimental: vi.fn(() => { + throw new Error('failed page held by another subscriber'); + }) + } as never; + + const cleanup = subscribePaginated(client, ref, {}, 10, vi.fn(), onError); + + expect(onError).toHaveBeenCalledWith(new Error('failed page held by another subscriber')); + expect(() => cleanup()).not.toThrow(); + }); + + it('reports a failed page that getCurrentValue() throws inside the update callback', () => { + let fail = false; + let notify = () => {}; + const unsubscribe = Object.assign(vi.fn(), { + getCurrentValue: () => { + if (fail) throw new Error('page failed'); + return undefined; + } + }); + const onError = vi.fn(); + subscribePaginated( + clientWith((onUpdate) => { + notify = onUpdate; + return unsubscribe; + }), + ref, + {}, + 10, + vi.fn(), + onError + ); + + fail = true; + notify(); + + expect(onError).toHaveBeenCalledWith(new Error('page failed')); + }); + + it('delivers a snapshot the client reports synchronously while subscribing, once', () => { + const unsubscribe = Object.assign(vi.fn(), { getCurrentValue: () => page }); + const onSnapshot = vi.fn(); + + subscribePaginated( + clientWith((onUpdate) => { + onUpdate(); // before the subscription is returned + return unsubscribe; + }), + ref, + {}, + 10, + onSnapshot, + vi.fn() + ); + + expect(onSnapshot).toHaveBeenCalledOnce(); + expect(onSnapshot).toHaveBeenCalledWith(page); + }); + + it('does not read the value after the client reported an error synchronously', () => { + const getCurrentValue = vi.fn(() => page); + const onError = vi.fn(); + + subscribePaginated( + clientWith((_onUpdate, reportError) => { + reportError(new Error('boom')); + return Object.assign(vi.fn(), { getCurrentValue }); + }), + ref, + {}, + 10, + vi.fn(), + onError + ); + + expect(onError).toHaveBeenCalledOnce(); + expect(getCurrentValue).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/shared/paginated_subscription.ts b/src/lib/shared/paginated_subscription.ts new file mode 100644 index 0000000..3c7e456 --- /dev/null +++ b/src/lib/shared/paginated_subscription.ts @@ -0,0 +1,76 @@ +/** + * Safe subscription to a Convex paginated query, shared by `usePaginatedQuery` + * and the detached paginated query behind `convexLoadPaginated`. + * + * The Convex client can throw instead of calling `onError`: from + * `getCurrentValue()` once a page has failed, and from + * `onPaginatedUpdate_experimental()` itself when another subscriber already + * holds the query in a failed state (get-convex/convex-js#193). Thrown errors + * are reported through `onError` here, so callers always get a cleanup function + * back and their state machine sees the error. + */ +import type { ConvexClient, PaginationStatus } from 'convex/browser'; +import type { FunctionArgs, FunctionReference } from 'convex/server'; + +/** One update of a paginated query, as delivered by the Convex client. */ +export type PaginatedSnapshot = { + results: unknown[]; + status: PaginationStatus; + loadMore: (numItems: number) => boolean; +}; + +const toError = (error: unknown) => (error instanceof Error ? error : new Error(String(error))); + +/** + * Subscribe and report every snapshot or error. Returns a function that ends + * the subscription; safe to call when subscribing failed. + */ +export function subscribePaginated>( + client: Pick, + query: Query, + args: FunctionArgs, + initialNumItems: number, + onSnapshot: (snapshot: PaginatedSnapshot) => void, + onError: (error: Error) => void +): () => void { + let subscription: ReturnType | undefined; + let failed = false; + + const read = () => { + let current: PaginatedSnapshot | undefined; + try { + current = subscription?.getCurrentValue() as PaginatedSnapshot | undefined; + } catch (error) { + failed = true; + onError(toError(error)); + return; + } + if (current) onSnapshot(current); + }; + + try { + subscription = client.onPaginatedUpdate_experimental( + query, + args, + { initialNumItems }, + // A callback the client runs synchronously, before `subscription` is + // assigned, is covered by the read below. + () => { + if (subscription) read(); + }, + (error: Error) => { + failed = true; + onError(error); + } + ); + } catch (error) { + onError(toError(error)); + return () => {}; + } + + // Cached value of a query another subscriber already holds, or a snapshot + // delivered synchronously while subscribing. + if (!failed) read(); + + return () => subscription?.(); +} diff --git a/src/lib/sveltekit/paginated-query-detached.svelte.ts b/src/lib/sveltekit/paginated-query-detached.svelte.ts index 149da6e..c2bd9b0 100644 --- a/src/lib/sveltekit/paginated-query-detached.svelte.ts +++ b/src/lib/sveltekit/paginated-query-detached.svelte.ts @@ -24,6 +24,7 @@ import { import { markRouteQuery, type SubscriptionHandle } from './query-lifecycle.js'; import { paginatedQueryKey } from './query-key.js'; import { createRouteQuery } from './route-data.svelte.js'; +import { subscribePaginated, type PaginatedSnapshot } from '../shared/paginated_subscription.js'; import type { DetachedQueryOptions } from './query-detached.svelte.js'; export type DetachedPaginatedQueryResult> = { @@ -129,11 +130,7 @@ export function openDetachedPaginatedQuery boolean; - }) => { + const onSnapshot = (current: PaginatedSnapshot) => { machine.onUpdate({ results: current.results as PageItem[], status: current.status, @@ -141,26 +138,34 @@ export function openDetachedPaginatedQuery { + if (subscriptionGeneration !== generation) return; + if (machine.onError(e)) { + // InvalidCursor: the machine reset pagination (once). Start over with + // a fresh subscription; a load keeps waiting for its first page. + queueMicrotask(restart); + return; + } + settleFirstValue?.(e); + }; - // Create subscription - const subscription = client.onPaginatedUpdate_experimental( + unsubscribe = subscribePaginated( + client, query, - args, - { initialNumItems: options.initialNumItems }, - () => { - const current = subscription.getCurrentValue?.(); - if (current) onSnapshot(current); - }, - (e: Error) => { - machine.onError(e); - settleFirstValue?.(e); - } + args as FunctionArgs, + options.initialNumItems, + onSnapshot, + onError ); - unsubscribe = subscription; + }; - // Check for synchronously available cached value - const current = subscription.getCurrentValue?.(); - if (current) onSnapshot(current); + /** Replace the subscription with a fresh one, e.g. after an InvalidCursor reset. */ + const restart = () => { + if (!wanted || !unsubscribe) return; + generation += 1; + unsubscribe(); + unsubscribe = undefined; + subscribe(); }; const handle: SubscriptionHandle = { diff --git a/src/lib/sveltekit/query-detached.spec.ts b/src/lib/sveltekit/query-detached.spec.ts index ce0d915..b5c6a2f 100644 --- a/src/lib/sveltekit/query-detached.spec.ts +++ b/src/lib/sveltekit/query-detached.spec.ts @@ -642,3 +642,90 @@ describe('openDetachedPaginatedQuery — immediate subscription with first page' await expect(firstValue).rejects.toThrow('disabled or closed'); }); }); + +describe('openDetachedPaginatedQuery — failed pages (#61)', () => { + const invalidCursor = () => new Error('InvalidCursor: the cursor is no longer valid'); + + /** A subscription whose current value or failure can be set by the test. */ + function paginatedSubscription() { + let current: { results: unknown[]; status: string; loadMore: () => boolean } | Error = { + results: [], + status: 'LoadingFirstPage', + loadMore: () => false + }; + const subscription = Object.assign(vi.fn(), { + getCurrentValue: () => { + if (current instanceof Error) throw current; + return current; + } + }); + client.onPaginatedUpdate_experimental.mockReturnValueOnce(subscription); + return { + subscription, + deliver(results: unknown[]) { + current = { results, status: 'CanLoadMore', loadMore: () => true }; + }, + fail(error: Error) { + current = error; + } + }; + } + + const callbacks = (call: number) => { + const [, , , onUpdate, onError] = client.onPaginatedUpdate_experimental.mock.calls[call] as [ + unknown, + unknown, + unknown, + () => void, + (error: Error) => void + ]; + return { onUpdate, onError }; + }; + + const open = () => + openDetachedPaginatedQuery(ref, {}, { initialNumItems: 10, scope: 'route', immediate: true }); + + it('resubscribes once after an InvalidCursor, and the load keeps waiting for the first page', async () => { + const first = paginatedSubscription(); + const second = paginatedSubscription(); + const { result, firstValue } = open(); + + callbacks(0).onError(invalidCursor()); + await Promise.resolve(); + + expect(first.subscription).toHaveBeenCalledOnce(); + expect(client.onPaginatedUpdate_experimental).toHaveBeenCalledTimes(2); + expect(await settledState(firstValue)).toBe('pending'); + + second.deliver([{ id: 1 }]); + callbacks(1).onUpdate(); + + expect(await settledState(firstValue)).toBe('resolved'); + expect(result.results).toEqual([{ id: 1 }]); + }); + + it('surfaces the error when the cursor keeps failing after the reset', async () => { + paginatedSubscription(); + paginatedSubscription(); + const { result, firstValue } = open(); + + callbacks(0).onError(invalidCursor()); + await Promise.resolve(); + callbacks(1).onError(invalidCursor()); + + expect(await settledState(firstValue)).toBe('rejected'); + expect(client.onPaginatedUpdate_experimental).toHaveBeenCalledTimes(2); + expect(result.error?.message).toContain('InvalidCursor'); + expect(result.isLoading).toBe(false); + }); + + it('reports a failed page that getCurrentValue() throws, instead of throwing', async () => { + const subscription = paginatedSubscription(); + subscription.fail(new Error('page failed')); + + const { result, firstValue } = open(); + + expect(await settledState(firstValue)).toBe('rejected'); + expect(result.error?.message).toBe('page failed'); + }); +}); diff --git a/src/lib/use_paginated_query.svelte.ts b/src/lib/use_paginated_query.svelte.ts index 4ba4014..53f0d13 100644 --- a/src/lib/use_paginated_query.svelte.ts +++ b/src/lib/use_paginated_query.svelte.ts @@ -5,6 +5,7 @@ import { useConvexClient } from './client.svelte.js'; import { SKIP } from './shared/args.js'; import { parseArgsWithSkip } from './internal/args.svelte.js'; import { isClientActive } from './internal/client_status.js'; +import { subscribePaginated } from './shared/paginated_subscription.js'; import type { PageItem, PaginatedReturnType, @@ -134,50 +135,25 @@ export function usePaginatedQuery>( return; } - // Track if we've received data via callback to avoid duplicate processing - let hasReceivedUpdate = false; - - // Create subscription to Convex paginated query - const unsubscribe = client.onPaginatedUpdate_experimental( + // Subscribe; errors the client throws (e.g. for a failed page) reach the + // machine like errors from onError, and cleanup is always returned. + const unsubscribe = subscribePaginated( + client, query, - argsObject, - { initialNumItems: opts.initialNumItems }, - () => { - hasReceivedUpdate = true; - const current = unsubscribe.getCurrentValue?.(); - if (!current) return; - - // Feed update to state machine (handles hydration guard, etc.) + argsObject as FunctionArgs, + opts.initialNumItems, + (current) => machine.onUpdate({ results: current.results as PageItem[], status: current.status, loadMore: (numItems: number) => current.loadMore(numItems) - }); - }, - (error: Error) => { - hasReceivedUpdate = true; - // Feed error to state machine (handles InvalidCursor detection) - machine.onError(error); - // If InvalidCursor was detected, resetKey changed and effect will re-run - } + }), + // An InvalidCursor resets the machine (once), which changes resetKey + // and re-runs this effect. + (error) => machine.onError(error) ); - // Get initial cached value if available (only if callback hasn't fired synchronously) - if (!hasReceivedUpdate) { - const current = unsubscribe.getCurrentValue?.(); - if (current) { - machine.onUpdate({ - results: current.results as PageItem[], - status: current.status, - loadMore: (numItems: number) => current.loadMore(numItems) - }); - } - } - - // Cleanup on unmount or re-run - return () => { - unsubscribe.unsubscribe(); - }; + return unsubscribe; }); return { From 556756bc4815c9dcb78f575f37b89105f90dc35c Mon Sep 17 00:00:00 2001 From: Micha Mailaender <87228994+mmailaender@users.noreply.github.com> Date: Tue, 13 Oct 2026 10:23:02 +0200 Subject: [PATCH 2/2] Address review: don't retry when subscribing itself throws onPaginatedUpdate_experimental() registers the subscription before the cached-value lookup that throws for a failed page, and returns no handle to release it (get-convex/convex-js#193). The client shares one paginated query per args, so resubscribing after such an error fails the same way and leaves another registration behind. Report these errors as not retryable: the state machine surfaces them (also an InvalidCursor) instead of resetting, so usePaginatedQuery and the detached query don't resubscribe. --- src/lib/shared/paginated_query_state.spec.ts | 10 ++++++++++ src/lib/shared/paginated_query_state.ts | 7 +++++-- src/lib/shared/paginated_subscription.spec.ts | 13 +++++++++---- src/lib/shared/paginated_subscription.ts | 14 ++++++++++---- .../sveltekit/paginated-query-detached.svelte.ts | 4 ++-- src/lib/sveltekit/query-detached.spec.ts | 13 +++++++++++++ src/lib/use_paginated_query.svelte.ts | 4 ++-- 7 files changed, 51 insertions(+), 14 deletions(-) diff --git a/src/lib/shared/paginated_query_state.spec.ts b/src/lib/shared/paginated_query_state.spec.ts index 2bff589..d06ef12 100644 --- a/src/lib/shared/paginated_query_state.spec.ts +++ b/src/lib/shared/paginated_query_state.spec.ts @@ -259,6 +259,16 @@ describe('PaginatedQueryStateMachine InvalidCursor reset limit (#61)', () => { expect(machine.getSnapshot().error?.message).toContain('InvalidCursor'); }); + it('surfaces an InvalidCursor without resetting when allowReset is false', () => { + const machine = machineWithArgs(); + const before = machine.getSnapshot().resetKey; + + expect(machine.onError(invalidCursor(), { allowReset: false })).toBe(false); + + expect(machine.getSnapshot().resetKey).toBe(before); + expect(machine.getSnapshot().error?.message).toContain('InvalidCursor'); + }); + it('allows another reset once a page arrived', () => { const machine = machineWithArgs(); machine.onError(invalidCursor()); diff --git a/src/lib/shared/paginated_query_state.ts b/src/lib/shared/paginated_query_state.ts index 37d9a4e..ce24d0f 100644 --- a/src/lib/shared/paginated_query_state.ts +++ b/src/lib/shared/paginated_query_state.ts @@ -362,10 +362,13 @@ export class PaginatedQueryStateMachine { * * Detects InvalidCursor errors and triggers a pagination reset. * + * @param options.allowReset - `false` surfaces even an InvalidCursor as the + * error, e.g. when resubscribing can't help. * @returns `true` if we detected and handled an InvalidCursor (framework should resubscribe) */ - onError(error: Error): boolean { - if (this.isInvalidCursorError(error) && this.invalidCursorResetArmed) { + onError(error: Error, options: { allowReset?: boolean } = {}): boolean { + const allowReset = options.allowReset ?? true; + if (allowReset && this.isInvalidCursorError(error) && this.invalidCursorResetArmed) { this.invalidCursorResetArmed = false; console.warn('PaginatedQueryStateMachine: InvalidCursor detected, resetting:', error.message); this.pendingLoadMoreNumItems = null; diff --git a/src/lib/shared/paginated_subscription.spec.ts b/src/lib/shared/paginated_subscription.spec.ts index 115d8f7..0c239d6 100644 --- a/src/lib/shared/paginated_subscription.spec.ts +++ b/src/lib/shared/paginated_subscription.spec.ts @@ -39,13 +39,13 @@ describe('subscribePaginated', () => { onError ); - expect(onError).toHaveBeenCalledWith(new Error('page failed')); + expect(onError).toHaveBeenCalledWith(new Error('page failed'), true); expect(onSnapshot).not.toHaveBeenCalled(); cleanup(); expect(unsubscribe).toHaveBeenCalledOnce(); }); - it('reports an error thrown by onPaginatedUpdate_experimental itself', () => { + it('reports an error thrown by onPaginatedUpdate_experimental itself, as not retryable', () => { const onError = vi.fn(); const client = { onPaginatedUpdate_experimental: vi.fn(() => { @@ -55,7 +55,12 @@ describe('subscribePaginated', () => { const cleanup = subscribePaginated(client, ref, {}, 10, vi.fn(), onError); - expect(onError).toHaveBeenCalledWith(new Error('failed page held by another subscriber')); + // Not retryable: the client registered the subscription before throwing and + // shares it per args, so a retry would fail the same way (convex-js#193). + expect(onError).toHaveBeenCalledWith( + new Error('failed page held by another subscriber'), + false + ); expect(() => cleanup()).not.toThrow(); }); @@ -84,7 +89,7 @@ describe('subscribePaginated', () => { fail = true; notify(); - expect(onError).toHaveBeenCalledWith(new Error('page failed')); + expect(onError).toHaveBeenCalledWith(new Error('page failed'), true); }); it('delivers a snapshot the client reports synchronously while subscribing, once', () => { diff --git a/src/lib/shared/paginated_subscription.ts b/src/lib/shared/paginated_subscription.ts index 3c7e456..1605323 100644 --- a/src/lib/shared/paginated_subscription.ts +++ b/src/lib/shared/paginated_subscription.ts @@ -8,6 +8,12 @@ * holds the query in a failed state (get-convex/convex-js#193). Thrown errors * are reported through `onError` here, so callers always get a cleanup function * back and their state machine sees the error. + * + * When `onPaginatedUpdate_experimental()` throws, the client has already + * registered the subscription but returned no handle to release it — only a + * fix in the client can roll that back (convex-js#193). Such errors are + * reported as not retryable: the client shares one paginated query per args, so + * a retry would hit the same failure and leave another registration behind. */ import type { ConvexClient, PaginationStatus } from 'convex/browser'; import type { FunctionArgs, FunctionReference } from 'convex/server'; @@ -31,7 +37,7 @@ export function subscribePaginated>( args: FunctionArgs, initialNumItems: number, onSnapshot: (snapshot: PaginatedSnapshot) => void, - onError: (error: Error) => void + onError: (error: Error, retryable: boolean) => void ): () => void { let subscription: ReturnType | undefined; let failed = false; @@ -42,7 +48,7 @@ export function subscribePaginated>( current = subscription?.getCurrentValue() as PaginatedSnapshot | undefined; } catch (error) { failed = true; - onError(toError(error)); + onError(toError(error), true); return; } if (current) onSnapshot(current); @@ -60,11 +66,11 @@ export function subscribePaginated>( }, (error: Error) => { failed = true; - onError(error); + onError(error, true); } ); } catch (error) { - onError(toError(error)); + onError(toError(error), false); return () => {}; } diff --git a/src/lib/sveltekit/paginated-query-detached.svelte.ts b/src/lib/sveltekit/paginated-query-detached.svelte.ts index c2bd9b0..f2a7681 100644 --- a/src/lib/sveltekit/paginated-query-detached.svelte.ts +++ b/src/lib/sveltekit/paginated-query-detached.svelte.ts @@ -138,9 +138,9 @@ export function openDetachedPaginatedQuery { + const onError = (e: Error, retryable: boolean) => { if (subscriptionGeneration !== generation) return; - if (machine.onError(e)) { + if (machine.onError(e, { allowReset: retryable })) { // InvalidCursor: the machine reset pagination (once). Start over with // a fresh subscription; a load keeps waiting for its first page. queueMicrotask(restart); diff --git a/src/lib/sveltekit/query-detached.spec.ts b/src/lib/sveltekit/query-detached.spec.ts index b5c6a2f..7ea2bec 100644 --- a/src/lib/sveltekit/query-detached.spec.ts +++ b/src/lib/sveltekit/query-detached.spec.ts @@ -719,6 +719,19 @@ describe('openDetachedPaginatedQuery — failed pages (#61)', () => { expect(result.isLoading).toBe(false); }); + it('does not retry when subscribing itself throws (failed query held by another subscriber)', async () => { + client.onPaginatedUpdate_experimental.mockImplementationOnce(() => { + throw invalidCursor(); + }); + + const { result, firstValue } = open(); + await Promise.resolve(); + + expect(client.onPaginatedUpdate_experimental).toHaveBeenCalledOnce(); + expect(await settledState(firstValue)).toBe('rejected'); + expect(result.error?.message).toContain('InvalidCursor'); + }); + it('reports a failed page that getCurrentValue() throws, instead of throwing', async () => { const subscription = paginatedSubscription(); subscription.fail(new Error('page failed')); diff --git a/src/lib/use_paginated_query.svelte.ts b/src/lib/use_paginated_query.svelte.ts index 53f0d13..4d5d1ce 100644 --- a/src/lib/use_paginated_query.svelte.ts +++ b/src/lib/use_paginated_query.svelte.ts @@ -149,8 +149,8 @@ export function usePaginatedQuery>( loadMore: (numItems: number) => current.loadMore(numItems) }), // An InvalidCursor resets the machine (once), which changes resetKey - // and re-runs this effect. - (error) => machine.onError(error) + // and re-runs this effect — unless resubscribing can't help. + (error, retryable) => machine.onError(error, { allowReset: retryable }) ); return unsubscribe;