From 697764c7962f4c388b28b3a9649f4825f3ef44bf Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:52:43 +0100 Subject: [PATCH 1/2] perf(query-core): coalesce notifyManager flushes within the same synchronous tick Previously, TanStack Query's notifyManager called scheduleFn and batchNotifyFn once per top-level batch() call and bypassed batchNotifyFn for unbatched schedule() / batchCalls() calls. Coalesce all flushes and scheduled callbacks within the same synchronous tick into a single pending queue and single scheduleFn/batchNotifyFn invocation in FIFO order. Clear the pending queue on flush execution, synchronous scheduler errors, setScheduler(), and at the microtask boundary so dropped fake timers cannot wedge subsequent flushes. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../notify-manager-same-tick-coalescing.md | 5 + .../src/__tests__/notifyManager.test.tsx | 409 ++++++++++++++++++ packages/query-core/src/notifyManager.ts | 44 +- 3 files changed, 449 insertions(+), 9 deletions(-) create mode 100644 .changeset/notify-manager-same-tick-coalescing.md diff --git a/.changeset/notify-manager-same-tick-coalescing.md b/.changeset/notify-manager-same-tick-coalescing.md new file mode 100644 index 00000000000..7ce026d19ac --- /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 synchronous tick into a single scheduled batch. diff --git a/packages/query-core/src/__tests__/notifyManager.test.tsx b/packages/query-core/src/__tests__/notifyManager.test.tsx index adbf1f1030e..d85f182cca7 100644 --- a/packages/query-core/src/__tests__/notifyManager.test.tsx +++ b/packages/query-core/src/__tests__/notifyManager.test.tsx @@ -105,4 +105,413 @@ describe('notifyManager', () => { await vi.advanceTimersByTimeAsync(0) expect(callbackSpy).toHaveBeenCalledWith(1, 'test') }) + + it('should coalesce multiple top-level batch calls in the same synchronous tick', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch1-a')) + notifyManagerTest.schedule(() => order.push('batch1-b')) + }) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch2-a')) + }) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch3-a')) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(0) + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual([ + 'batch1-a', + 'batch1-b', + 'batch2-a', + 'batch3-a', + ]) + }) + + it('should coalesce unbatched schedule and batchCalls calls in the same synchronous tick', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + const batchedPush = notifyManagerTest.batchCalls((label: string) => { + order.push(label) + }) + + notifyManagerTest.schedule(() => order.push('schedule-1')) + batchedPush('batchCalls-1') + notifyManagerTest.schedule(() => order.push('schedule-2')) + batchedPush('batchCalls-2') + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual([ + 'schedule-1', + 'batchCalls-1', + 'schedule-2', + 'batchCalls-2', + ]) + }) + + it('should coalesce mixed batch, schedule, and batchCalls calls in FIFO order', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + const batchedPush = notifyManagerTest.batchCalls((label: string) => { + order.push(label) + }) + + notifyManagerTest.schedule(() => order.push('schedule-1')) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch1-a')) + batchedPush('batch1-b') + }) + batchedPush('batchCalls-1') + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch2-a')) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual([ + 'schedule-1', + 'batch1-a', + 'batch1-b', + 'batchCalls-1', + 'batch2-a', + ]) + }) + + it('should not wedge when fake timers drop a pending flush without running it', async () => { + const notifyManagerTest = createNotifyManager() + const droppedCallback = vi.fn<() => void>() + const nextCallback = vi.fn<() => void>() + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(droppedCallback) + }) + + // Simulate a test ending with fake timers active and never flushing them + vi.clearAllTimers() + vi.useRealTimers() + await Promise.resolve() + + vi.useFakeTimers() + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(nextCallback) + }) + + await vi.advanceTimersByTimeAsync(0) + + expect(droppedCallback).not.toHaveBeenCalled() + expect(nextCallback).toHaveBeenCalledTimes(1) + }) + + it('should support synchronous custom schedulers without double-running or flushing early', () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('first-a')) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('first-b')) + }) + expect(order).toStrictEqual([]) + expect(scheduleSpy).toHaveBeenCalledTimes(0) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual(['first-a', 'first-b']) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('second-a')) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(order).toStrictEqual(['first-a', 'first-b', 'second-a']) + }) + + it('should handle re-entrant scheduling during a synchronous custom scheduler flush', () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => { + order.push('first-a') + notifyManagerTest.schedule(() => order.push('reentrant')) + }) + notifyManagerTest.schedule(() => order.push('first-b')) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b']) + }) + + it('should queue re-entrant schedule and batch calls during flush for the next tick', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => { + order.push('tick1-a') + notifyManagerTest.schedule(() => order.push('tick2-a')) + }) + notifyManagerTest.schedule(() => { + order.push('tick1-b') + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('tick2-b')) + }) + }) + }) + + 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 recover cleanly when a callback throws during batchNotifyFn', async () => { + const notifyManagerTest = createNotifyManager() + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const afterErrorCallback = vi.fn<() => void>() + + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => { + throw new Error('flush failure') + }) + }) + + expect(() => vi.advanceTimersByTime(0)).toThrow('flush failure') + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(afterErrorCallback) + }) + + await vi.advanceTimersByTimeAsync(0) + + expect(afterErrorCallback).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + }) + + it('should still coalesce and flush callbacks when a subsequent batch in the same tick throws', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch1')) + }) + + expect(() => { + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('batch2-before-throw')) + throw new Error('batch failure') + }) + }).toThrow('batch failure') + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual(['batch1', 'batch2-before-throw']) + }) + + it('should recover cleanly when a custom scheduler throws synchronously', async () => { + const notifyManagerTest = createNotifyManager() + let shouldThrow = true + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + if (shouldThrow) { + throw new Error('scheduler failure') + } + setTimeout(cb, 0) + }) + const callbackSpy = vi.fn<() => void>() + + notifyManagerTest.setScheduler(scheduleSpy) + + expect(() => { + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(vi.fn()) + }) + }).toThrow('scheduler failure') + + shouldThrow = false + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(callbackSpy) + }) + + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + expect(callbackSpy).toHaveBeenCalledTimes(1) + }) + + it('should schedule a new flush across separate ticks', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('tick1')) + }) + + // Cross the microtask boundary before the first timer fires + await Promise.resolve() + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('tick2')) + }) + + expect(scheduleSpy).toHaveBeenCalledTimes(2) + + await vi.advanceTimersByTimeAsync(0) + + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(order).toStrictEqual(['tick1', 'tick2']) + + // Also verify scheduling after a completed flush + notifyManagerTest.schedule(() => order.push('tick3')) + await vi.advanceTimersByTimeAsync(0) + + expect(scheduleSpy).toHaveBeenCalledTimes(3) + expect(batchNotifySpy).toHaveBeenCalledTimes(3) + expect(order).toStrictEqual(['tick1', 'tick2', 'tick3']) + }) + + it('should coalesce same-tick batches when using queueMicrotask as scheduler', async () => { + const notifyManagerTest = createNotifyManager() + const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => + queueMicrotask(cb), + ) + const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const order: Array = [] + + notifyManagerTest.setScheduler(scheduleSpy) + notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => { + order.push('first-a') + notifyManagerTest.schedule(() => order.push('second-a')) + }) + }) + notifyManagerTest.batch(() => { + notifyManagerTest.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(scheduleSpy).toHaveBeenCalledTimes(2) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + }) + + it('should not coalesce into a previous scheduler after setScheduler is called', async () => { + const notifyManagerTest = createNotifyManager() + const firstScheduler = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const secondScheduler = vi.fn<(cb: () => void) => void>((cb) => { + setTimeout(cb, 0) + }) + const order: Array = [] + + notifyManagerTest.setScheduler(firstScheduler) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('first')) + }) + + notifyManagerTest.setScheduler(secondScheduler) + notifyManagerTest.batch(() => { + notifyManagerTest.schedule(() => order.push('second')) + }) + + expect(firstScheduler).toHaveBeenCalledTimes(1) + expect(secondScheduler).toHaveBeenCalledTimes(1) + + await vi.advanceTimersByTimeAsync(0) + expect(order).toStrictEqual(['first', 'second']) + }) }) diff --git a/packages/query-core/src/notifyManager.ts b/packages/query-core/src/notifyManager.ts index ffd507f8854..ad573e02fef 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,47 @@ 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 => { + if (!queue.length) { + return + } + if (pendingQueue) { + for (const callback of queue) { + pendingQueue.push(callback) + } + queue.length = 0 + return + } const originalQueue = queue queue = [] - if (originalQueue.length) { + 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 same-tick window at the microtask boundary so dropped timers + // (for example, fake timers cleared in tests) cannot wedge future flushes. + if (pendingQueue === originalQueue) { + queueMicrotask(clearPending) } } @@ -62,6 +85,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 synchronous 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 +119,7 @@ export function createNotifyManager() { }, /** * Schedules a function to be run on the next batch. + * Multiple calls within the same synchronous 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 +167,7 @@ export function createNotifyManager() { */ setScheduler: (fn: ScheduleFunction) => { scheduleFn = fn + pendingQueue = undefined }, } as const } From b2fcb2745e0c32f961503b34ea743089822c7957 Mon Sep 17 00:00:00 2001 From: Manuel Schiller <6340397+schiller-manuel@users.noreply.github.com> Date: Fri, 4 Dec 2026 19:30:44 +0100 Subject: [PATCH 2/2] fix(query-core): close notifyManager coalescing window with Promise job Use Promise.resolve().then(clearPending) instead of queueMicrotask so fake timers that mock queueMicrotask (such as Jest defaults or Vitest with queueMicrotask in toFake) cannot stall subsequent TanStack Query flushes when timers are cleared. Reset queue before the pendingQueue coalescing check to simplify flush and trim bundle size, update JSDoc and changeset wording, and consolidate notifyManager tests with coverage for faked queueMicrotask recovery and microtask window boundaries. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../notify-manager-same-tick-coalescing.md | 2 +- .../src/__tests__/notifyManager.test.tsx | 518 +++++------------- packages/query-core/src/notifyManager.ts | 22 +- 3 files changed, 163 insertions(+), 379 deletions(-) diff --git a/.changeset/notify-manager-same-tick-coalescing.md b/.changeset/notify-manager-same-tick-coalescing.md index 7ce026d19ac..025f9934a07 100644 --- a/.changeset/notify-manager-same-tick-coalescing.md +++ b/.changeset/notify-manager-same-tick-coalescing.md @@ -2,4 +2,4 @@ '@tanstack/query-core': patch --- -Coalesce `notifyManager` flushes and scheduled callbacks within the same synchronous tick into a single scheduled batch. +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 d85f182cca7..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,501 +25,270 @@ 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 notifyManagerTest = createNotifyManager() - const notifySpy = vi.fn<(callback: () => void) => void>() - notifyManagerTest.setScheduler(customCallback) - notifyManagerTest.setNotifyFunction(notifySpy) - - notifyManagerTest.batch(() => notifyManagerTest.schedule(vi.fn)) - - expect(customCallback).toHaveBeenCalledTimes(1) - await vi.advanceTimersByTimeAsync(0) - expect(notifySpy).toHaveBeenCalledTimes(1) - }) - - it('should notify if error is thrown', async () => { - const notifyManagerTest = createNotifyManager() - const notifySpy = vi.fn<(callback: () => void) => void>() - - notifyManagerTest.setNotifyFunction(notifySpy) - - try { - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(vi.fn) - throw new Error('Foo') - }) - } catch {} - - await vi.advanceTimersByTimeAsync(0) - expect(notifySpy).toHaveBeenCalledTimes(1) - }) - - 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>() - - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(callbackSpy1) - notifyManagerTest.schedule(callbackSpy2) - }) - - await vi.advanceTimersByTimeAsync(0) - expect(batchNotifySpy).toHaveBeenCalledWith(expect.any(Function)) - expect(callbackSpy1).toHaveBeenCalledWith() - expect(callbackSpy2).toHaveBeenCalledWith() - }) - - it('should batch calls correctly', async () => { - const notifyManagerTest = createNotifyManager() - const callbackSpy = vi.fn<(a: number, b: string) => void>() - - const batchedFn = notifyManagerTest.batchCalls((a: number, b: string) => { - callbackSpy(a, b) - }) - - batchedFn(1, 'test') - await vi.advanceTimersByTimeAsync(0) - expect(callbackSpy).toHaveBeenCalledWith(1, 'test') - }) - - it('should coalesce multiple top-level batch calls in the same synchronous tick', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + const notifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) const order: Array = [] + manager.setNotifyFunction(notifySpy) - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch1-a')) - notifyManagerTest.schedule(() => order.push('batch1-b')) - }) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch2-a')) - }) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch3-a')) - }) + 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) - expect(batchNotifySpy).toHaveBeenCalledTimes(0) - await vi.advanceTimersByTimeAsync(0) - - expect(scheduleSpy).toHaveBeenCalledTimes(1) + await Promise.resolve() + expect(order).toStrictEqual(['first-a', 'first-b']) + expect(scheduleSpy).toHaveBeenCalledTimes(2) expect(batchNotifySpy).toHaveBeenCalledTimes(1) - expect(order).toStrictEqual([ - 'batch1-a', - 'batch1-b', - 'batch2-a', - 'batch3-a', - ]) - }) - - it('should coalesce unbatched schedule and batchCalls calls in the same synchronous tick', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - const batchedPush = notifyManagerTest.batchCalls((label: string) => { - order.push(label) - }) - notifyManagerTest.schedule(() => order.push('schedule-1')) - batchedPush('batchCalls-1') - notifyManagerTest.schedule(() => order.push('schedule-2')) - batchedPush('batchCalls-2') - - expect(scheduleSpy).toHaveBeenCalledTimes(1) - - await vi.advanceTimersByTimeAsync(0) - - expect(scheduleSpy).toHaveBeenCalledTimes(1) - expect(batchNotifySpy).toHaveBeenCalledTimes(1) - expect(order).toStrictEqual([ - 'schedule-1', - 'batchCalls-1', - 'schedule-2', - 'batchCalls-2', - ]) + await Promise.resolve() + expect(order).toStrictEqual(['first-a', 'first-b', 'second-a']) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(notifySpy).toHaveBeenCalledTimes(3) }) - it('should coalesce mixed batch, schedule, and batchCalls calls in FIFO order', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + it('should coalesce batch, schedule, and batchCalls in FIFO order', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - const batchedPush = notifyManagerTest.batchCalls((label: string) => { - order.push(label) + const batchedPush = manager.batchCalls((label: string, n: number) => { + order.push(`${label}-${n}`) }) - notifyManagerTest.schedule(() => order.push('schedule-1')) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch1-a')) - batchedPush('batch1-b') - }) - batchedPush('batchCalls-1') - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch2-a')) + 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', - 'batchCalls-1', + 'batch1-b-1', + 'batchCalls-2', 'batch2-a', + 'schedule-2', ]) }) - it('should not wedge when fake timers drop a pending flush without running it', async () => { - const notifyManagerTest = createNotifyManager() - const droppedCallback = vi.fn<() => void>() - const nextCallback = vi.fn<() => void>() - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(droppedCallback) - }) + 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>() - // Simulate a test ending with fake timers active and never flushing them + manager.batch(() => manager.schedule(dropped)) vi.clearAllTimers() vi.useRealTimers() await Promise.resolve() - vi.useFakeTimers() - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(nextCallback) - }) - + vi.useFakeTimers({ toFake: [...toFake] }) + manager.batch(() => manager.schedule(next)) await vi.advanceTimersByTimeAsync(0) - expect(droppedCallback).not.toHaveBeenCalled() - expect(nextCallback).toHaveBeenCalledTimes(1) + expect(dropped).not.toHaveBeenCalled() + expect(next).toHaveBeenCalledTimes(1) }) - it('should support synchronous custom schedulers without double-running or flushing early', () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + it('should support synchronous schedulers with nesting and reentrant calls', () => { + const { manager, scheduleSpy, batchNotifySpy } = setup((cb) => cb()) const order: Array = [] - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('first-a')) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('first-b')) + 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(1) - expect(batchNotifySpy).toHaveBeenCalledTimes(1) - expect(order).toStrictEqual(['first-a', 'first-b']) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('second-a')) - }) - expect(scheduleSpy).toHaveBeenCalledTimes(2) expect(batchNotifySpy).toHaveBeenCalledTimes(2) - expect(order).toStrictEqual(['first-a', 'first-b', 'second-a']) - }) - - it('should handle re-entrant scheduling during a synchronous custom scheduler flush', () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) + expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b']) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => { - order.push('first-a') - notifyManagerTest.schedule(() => order.push('reentrant')) - }) - notifyManagerTest.schedule(() => order.push('first-b')) - }) + manager.batch(() => manager.schedule(() => order.push('second-a'))) - expect(scheduleSpy).toHaveBeenCalledTimes(2) - expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b']) + expect(scheduleSpy).toHaveBeenCalledTimes(3) + expect(batchNotifySpy).toHaveBeenCalledTimes(3) + expect(order).toStrictEqual(['first-a', 'reentrant', 'first-b', 'second-a']) }) - it('should queue re-entrant schedule and batch calls during flush for the next tick', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) + it('should queue re-entrant calls during flush for the next tick', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() const order: Array = [] - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => { + manager.batch(() => { + manager.schedule(() => { order.push('tick1-a') - notifyManagerTest.schedule(() => order.push('tick2-a')) + manager.schedule(() => order.push('tick2-a')) }) - notifyManagerTest.schedule(() => { + manager.schedule(() => { order.push('tick1-b') - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('tick2-b')) - }) + manager.batch(() => manager.schedule(() => order.push('tick2-b'))) }) }) 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 recover cleanly when a callback throws during batchNotifyFn', async () => { - const notifyManagerTest = createNotifyManager() - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const afterErrorCallback = vi.fn<() => void>() - - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => { - throw new Error('flush failure') - }) - }) - - expect(() => vi.advanceTimersByTime(0)).toThrow('flush failure') + it('should still coalesce and flush callbacks when a batch throws', async () => { + const { manager, scheduleSpy, batchNotifySpy } = setup() + const order: Array = [] - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(afterErrorCallback) - }) + 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(afterErrorCallback).toHaveBeenCalledTimes(1) - expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(scheduleSpy).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(1) + expect(order).toStrictEqual(['batch1', 'batch2']) }) - it('should still coalesce and flush callbacks when a subsequent batch in the same tick throws', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) + 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>() - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch1')) + manager.batch(() => { + manager.schedule(() => { + throw new Error('flush failure') + }) + manager.schedule(skipped) }) - expect(() => { - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('batch2-before-throw')) - throw new Error('batch failure') - }) - }).toThrow('batch failure') + expect(() => vi.advanceTimersByTime(0)).toThrow('flush failure') + expect(skipped).not.toHaveBeenCalled() + manager.batch(() => manager.schedule(recovered)) await vi.advanceTimersByTimeAsync(0) - expect(scheduleSpy).toHaveBeenCalledTimes(1) - expect(batchNotifySpy).toHaveBeenCalledTimes(1) - expect(order).toStrictEqual(['batch1', 'batch2-before-throw']) + expect(recovered).toHaveBeenCalledTimes(1) + expect(batchNotifySpy).toHaveBeenCalledTimes(2) }) it('should recover cleanly when a custom scheduler throws synchronously', async () => { - const notifyManagerTest = createNotifyManager() let shouldThrow = true - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - if (shouldThrow) { - throw new Error('scheduler failure') - } + const { manager, scheduleSpy } = setup((cb) => { + if (shouldThrow) throw new Error('scheduler failure') setTimeout(cb, 0) }) const callbackSpy = vi.fn<() => void>() - notifyManagerTest.setScheduler(scheduleSpy) - - expect(() => { - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(vi.fn()) - }) - }).toThrow('scheduler failure') + expect(() => manager.batch(() => manager.schedule(vi.fn()))).toThrow( + 'scheduler failure', + ) shouldThrow = false - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(callbackSpy) - }) - + manager.batch(() => manager.schedule(callbackSpy)) await vi.advanceTimersByTimeAsync(0) expect(scheduleSpy).toHaveBeenCalledTimes(2) expect(callbackSpy).toHaveBeenCalledTimes(1) }) - it('should schedule a new flush across separate ticks', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) + 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() }) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('tick1')) - }) + 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')), + ) - // Cross the microtask boundary before the first timer fires await Promise.resolve() - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('tick2')) - }) - + await Promise.resolve() expect(scheduleSpy).toHaveBeenCalledTimes(2) await vi.advanceTimersByTimeAsync(0) + expect(batches).toStrictEqual([['sync', 'before'], ['after']]) - expect(batchNotifySpy).toHaveBeenCalledTimes(2) - expect(order).toStrictEqual(['tick1', 'tick2']) - - // Also verify scheduling after a completed flush - notifyManagerTest.schedule(() => order.push('tick3')) + manager.schedule(() => currentBatch.push('next-tick')) await vi.advanceTimersByTimeAsync(0) expect(scheduleSpy).toHaveBeenCalledTimes(3) - expect(batchNotifySpy).toHaveBeenCalledTimes(3) - expect(order).toStrictEqual(['tick1', 'tick2', 'tick3']) - }) - - it('should coalesce same-tick batches when using queueMicrotask as scheduler', async () => { - const notifyManagerTest = createNotifyManager() - const scheduleSpy = vi.fn<(cb: () => void) => void>((cb) => - queueMicrotask(cb), - ) - const batchNotifySpy = vi.fn<(cb: () => void) => void>((cb) => cb()) - const order: Array = [] - - notifyManagerTest.setScheduler(scheduleSpy) - notifyManagerTest.setBatchNotifyFunction(batchNotifySpy) - - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => { - order.push('first-a') - notifyManagerTest.schedule(() => order.push('second-a')) - }) - }) - notifyManagerTest.batch(() => { - notifyManagerTest.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(scheduleSpy).toHaveBeenCalledTimes(2) - expect(batchNotifySpy).toHaveBeenCalledTimes(2) + expect(batches).toStrictEqual([ + ['sync', 'before'], + ['after'], + ['next-tick'], + ]) }) - it('should not coalesce into a previous scheduler after setScheduler is called', async () => { - const notifyManagerTest = createNotifyManager() - const firstScheduler = vi.fn<(cb: () => void) => void>((cb) => { - setTimeout(cb, 0) - }) + 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 = [] - notifyManagerTest.setScheduler(firstScheduler) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('first')) - }) - - notifyManagerTest.setScheduler(secondScheduler) - notifyManagerTest.batch(() => { - notifyManagerTest.schedule(() => order.push('second')) - }) + 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) diff --git a/packages/query-core/src/notifyManager.ts b/packages/query-core/src/notifyManager.ts index ad573e02fef..7822e51fe26 100644 --- a/packages/query-core/src/notifyManager.ts +++ b/packages/query-core/src/notifyManager.ts @@ -42,18 +42,17 @@ export function createNotifyManager() { } } const flush = (): void => { - if (!queue.length) { + const originalQueue = queue + if (!originalQueue.length) { return } + queue = [] if (pendingQueue) { - for (const callback of queue) { + for (const callback of originalQueue) { pendingQueue.push(callback) } - queue.length = 0 return } - const originalQueue = queue - queue = [] pendingQueue = originalQueue const clearPending = () => { if (pendingQueue === originalQueue) { @@ -73,10 +72,13 @@ export function createNotifyManager() { clearPending() throw error } - // Close the same-tick window at the microtask boundary so dropped timers - // (for example, fake timers cleared in tests) cannot wedge future flushes. + // 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) { - queueMicrotask(clearPending) + void Promise.resolve().then(clearPending) } } @@ -85,7 +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 synchronous tick are coalesced into a single scheduled batch. + * 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`. @@ -119,7 +121,7 @@ export function createNotifyManager() { }, /** * Schedules a function to be run on the next batch. - * Multiple calls within the same synchronous tick are coalesced into a single scheduled 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,