Skip to content

[Serve] Avoid duplicate acquire timestamp on CapacityQueue slow path - #68652

Open
banlor wants to merge 1 commit into
ray-project:masterfrom
banlor:fix/serve-capacity-queue-slow-path-timestamp
Open

banlor wants to merge 1 commit into
ray-project:masterfrom
banlor:fix/serve-capacity-queue-slow-path-timestamp

Conversation

@banlor

@banlor banlor commented Nov 29, 2026

Copy link
Copy Markdown

Description

In CapacityQueue.acquire(), when a caller waits on the slow path, _fulfill_waiters() already increments in_flight and records the acquire timestamp before resolving the future. Calling _record_acquire_timestamp(replica_id) again after await asyncio.wait_for(future, ...) left an extra timestamp in _in_flight_timestamps[replica_id].

After that caller calls release(), the extra timestamp stays behind and is later popped by _reap_expired_tokens(), decrementing in_flight on a subsequent live request and allowing concurrent requests to exceed max_capacity.

This removes the duplicate _record_acquire_timestamp() call on slow-path resumption, splits out _reap_expired_tokens_once() for deterministic clock-based tests, and adds unit tests covering slow-path release (idle and follow-up active acquire) as well as multiple queued FIFO waiters under TTL.

Related issues

Fixes #68640

Additional information

Ran python/ray/serve/tests/unit/test_capacity_queue.py (43 passed) and ruff check on both modified files.

@banlor
banlor requested a review from a team as a code owner November 29, 2026 16:01

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors the token TTL reaping logic in capacity_queue.py by extracting _reap_expired_tokens_once to facilitate testing, and updates the acquire method to rely on _fulfill_waiters for token accounting. It also adds comprehensive unit tests to verify FIFO ordering and expiration behavior. A critical feedback item highlights a potential race condition in acquire where a waiter cancellation or timeout after token allocation could lead to a token leak; a code suggestion is provided to safely release the token in such cases.

Comment on lines 245 to 250
try:
replica_id = await asyncio.wait_for(future, timeout=timeout)
self._record_acquire_timestamp(replica_id)
return replica_id
# _fulfill_waiters() accounts for the token before waking this waiter.
return await asyncio.wait_for(future, timeout=timeout)
except asyncio.TimeoutError:
self._total_timeouts += 1
self._waiters = deque((f, t) for f, t in self._waiters if f is not future)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

There is a potential race condition where a waiter is cancelled (or times out) after _fulfill_waiters() has already allocated a token and called future.set_result(replica_id), but before the waiter task actually resumes and returns. In this scenario, asyncio.wait_for raises CancelledError (or TimeoutError), causing the token to be leaked because the caller never receives the replica_id to release it.\n\nTo prevent this leak, we should check if the future was completed successfully and release the allocated token if an exception or cancellation occurs.

        try:\n            try:\n                # _fulfill_waiters() accounts for the token before waking this waiter.\n                return await asyncio.wait_for(future, timeout=timeout)\n            except BaseException:\n                if future.done() and not future.cancelled():\n                    self.release(future.result())\n                raise\n        except asyncio.TimeoutError:\n            self._total_timeouts += 1\n            self._waiters = deque((f, t) for f, t in self._waiters if f is not future)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant