diff --git a/.changeset/notify-manager-same-tick-coalescing.md b/.changeset/notify-manager-same-tick-coalescing.md new file mode 100644 index 00000000000..025f9934a07 --- /dev/null +++ b/.changeset/notify-manager-same-tick-coalescing.md @@ -0,0 +1,5 @@ +--- +'@tanstack/query-core': patch +--- + +Coalesce `notifyManager` flushes and scheduled callbacks within the same tick into a single scheduled batch. Unbatched `schedule()` and `batchCalls()` callbacks now also run inside `batchNotifyFn`, coalesced callbacks can run before timers or microtasks queued between flushes (so fewer intermediate renders may be observed), and an error thrown by one callback skips remaining callbacks in that task. diff --git a/packages/query-core/src/__tests__/notifyManager.test.tsx b/packages/query-core/src/__tests__/notifyManager.test.tsx index adbf1f1030e..213463055ae 100644 --- a/packages/query-core/src/__tests__/notifyManager.test.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test.tsx @@ -3,6 +3,19 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createNotifyManager } from '../notifyManager' describe('notifyManager', () => { + const setup = ( + scheduler: (cb: () => void) => void = (cb) => { + setTimeout(cb, 0) + }, + ) => { + const manager = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>(scheduler) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + manager.setScheduler(scheduleSpy) + manager.setBatchNotifyFunction(batchNotifySpy) + return { manager, scheduleSpy, batchNotifySpy } + } + beforeEach(() => { vi.useFakeTimers() }) @@ -12,97 +25,275 @@ describe('notifyManager', () => { }) it('should use default notifyFn', async () => { - const notifyManagerTest = createNotifyManager() + const manager = createNotifyManager() const callbackSpy = vi.fn<() => void>() - notifyManagerTest.schedule(callbackSpy) + manager.schedule(callbackSpy) await vi.advanceTimersByTimeAsync(0) expect(callbackSpy).toHaveBeenCalledWith() }) - it('should use default batchNotifyFn', async () => { - const notifyManagerTest = createNotifyManager() - const callbackScheduleSpy = vi.fn<() => Promise>(() => sleep(20)) - const callbackBatchLevel2Spy = vi - .fn<() => void>() - .mockImplementation(() => { - notifyManagerTest.schedule(callbackScheduleSpy) - }) - const callbackBatchLevel1Spy = vi - .fn<() => void>() - .mockImplementation(() => { - notifyManagerTest.batch(callbackBatchLevel2Spy) - }) - notifyManagerTest.batch(callbackBatchLevel1Spy) + it('should use default batchNotifyFn with nested batches', async () => { + const manager = createNotifyManager() + const scheduleSpy = vi.fn<() => Promise>(() => sleep(20)) + const level2 = vi.fn<() => void>(() => manager.schedule(scheduleSpy)) + const level1 = vi.fn<() => void>(() => manager.batch(level2)) + manager.batch(level1) await vi.advanceTimersByTimeAsync(0) - expect(callbackBatchLevel1Spy).toHaveBeenCalledTimes(1) - expect(callbackBatchLevel2Spy).toHaveBeenCalledTimes(1) - expect(callbackScheduleSpy).toHaveBeenCalledTimes(1) + + expect(level1).toHaveBeenCalledTimes(1) + expect(level2).toHaveBeenCalledTimes(1) + expect(scheduleSpy).toHaveBeenCalledTimes(1) }) - it('should use a custom scheduler when configured', async () => { - const customCallback = vi.fn<(callback: () => void) => void>((cb) => + it('should use a custom scheduler and notifyFn with coalescing', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup((cb) => queueMicrotask(cb), ) + const notifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + manager.setNotifyFunction(notifySpy) + + manager.batch(() => + manager.schedule(() => { + order.push('first-a') + manager.schedule(() => order.push('second-a')) + }), + ) + manager.batch(() => manager.schedule(() => order.push('first-b'))) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + + await Promise.resolve() + expect(order).toStrictEqual(['first-a', 'first-b']) + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + + await Promise.resolve() + expect(order).toStrictEqual(['first-a', 'first-b', 'second-a']) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(notifySpy).toHaveBeenCalledTimes(3) + }) + + it('should coalesce batch, schedule, and batchCalls in FIFO order', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() + const order: Array = [] + const batchedPush = manager.batchCalls((label: string, n: number) => { + order.push(`${label}-${n}`) + }) + + manager.schedule(() => order.push('schedule-1')) + manager.batch(() => { + manager.schedule(() => order.push('batch1-a')) + batchedPush('batch1-b', 1) + }) + batchedPush('batchCalls', 2) + manager.batch(() => manager.schedule(() => order.push('batch2-a'))) + manager.schedule(() => order.push('schedule-2')) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(0) + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) + expect(order).toStrictEqual([ + 'schedule-1', + 'batch1-a', + 'batch1-b-1', + 'batchCalls-2', + 'batch2-a', + 'schedule-2', + ]) + }) - const notifyManagerTest = createNotifyManager() - const notifySpy = vi.fn<(callback: () => void) => void>() - notifyManagerTest.setScheduler(customCallback) - notifyManagerTest.setNotifyFunction(notifySpy) + it('should not wedge when fake timers drop a pending flush', async () => { + const toFake = ['setTimeout', 'clearTimeout', 'queueMicrotask'] as const + vi.useFakeTimers({ toFake: [...toFake] }) + const manager = createNotifyManager() + const dropped = vi.fn<() => void>() + const next = vi.fn<() => void>() - notifyManagerTest.batch(() => notifyManagerTest.schedule(vi.fn)) + manager.batch(() => manager.schedule(dropped)) + vi.clearAllTimers() + vi.useRealTimers() + await Promise.resolve() - expect(customCallback).toHaveBeenCalledTimes(1) + vi.useFakeTimers({ toFake: [...toFake] }) + manager.batch(() => manager.schedule(next)) await vi.advanceTimersByTimeAsync(0) - expect(notifySpy).toHaveBeenCalledTimes(1) + + expect(dropped).not.toHaveBeenCalled() + expect(next).toHaveBeenCalledTimes(1) }) - it('should notify if error is thrown', async () => { - const notifyManagerTest = createNotifyManager() - const notifySpy = vi.fn<(callback: () => void) => void>() + it('should support synchronous schedulers with nesting and reentrant calls', () => { + const { manager, scheduleSpy, batchNotifySpy } = setup((cb) => cb()) + const order: Array = [] + + manager.batch(() => { + manager.schedule(() => { + order.push('first-a') + manager.schedule(() => order.push('reentrant')) + }) + manager.batch(() => manager.schedule(() => order.push('first-b'))) + expect(order).toStrictEqual([]) + expect(scheduleSpy).toHaveBeenCalledTimes(0) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b']) + + manager.batch(() => manager.schedule(() => order.push('second-a'))) + + expect(scheduleSpy).toHaveBeenCalledTimes(3) + expect(batchNotifySpy).toHaveBeenCalledTimes(3) + expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b', 'second-a']) + }) - notifyManagerTest.setNotifyFunction(notifySpy) + it('should queue re-entrant calls during flush for the next tick', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() + const order: Array = [] - try { - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(vi.fn) - throw new Error('Foo') + manager.batch(() => { + manager.schedule(() => { + order.push('tick1-a') + manager.schedule(() => order.push('tick2-a')) + }) + manager.schedule(() => { + order.push('tick1-b') + manager.batch(() => manager.schedule(() => order.push('tick2-b'))) }) - } catch {} + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + + await vi.runOnlyPendingTimersAsync() + expect(order).toStrictEqual(['tick1-a', 'tick1-b']) + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + + await vi.runOnlyPendingTimersAsync() + expect(order).toStrictEqual(['tick1-a', 'tick1-b', 'tick2-a', 'tick2-b']) + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + }) + + it('should still coalesce and flush callbacks when a batch throws', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() + const order: Array = [] + + manager.batch(() => manager.schedule(() => order.push('batch1'))) + expect(() => + manager.batch(() => { + manager.schedule(() => order.push('batch2')) + throw new Error('batch failure') + }), + ).toThrow('batch failure') await vi.advanceTimersByTimeAsync(0) - expect(notifySpy).toHaveBeenCalledTimes(1) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual(['batch1', 'batch2']) }) - it('should use custom batch notify function', async () => { - const notifyManagerTest = createNotifyManager() - const batchNotifySpy = vi.fn<(callback: () => void) => void>((cb) => cb()) - const callbackSpy1 = vi.fn<() => void>() - const callbackSpy2 = vi.fn<() => void>() + it('should skip remaining callbacks and recover on callback error', async () => { + const { manager, batchNotifySpy } = setup() + const skipped = vi.fn<() => void>() + const recovered = vi.fn<() => void>() + + manager.batch(() => { + manager.schedule(() => { + throw new Error('flush failure') + }) + manager.schedule(skipped) + }) + + expect(() => vi.advanceTimersByTime(0)).toThrow('flush failure') + expect(skipped).not.toHaveBeenCalled() + + manager.batch(() => manager.schedule(recovered)) + await vi.advanceTimersByTimeAsync(0) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + expect(recovered).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + }) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(callbackSpy1) - notifyManagerTest.schedule(callbackSpy2) + it('should recover cleanly when a custom scheduler throws synchronously', async () => { + let shouldThrow = true + const { manager, scheduleSpy } = setup((cb) => { + if (shouldThrow) throw new Error('scheduler failure') + setTimeout(cb, 0) }) + const callbackSpy = vi.fn<() => void>() + + expect(() => manager.batch(() => manager.schedule(vi.fn()))).toThrow( + 'scheduler failure', + ) + shouldThrow = false + manager.batch(() => manager.schedule(callbackSpy)) await vi.advanceTimersByTimeAsync(0) - expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) - expect(callbackSpy1).toHaveBeenCalledWith() - expect(callbackSpy2).toHaveBeenCalledWith() + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(callbackSpy).toHaveBeenCalledTimes(1) }) - it('should batch calls correctly', async () => { - const notifyManagerTest = createNotifyManager() - const callbackSpy = vi.fn<(a: number, b: string) => void>() + it('should coalesce prior microtasks, but separate later microtasks and ticks', async () => { + const { manager, scheduleSpy } = setup() + const batches: Array> = [] + let currentBatch: Array = [] + manager.setBatchNotifyFunction((cb) => { + currentBatch = [] + batches.push(currentBatch) + cb() + }) + + void Promise.resolve().then(() => + manager.schedule(() => currentBatch.push('before')), + ) + manager.batch(() => manager.schedule(() => currentBatch.push('sync'))) + void Promise.resolve().then(() => + manager.schedule(() => currentBatch.push('after')), + ) - const batchedFn = notifyManagerTest.batchCalls((a: number, b: string) => { - callbackSpy(a, b) + await Promise.resolve() + await Promise.resolve() + expect(scheduleSpy).toHaveBeenCalledTimes(2) + + await vi.advanceTimersByTimeAsync(0) + expect(batches).toStrictEqual([['sync', 'before'], ['after']]) + + manager.schedule(() => currentBatch.push('next-tick')) + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(3) + expect(batches).toStrictEqual([ + ['sync', 'before'], + ['after'], + ['next-tick'], + ]) + }) + + it('should reset the coalescing window when setScheduler is called', async () => { + const { manager, scheduleSpy: firstScheduler } = setup() + const secondScheduler = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) }) + const order: Array = [] + + manager.batch(() => manager.schedule(() => order.push('first'))) + manager.setScheduler(secondScheduler) + manager.batch(() => manager.schedule(() => order.push('second'))) + + expect(firstScheduler).toHaveBeenCalledTimes(1) + expect(secondScheduler).toHaveBeenCalledTimes(1) - batchedFn(1, 'test') await vi.advanceTimersByTimeAsync(0) - expect(callbackSpy).toHaveBeenCalledWith(1, 'test') + expect(order).toStrictEqual(['first', 'second']) }) }) diff --git a/packages/query-core/src/notifyManager.ts b/packages/query-core/src/notifyManager.ts index ffd507f8854..7822e51fe26 100644 --- a/packages/query-core/src/notifyManager.ts +++ b/packages/query-core/src/notifyManager.ts @@ -19,12 +19,13 @@ type ScheduleFunction = (callback: () => void) => void export const defaultScheduler: ScheduleFunction = systemSetTimeoutZero /** - * Creates a notify manager, which schedules and batches notifications to subscribers. Query uses a - * single instance of it, exported as {@link notifyManager}. + * Creates a notify manager, which schedules and batches notifications to subscribers. TanStack Query + * uses a single instance of it, exported as {@link notifyManager}. * @returns A new notify manager. */ export function createNotifyManager() { let queue: Array = [] + let pendingQueue: Array | undefined let transactions = 0 let notifyFn: NotifyFunction = (callback) => { callback() @@ -35,25 +36,49 @@ export function createNotifyManager() { let scheduleFn = defaultScheduler const schedule = (callback: NotifyCallback): void => { - if (transactions) { - queue.push(callback) - } else { - scheduleFn(() => { - notifyFn(callback) - }) + queue.push(callback) + if (!transactions) { + flush() } } const flush = (): void => { const originalQueue = queue + if (!originalQueue.length) { + return + } queue = [] - if (originalQueue.length) { + if (pendingQueue) { + for (const callback of originalQueue) { + pendingQueue.push(callback) + } + return + } + pendingQueue = originalQueue + const clearPending = () => { + if (pendingQueue === originalQueue) { + pendingQueue = undefined + } + } + try { scheduleFn(() => { + clearPending() batchNotifyFn(() => { originalQueue.forEach((callback) => { notifyFn(callback) }) }) }) + } catch (error) { + clearPending() + throw error + } + // Close the window at the end of this tick even if the task is dropped (e.g. fake + // timers cleared). A promise job is used because fake timers (including Jest's + // defaults) can fake queueMicrotask, but not native promises. Note: callbacks + // scheduled later in the same tick right after timers are dropped still join that + // dropped task, bounded to this tick. + if (pendingQueue === originalQueue) { + void Promise.resolve().then(clearPending) } } @@ -62,6 +87,7 @@ export function createNotifyManager() { * Batches all updates scheduled inside the passed callback. * This is mainly used internally to optimize query client updating. * Batches can be nested; the queue is only flushed once the outermost `batch` call finishes. + * Multiple flushes within the same tick are coalesced into a single scheduled batch. * The return value of `callback` is passed through. * @param callback - The function to run in the batch. * @returns The return value of `callback`. @@ -95,6 +121,7 @@ export function createNotifyManager() { }, /** * Schedules a function to be run on the next batch. + * Multiple calls within the same tick are coalesced into a single scheduled batch. * By default, the batch is run with a `setTimeout`, but this can be configured via `setScheduler`. */ schedule, @@ -142,6 +169,7 @@ export function createNotifyManager() { */ setScheduler: (fn: ScheduleFunction) => { scheduleFn = fn + pendingQueue = undefined }, } as const }