fix: falsy queue items, AsyncRetryer memory leak, wait bypass, and Awaited return types #246
main fromrefs/pull/246/head·merged by KevinVandy @tanstack/pacer#
- AsyncQueuer / Queuer — falsy items (
0,'',false) are no longer silently skipped by the processing loop (=== undefinedcheck), andaddItem(null)no longer throws reading.priority. Closes #200 - AsyncRetryer — removed the devtools event-client integration. Retryers are created per-execution by the async utils, so every execution permanently accumulated an event listener, a live registry entry (
"<key>-retryer-N", or"undefined-retryer-N"with no key), and queued devtools events — unbounded memory growth, worst in Node. No devtools package ever consumed retryer events, so no functionality is lost; parents now passasyncRetryerOptionsthrough unmodified andkeyremains a plain identifier. Closes #198 - AsyncQueuer —
pendingTicknow staystruewhile executions or wait timers are pending (matching the sync Queuer), soaddItem()during thewaitwindow no longer triggers immediate processing. Task errors no longer kill the processing chain or emit unhandled rejections, andflush/flushAsBatchrestart the tick chain they interrupt. Closes #188 - AsyncDebouncer / AsyncThrottler / AsyncRateLimiter —
maybeExecute,flush,lastResultstate, andonSuccess(plus theasyncDebounce/asyncThrottle/asyncRateLimithelpers) now useAwaited<ReturnType<TFn>>instead of double-wrapping promises. Closes #156
@tanstack/react-pacer, @tanstack/preact-pacer#
useAsyncDebouncedCallback,useAsyncThrottledCallback, anduseAsyncRateLimitedCallbacknow returnPromise<Awaited<ReturnType<TFn>> | undefined>, matching the angular adapter and actual runtime behavior.
Builds on the diagnoses in #201, #199, #189, and #157 — authors are co-credited on the commit. #189's approach needed extension: without error handling in the tick chain and pendingTick reconciliation in flush, the queue could deadlock.
🤖 Generated with Claude Code
Summary by CodeRabbit#
Bug Fixes
- Preserved falsy and nullish queue items during processing.
- Improved asynchronous queue timing, flushing, recovery, and error handling.
- Rejected unsupported
undefinedqueue items with appropriate rejection handling. - Improved concurrent execution tracking for asynchronous rate limiting.
- Prevented unnecessary internal retry activity from contributing to devtools memory growth.
- Corrected async callback results to resolve with awaited values or
undefinedwhen applicable.
Documentation
- Updated React and Preact callback documentation to reflect awaited results and possible
undefinedvalues. - Refreshed API source references, queue behavior, and return type descriptions.
- Updated React and Preact callback documentation to reflect awaited results and possible
- 1
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/pacer/src/async-queuer.ts (1)
434-475: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy liftTrack active executions by identity.
Line 444 stores only the item value in
activeItems. Theexecutecleanup removes every active entry equal to the completed item.If two equal items execute concurrently, such as two
0values, the first completion removes both entries. A later tick can then exceedconcurrency.Track each scheduled execution with a unique identity. Remove only the matching execution when it settles. Add a concurrency test with duplicate primitive values.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/async-queuer.ts` around lines 434 - 475, Update the scheduling flow around peekNextItem, activeItems, and execute so each scheduled execution has a unique identity rather than tracking only the item value. Ensure settlement cleanup removes only the matching execution, preserving accurate concurrency when duplicate primitive items run concurrently. Add a test covering duplicate values such as two 0 items with concurrent execution.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@docs/framework/preact/reference/functions/useAsyncThrottledCallback.md`: - Around line 22-23: Update the return-value description for useAsyncThrottledCallback to state that disabled calls resolve with undefined, while throttled calls using trailing: true schedule a trailing execution whose promise resolves or rejects with the callback result. Remove the claim that every throttled call resolves with undefined and document the trailing behavior explicitly. In `@packages/pacer/src/async-debouncer.ts`: - Around line 375-380: The async debouncer flow around currentAsyncRetryer.execute must distinguish a successful result from undefined returned for disabled or non-throwing retry failures. Only update lastResult/successCount and invoke onSuccess when execution actually succeeds; otherwise preserve the failure path and avoid passing undefined to onSuccess. Add coverage for a rejected callback with asyncRetryerOptions.throwOnError set to false. In `@packages/pacer/src/async-queuer.ts`: - Around line 676-684: Restore the tick chain for every flush outcome in AsyncQueuer: at packages/pacer/src/async-queuer.ts:676-684, use Promise.allSettled for direct execute calls, restore pendingTick and restart processing before re-throwing any captured failure; at packages/pacer/src/async-queuer.ts:694-697, move state restoration into finally and call `#tick`() when the queuer is running and items were added while batchFunction awaited. --- Outside diff comments: In `@packages/pacer/src/async-queuer.ts`: - Around line 434-475: Update the scheduling flow around peekNextItem, activeItems, and execute so each scheduled execution has a unique identity rather than tracking only the item value. Ensure settlement cleanup removes only the matching execution, preserving accurate concurrency when duplicate primitive items run concurrently. Add a test covering duplicate values such as two 0 items with concurrent execution.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
d04db3b5-7d17-436c-adb5-315c6854972f📥 Commits
Reviewing files that changed from the base of the PR and between bd9621752367c1446430af9146b72e04ed991798 and 4ab7a8f67a62c9b5683faa614f564243c5e215d5.
📒 Files selected for processing (47)
.changeset/async-queuer-falsy-items.md.changeset/async-queuer-pending-tick.md.changeset/awaited-return-types.md.changeset/retryer-key-guard.mddocs/framework/preact/reference/functions/useAsyncDebouncedCallback.mddocs/framework/preact/reference/functions/useAsyncRateLimitedCallback.mddocs/framework/preact/reference/functions/useAsyncThrottledCallback.mddocs/framework/react/reference/functions/useAsyncDebouncedCallback.mddocs/framework/react/reference/functions/useAsyncRateLimitedCallback.mddocs/framework/react/reference/functions/useAsyncThrottledCallback.mddocs/reference/classes/AsyncDebouncer.mddocs/reference/classes/AsyncQueuer.mddocs/reference/classes/AsyncRateLimiter.mddocs/reference/classes/AsyncRetryer.mddocs/reference/classes/AsyncThrottler.mddocs/reference/functions/asyncDebounce.mddocs/reference/functions/asyncQueue.mddocs/reference/functions/asyncRateLimit.mddocs/reference/functions/asyncRetry.mddocs/reference/functions/asyncRetryerOptions.mddocs/reference/functions/asyncThrottle.mddocs/reference/interfaces/AsyncDebouncerOptions.mddocs/reference/interfaces/AsyncDebouncerState.mddocs/reference/interfaces/AsyncRateLimiterOptions.mddocs/reference/interfaces/AsyncRateLimiterState.mddocs/reference/interfaces/AsyncRetryerOptions.mddocs/reference/interfaces/AsyncRetryerState.mddocs/reference/interfaces/AsyncThrottlerOptions.mddocs/reference/interfaces/AsyncThrottlerState.mdpackages/pacer/src/async-debouncer.tspackages/pacer/src/async-queuer.tspackages/pacer/src/async-rate-limiter.tspackages/pacer/src/async-retryer.tspackages/pacer/src/async-throttler.tspackages/pacer/src/queuer.tspackages/pacer/tests/async-debouncer.test.tspackages/pacer/tests/async-queuer.test.tspackages/pacer/tests/async-rate-limiter.test.tspackages/pacer/tests/async-retryer.test.tspackages/pacer/tests/async-throttler.test.tspackages/pacer/tests/queuer.test.tspackages/preact-pacer/src/async-debouncer/useAsyncDebouncedCallback.tspackages/preact-pacer/src/async-rate-limiter/useAsyncRateLimitedCallback.tspackages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.tspackages/react-pacer/src/async-debouncer/useAsyncDebouncedCallback.tspackages/react-pacer/src/async-rate-limiter/useAsyncRateLimitedCallback.tspackages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts
docs/framework/preact/reference/functions/useAsyncThrottledCallback.md lines 22 to 23OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -19,4 +19,5 @@1919 regardless of how many times it is called. If called multiple times during the wait period,2020 only the first invocation will execute, and subsequent calls will be ignored until2121 the wait period has elapsed. The returned function always returns a promise22-that resolves or rejects with the result of the original async function.22+that resolves or rejects with the result of the original async function, or23+resolves with `undefined` if the call was throttled or the throttler is disabled.📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the throttled-call result description.
With
trailing: true, a call during the wait period schedules a trailing execution. That promise resolves or rejects with the callback result. It does not necessarily resolve withundefined.Document
undefinedonly for disabled calls. Also describe the trailing execution behavior.Proposed documentation update
- only the first invocation will execute, and subsequent calls will be ignored until - the wait period has elapsed. The returned function always returns a promise - that resolves or rejects with the result of the original async function, or - resolves with `undefined` if the call was throttled or the throttler is disabled. + calls during the wait period can schedule a trailing execution when `trailing` + is enabled. The returned function always returns a promise that resolves or + rejects with the result of the original async function. Calls made while the + throttler is disabled resolve with `undefined`.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@docs/framework/preact/reference/functions/useAsyncThrottledCallback.md` around lines 22 - 23, Update the return-value description for useAsyncThrottledCallback to state that disabled calls resolve with undefined, while throttled calls using trailing: true schedule a trailing execution whose promise resolves or rejects with the callback result. Remove the claim that every throttled call resolves with undefined and document the trailing behavior explicitly.✅ Addressed in commit aaf064b
@@ -363,16 +365,16 @@363365 if (!this.#getEnabled()) return undefined364366 const currentMaybeExecuteCount = this.store.state.maybeExecuteCount + 1365367366368 try {367369 this.#setState({ isExecuting: true })368- const currentAsyncRetryer = new AsyncRetryer(this.fn, {369- ...this.options.asyncRetryerOptions,370- key: `${this.key}-retryer-${currentMaybeExecuteCount}`,371- })370+ const currentAsyncRetryer = new AsyncRetryer(371+ this.fn,372+ this.options.asyncRetryerOptions,373+ )372374 this.asyncRetryers.set(currentMaybeExecuteCount, currentAsyncRetryer)373375 const result = await currentAsyncRetryer.execute(...args) // EXECUTE!374376 this.#setState({375377 lastResult: result,376378 successCount: this.store.state.successCount + 1,377379 })378- this.options.onSuccess?.(result as ReturnType<TFn>, args, this)380+ this.options.onSuccess?.(result as Awaited<ReturnType<TFn>>, args, this)🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Do not report a non-successful retryer result as success.
AsyncRetryer.executecan resolveundefinedwhen its retryer is disabled or whenthrowOnErroris false. This path still incrementssuccessCountand callsonSuccess. For a callback that returnsPromise<string>, Line 380 can callonSuccesswithundefined.Detect successful retryer completion before updating success state or calling
onSuccess. Add coverage for a rejected function withasyncRetryerOptions.throwOnError: false.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/async-debouncer.ts` around lines 375 - 380, The async debouncer flow around currentAsyncRetryer.execute must distinguish a successful result from undefined returned for disabled or non-throwing retry failures. Only update lastResult/successCount and invoke onSuccess when execution actually succeeds; otherwise preserve the failure path and avoid passing undefined to onSuccess. Add coverage for a rejected callback with asyncRetryerOptions.throwOnError set to false.Real but pre-existing, and identical across all five async utilities (not just the debouncer) — the internal retryer resolving
undefined(disabled, swallowed final error, or abort) is currently indistinguishable from a successfulundefinedresult. Deciding how those outcomes should settle at the parent level is a semantic change, so it's split out as #247 rather than expanded here.@KevinVandy, acknowledged. The finding is valid, but it requires a shared semantic change across the async utilities. Tracking it in#247is appropriate. I will not treat it as required work for this PR.🐇💭
You are interacting with an AI system.packages/pacer/src/async-queuer.ts lines 693 to 719Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -658,7 +673,12 @@658673 numberOfItems: number = this.store.state.items.length,659674 position?: QueuePosition,660675 ): Promise<void> => {661- this.#clearTimeouts() // clear any pending timeouts676+ this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)662677 await Promise.all(663678 Array.from({ length: numberOfItems }, () => this.execute(position)),664679 )680+ // the tick chain was killed above; restart it so remaining and future items process681+ this.#setState({ pendingTick: false })682+ if (this.store.state.isRunning && this.store.state.items.length > 0) {683+ this.#tick()684+ }🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Restore the tick chain after all flush outcomes.
Both methods clear the timer chain before awaiting work. A rejection skips the
pendingTickreset. FutureaddItemcalls then do not start processing.packages/pacer/src/async-queuer.ts#L676-L684: UsePromise.allSettledso all direct executions settle before restarting the tick chain. Re-throw a captured failure only after state restoration.packages/pacer/src/async-queuer.ts#L694-L697: Put state restoration infinally. If items were added whilebatchFunctionawaited, call#tick()when the queuer is running.
Proposed scheduling cleanup
- await Promise.all( + const results = await Promise.allSettled( Array.from({ length: numberOfItems }, () => this.execute(position)), ) - this.#setState({ pendingTick: false }) - if (this.store.state.isRunning && this.store.state.items.length > 0) { - this.#tick() - } + this.#setState({ pendingTick: false }) + if (this.store.state.isRunning && this.store.state.items.length > 0) { + this.#tick() + } + const failure = results.find( + (result): result is PromiseRejectedResult => result.status === 'rejected', + ) + if (failure) throw failure.reason- await batchFunction(items) - this.#setState({ pendingTick: false }) + try { + await batchFunction(items) + } finally { + this.#setState({ pendingTick: false }) + if (this.store.state.isRunning && this.store.state.items.length > 0) { + this.#tick() + } + }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
Suggested change693+ this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)694+ const results = await Promise.allSettled(695+ Array.from({ length: numberOfItems }, () => this.execute(position)),696+ )697+ // the tick chain was killed above; restart it so remaining and future items process698+ this.#setState({ pendingTick: false })699+ if (this.store.state.isRunning && this.store.state.items.length > 0) {700+ this.#tick()701+ }702+ const failure = results.find(703+ (result): result is PromiseRejectedResult => result.status === 'rejected',704+ )705+ if (failure) throw failure.reasonSuggested change693+ this.#clearTimeouts() // clear any pending timeouts (kills the tick chain)694+ const items = this.#getAllItems()695+ try {696+ await batchFunction(items)697+ } finally {698+ this.#setState({ pendingTick: false })699+ if (this.store.state.isRunning && this.store.state.items.length > 0) {700+ this.#tick()701+ }702+ }📍 Affects 1 file
packages/pacer/src/async-queuer.ts#L676-L684(this comment)packages/pacer/src/async-queuer.ts#L694-L697
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/async-queuer.ts` around lines 676 - 684, Restore the tick chain for every flush outcome in AsyncQueuer: at packages/pacer/src/async-queuer.ts:676-684, use Promise.allSettled for direct execute calls, restore pendingTick and restart processing before re-throwing any captured failure; at packages/pacer/src/async-queuer.ts:694-697, move state restoration into finally and call `#tick`() when the queuer is running and items were added while batchFunction awaited.✅ Addressed in commit aaf064b
Pull request overview#
This PR fixes several correctness and ergonomics issues across TanStack Pacer’s async utilities and framework adapters, focusing on queue item handling, wait semantics, memory usage, and TypeScript return types.
Changes:
- Fix AsyncQueuer/Queuer item handling so falsy values are not skipped and
nullno longer crashes default priority handling. - Remove AsyncRetryer’s devtools event-client integration to prevent unbounded listener/queued-event memory growth from per-execution retryers.
- Align async utility return types (and react/preact hooks) to
Promise<Awaited<ReturnType<TFn>> | undefined>and update docs/tests accordingly.
Reviewed changes#
Copilot reviewed 47 out of 47 changed files in this pull request and generated 3 comments.
Show a summary per file
File Description packages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts Update hook return type to awaited + undefinedand simplify callback wrapper.packages/react-pacer/src/async-rate-limiter/useAsyncRateLimitedCallback.ts Update hook return type to awaited + undefined.packages/react-pacer/src/async-debouncer/useAsyncDebouncedCallback.ts Update hook return type to awaited + undefinedand simplify callback wrapper.packages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.ts Update hook return type to awaited + undefined.packages/preact-pacer/src/async-rate-limiter/useAsyncRateLimitedCallback.ts Update hook return type to awaited + undefined.packages/preact-pacer/src/async-debouncer/useAsyncDebouncedCallback.ts Update hook return type to awaited + undefined.packages/pacer/tests/queuer.test.ts Add regression test for nullitems in sync Queuer.packages/pacer/tests/async-throttler.test.ts Add devtools-registry and type-inference tests for AsyncThrottler. packages/pacer/tests/async-retryer.test.ts Add test ensuring AsyncRetryer does not register in devtools registry. packages/pacer/tests/async-rate-limiter.test.ts Add devtools-registry and type-inference tests for AsyncRateLimiter. packages/pacer/tests/async-queuer.test.ts Add tests for falsy/null items, wait semantics, error continuity, and devtools registry behavior. packages/pacer/tests/async-debouncer.test.ts Add devtools-registry and type-inference tests for AsyncDebouncer. packages/pacer/src/queuer.ts Make default priority access null-safe for nullitems.packages/pacer/src/async-throttler.ts Use Awaited<ReturnType<TFn>>in state/returns and stop keying internal retryers for devtools.packages/pacer/src/async-retryer.ts Remove devtools event-client integration; clarify keyas identifier-only.packages/pacer/src/async-rate-limiter.ts Use Awaited<ReturnType<TFn>>in state/returns and stop keying internal retryers for devtools.packages/pacer/src/async-queuer.ts Fix falsy-item peeking, wait/pendingTick behavior, error swallowing in tick chain, null-safe priority access, and flush chain restart. packages/pacer/src/async-debouncer.ts Use Awaited<ReturnType<TFn>>in state/returns and stop keying internal retryers for devtools.docs/reference/interfaces/AsyncThrottlerState.md Update lastResultdocs to awaited type.docs/reference/interfaces/AsyncThrottlerOptions.md Update onSuccessresult type docs to awaited type.docs/reference/interfaces/AsyncRetryerState.md Update source line references due to code changes. docs/reference/interfaces/AsyncRetryerOptions.md Update retryer keydocumentation and source references.docs/reference/interfaces/AsyncRateLimiterState.md Update lastResultdocs to awaited type.docs/reference/interfaces/AsyncRateLimiterOptions.md Update onSuccessresult type docs to awaited type.docs/reference/interfaces/AsyncDebouncerState.md Update lastResultdocs to awaited type.docs/reference/interfaces/AsyncDebouncerOptions.md Update onSuccessresult type docs to awaited type.docs/reference/functions/asyncThrottle.md Update helper return type docs to awaited type and source refs. docs/reference/functions/asyncRetryerOptions.md Update source refs. docs/reference/functions/asyncRetry.md Update source refs. docs/reference/functions/asyncRateLimit.md Update helper return type docs to awaited type. docs/reference/functions/asyncQueue.md Update source refs. docs/reference/functions/asyncDebounce.md Update helper return type docs to awaited type and source refs. docs/reference/classes/AsyncThrottler.md Update method return type docs + source refs. docs/reference/classes/AsyncRetryer.md Update source refs after devtools integration removal. docs/reference/classes/AsyncRateLimiter.md Update method return type docs. docs/reference/classes/AsyncQueuer.md Update source refs after tick/flush changes. docs/reference/classes/AsyncDebouncer.md Update method return type docs + source refs. docs/framework/react/reference/functions/useAsyncThrottledCallback.md Update hook signature and description to include undefined.docs/framework/react/reference/functions/useAsyncRateLimitedCallback.md Update hook signature to include undefined.docs/framework/react/reference/functions/useAsyncDebouncedCallback.md Update hook signature and description to include undefined.docs/framework/preact/reference/functions/useAsyncThrottledCallback.md Update hook signature and description to include undefined.docs/framework/preact/reference/functions/useAsyncRateLimitedCallback.md Update hook signature to include undefined.docs/framework/preact/reference/functions/useAsyncDebouncedCallback.md Update hook signature and description to include undefined..changeset/retryer-key-guard.md Changeset for removing retryer devtools event-client integration to fix memory growth. .changeset/awaited-return-types.md Changeset for awaited return types across async utilities + react/preact adapters. .changeset/async-queuer-pending-tick.md Changeset for AsyncQueuer wait/pendingTick semantics and chain resilience. .changeset/async-queuer-falsy-items.md Changeset for falsy/null item handling in Queuer/AsyncQueuer. Suppressed comments (1)
packages/pacer/src/async-queuer.ts:698
flushAsBatch()clears timeouts (killing the tick chain) and only setspendingTick: falseafter awaitingbatchFunction, but it never restarts#tick()if items are enqueued during that await. IfpendingTickwas true whenflushAsBatch()started (common when a wait timer was pending), anaddItem()during the batch will not trigger#tick(), and after the batch completes the queue can remain stuck until another item is added orstart()is called again.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
@@ -458,4 +469,8 @@458469 })()459470 }460471461- this.#setState({ pendingTick: false })472+ // pendingTick must stay true while executions or wait timers are pending so473+ // that addItem does not trigger an extra tick that bypasses the wait period474+ if (!scheduledAsyncWork) {475+ this.#setState({ pendingTick: false })476+ }pendingTickis cleared solely based onscheduledAsyncWork, but there can still be pending executions (activeItems.length > 0) or outstanding wait timers (#timeoutIds.size > 0). In those casesaddItem()can observependingTick: falseand trigger an extra#tick()during a wait window, reintroducing the wait-bypass behavior (especially with concurrency > 1 and multiple overlapping wait timers). Consider only clearingpendingTickwhen there are no active items and no scheduled timeouts.This issue also appears on line 694 of the same file.
Verified this doesn't reproduce a wait bypass or stall. The two cases where
pendingTickisfalsewhile work is outstanding are both intentional:- Active executions, free slot: completions always re-tick (or schedule the wait timer), so nothing stalls — and
addItemobservingpendingTick: falsehere is what lets a new item start immediately on a free concurrency slot instead of waiting for an unrelated long-running execution to finish. Clearing only whenactiveItems.length === 0would regress that. - Outstanding wait timer: the only such window is after another slot's timer already fired on an empty queue — i.e. that slot's full wait elapsed with nothing to do. A new item then starts on that slot with its wait spacing fully honored (probed: start ≥
waitafter the slot's previous completion; no stall, no double-processing). The dangerous overlap case — item added while wait windows are still active — keepspendingTick: trueand is covered by theconcurrency > 1mid-wait test, which asserts the item is held until the window elapses.
@@ -492,4 +507,4 @@492507 const priority =493508 this.options.getPriority !== defaultOptions.getPriority494509 ? this.options.getPriority!(item)495- : (item as any).priority510+ : (item as any)?.priorityChanging the default priority access to optional chaining allows
addItem(undefined)to succeed, butundefinedis also used as the sentinel value for "no item" (peekNextItem()/getNextItem()return type). This can stall the processing loop indefinitely if anundefineditem is ever enqueued (e.g.,peekNextItem()returnsundefinedand the tick breaks without removing it). It’s safer to explicitly reject/throw onundefineditems until the API is redesigned to support them.Fixed in 58a9745d:
addItemnow rejectsundefinedthrough the standard rejection path (rejectionCount+onReject+return false) with a jsdoc note, so the sentinel can never enter the queue and wedge the loop. Test covers rejection plus continued processing of items behind it.@@ -421,4 +421,4 @@421421 const priority =422422 this.options.getPriority !== defaultOptions.getPriority423423 ? this.options.getPriority!(item)424- : (item as any).priority424+ : (item as any)?.priorityChanging the default priority access to optional chaining allows
addItem(undefined)to succeed, butundefinedis also treated as the sentinel value for "no item" in the processing loop (e.g.,#tick()breaks whenexecute()returnsundefined). If anundefineditem is enqueued ahead of other items, the tick will break early and remaining queued items may never be processed until another tick is triggered. Consider explicitly rejecting/throwing onundefineditems inaddItem()to avoid creating a stuck queue state.Fixed in 58a9745d: same guard applied to the sync
Queuer.addItem(reject viarejectionCount/onReject/return false), with a matching test.- Fix AsyncQueuer/Queuer item handling so falsy values are not skipped and
View your CI Pipeline Execution ↗ for commit 4ab7a8f67a62c9b5683faa614f564243c5e215d5
Command Status Duration Result nx affected --targets=test:eslint,test:sherif,t...✅ Succeeded 5m 4s View ↗ nx run-many --targets=build --exclude=examples/**✅ Succeeded 16s View ↗
☁️ Nx Cloud last updated this comment at
2026-08-06 23:42:37UTCMore templates
- @tanstack/pacer-example-angular-async-batch
- @tanstack/pacer-example-angular-async-debounce
- @tanstack/pacer-example-angular-async-rate-limit
- @tanstack/pacer-example-angular-async-retry
- @tanstack/pacer-example-angular-async-throttle
- @tanstack/pacer-example-angular-batch
- @tanstack/pacer-example-angular-debounce
- @tanstack/pacer-example-angular-inject-async-batched-callback
- @tanstack/pacer-example-angular-inject-async-batcher
- @tanstack/pacer-example-angular-inject-async-debounced-callback
- @tanstack/pacer-example-angular-inject-async-debouncer
- @tanstack/pacer-example-angular-inject-async-queued-signal
- @tanstack/pacer-example-angular-inject-async-queuer
- @tanstack/pacer-example-angular-inject-async-rate-limiter
- @tanstack/pacer-example-angular-inject-async-rate-limiter-with-persister
- @tanstack/pacer-example-angular-inject-async-throttled-callback
- @tanstack/pacer-example-angular-inject-async-throttler
- @tanstack/pacer-example-angular-inject-batched-callback
- @tanstack/pacer-example-angular-inject-batcher
- @tanstack/pacer-example-angular-inject-debounced-callback
- @tanstack/pacer-example-angular-inject-debounced-signal
- @tanstack/pacer-example-angular-inject-debounced-value
- @tanstack/pacer-example-angular-inject-debouncer
- @tanstack/pacer-example-angular-inject-queued-signal
- @tanstack/pacer-example-angular-inject-queued-value
- @tanstack/pacer-example-angular-inject-queuer
- @tanstack/pacer-example-angular-inject-queuer-with-persister
- @tanstack/pacer-example-angular-inject-rate-limited-callback
- @tanstack/pacer-example-angular-inject-rate-limited-signal
- @tanstack/pacer-example-angular-inject-rate-limited-value
- @tanstack/pacer-example-angular-inject-rate-limiter
- @tanstack/pacer-example-angular-inject-rate-limiter-with-persister
- @tanstack/pacer-example-angular-inject-throttled-callback
- @tanstack/pacer-example-angular-inject-throttled-signal
- @tanstack/pacer-example-angular-inject-throttled-value
- @tanstack/pacer-example-angular-inject-throttler
- @tanstack/pacer-example-angular-queue
- @tanstack/pacer-example-angular-rate-limit
- @tanstack/pacer-example-angular-throttle
- @tanstack/pacer-example-preact-async-batch
- @tanstack/pacer-example-preact-async-debounce
- @tanstack/pacer-example-preact-async-rate-limit
- @tanstack/pacer-example-preact-async-retry
- @tanstack/pacer-example-preact-async-throttle
- @tanstack/pacer-example-preact-batch
- @tanstack/pacer-example-preact-debounce
- @tanstack/pacer-example-preact-queue
- @tanstack/pacer-example-preact-rate-limit
- @tanstack/pacer-example-preact-throttle
- @tanstack/pacer-example-preact-async-batched-callback
- @tanstack/pacer-example-preact-async-batcher
- @tanstack/pacer-example-preact-use-async-debounced-callback
- @tanstack/pacer-example-preact-use-async-debouncer
- @tanstack/pacer-example-preact-async-queued-state
- @tanstack/pacer-example-preact-async-queuer
- @tanstack/pacer-example-preact-async-rate-limiter
- @tanstack/pacer-example-preact-async-rate-limiter-with-persister
- @tanstack/pacer-example-preact-async-throttled-callback
- @tanstack/pacer-example-preact-async-throttler
- @tanstack/pacer-example-preact-batched-callback
- @tanstack/pacer-example-preact-LBatcher
- @tanstack/pacer-example-preact-use-debounced-callback
- @tanstack/pacer-example-preact-use-debounced-state
- @tanstack/pacer-example-preact-use-debounced-value
- @tanstack/pacer-example-preact-use-debouncer
- @tanstack/pacer-example-preact-queued-state
- @tanstack/pacer-example-preact-queued-value
- @tanstack/pacer-example-preact-queuer
- @tanstack/pacer-example-preact-queuer-with-persister
- @tanstack/pacer-example-preact-rate-limited-callback
- @tanstack/pacer-example-preact-rate-limited-state
- @tanstack/pacer-example-preact-rate-limited-value
- @tanstack/pacer-example-preact-rate-limiter
- @tanstack/pacer-example-preact-rate-limiter-with-persister
- @tanstack/pacer-example-preact-use-throttled-callback
- @tanstack/pacer-example-preact-use-throttled-state
- @tanstack/pacer-example-preact-use-throttled-value
- @tanstack/pacer-example-preact-use-throttler
- @tanstack/pacer-example-preact-util-comparison
- @tanstack/pacer-example-react-asyncbatch
- @tanstack/pacer-example-react-async-debounce
- @tanstack/pacer-example-react-async-rate-limit
- @tanstack/pacer-example-react-asyncretry
- @tanstack/pacer-example-react-async-throttle
- @tanstack/pacer-example-react-batch
- @tanstack/pacer-example-react-debounce
- @tanstack/pacer-example-react-queue
- @tanstack/pacer-example-react-rate-limit
- @tanstack/pacer-example-react-query-debounced-prefetch
- @tanstack/pacer-example-react-query-queued-prefetch
- @tanstack/pacer-example-react-query-throttled-prefetch
- @tanstack/pacer-example-react-throttle
- @tanstack/pacer-example-react-use-async-batched-callback
- @tanstack/pacer-example-react-use-async-batcher
- @tanstack/pacer-example-react-use-async-debounced-callback
- @tanstack/pacer-example-react-use-async-debouncer
- @tanstack/pacer-example-react-use-async-queuer-state
- @tanstack/pacer-example-react-use-async-queuer
- @tanstack/pacer-example-react-use-async-rate-limiter
- @tanstack/pacer-example-react-use-async-rate-limiter-with-persister
- @tanstack/pacer-example-react-use-async-throttled-callback
- @tanstack/pacer-example-react-use-async-throttler
- @tanstack/pacer-example-react-use-batched-callback
- @tanstack/pacer-example-react-use-batcher
- @tanstack/pacer-example-react-use-debounced-callback
- @tanstack/pacer-example-react-use-debounced-state
- @tanstack/pacer-example-react-use-debounced-value
- @tanstack/pacer-example-react-use-debouncer
- @tanstack/pacer-example-react-use-queued-state
- @tanstack/pacer-example-react-use-queued-value
- @tanstack/pacer-example-react-use-queuer
- @tanstack/pacer-example-react-use-queuer-with-persister
- @tanstack/pacer-example-react-use-rate-limited-callback
- @tanstack/pacer-example-react-use-rate-limited-state
- @tanstack/pacer-example-react-use-rate-limited-value
- @tanstack/pacer-example-react-use-rate-limiter
- @tanstack/pacer-example-react-use-rate-limiter-with-persister
- @tanstack/pacer-example-react-use-throttled-callback
- @tanstack/pacer-example-react-use-throttled-state
- @tanstack/pacer-example-react-use-throttled-value
- @tanstack/pacer-example-react-use-throttler
- @tanstack/pacer-example-react-util-comparison
- @tanstack/pacer-example-solid-async-batch
- @tanstack/pacer-example-solid-async-debounce
- @tanstack/pacer-example-solid-async-rate-limit
- @tanstack/pacer-example-solid-async-throttle
- @tanstack/pacer-example-solid-batch
- @tanstack/pacer-example-solid-create-async-batcher
- @tanstack/pacer-example-solid-create-async-debouncer
- @tanstack/pacer-example-solid-create-async-queuer
- @tanstack/pacer-example-solid-create-async-rate-limiter
- @tanstack/pacer-example-solid-create-async-throttler
- @tanstack/pacer-example-solid-create-batcher
- @tanstack/pacer-example-solid-create-debounced-signal
- @tanstack/pacer-example-solid-create-debounced-value
- @tanstack/pacer-example-solid-create-debouncer
- @tanstack/pacer-example-solid-create-queued-signal
- @tanstack/pacer-example-solid-create-queuer
- @tanstack/pacer-example-solid-create-rate-limited-signal
- @tanstack/pacer-example-solid-create-rate-limited-value
- @tanstack/pacer-example-solid-create-rate-limiter
- @tanstack/pacer-example-solid-create-throttled-signal
- @tanstack/pacer-example-solid-create-throttled-value
- @tanstack/pacer-example-solid-create-throttler
- @tanstack/pacer-example-solid-debounce
- @tanstack/pacer-example-solid-queue
- @tanstack/pacer-example-solid-rate-limit
- @tanstack/pacer-example-solid-throttle
- @tanstack/pacer-example-vanilla-lite-batcher
- @tanstack/pacer-example-vanilla-lite-debouncer
- @tanstack/pacer-example-vanilla-lite-queuer
- @tanstack/pacer-example-vanilla-lite-rate-limiter
- @tanstack/pacer-example-vanilla-lite-throttler
- @tanstack/pacer-example-vanilla-lite-batch
- @tanstack/pacer-example-vanilla-lite-debounce
- @tanstack/pacer-example-vanilla-lite-queue
- @tanstack/pacer-example-vanilla-lite-rate-limit
- @tanstack/pacer-example-vanilla-lite-throttle
@tanstack/angular-pacer
npm i https://pkg.pr.new/@tanstack/angular-pacer@246@tanstack/pacer
npm i https://pkg.pr.new/@tanstack/pacer@246@tanstack/pacer-devtools
npm i https://pkg.pr.new/@tanstack/pacer-devtools@246@tanstack/pacer-lite
npm i https://pkg.pr.new/@tanstack/pacer-lite@246@tanstack/preact-pacer
npm i https://pkg.pr.new/@tanstack/preact-pacer@246@tanstack/preact-pacer-devtools
npm i https://pkg.pr.new/@tanstack/preact-pacer-devtools@246@tanstack/react-pacer
npm i https://pkg.pr.new/@tanstack/react-pacer@246@tanstack/react-pacer-devtools
npm i https://pkg.pr.new/@tanstack/react-pacer-devtools@246@tanstack/solid-pacer
npm i https://pkg.pr.new/@tanstack/solid-pacer@246@tanstack/solid-pacer-devtools
npm i https://pkg.pr.new/@tanstack/solid-pacer-devtools@246commit:
edb6b61Addressed the CodeRabbit review in aaf064b:
- flush()/flushAsBatch() error paths (confirmed via failing test first):
flushnow usesPromise.allSettled, restorespendingTick, and restarts the tick chain before rethrowing the first failure — remaining items resume at the normalwaitspacing.flushAsBatchrestores the chain in afinally, picking up items added while the batch function was awaiting. - Duplicate-item concurrency accounting (pre-existing, confirmed — measured 3 concurrent executions with
concurrency: 2and duplicate0items):execute()now removes a singleactiveItemsoccurrence by index instead of filtering all equal values. Went with the minimal identity fix rather than execution-ID tracking; tests cover duplicate primitives at and above the limit. - Docs wording: the react/preact throttled/debounced callback docstrings no longer claim throttled or superseded calls resolve with
undefined— trailing executions share their result, superseded calls resolve with the most recent result. Reference docs regenerated. onSuccess(undefined)when the internal retryer swallows a failure: real but pre-existing and identical across all five async utilities (not just the debouncer), and the fix requires deciding what "success" means for swallowed errors and aborts — split out as a follow-up issue rather than expanding this PR.
New coverage: 9 tests around flush robustness (rejection, partial flush, batch rejection, stopped queuer, mid-batch adds) and duplicate-item concurrency accounting. 551 tests passing.
🤖 Generated with Claude Code
- flush()/flushAsBatch() error paths (confirmed via failing test first):
🧹 Nitpick comments (3)
packages/pacer/src/async-queuer.ts (2)
435-447: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winCopy
activeItemsbefore mutation.Line 435 takes the array reference from store state. Line 444 pushes into that same array, so the store state is mutated in place before
#setStateruns. Subscribers that compareactiveItemsby reference cannot detect the change, and the state beforesetStateis already dirty.executeat lines 657-663 correctly copies before mutating; use the same pattern here.♻️ Proposed change
- const activeItems = this.store.state.activeItems + const activeItems = [...this.store.state.activeItems] while ( activeItems.length < this.#getConcurrency() && this.store.state.items.length > 0 ) { const nextItem = this.peekNextItem() if (nextItem === undefined) { break } activeItems.push(nextItem) this.#setState({ - activeItems, + activeItems: [...activeItems], })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/async-queuer.ts` around lines 435 - 447, Copy this.store.state.activeItems into a new array before the while loop in the active-item scheduling flow, then mutate that copy and pass it to `#setState`. Follow the existing copy-before-mutation pattern used by execute, while preserving the current concurrency and next-item checks.
717-727: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low valueConsider matching the wait spacing that
flushapplies.flushrestarts the chain through asetTimeoutwhenwait > 0(lines 689-700).flushAsBatchcalls#tick()directly, so the first remaining item runs with no wait spacing after the batch settles. Align both paths if the wait contract must hold after every flush variant.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/async-queuer.ts` around lines 717 - 727, Update flushAsBatch’s finally block to restart the tick chain using the same wait-aware scheduling behavior as flush, rather than calling `#tick`() directly. Reuse the existing wait handling from flush while preserving the current running-state and non-empty-items checks.packages/pacer/tests/async-queuer.test.ts (1)
1459-1471: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winStrengthen this test so it verifies the
finallyrestart.flushAsBatchdoes not setpendingTickbefore it awaits. Line 1464 callsstart(), which seespendingTick === falseand starts the tick chain right away.'late'therefore processes before the batch settles, and the assertion passes even if thefinallyblock at lines 721-727 is removed. Assert the intermediate state, or drive the item addition after the queuer is already running.💚 Proposed test tightening
asyncQueuer.addItem('late') asyncQueuer.start() + // 'late' must not be processed until the batch settles and the chain restarts + expect(results).toEqual([]) + await vi.advanceTimersByTimeAsync(50) await batchPromise await vi.advanceTimersByTimeAsync(100)🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/tests/async-queuer.test.ts` around lines 1459 - 1471, Strengthen the flushAsBatch test around asyncQueuer.flushAsBatch, asyncQueuer.addItem, and asyncQueuer.start so it proves the queued “late” item is processed only after the batch promise settles and the finally-based restart runs. Assert the intermediate batches/results state before awaiting batchPromise, or add the item after the queuer is already running, while preserving the final expected batch and result assertions.🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Nitpick comments: In `@packages/pacer/src/async-queuer.ts`: - Around line 435-447: Copy this.store.state.activeItems into a new array before the while loop in the active-item scheduling flow, then mutate that copy and pass it to `#setState`. Follow the existing copy-before-mutation pattern used by execute, while preserving the current concurrency and next-item checks. - Around line 717-727: Update flushAsBatch’s finally block to restart the tick chain using the same wait-aware scheduling behavior as flush, rather than calling `#tick`() directly. Reuse the existing wait handling from flush while preserving the current running-state and non-empty-items checks. In `@packages/pacer/tests/async-queuer.test.ts`: - Around line 1459-1471: Strengthen the flushAsBatch test around asyncQueuer.flushAsBatch, asyncQueuer.addItem, and asyncQueuer.start so it proves the queued “late” item is processed only after the batch promise settles and the finally-based restart runs. Assert the intermediate batches/results state before awaiting batchPromise, or add the item after the queuer is already running, while preserving the final expected batch and result assertions.
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
ee971725-03c6-4f5f-a7ef-ceb4f55b4372📥 Commits
Reviewing files that changed from the base of the PR and between 4ab7a8f67a62c9b5683faa614f564243c5e215d5 and aaf064b3290f9a7b6773ed969ac9ba488cd88c81.
📒 Files selected for processing (12)
docs/framework/preact/reference/functions/useAsyncDebouncedCallback.mddocs/framework/preact/reference/functions/useAsyncThrottledCallback.mddocs/framework/react/reference/functions/useAsyncDebouncedCallback.mddocs/framework/react/reference/functions/useAsyncThrottledCallback.mddocs/reference/classes/AsyncQueuer.mddocs/reference/functions/asyncQueue.mdpackages/pacer/src/async-queuer.tspackages/pacer/tests/async-queuer.test.tspackages/preact-pacer/src/async-debouncer/useAsyncDebouncedCallback.tspackages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.tspackages/react-pacer/src/async-debouncer/useAsyncDebouncedCallback.tspackages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts
🚧 Files skipped from review as they are similar to previous changes (7)
- packages/preact-pacer/src/async-debouncer/useAsyncDebouncedCallback.ts
- packages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts
- packages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.ts
- packages/react-pacer/src/async-debouncer/useAsyncDebouncedCallback.ts
- docs/reference/functions/asyncQueue.md
- docs/framework/react/reference/functions/useAsyncThrottledCallback.md
- docs/reference/classes/AsyncQueuer.md
Pull request overview#
Copilot reviewed 47 out of 47 changed files in this pull request and generated no new comments.
Suppressed comments (1)
packages/pacer/src/async-queuer.ts:666
isExecutingis always set tofalsewhen an execution settles, even if other executions are still in-flight (e.g. concurrency > 1 or a manualexecute/flushcall overlapping). This makesstore.state.isExecutinginaccurate for consumers.
Pull request overview#
Copilot reviewed 51 out of 51 changed files in this pull request and generated no new comments.
Suppressed comments (5)
packages/pacer/tests/async-throttler.test.ts:1028
- This test enables fake timers via
vi.useFakeTimers()in the describe-levelbeforeEach, but never restores real timers. That can leak fake-timer state into subsequent tests in this file and cause hangs/flakiness. Ensure timers are restored (ideally viatry/finallyin the test body or anafterEachthat callsvi.useRealTimers()). packages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.ts:16 - The JSDoc claims that calls made during the throttle wait window “share the trailing execution's result”. In
AsyncThrottler.maybeExecute, each new call resolves the previous pending promise immediately via#resolvePreviousPromiseInternal()(with the most recentlastResult), so only the most recent call can resolve with the trailing execution’s result. The docs should reflect the actual promise resolution behavior. docs/framework/react/reference/functions/useAsyncThrottledCallback.md:23 - This reference doc says calls during the wait period “share the trailing execution's result”, but
AsyncThrottler.maybeExecuteresolves the previous pending promise immediately on each new call (with the most recentlastResult). Only the most recent call can resolve with the trailing execution’s result, so this description should be updated.
regardless of how many times it is called. Calls made during the wait period can schedule a single trailing execution with the latest arguments when `trailing` is enabled (the default), and those calls share the trailing execution's result. The returned function always returns a promise that resolves or rejects with the result of the original async function, and resolves with `undefined` when the throttler is disabled.docs/framework/preact/reference/functions/useAsyncThrottledCallback.md:23
- This reference doc says calls during the wait period “share the trailing execution's result”, but
AsyncThrottler.maybeExecuteresolves the previous pending promise immediately on each new call (with the most recentlastResult). Only the most recent call can resolve with the trailing execution’s result, so this description should be updated.
regardless of how many times it is called. Calls made during the wait period can schedule a single trailing execution with the latest arguments when `trailing` is enabled (the default), and those calls share the trailing execution's result. The returned function always returns a promise that resolves or rejects with the result of the original async function, and resolves with `undefined` when the throttler is disabled.packages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts:16
- The JSDoc claims that calls made during the throttle wait window “share the trailing execution's result”. In
AsyncThrottler.maybeExecute, each new call resolves the previous pending promise immediately via#resolvePreviousPromiseInternal()(with the most recentlastResult), so only the most recent call can resolve with the trailing execution’s result. The docs should reflect the actual promise resolution behavior.
- This test enables fake timers via
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. Inline comments: In `@packages/pacer/src/queuer.ts`: - Line 393: Update the addItem() return documentation in packages/pacer/src/queuer.ts near lines 393-393 to state that it returns false when the queue is full or when the item is undefined; regenerate or apply the same return-contract update in docs/reference/classes/Queuer.md lines 174-177, docs/framework/angular/reference/interfaces/QueuedSignal.md lines 41-42, and docs/reference/functions/queue.md lines 73-74.🪄 Autofix
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
e13d8ea1-3350-4228-ac4d-0023a767e512📥 Commits
Reviewing files that changed from the base of the PR and between aaf064b3290f9a7b6773ed969ac9ba488cd88c81 and 58a9745dd49a1e384cf9a51086c5b6e66c65e9d1.
📒 Files selected for processing (10)
docs/framework/angular/reference/interfaces/AsyncQueuedSignal.mddocs/framework/angular/reference/interfaces/QueuedSignal.mddocs/reference/classes/AsyncQueuer.mddocs/reference/classes/Queuer.mddocs/reference/functions/asyncQueue.mddocs/reference/functions/queue.mdpackages/pacer/src/async-queuer.tspackages/pacer/src/queuer.tspackages/pacer/tests/async-queuer.test.tspackages/pacer/tests/queuer.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- docs/reference/functions/asyncQueue.md
- packages/pacer/src/async-queuer.ts
- packages/pacer/tests/queuer.test.ts
@@ -390,3 +390,4 @@390390391391 /**392392 * Adds an item to the queue. If the queue is full, the item is rejected and onReject is called.393+ * `undefined` cannot be queued (it is the internal "no item" sentinel) and is always rejected.📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Align the
addItem()rejection documentation.The new undefined branch returns
falsewhen the queue is not full. Update the source JSDoc and regenerate the affected references so the return contract includes both full-queue rejection and undefined rejection.packages/pacer/src/queuer.ts#L393-L393: update the return description near Line 396.docs/reference/classes/Queuer.md#L174-L177: update the return description near Line 180.docs/framework/angular/reference/interfaces/QueuedSignal.md#L41-L42: update the return description near Line 45.docs/reference/functions/queue.md#L73-L74: update the return description near Line 77.
📍 Affects 4 files
packages/pacer/src/queuer.ts#L393-L393(this comment)docs/reference/classes/Queuer.md#L174-L177docs/framework/angular/reference/interfaces/QueuedSignal.md#L41-L42docs/reference/functions/queue.md#L73-L74
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/pacer/src/queuer.ts` at line 393, Update the addItem() return documentation in packages/pacer/src/queuer.ts near lines 393-393 to state that it returns false when the queue is full or when the item is undefined; regenerate or apply the same return-contract update in docs/reference/classes/Queuer.md lines 174-177, docs/framework/angular/reference/interfaces/QueuedSignal.md lines 41-42, and docs/reference/functions/queue.md lines 73-74.Addressed the latest CodeRabbit nitpicks and Copilot suppressed comments in edb6b61c (these were review-body comments, not resolvable threads):
Fixed
#ticknow copiesactiveItemsbefore mutating (matchingexecute's pattern), so store state is never dirtied in place and array-reference selectors observe the change.isExecutingnow staystrueuntil every overlapping execution settles, derived from the live internal-retryer count — fixes the pre-existing inaccuracy in bothAsyncQueuer(concurrency > 1) andAsyncRateLimiter(overlapping window executions), with tests using staggered completions.- The flushAsBatch mid-batch test was strengthened, though not with the suggested diff —
expect(results).toEqual([])afterstart()would fail because the task fn runs synchronously on thestart()stack. Instead the test now begins with a running queue mid-wait (pendingTick: true), so the added item cannot be processed by anything except thefinally-restart; removing that block now fails the test. - The throttled-callback docstrings from the previous round were still wrong (good catch): only the most recent call during the wait period resolves with the trailing execution's result — each superseded call's promise resolves immediately with the previous result. Docstrings and reference docs now describe that.
- Added the missing
afterEachtimer restore to the new throttler test describe.
Declined
- Aligning
flushAsBatch's restart withflush's wait-scheduled restart: the items present after a batch settles were added during the batch to an empty queue — processing them immediately matchesaddItem-to-idle semantics.flush's remaining items sat behind just-executed tasks, which is why the wait spacing applies there.
555 tests passing.
🤖 Generated with Claude Code
Pull request overview#
Copilot reviewed 51 out of 51 changed files in this pull request and generated no new comments.
Suppressed comments (2)
packages/pacer/src/queuer.ts:436
- When
getPriorityis left at its default,addItembypassesdefaultOptions.getPriority(which defaults missing/nullish priorities to0) and instead reads(item as any)?.prioritydirectly. This changes semantics: items with nopriority(ornull) end up withpriority === undefined, skipping the priority-insertion branch and potentially ordering incorrectly vs negative/zero priorities. Align the fast-path withdefaultOptions.getPriorityby applying?? 0(and same forexistingPriority). packages/pacer/src/async-queuer.ts:522 - Like
Queuer.addItem, the defaultgetPriorityisitem?.priority ?? 0, but the fast-path here reads(item as any)?.prioritydirectly whengetPriorityis unchanged. That meansnullitems (and items with missingpriority) getpriority === undefinedinstead of0, which can skip priority insertion or mis-order items compared to negative/zero priorities. Use?? 0to match the documented default behavior (and apply the same change toexistingPriority).
- When
KevinVandy merged thisdc47121
KevinVandy closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro Plus
Run ID:
491aae1d-5c9e-434b-bd79-8ee03e246fd8📥 Commits
Reviewing files that changed from the base of the PR and between 58a9745dd49a1e384cf9a51086c5b6e66c65e9d1 and edb6b61c4503a472ecfce975f1a8eff97c2ff91e.
📒 Files selected for processing (13)
docs/framework/preact/reference/functions/useAsyncThrottledCallback.mddocs/framework/react/reference/functions/useAsyncThrottledCallback.mddocs/reference/classes/AsyncQueuer.mddocs/reference/classes/AsyncRateLimiter.mddocs/reference/functions/asyncQueue.mddocs/reference/functions/asyncRateLimit.mdpackages/pacer/src/async-queuer.tspackages/pacer/src/async-rate-limiter.tspackages/pacer/tests/async-queuer.test.tspackages/pacer/tests/async-rate-limiter.test.tspackages/pacer/tests/async-throttler.test.tspackages/preact-pacer/src/async-throttler/useAsyncThrottledCallback.tspackages/react-pacer/src/async-throttler/useAsyncThrottledCallback.ts🚧 Files skipped from review as they are similar to previous changes (12)
📝 Walkthrough
Walkthrough#
The PR fixes
AsyncQueueritem and tick handling, removes internalAsyncRetryerdevtools registration, corrects async return types withAwaited, updates React and Preact hooks, refreshes reference links, and adds tests and patch changesets.Changes#
Async utility behavior
packages/pacer/src/async-queuer.ts,packages/pacer/src/queuer.ts,packages/pacer/tests/async-queuer.test.ts,packages/pacer/tests/queuer.test.tspackages/pacer/src/async-retryer.ts,packages/pacer/tests/async-*.test.tspackages/pacer/src/async-debouncer.ts,packages/pacer/src/async-rate-limiter.ts,packages/pacer/src/async-throttler.ts,packages/react-pacer/src/...,packages/preact-pacer/src/...Awaited<ReturnType<TFn>>. Skipped, superseded, throttled, or disabled calls may resolve toundefined.docs/reference/...,docs/framework/...,.changeset/*Estimated code review effort: 3 (Moderate) | ~25 minutes
Possibly related PRs
Suggested reviewers:
copilot🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
✨ Finishing Touches
📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.
❤️ Share