Skip to content

Conversation

@Tabrizian
Copy link
Member

@Tabrizian Tabrizian commented Aug 20, 2025

Summary by CodeRabbit

  • Refactor

    • Centralized per-request response handling and guarded waiting to simplify internal flow.
  • Performance

    • Optional parallel response dispatch retained to improve throughput and responsiveness.
  • Bug Fixes

    • More reliable synchronization and counter handling to prevent races and intermittent assertions.
  • Tests

    • Re-enabled two previously-waived integration tests.
  • Chores

    • No changes to public APIs or external signatures.

Description

Test Coverage

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 the stage-list parameter 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.md
and the scripts/test_to_stage_mapping.py helper.

kill

kill

Kill all running builds associated with pull request.

skip

skip --comment COMMENT

Skip 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-pipeline

Reuse 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.

@Tabrizian Tabrizian requested a review from a team as a code owner August 20, 2025 19:11
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

📝 Walkthrough

Walkthrough

Centralizes per-request response progression in cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp by adding a private sendResponse helper, initializing per-request counters, guarded waiting, and moving block hashes into requests; and removes 2 SKIP entries from tests/integration/test_lists/waives.txt. Public APIs unchanged.

Changes

Cohort / File(s) Summary
Response flow refactor
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
Added private sendResponse(std::vector<size_t> const& blockHashes, std::map<RequestIdType, Response>::iterator it); refactored response() to initialize per-request counters (mRemainSendCount[reqId]) and mCurrentRequest, replace inline decrement/dispatch logic with sendResponse, use a guarded wait loop on mResponderCv when no ready response, decrement and assert remaining count, move blockHashes into llmRequest->setRequestedBlockHashes, conditionally dispatch sendAndRemoveResponse on a new thread when EnvParallelCacheSend is true (or inline otherwise), call removeResponse(it), and clear mCurrentRequest. Synchronization primitives and public signatures retained.
Test gating changes
tests/integration/test_lists/waives.txt
Removed 2 SKIP entries enabling previously waived integration tests (Llama3 MMLU cases). No runtime code changes.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller
  participant DataTransceiver
  participant Sender
  participant LlmRequest

  Caller->>DataTransceiver: response()
  activate DataTransceiver

  alt ready response present
    DataTransceiver->>DataTransceiver: prepare reqId/counter if new
    DataTransceiver->>DataTransceiver: call sendResponse(blockHashes,it)
  else wait for ready response
    loop wait/recheck
      DataTransceiver-->>DataTransceiver: wait(mResponderCv) / recheck getCurrentResponse()
    end
    DataTransceiver->>DataTransceiver: call sendResponse(blockHashes,it)
  end

  rect rgba(200,230,255,0.18)
    note right of DataTransceiver: sendResponse flow
    DataTransceiver->>DataTransceiver: reqId = mCurrentRequest.value()\n--mRemainSendCount[reqId] (assert >=0)
    DataTransceiver->>LlmRequest: setRequestedBlockHashes(move(blockHashes))
    alt EnvParallelCacheSend == true
      DataTransceiver->>Sender: spawn thread -> sendAndRemoveResponse(...)
    else
      DataTransceiver->>Sender: sendAndRemoveResponse(...) (inline)
    end
    DataTransceiver->>DataTransceiver: removeResponse(it)\nclear mCurrentRequest
  end

  deactivate DataTransceiver
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • pcastonguay
  • chuangz0
  • Shixiaowei02

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 6d9d585 and 261c4db.

📒 Files selected for processing (2)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2 hunks)
  • tests/integration/test_lists/waives.txt (0 hunks)
💤 Files with no reviewable changes (1)
  • tests/integration/test_lists/waives.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
⏰ 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
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @coderabbitai title anywhere in the PR title to generate the title automatically.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a 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 (1)
tests/integration/defs/accuracy/test_disaggregated_serving.py (1)

144-148: Instance-specific NSYS output per ctx server.

Create per-instance NSYS args so each server writes a distinct report.

Apply this diff:

-        ctx_server_args = nsys_args + common_args + [
+        nsys_args = nsys_args_base + [f"--output=ctx_server_trace_{port}"]
+        ctx_server_args = nsys_args + common_args + [
             "--port",
             str(port), "--extra_llm_api_options", ctx_server_config_path,
             f"--tp_size={ctx_tp}", f"--pp_size={ctx_pp}"
         ]

Optional: gate profiling to environments where NSYS is available (e.g., only when os.environ.get("TLLM_ENABLE_NSYS_CTX") == "1", or if shutil.which("nsys") is not None) to avoid CI failures.

🧹 Nitpick comments (4)
tensorrt_llm/_torch/pyexecutor/py_executor.py (2)

799-819: Block on isend only when you’re about to finalize the same microbatch (avoid unnecessary stall on last PP rank).

The added wait() at Line 818 ensures memory lifetime before resource reclamation on non-last PP ranks (good to prevent UAF). However, on the last PP rank Stage 2 and Stage 3 operate on different prev_microbatch_ids, so this wait is not required and may reduce overlap. Restrict the post-isend wait to non-last PP ranks.

Apply this diff:

-                        self.send_handles[prev_microbatch_id].wait()
+                        # Non-last PP ranks finalize the same microbatch in Stage 3, so ensure send completes.
+                        if not self.dist.is_last_pp_rank:
+                            self.send_handles[prev_microbatch_id].wait()

Also, minor: needs_logits currently uses scheduled_batch, but the data being sent belongs to previous_batch. Consider basing the decision on previous_batch.sample_state.scheduled_requests to avoid mismatch if current/previous batches diverge. Not critical to this PR, but worth a follow-up.


1-10: Missing NVIDIA SPDX header for Python source.

Per repo guidelines, prepend the NVIDIA copyright header to Python files.

I can provide a ready-to-paste header if you want.

tests/integration/defs/accuracy/test_disaggregated_serving.py (1)

1-18: Missing NVIDIA SPDX header in test file.

Tests are also source files. Please prepend the NVIDIA header to comply with the repo standard.

cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

223-236: Avoid unnecessary copy and dangling lifetime risk; remove unused blockHashes copy and bind by value.

The temporary RequestInfo from recvRequestInfo() is currently bound to a const reference, and you copy blockHashes into a local that isn’t used afterwards. Clean this up and move the RequestInfo into the map.

Apply this diff:

-                std::vector<size_t> blockHashes;
-                auto const& requestInfo = mSender->recvRequestInfo();
-                auto reqId = requestInfo.getRequestId();
-                blockHashes = requestInfo.getBlockHashes();
+                auto requestInfo = mSender->recvRequestInfo();
+                auto reqId = requestInfo.getRequestId();
                 {
                     std::unique_lock lk(mSendMutex);
-                    mRequestInfoMap[reqId] = std::move(requestInfo);
+                    mRequestInfoMap[reqId] = std::move(requestInfo);
                     if (mRemainSendCount.find(reqId) == mRemainSendCount.end())
                     {
                         mRemainSendCount[reqId] = mSender->getCounterpartsCount(reqId);
                     }
                 }
                 sendResponse(reqId);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9a8f9b3 and 718b583.

📒 Files selected for processing (3)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (4 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (1 hunks)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py (2 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tests/integration/defs/accuracy/test_disaggregated_serving.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tests/integration/defs/accuracy/test_disaggregated_serving.py
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧠 Learnings (1)
📚 Learning: 2025-08-06T08:18:28.669Z
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🔇 Additional comments (1)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

274-281: Lock ordering looks consistent, but please double-check for future changes.

sendResponse() acquires mSendMutex then (temporarily) mResponderMutex and later removeResponse() acquires mResponderMutex (and mCondMutex). Elsewhere, respondAndSendAsync() acquires mResponderMutex first, but releases it before calling sendResponse(). This avoids an immediate inversion. Keep this ordering in mind for future edits.

If you want, I can scan the repository to ensure no other code paths acquire mResponderMutex then mSendMutex in that order, which could deadlock.

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from 718b583 to 9b63bd7 Compare August 20, 2025 20:22
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
tests/integration/defs/accuracy/test_disaggregated_serving.py (3)

53-53: Replace PEP 585 built-in generics with typing.List for Python 3.8+.

list[... ] requires Python 3.9+. Use List[...] which you already import.

Apply this diff:

-        self.futures: list[concurrent.futures.Future[RequestOutput]] = []
+        self.futures: List[concurrent.futures.Future[RequestOutput]] = []

61-64: Avoid cancel_futures in ThreadPoolExecutor.shutdown for Python 3.8.

cancel_futures was added in Python 3.9. The manual future.cancel() loop above already handles pending futures.

Apply this diff:

-        self.shutdown(wait=True, cancel_futures=True)
+        self.shutdown(wait=True)

193-201: Add timeouts and a bounded wait for the health probe to avoid indefinite hangs.

requests.get() without a timeout can hang forever; the loop also lacks a global deadline even though the server is launched with --server_start_timeout 3600.

Apply this diff:

             ]):
-                while True:
+                start = time.monotonic()
+                timeout_s = 3600
+                while True:
                     time.sleep(1)
                     try:
                         print("Checking health endpoint")
-                        response = requests.get("http://localhost:8000/health")
+                        response = requests.get("http://localhost:8000/health", timeout=5)
                         if response.status_code == 200:
                             break
-                    except requests.exceptions.ConnectionError:
+                    except requests.exceptions.RequestException:
                         continue
+                    if time.monotonic() - start > timeout_s:
+                        raise RuntimeError("disaggregated server did not become healthy within 3600s")
🧹 Nitpick comments (3)
tests/integration/defs/accuracy/test_disaggregated_serving.py (3)

186-186: Make max_workers configurable for CI tuning.

Allow overriding via env var to ease A/B testing and CI tuning without touching code.

Apply this diff:

-    with MyThreadPoolExecutor(max_workers=4) as thread_pool, temp_dir:
+    workers = int(os.getenv("TRTLLM_TEST_MAX_WORKERS", "4"))
+    with MyThreadPoolExecutor(max_workers=workers) as thread_pool, temp_dir:

1-1: Missing NVIDIA copyright header.

Per project guidelines, prepend the current-year NVIDIA header.

Apply this diff at the top of the file:

+# Copyright (c) 2025, NVIDIA CORPORATION & AFFILIATES. All rights reserved.

658-659: Remove stray no-op lines.

These two lines are orphan expressions and do nothing; likely leftovers.

Apply this diff:

-        ctx_server_config["cache_transceiver_config"]
-        ctx_server_config["cache_transceiver_config"]
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 718b583 and 9b63bd7.

📒 Files selected for processing (4)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (4 hunks)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp (0 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (1 hunks)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py (1 hunks)
💤 Files with no reviewable changes (1)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧰 Additional context used
📓 Path-based instructions (2)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tests/integration/defs/accuracy/test_disaggregated_serving.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tests/integration/defs/accuracy/test_disaggregated_serving.py
🧠 Learnings (1)
📓 Common learnings
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.
⏰ 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 (2)
tests/integration/defs/accuracy/test_disaggregated_serving.py (2)

186-186: Lowering thread-pool concurrency to 4 looks reasonable for stabilizing disagg PP send/recv.

This should reduce contention and flakiness when non-last PP ranks block on isend handles. No API changes, so low blast radius.


231-239: Streaming path isn’t handled; confirm it’s unused in this harness.

client.completions.create(..., stream=True) yields an event stream, not a single response. Since send_request assumes a non-streaming object, ensure streaming is always False in this test, or add streaming handling.

Would you like me to add a guarded streaming implementation for completeness?

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch 2 times, most recently from 33978ba to 0653c4b Compare August 20, 2025 20:36
@Tabrizian Tabrizian changed the title Fix disagg pp bug [https://nvbugs/5434320][bug] Fix disagg pp bug Aug 20, 2025
@Tabrizian
Copy link
Member Author

/bot run --add-multi-gpu-test --disable-fail-fast

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

178-182: Incomplete cleanup in destructor

The destructor calls terminate() but doesn't wait for mResponseFuture to complete, which could lead to the response thread accessing destroyed members.

 ~Impl()
 {
     terminate();
+    if (mResponseFuture.valid())
+    {
+        mResponseFuture.wait();
+    }
 }
♻️ Duplicate comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

107-149: Performance: Consider using move semantics for block hashes

The code copies the block hash vector on line 123 and then moves it on line 133. Since the RequestInfo is being erased immediately after, you can avoid the copy by adding a move-out accessor.

Add a takeBlockHashes() method to RequestInfo (in the header file):

std::vector<size_t> takeBlockHashes() noexcept { return std::move(mBlockHashes); }

Then update line 123:

-        auto blockHashes = it->second.getBlockHashes();
+        auto blockHashes = it->second.takeBlockHashes();

135-141: Thread safety concern: Detached thread captures this

The detached thread on lines 138-140 captures this, which can lead to undefined behavior if the DataResponder::Impl instance is destroyed while the thread is still running.

Consider one of these solutions:

  1. Track the threads and join them in the destructor
  2. Use a thread pool with proper lifecycle management
  3. Use std::async which returns a future that can be tracked

Example fix using futures:

+private:
+    std::vector<std::future<void>> mSendFutures;
+
 public:
+    ~Impl()
+    {
+        terminate();
+        // Wait for all pending sends to complete
+        for (auto& future : mSendFutures)
+        {
+            if (future.valid())
+            {
+                future.wait();
+            }
+        }
+    }

And update the detached thread creation:

-                std::thread(
-                    &DataResponder::Impl::sendAndRemoveResponse, this, reqId, std::move(readyResponseIt->second))
-                    .detach();
+                mSendFutures.push_back(
+                    std::async(std::launch::async,
+                        &DataResponder::Impl::sendAndRemoveResponse, this, reqId, std::move(readyResponseIt->second)));
🧹 Nitpick comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

274-274: Naming convention: Inconsistent mutex ordering

The mutex declaration order mCondMutex, mSendMutex, mResponderMutex doesn't follow a clear pattern. Consider ordering them alphabetically or by usage frequency for better readability.

-    std::mutex mCondMutex, mSendMutex, mResponderMutex;
+    std::mutex mCondMutex, mResponderMutex, mSendMutex;

124-126: Add defensive check for negative count

While the code checks that count >= 0 after decrement, it would be more defensive to also ensure mRemainSendCount[reqId] is positive before decrementing.

+        TLLM_CHECK(mRemainSendCount[reqId] > 0);
         auto count = --mRemainSendCount[reqId];
         TLLM_CHECK(count >= 0);
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9b63bd7 and 33978ba.

📒 Files selected for processing (5)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (4 hunks)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp (0 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (1 hunks)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py (1 hunks)
  • tests/integration/test_lists/waives.txt (0 hunks)
💤 Files with no reviewable changes (2)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp
  • tests/integration/test_lists/waives.txt
🚧 Files skipped from review as they are similar to previous changes (2)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • tests/integration/defs/accuracy/test_disaggregated_serving.py
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧠 Learnings (2)
📓 Common learnings
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.
📚 Learning: 2025-08-06T08:18:28.669Z
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🔇 Additional comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

111-117: No deadlock risk between mSendMutex and mResponderMutex
A review of every lock invocation in dataTransceiver.cpp shows that the only time both mSendMutex and mResponderMutex are held together (lines 109–111) acquires them in the same order, and there are no code paths that acquire mResponderMutex first and then attempt mSendMutex. All other uses lock only one mutex at a time.

• Lines 109–111: unique_lock lk(mSendMutex); then unique_lock lkResp(mResponderMutex);
• Lines 156 & 262: only unique_lock lkResp(mResponderMutex);
• Line 228: only unique_lock lk(mSendMutex);

Because there is no reverse ordering anywhere, there is no inconsistent lock ordering and no deadlock risk here.


224-235: False positive: sendResponse ordering is correct

The call to sendResponse(reqId) immediately after storing the new requestInfo is intentionally there to flush any previously queued responses for that request ID.

– In the receive loop, sendResponse locks mSendMutex then mResponderMutex, checks mReadyResponses for reqId, and simply returns if no response is pending.
– New responses are only ever added to mReadyResponses in respondAndSendAsync (lines 157–159), which then immediately calls sendResponse to deliver them.

Because respondAndSendAsync both enqueues the response and invokes sendResponse under the proper locks, there is no race or ordering issue: the early-return in the receive path is expected and harmless.

Likely an incorrect or invalid review comment.

@Tabrizian Tabrizian requested a review from pcastonguay August 20, 2025 20:41
@tensorrt-cicd
Copy link
Collaborator

PR_Github #15950 [ run ] triggered by Bot

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

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)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

238-245: Concurrent access to mReadyResponses in exception path

The catch block iterates mReadyResponses without mResponderMutex, which races with other threads adding/removing entries.

Guard the map while propagating exceptions:

catch (std::exception const& err)
{
    TLLM_LOG_ERROR("Exception in DataResponder response: %s", err.what());
    {
        std::unique_lock lk(mResponderMutex);
        for (auto& it : mReadyResponses)
        {
            it.second.mPromise.set_exception(std::current_exception());
        }
    }
}
♻️ Duplicate comments (1)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

123-127: Build break + unnecessary copy: implement and use a move-out accessor for block hashes

RequestInfo::getBlockHashes() is called here but no such accessor is defined in this TU; additionally, you immediately move the vector into llmRequest->setRequestedBlockHashes(...), so copying first is wasteful. Use a move-taking accessor instead.

Apply this minimal fix now (assuming you add takeBlockHashes() on RequestInfo as shown below):

-        auto blockHashes = it->second.getBlockHashes();
+        auto blockHashes = it->second.takeBlockHashes();
         auto count = --mRemainSendCount[reqId];

Add the accessors to RequestInfo (header; shown here for clarity):

// In class RequestInfo (public):
[[nodiscard]] std::vector<size_t> const& getBlockHashes() const noexcept { return mBlockHashes; }
// Move-out accessor to avoid copying when the entry is about to be erased:
std::vector<size_t> takeBlockHashes() noexcept { return std::move(mBlockHashes); }
🧹 Nitpick comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (1)

111-118: Lock ordering and iterator lifetime — reduce risk of future deadlocks

sendResponse currently takes mSendMutex then briefly takes mResponderMutex, releases it, and continues using the iterator. This is likely safe (std::map insertions don’t invalidate iterators; erasures are controlled). However, to avoid subtle lock-ordering hazards if future code paths acquire these locks in different orders, consider atomically acquiring both:

-        std::unique_lock lk(mSendMutex);
-        // Send context cache is not called for this request yet.
-        std::unique_lock<std::mutex> lkResp(mResponderMutex);
+        std::scoped_lock lk(mSendMutex, mResponderMutex);
         auto readyResponseIt = mReadyResponses.find(reqId);
         if (readyResponseIt == mReadyResponses.end())
         {
             return;
         }
-        lkResp.unlock();
+        // mResponderMutex remains held or release here if you prefer

If you keep the current scheme, ensure no other code path locks mResponderMutex and then tries to grab mSendMutex.

tensorrt_llm/_torch/pyexecutor/py_executor.py (1)

818-821: Blocking on isend_object removes PP overlap; gate it and clear handle after wait

The immediate wait() ensures correctness on problematic nodes but also serializes the PP communication path and can hurt throughput.

Consider guarding with an env flag and clearing the handle after waiting to avoid a redundant wait later:

-                        self.send_handles[
-                            prev_microbatch_id] = self.dist.isend_object(
+                        handle = self.dist.isend_object(
                                 (
                                     serialized_logits,
                                     sample_state.host,
                                 ),
                                 dest=self.dist.next_pp_rank,
                                 tag=prev_microbatch_id)
-                        # TODO: remove this wait, without this wait
-                        # there is an intermittent hang on some nodes.
-                        self.send_handles[prev_microbatch_id].wait()
+                        # Keep for later completion checks
+                        self.send_handles[prev_microbatch_id] = handle
+                        # TODO: remove this guarded wait after root cause is fixed.
+                        if os.environ.get("TLLM_FORCE_SYNC_PP_SEND", "0") == "1":
+                            handle.wait()
+                            # Prevent double-wait in the next iteration
+                            self.send_handles[prev_microbatch_id] = None

Follow-up:

  • Please confirm this wait resolves the intermittent hang on the affected nodes and share repro details so we can pursue a targeted fix (e.g., NCCL PG settings, tags, or ordering).
  • If hang persists, add a watchdog log if wait exceeds a threshold to aid triage.
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 33978ba and 0653c4b.

📒 Files selected for processing (5)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (4 hunks)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp (0 hunks)
  • tensorrt_llm/_torch/pyexecutor/py_executor.py (1 hunks)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py (1 hunks)
  • tests/integration/test_lists/waives.txt (0 hunks)
💤 Files with no reviewable changes (2)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp
  • tests/integration/test_lists/waives.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py
🧰 Additional context used
📓 Path-based instructions (5)
**/*.py

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.py: Python code must target Python 3.8+
Python indentation: 4 spaces, no tabs
Maintain module namespace in imports (from package.subpackage import foo; then use foo.SomeClass())
Python file names use snake_case
Python class names use PascalCase
Python functions/methods and local variables use snake_case; variables starting with a number get k_ prefix (e.g., k_99th_percentile)
Global variables use G_ prefixed UPPER_SNAKE_CASE (e.g., G_MY_GLOBAL)
Constants use UPPER_SNAKE_CASE in Python
Avoid shadowing variables from outer scopes in Python
Initialize all externally visible members of a Python class in init
Prefer docstrings for interfaces used outside a file; comments for local code
Use Google-style docstrings for classes and functions (Sphinx-parsable)
Document attributes/variables inline with short docstrings
Avoid reflection when simple alternatives exist (e.g., prefer explicit parameters over dict(**locals()))
In try/except, catch the narrowest exceptions possible
For duck-typing with try/except, keep try body minimal and put logic in else

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • tensorrt_llm/_torch/pyexecutor/py_executor.py
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit Inference Engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧠 Learnings (2)
📓 Common learnings
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.
📚 Learning: 2025-08-06T08:18:28.669Z
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧬 Code Graph Analysis (1)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (3)
cpp/tests/batch_manager/cacheTransceiverTest.cpp (8)
  • llmRequest (421-450)
  • llmRequest (421-421)
  • llmRequest (872-903)
  • llmRequest (872-872)
  • llmRequest (905-912)
  • llmRequest (905-905)
  • llmRequest (914-933)
  • llmRequest (914-914)
cpp/tensorrt_llm/common/envUtils.cpp (2)
  • getEnvParallelCacheSend (327-331)
  • getEnvParallelCacheSend (327-327)
cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp (1)
  • requestInfo (152-152)
🔇 Additional comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

160-160: Proactive trigger looks good

Calling sendResponse(llmRequest.mRequestId) immediately after enqueuing the ready response reduces latency and improves progress. No issues.


272-281: New synchronization members are reasonable

Introducing mSendMutex and per-request mRequestInfoMap is a sensible way to coordinate ready responses with received request-info. Names follow the style guide; types are appropriate.

@tensorrt-cicd
Copy link
Collaborator

PR_Github #15950 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #242 completed with status: 'FAILURE'

@pcastonguay
Copy link
Collaborator

@chuangz0 can you review the changes to the dataTransceiver? Thanks

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from 0653c4b to 72f97a3 Compare August 21, 2025 19:43
@Tabrizian
Copy link
Member Author

/bot run --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16079 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16079 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #253 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from 83babf0 to 4fd2f93 Compare August 22, 2025 19:00
@Tabrizian
Copy link
Member Author

/bot run --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16216 [ run ] triggered by Bot

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

138-144: Thread management approach addresses previous safety concerns

Using mSendThreads.emplace_back() instead of detached threads properly addresses the use-after-free risk that was flagged in previous reviews. The threads are now tracked and joined in the destructor.


107-147: Critical: getBlockHashes() method missing - build will fail

Line 123 calls it->second.getBlockHashes() but this method is not defined in the RequestInfo class in this translation unit, causing a compilation error.

Based on past review feedback, you need to implement RequestInfo::getBlockHashes() and preferably add a move-taking accessor to avoid unnecessary copying since the RequestInfo is immediately erased:

Add to RequestInfo class in the header file:

[[nodiscard]] const std::vector<size_t>& getBlockHashes() const noexcept { return mBlockHashes; }
// Move-out accessor to avoid copying when the entry is about to be erased:
std::vector<size_t> takeBlockHashes() noexcept { return std::move(mBlockHashes); }

Then update the usage:

-        auto blockHashes = it->second.getBlockHashes();
+        auto blockHashes = it->second.takeBlockHashes();
🧹 Nitpick comments (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

276-276: Mutex declaration alignment issue

The mutex declaration doesn't follow proper C++ formatting - all three mutexes are declared on a single line which hurts readability.

Apply this diff for better readability:

-    std::mutex mCondMutex, mSendMutex, mResponderMutex;
+    std::mutex mCondMutex;
+    std::mutex mSendMutex;
+    std::mutex mResponderMutex;

179-184: Thread cleanup logic is correct but could be more robust

The destructor properly joins all threads before clearing the vector. However, consider adding exception safety around thread joining.

Apply this diff for more robust cleanup:

         for (auto& thread : mSendThreads)
         {
-            thread.join();
+            if (thread.joinable())
+            {
+                thread.join();
+            }
         }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 83babf0 and 4fd2f93.

📒 Files selected for processing (4)
  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (5 hunks)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp (0 hunks)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py (1 hunks)
  • tests/integration/test_lists/waives.txt (0 hunks)
💤 Files with no reviewable changes (2)
  • cpp/tensorrt_llm/batch_manager/llmRequest.cpp
  • tests/integration/test_lists/waives.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration/defs/accuracy/test_disaggregated_serving.py
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh}: In C++, close namespaces with a comment naming the namespace (e.g., } // namespace foo)
Prefer const/constexpr variables over #define for constants
Declare variables const if not modified after initialization
Use Allman brace style in C++
C++ filenames use lowerCamelCase and must be case-insensitively unique within a build target
C++ type names use UpperCamelCase
Local variables, methods, and namespaces use lowerCamelCase
Global non-static variables not in anonymous namespace use gPrefix lowerCamelCase (e.g., gExample)
Static globals or globals in anonymous namespaces use sPrefix lowerCamelCase
Locally visible static variables start with 's' (e.g., static std::once_flag sFlag;)
Member variables use mPrefix lowerCamelCase; public members may omit but are encouraged to use 'm'
Constants (enums, global/static/function-scope magic numbers) use kPREFIXED_UPPER_SNAKE (e.g., kDIGIT_NUM)
If macros are unavoidable, use UPPER_SNAKE_CASE (prefer constants over #define)
Constructor parameter that conflicts with a public member name gets trailing underscore (foo_)
Literal suffixes should be uppercase (e.g., 1234L not 1234l)
C++: use spaces only; indent 4 spaces
Run clang-format (LLVM style) before submitting; wrap lines at 120 characters
If formatting must be bypassed, use // clang-format off/on around the section
Prefer smart pointers; use unique_ptr for sole ownership, shared_ptr for shared; weak_ptr only in exceptional cases
Do not use deprecated pre-C++11 smart pointers
Use C++ style comments; avoid C comments except special inline cases; prefer // single-line
Capitalize and punctuate full-sentence comments
Follow Doxygen rules: use //! for comments and //!< for members in C++
Disable code with #if/#endif and mnemonic conditions; avoid commented-out code; avoid dead code
Do not throw exceptions across library boundaries
Use least-forceful casts; avoid removing const/volatile; avoid C-style and functional casts (except constructors); p...

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

**/*.{cpp,cxx,cc,cu}: Avoid literal values except for 0, nullptr, true, false; use named constexpr for other literals
Place semicolon of empty for/while loop on a new line
Always use brace-delimited bodies for switch/while/do-for/if/else
Use inline C comments in argument lists when parameter meaning is unclear (e.g., /* checkForErrors = */ false)
Do not use assignment in subexpressions (e.g., if (x = y) ... is forbidden)
Switch on enums should enumerate all values and omit default to catch new values at compile time
Structure switch statements; prohibit fallthrough except between empty cases; each case ends with break or throw; return at end of case not allowed; put break inside braces for compound case
Prefer anonymous namespaces over static for internal linkage of functions
Every defined function must be called at least once (no unused methods)

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{h,hpp,hxx,hh,cuh,cpp,cxx,cc,cu}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Parameter names must be consistent between declarations and definitions

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
**/*.{cpp,cxx,cc,cu,h,hpp,hxx,hh,cuh,py}

📄 CodeRabbit inference engine (CODING_GUIDELINES.md)

Prepend NVIDIA copyright header (current year) to all source files

Files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
🧠 Learnings (1)
📚 Learning: 2025-08-06T08:18:28.669Z
Learnt from: zhengd-nv
PR: NVIDIA/TensorRT-LLM#6633
File: cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp:145-155
Timestamp: 2025-08-06T08:18:28.669Z
Learning: In cpp/tensorrt_llm/batch_manager/dataTransceiverImpl.cpp, the existing `mMtxForMap` mutex in DataSenderImpl is sufficient to synchronize measurement file operations in the `release` method, as all file operations occur within the same critical section that protects the `mRequestToSession` map access.

Applied to files:

  • cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp
⏰ 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 (2)
cpp/tensorrt_llm/batch_manager/dataTransceiver.cpp (2)

227-237: Good refactoring - per-request state management

The migration from single current request tracking to per-request mapping in mRequestInfoMap properly addresses the concurrency issues. The logic correctly stores the RequestInfo and initializes reference counting for each request.


159-159: Excellent architectural improvement

The immediate call to sendResponse(llmRequest.mRequestId) after enqueueing the ready response creates a proper event-driven dispatch mechanism. This replaces the previous blocking approach with a more responsive design.

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from 4fd2f93 to d536bd2 Compare August 25, 2025 00:48
@Tabrizian
Copy link
Member Author

/bot run --add-multi-gpu-test --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16335 [ run ] triggered by Bot

@chuangz0
Copy link
Collaborator

chuangz0 commented Aug 25, 2025

Inside pp_loop, send_ctx_cache is called on previous_batch.context_reqs.
Is it possible to call send_ctx_cache or respond_and_send_async directly on current_batch/scheduled_batch.context_reqs after forward_step? @pcastonguay @Tabrizian . Perhaps this could also ensure that before creating the response, all ranks have the ctx_cache information saved in the cache transceiver.
cc @Shixiaowei02

I am somewhat concerned that the changes in this PR might potentially cause a deadlock issue, although I have not yet found a case that would lead to a deadlock.
Our sendAndRemoveResponse and recvSync functions are blocking. recvSync must wait until all the corresponding context ranks have called sendSync before it can complete.
For example, rank0 of gen requests the same request's kvCache from context ranks 0, 1, 2, and 3. Gen's rank0 needs to sequentially wait for sendSync from ranks 0, 1, 2, and 3.

@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from c480836 to e90e18a Compare August 26, 2025 16:59
@Tabrizian
Copy link
Member Author

/bot run

Signed-off-by: Iman Tabrizian <[email protected]>
Signed-off-by: Iman Tabrizian <[email protected]>
@Tabrizian Tabrizian force-pushed the user/imant/fixDisaggBug branch from e90e18a to 169a658 Compare August 26, 2025 17:03
@tensorrt-cicd
Copy link
Collaborator

PR_Github #16581 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16577 [ run ] completed with state ABORTED

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16581 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #313 completed with status: 'FAILURE'

@Tabrizian
Copy link
Member Author

/bot run --only-multi-gpu-test

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16652 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16652 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #322 (Partly Tested) completed with status: 'SUCCESS'

@pcastonguay
Copy link
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16688 [ run ] triggered by Bot

@tensorrt-cicd
Copy link
Collaborator

PR_Github #16688 [ run ] completed with state SUCCESS
/LLM/release-1.0/L0_MergeRequest_PR pipeline #326 completed with status: 'SUCCESS'

@pcastonguay pcastonguay merged commit 91c4af3 into NVIDIA:release/1.0 Aug 27, 2025
5 checks passed
yuanjingx87 pushed a commit that referenced this pull request Aug 28, 2025
@Tabrizian Tabrizian deleted the user/imant/fixDisaggBug branch August 28, 2025 17:51
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 4, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 5, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 5, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 6, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 6, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 7, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 8, 2025
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Sep 8, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants