- 
                Notifications
    You must be signed in to change notification settings 
- Fork 1.8k
[None][fix] RPC stability #8711
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
Signed-off-by: Superjomn <[email protected]>
Remove pending requests processing, shutdown immediately Signed-off-by: Superjomn <[email protected]>
Signed-off-by: Superjomn <[email protected]>
| 📝 WalkthroughWalkthroughRPC infrastructure hardening for resilience and graceful shutdown. Changes include immediate shutdown with request cancellation semantics, improved event loop startup reliability via increased delays and synchronization, centralized error handling helpers, and removal of test waivers with enhanced resource cleanup patterns. Changes
 Sequence Diagram(s)sequenceDiagram
    participant Client
    participant Server
    participant Queue
    participant Worker
    note over Client,Worker: Normal Request Processing Flow
    Client->>Server: submit_request(req)
    Server->>Server: _handle_shutdown_request()
    alt Shutdown Active
        Server->>Queue: cancel pending requests
        Server->>Client: send RPCCancelled error
    else Normal Path
        Server->>Worker: process_request()
        Worker-->>Server: response
        Server->>Client: send_response()
    end
    note over Client,Worker: Shutdown Initiated
    Client->>Server: shutdown()
    Server->>Queue: _cancel_pending_queue_requests()
    activate Queue
    loop For each pending request
        Queue->>Client: send RPCCancelled error
    end
    deactivate Queue
    Server->>Worker: executor.shutdown(wait=False)
    Server->>Server: cancel main_loop task
    Server->>Server: stop event loop
sequenceDiagram
    participant Caller
    participant Proxy
    participant EventLoop
    participant Client
    note over Caller,Client: RPC Proxy Initialization with Sync
    Caller->>Proxy: __init__()
    Proxy->>Proxy: create main_loop_started Event
    Proxy->>Client: start_response_reader()
    activate EventLoop
    Proxy->>EventLoop: run main_loop tasks
    rect rgb(200, 220, 255)
        note over Proxy: Main loop ready
        Proxy->>Proxy: set main_loop_started
    end
    deactivate EventLoop
    Caller->>Proxy: await main_loop_started.wait(timeout)
    alt Timeout
        Proxy->>Caller: raise TimeoutError
    else Ready
        Caller->>Proxy: proceed with execute()
    end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes 
 Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
 ✅ Passed checks (1 passed)
 ✨ Finishing touches
 🧪 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. Comment  | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️  Outside diff range comments (5)
tensorrt_llm/executor/rpc/rpc_client.py (2)
1-8: Add NVIDIA Apache-2.0 header (2025).Per repo guidelines, prepend the standard NVIDIA Apache-2.0 header to all .py sources.
As per coding guidelines
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + import asyncio import concurrent.futures import threading import time
323-327: Comment/code mismatch: apply “timeout + 1s” or update comment.Either add 1s headroom or fix the comment. Adding headroom matches intent and avoids client timing out before server’s timeout response arrives.
- # Add 1 second to the timeout to ensure the client can get - res = await asyncio.wait_for(future, timeout) + # Add 1 second to the timeout to ensure the client can get server error + res = await asyncio.wait_for(future, timeout + 1.0)tests/unittest/executor/test_rpc.py (1)
1-6: Add NVIDIA Apache-2.0 header (2025).Tests are also source files; prepend the header.
As per coding guidelines
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# See the License for the specific language governing permissions and +# limitations under the License. + import asyncio import timetensorrt_llm/executor/rpc_proxy.py (1)
1-20: Add NVIDIA Apache-2.0 header (2025).Prepend the standard header.
As per coding guidelines
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# See the License for the specific language governing permissions and +# limitations under the License. + import asyncio import atexittensorrt_llm/executor/rpc/rpc_server.py (1)
1-16: Add NVIDIA Apache-2.0 header (2025).Prepend the standard header.
As per coding guidelines
+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# See the License for the specific language governing permissions and +# limitations under the License. + import asyncio import inspect
🧹 Nitpick comments (10)
tensorrt_llm/executor/rpc/rpc_client.py (2)
254-271: Reader startup robustness: narrow exception and log stack.Logic is good; avoid blind
except Exceptionand log traceback for diagnosis.- except Exception as e: - logger_debug(f"Error starting response reader: {e}") + except (RuntimeError, asyncio.CancelledError) as e: + logger_debug(f"Error starting response reader: {e}") + except Exception: + logger.exception("Error starting response reader") # Don't raise here, let it retry on next call self._reader_task = NoneRuff BLE001.
359-359: Replace fixed sleep with readiness wait.Poll
is_running()with a short backoff and timeout instead of a magic 0.2s.- # Give the loop a moment to start - time.sleep(0.2) + # Wait for the loop to start running (max 1s) + waited = 0.0 + while not self._loop.is_running() and waited < 1.0: + time.sleep(0.01) + waited += 0.01tests/unittest/executor/test_rpc.py (4)
217-229: Test semantics: create pendings before shutdown.This test now enqueues requests after triggering shutdown. To validate “pending requests are cancelled when server shuts down,” enqueue first, then shutdown.
- client = RPCClient(addr) - try: - client.shutdown_server() - pending_futures = [client.task().remote_future() for _ in range(10)] + client = RPCClient(addr) + try: + pending_futures = [client.task().remote_future() for _ in range(10)] + client.shutdown_server()
284-297: Ensure deterministic server teardown.After remote shutdown, explicitly call
server.shutdown()locally to join the dispatcher instead of relying onsleep(1.0).- finally: - # Wait for the server dispatcher thread to quit - time.sleep(1.0) + finally: + # Join dispatcher deterministically + server.shutdown()
299-301: Track flaky test with an issue ID.Add a reference (issue/URL) to the skip reason to avoid permanent skip.
-@pytest.mark.skip(reason="This test is flaky, need to fix it") +@pytest.mark.skip(reason="Flaky; tracked in ISSUE-XXXX: fix perf timing nondeterminism")
375-393: Teardown order and sleeps.Good: server first, then client. Prefer joining or polling over fixed
sleep(1.0)to shorten tests and reduce flakiness.- # Wait longer to ensure all background threads exit completely - time.sleep(1.0) + # Optional: poll for thread shutdown instead of fixed sleep + # e.g., wait up to 1s in 20 * 50ms steps if availabletensorrt_llm/executor/rpc_proxy.py (4)
67-77: Avoid inner import; consider public starter.
- Remove inner
import time; use the module-level import.- Using a private
_start_response_reader_lazilyis brittle; consider exposing a publicensure_reader_started()on RPCClient later.- if hasattr(self.rpc_client, '_start_response_reader_lazily'): - self.rpc_client._start_response_reader_lazily() - # Give response reader time to start - import time - time.sleep(0.1) + if hasattr(self.rpc_client, '_start_response_reader_lazily'): + self.rpc_client._start_response_reader_lazily() + time.sleep(0.1) # Give response reader time to start
298-320: Register result before submit; drop unused exception var and log.
- Great race fix moving registration before send.
- Remove unused
eand log with traceback if needed.- except Exception as e: + except Exception: # Clean up on error self._results.pop(client_id, None) - raise + logger.exception("submit() failed") + raiseRuff F841.
346-364: Shutdown: avoid blind except, prefer logger.exception.Use specific exceptions where possible, or at least log stack traces.
- except Exception as e: - logger.warning(f"Error during main loop shutdown: {e}") + except Exception: + logger.exception("Error during main loop shutdown")- except Exception as e: - logger.warning(f"Error during MPI session shutdown: {e}") + except Exception: + logger.exception("Error during MPI session shutdown")- except Exception as e: - logger.warning(f"Error during RPC client close: {e}") + except Exception: + logger.exception("Error during RPC client close")Ruff BLE001.
369-373: Remove f-strings without placeholders.Ruff F541: unnecessary
fprefix.- logger_debug(f"Shutting down mpi session", color="yellow") + logger_debug("Shutting down mpi session", color="yellow") - logger_debug(f"Mpi session shutdown", color="yellow") + logger_debug("Mpi session shutdown", color="yellow")
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (7)
- tensorrt_llm/executor/rpc/rpc_client.py(3 hunks)
- tensorrt_llm/executor/rpc/rpc_server.py(12 hunks)
- tensorrt_llm/executor/rpc_proxy.py(8 hunks)
- tests/integration/test_lists/waives.txt(0 hunks)
- tests/unittest/executor/test_rpc.py(5 hunks)
- tests/unittest/executor/test_rpc_proxy.py(0 hunks)
- tests/unittest/executor/test_rpc_worker.py(0 hunks)
💤 Files with no reviewable changes (3)
- tests/integration/test_lists/waives.txt
- tests/unittest/executor/test_rpc_worker.py
- tests/unittest/executor/test_rpc_proxy.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{h,hpp,hh,hxx,cpp,cxx,cc,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Use only spaces, no tabs; indent with 4 spaces.
Files:
- tensorrt_llm/executor/rpc_proxy.py
- tensorrt_llm/executor/rpc/rpc_client.py
- tests/unittest/executor/test_rpc.py
- tensorrt_llm/executor/rpc/rpc_server.py
**/*.py
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
**/*.py: Python code must target Python 3.8+.
Indent Python code with 4 spaces; do not use tabs.
Maintain module namespace when importing; prefer 'from package.subpackage import foo' then 'foo.SomeClass()' instead of importing the class directly.
Python filenames should be snake_case (e.g., some_file.py).
Python classes use PascalCase names.
Functions and methods use snake_case names.
Local variables use snake_case; prefix 'k' for variables that start with a number (e.g., k_99th_percentile).
Global variables use upper SNAKE_CASE prefixed with 'G' (e.g., G_MY_GLOBAL).
Constants use upper SNAKE_CASE (e.g., MY_CONSTANT).
Avoid shadowing variables from an outer scope.
Initialize all externally visible members of a class in the constructor.
Prefer docstrings for interfaces that may be used outside a file; comments for in-function or file-local interfaces.
Use Google-style docstrings for classes and functions (Sphinx-parsable).
Document attributes and variables inline so they render under the class/function docstring.
Avoid reflection when a simpler, explicit approach suffices (e.g., avoid dict(**locals()) patterns).
In try/except, catch the most specific exceptions possible.
For duck-typing try/except, keep the try body minimal and use else for the main logic.
Files:
- tensorrt_llm/executor/rpc_proxy.py
- tensorrt_llm/executor/rpc/rpc_client.py
- tests/unittest/executor/test_rpc.py
- tensorrt_llm/executor/rpc/rpc_server.py
**/*.{cpp,cxx,cc,h,hpp,hh,hxx,cu,cuh,py}
📄 CodeRabbit inference engine (CODING_GUIDELINES.md)
Prepend the NVIDIA Apache-2.0 copyright header with current year to the top of all source files (e.g., .cpp, .h, .cu, .py).
Files:
- tensorrt_llm/executor/rpc_proxy.py
- tensorrt_llm/executor/rpc/rpc_client.py
- tests/unittest/executor/test_rpc.py
- tensorrt_llm/executor/rpc/rpc_server.py
🧬 Code graph analysis (4)
tensorrt_llm/executor/rpc_proxy.py (6)
tensorrt_llm/executor/rpc/rpc_common.py (1)
RPCCancelled(55-59)tensorrt_llm/executor/rpc/rpc_client.py (2)
_start_response_reader_lazily(252-270)
close(119-157)tensorrt_llm/executor/proxy.py (2)
submit(417-442)
shutdown(368-415)tensorrt_llm/executor/base_worker.py (2)
submit(526-558)
shutdown(560-568)tensorrt_llm/llmapi/utils.py (2)
stop(326-327)
logger_debug(103-116)tensorrt_llm/llmapi/llm.py (1)
shutdown(743-750)
tensorrt_llm/executor/rpc/rpc_client.py (1)
tensorrt_llm/llmapi/utils.py (1)
logger_debug(103-116)
tests/unittest/executor/test_rpc.py (3)
tensorrt_llm/executor/rpc/rpc_client.py (5)
RPCClient(72-507)
shutdown_server(110-117)
remote_future(58-63)
close(119-157)
remote(44-49)tensorrt_llm/executor/rpc/rpc_common.py (2)
RPCCancelled(55-59)
get_unique_ipc_addr(9-16)tensorrt_llm/executor/rpc/rpc_server.py (5)
RPCServer(17-587)
bind(82-94)
start(558-587)
address(72-74)
shutdown(96-150)
tensorrt_llm/executor/rpc/rpc_server.py (3)
tensorrt_llm/executor/rpc/rpc_common.py (6)
RPCCancelled(55-59)
RPCError(33-48)
RPCRequest(67-81)
RPCResponse(84-90)
RPCStreamingError(62-63)
RPCTimeout(51-52)tensorrt_llm/llmapi/utils.py (1)
logger_debug(103-116)tensorrt_llm/executor/ipc.py (1)
put_async(163-181)
🪛 Ruff (0.14.1)
tensorrt_llm/executor/rpc_proxy.py
165-165: Avoid specifying long messages outside the exception class
(TRY003)
316-316: Local variable e is assigned to but never used
Remove assignment to unused variable e
(F841)
362-362: Do not catch blind exception: Exception
(BLE001)
369-369: f-string without any placeholders
Remove extraneous f prefix
(F541)
371-371: f-string without any placeholders
Remove extraneous f prefix
(F541)
373-373: Do not catch blind exception: Exception
(BLE001)
379-379: Do not catch blind exception: Exception
(BLE001)
tensorrt_llm/executor/rpc/rpc_client.py
267-267: Do not catch blind exception: Exception
(BLE001)
tensorrt_llm/executor/rpc/rpc_server.py
191-191: Do not catch blind exception: Exception
(BLE001)
203-203: Store a reference to the return value of asyncio.create_task
(RUF006)
462-463: Abstract raise to an inner function
(TRY301)
462-463: Avoid specifying long messages outside the exception class
(TRY003)
483-484: Abstract raise to an inner function
(TRY301)
483-484: Avoid specifying long messages outside the exception class
(TRY003)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Pre-commit Check
🔇 Additional comments (6)
tests/unittest/executor/test_rpc.py (1)
472-481: LGTM: validates RPCCancelled on in-flight future after shutdown.tensorrt_llm/executor/rpc_proxy.py (2)
109-111: LGTM: handle RPCCancelled explicitly in fetch loop.
140-166: Main loop readiness signal: good; keep wait bounded.The event-based readiness + 5s wait is solid; nothing to change.
tensorrt_llm/executor/rpc/rpc_server.py (3)
248-266: LGTM: centralized error response helper is clear and correct.
289-301: LGTM: respect shutdown in worker loop before processing.
446-485: LGTM: graceful streaming cancellation on shutdown.Minor: Ruff TRY003 suggests moving long messages into exception types, but acceptable as-is.
| # Clear the queue and send cancelled errors for all pending requests | ||
| if self._queue is not None: | ||
| self._cancel_pending_queue_requests() | ||
|  | 
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Queue draining during shutdown may run on the wrong loop/thread.
_cancel_pending_queue_requests() schedules work on whatever loop is in the calling thread; asyncio.Queue is not thread-safe across loops. This risks cross-thread access or a no-op.
Fix by capturing the server loop and scheduling via run_coroutine_threadsafe:
-        if self._queue is not None:
-            self._cancel_pending_queue_requests()
+        if self._queue is not None:
+            self._cancel_pending_queue_requests()(see next comment for implementation)
Committable suggestion skipped: line range outside the PR's diff.
🤖 Prompt for AI Agents
In tensorrt_llm/executor/rpc/rpc_server.py around lines 121 to 124, the call to
_cancel_pending_queue_requests() may run on the wrong thread/loop because it
runs in the current thread; capture the server's asyncio loop (e.g., self._loop
when the server starts) and schedule the cancellation coroutine onto that loop
using asyncio.run_coroutine_threadsafe so the queue operations execute on the
correct loop; make _cancel_pending_queue_requests an async coroutine if it isn’t
already and replace the direct call with
run_coroutine_threadsafe(self._cancel_pending_queue_requests(), self._loop) (or
use loop.call_soon_threadsafe to submit a wrapper) to ensure thread-safe
draining.
Signed-off-by: Superjomn <[email protected]>
Summary by CodeRabbit
Release Notes
Bug Fixes
Tests
Description
Test Coverage
PR Checklist
Please review the following before submitting your PR:
PR description clearly explains what and why. If using CodeRabbit's summary, please make sure it makes sense.
PR Follows TRT-LLM CODING GUIDELINES to the best of your knowledge.
Test cases are provided for new code paths (see test instructions)
Any new dependencies have been scanned for license and vulnerabilities
CODEOWNERS updated if ownership changes
Documentation updated as needed
The reviewers assigned automatically/manually are appropriate for the PR.
Please check this after reviewing the above items as appropriate for this PR.
GitHub Bot Help
/bot [-h] ['run', 'kill', 'skip', 'reuse-pipeline'] ...Provide a user friendly way for developers to interact with a Jenkins server.
Run
/bot [-h|--help]to print this help message.See details below for each supported subcommand.
run [--reuse-test (optional)pipeline-id --disable-fail-fast --skip-test --stage-list "A10-PyTorch-1, xxx" --gpu-type "A30, H100_PCIe" --test-backend "pytorch, cpp" --add-multi-gpu-test --only-multi-gpu-test --disable-multi-gpu-test --post-merge --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx" --detailed-log --debug(experimental)]Launch build/test pipelines. All previously running jobs will be killed.
--reuse-test (optional)pipeline-id(OPTIONAL) : Allow the new pipeline to reuse build artifacts and skip successful test stages from a specified pipeline or the last pipeline if no pipeline-id is indicated. If the Git commit ID has changed, this option will be always ignored. The DEFAULT behavior of the bot is to reuse build artifacts and successful test results from the last pipeline.--disable-reuse-test(OPTIONAL) : Explicitly prevent the pipeline from reusing build artifacts and skipping successful test stages from a previous pipeline. Ensure that all builds and tests are run regardless of previous successes.--disable-fail-fast(OPTIONAL) : Disable fail fast on build/tests/infra failures.--skip-test(OPTIONAL) : Skip all test stages, but still run build stages, package stages and sanity check stages. Note: Does NOT update GitHub check status.--stage-list "A10-PyTorch-1, xxx"(OPTIONAL) : Only run the specified test stages. Examples: "A10-PyTorch-1, xxx". Note: Does NOT update GitHub check status.--gpu-type "A30, H100_PCIe"(OPTIONAL) : Only run the test stages on the specified GPU types. Examples: "A30, H100_PCIe". Note: Does NOT update GitHub check status.--test-backend "pytorch, cpp"(OPTIONAL) : Skip test stages which don't match the specified backends. Only support [pytorch, cpp, tensorrt, triton]. Examples: "pytorch, cpp" (does not run test stages with tensorrt or triton backend). Note: Does NOT update GitHub pipeline status.--only-multi-gpu-test(OPTIONAL) : Only run the multi-GPU tests. Note: Does NOT update GitHub check status.--disable-multi-gpu-test(OPTIONAL) : Disable the multi-GPU tests. Note: Does NOT update GitHub check status.--add-multi-gpu-test(OPTIONAL) : Force run the multi-GPU tests in addition to running L0 pre-merge pipeline.--post-merge(OPTIONAL) : Run the L0 post-merge pipeline instead of the ordinary L0 pre-merge pipeline.--extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx"(OPTIONAL) : Run the ordinary L0 pre-merge pipeline and specified test stages. Examples: --extra-stage "H100_PCIe-TensorRT-Post-Merge-1, xxx".--detailed-log(OPTIONAL) : Enable flushing out all logs to the Jenkins console. This will significantly increase the log volume and may slow down the job.--debug(OPTIONAL) : Experimental feature. Enable access to the CI container for debugging purpose. Note: Specify exactly one stage in thestage-listparameter to access the appropriate container environment. Note: Does NOT update GitHub check status.For guidance on mapping tests to stage names, see
docs/source/reference/ci-overview.mdand the
scripts/test_to_stage_mapping.pyhelper.kill
killKill all running builds associated with pull request.
skip
skip --comment COMMENTSkip testing for latest commit on pull request.
--comment "Reason for skipping build/test"is required. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.reuse-pipeline
reuse-pipelineReuse a previous pipeline to validate current commit. This action will also kill all currently running builds associated with the pull request. IMPORTANT NOTE: This is dangerous since lack of user care and validation can cause top of tree to break.