Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/notify-manager-same-tick-coalescing.md
Original file line number Diff line number Diff line change
@@ -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.
305 changes: 248 additions & 57 deletions packages/query-core/src/__tests__/notifyManager.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
Expand All @@ -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<void>>(() => 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<void>>(() => 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<string> = []
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<string> = []
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<string> = []

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<string> = []

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<string> = []

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<Array<string>> = []
let currentBatch: Array<string> = []
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<string> = []

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'])
})
})
Loading
Loading