Skip to content

[None][chore] KV Connector Refactor#11078

Merged
pcastonguay merged 3 commits into
NVIDIA:mainfrom
jthomson04:jthomson04/kv-connector-cleanup-v2
Feb 25, 2026
Merged

[None][chore] KV Connector Refactor#11078
pcastonguay merged 3 commits into
NVIDIA:mainfrom
jthomson04:jthomson04/kv-connector-cleanup-v2

Conversation

@jthomson04
Copy link
Copy Markdown
Collaborator

@jthomson04 jthomson04 commented Jan 29, 2026

Summary by CodeRabbit

  • Bug Fixes

    • Improved KV cache sequence management with better error handling for resource allocation failures.
  • Refactor

    • Enhanced KV cache connector integration workflow for more robust disaggregated generation support.
    • Streamlined internal KV cache resource management and state transitions.
  • Tests

    • Updated integration and unit tests to reflect improved KV cache handling and connector workflows.

✏️ Tip: You can customize this high-level summary in your review settings.

Implements the remaining refactors from #9186.

  • Restructures the call to get_num_new_matched_tokens to be called before being added to the scheduled batch.
  • Further unification of disagg and KV connector handling in the py executor
  • Simplified state management in the kv connector manager

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

  • Update tava architecture diagram if there is a significant design change in PR.

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

Details

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.

@jthomson04 jthomson04 changed the title feat: KV Connector Refactor [None][chore]: KV Connector Refactor Jan 29, 2026
@jthomson04 jthomson04 changed the title [None][chore]: KV Connector Refactor [None][chore] KV Connector Refactor Jan 29, 2026
@jthomson04
Copy link
Copy Markdown
Collaborator Author

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #33934 [ run ] triggered by Bot. Commit: c229b67

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #33934 [ run ] completed with state SUCCESS. Commit: c229b67
/LLM/main/L0_MergeRequest_PR pipeline #26174 completed with status: 'FAILURE'

⚠️ Action Required:

  • Please check the failed tests and fix your PR
  • If you cannot view the failures, ask the CI triggerer to share details
  • Once fixed, request an NVIDIA team member to trigger CI again

@jthomson04 jthomson04 marked this pull request as ready for review January 29, 2026 18:23
@jthomson04 jthomson04 requested review from a team as code owners January 29, 2026 18:23
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 29, 2026

📝 Walkthrough

Walkthrough

This pull request changes the addSequence method return type from void to bool across KV cache manager implementations, refactors the KvCacheConnectorManager to simplify state tracking and request readiness logic, and integrates new KV cache connector workflows into the executor and resource manager initialization paths.

Changes

Cohort / File(s) Summary
KV Cache Manager API Update
cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h, cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp, cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManager.cpp
Changed addSequence return type from void to bool in base class, implementation, and nanobind wrapper. Method now returns true on successful sequence addition and false on failure, replacing previous assertion-based error handling.
KV Cache Connector Manager Refactoring
tensorrt_llm/_torch/pyexecutor/kv_cache_connector.py
Removed finished_async_loading_requests tracking and should_add_sequence method. Renamed take_scheduled_requests_pending_load to mark_ready_requests with updated signature and return type. Simplified state transitions and request readiness computation.
Executor and Resource Manager Integration
tensorrt_llm/_torch/pyexecutor/py_executor.py, tensorrt_llm/_torch/pyexecutor/resource_manager.py
Added KV cache connector workflow integration into batch preparation and scheduling. Updated prepare_resources to use direct add_sequence calls with connector state updates. Removed _kv_connector_should_add_sequence helper method and adjusted conditional branching for disaggregated generation initialization.
Test Updates
tests/integration/defs/llmapi/test_llm_api_connector.py, tests/unittest/_torch/test_connector.py
Updated integration tests to reflect API call changes and adjusted token count assertions. Extended unit tests to validate multi-token prediction behavior with new imports and test case for KvCacheConnectorSchedulerOutputManager.

Sequence Diagram(s)

sequenceDiagram
    participant Executor as PyExecutor
    participant Connector as KvCacheConnectorManager
    participant KVMgr as KVCacheManager
    participant Scheduler as Scheduler

    Executor->>Executor: _fetch_and_activate_new_requests()
    Executor->>Connector: mark_ready_requests(fitting_disagg_gen_init_requests)
    Connector-->>Executor: List[LlmRequest]
    Executor->>Scheduler: reschedule()
    Executor->>KVMgr: prepare_resources()
    KVMgr->>KVMgr: add_sequence(req.py_request_id, ...)
    alt Sequence Added Successfully
        KVMgr->>KVMgr: allocate extra KV tokens
        KVMgr->>KVMgr: add draft tokens
        KVMgr->>Connector: update_state_after_alloc(block_ids)
    else Sequence Add Failed
        KVMgr-->>Executor: false
    end
    Executor->>Connector: get_num_new_matched_tokens()
    alt Load KV Async
        Connector->>Connector: add to loading state
    end
    Connector-->>Executor: num_matched_tokens
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested reviewers

  • achartier
  • kaiyux
  • lucaslie
🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive Description provides high-level context referencing PR #9186 and outlines three main changes, but lacks detailed explanation of what and why, missing Test Coverage section, and the template sections are incomplete. Add detailed explanation of the refactoring rationale, list relevant test files that validate the changes, and complete the PR checklist sections appropriately.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed Title clearly indicates this is a refactoring effort focused on KV Connector with proper format, and aligns with the raw_summary changes across multiple KV-related files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
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 (4)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (1)

1-3: Update the copyright year to include 2026.

The file was modified this year, so the header should reflect the latest meaningful modification date.

✏️ Proposed update
- * SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.

cpp/include/tensorrt_llm/batch_manager/kvCacheManager.h (1)

1-3: Update the copyright year to include 2026.

This header was modified this year, so the header should reflect the latest meaningful modification date.

✏️ Proposed update
- * Copyright (c) 2022-2024, NVIDIA CORPORATION.  All rights reserved.
+ * Copyright (c) 2022-2026, NVIDIA CORPORATION.  All rights reserved.

As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.

cpp/tensorrt_llm/nanobind/batch_manager/kvCacheManager.cpp (1)

1-3: Update the copyright year to include 2026.

This file was modified this year, so the header should reflect the latest meaningful modification date.

✏️ Proposed update
- * SPDX-FileCopyrightText: Copyright (c) 2022-2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
+ * SPDX-FileCopyrightText: Copyright (c) 2022-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.

As per coding guidelines: All TensorRT-LLM source files (.cpp, .h, .cu, .py, and other source files) should contain an NVIDIA copyright header with the year of latest meaningful modification.

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

463-474: Handle add_sequence failure explicitly to avoid silent allocation gaps.

add_sequence now returns a bool, but the failure path silently skips token allocation and connector updates while leaving the request scheduled. That can lead to missing KV cache state and downstream failures. Consider surfacing the failure immediately (raise/log + abort scheduling) so it can’t proceed in a half‑initialized state.

🔧 Proposed fix
-                    if self.impl.add_sequence(req.py_request_id, req.prompt_len,
-                                              req_beam_width, req):
-                        for _ in range(self.num_extra_kv_tokens):
-                            self.impl.add_token(req.py_request_id)
-                        for _ in range(get_draft_token_length(req)):
-                            self.impl.add_token(req.py_request_id)
-
-                        if self.kv_connector_manager is not None:
-                            block_ids = self.get_cache_indices(req)
-                            self.kv_connector_manager.update_state_after_alloc(
-                                req, block_ids)
+                    added = self.impl.add_sequence(req.py_request_id,
+                                                   req.prompt_len,
+                                                   req_beam_width, req)
+                    if not added:
+                        raise RuntimeError(
+                            f"KV cache add_sequence failed for request "
+                            f"{req.py_request_id}")
+                    for _ in range(self.num_extra_kv_tokens):
+                        self.impl.add_token(req.py_request_id)
+                    for _ in range(get_draft_token_length(req)):
+                        self.impl.add_token(req.py_request_id)
+
+                    if self.kv_connector_manager is not None:
+                        block_ids = self.get_cache_indices(req)
+                        self.kv_connector_manager.update_state_after_alloc(
+                            req, block_ids)
🤖 Fix all issues with AI agents
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_connector.py`:
- Around line 438-458: The bug is inconsistent keying of async-load tracking:
get_num_new_matched_tokens stores entries in new_async_requests.loading keyed by
request.request_id while mark_ready_requests checks and writes using
req.py_request_id, causing missed matches/overwrites; update mark_ready_requests
to consistently use request.request_id (check new_async_requests.loading_ids for
req.request_id, append ready requests the same way, and set
new_async_requests.loading[req.request_id] = req when replacing the canonical
request) so keys match get_num_new_matched_tokens; reference symbols:
mark_ready_requests, get_num_new_matched_tokens, new_async_requests.loading,
new_async_requests.loading_ids, req.request_id, req.py_request_id, and
LlmRequestState.CONTEXT_INIT.

In `@tests/integration/defs/llmapi/test_llm_api_connector.py`:
- Around line 393-402: The test test_connector_disagg_prefill removed the sleep
that ensured asynchronous KV connector callbacks finished, causing racey
asserts; restore synchronization by calling the generate_and_sleep helper after
the prefill_worker.generate and after the decode_worker.generate calls (or
replace those calls with a proper await/wait that blocks until
scheduler.build_connector_meta and related connector callbacks complete) so the
subsequent assertions on scheduler.build_connector_meta.call_count and mock
state are executed only after callbacks have finished.
🧹 Nitpick comments (2)
cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp (1)

2412-2431: Consider warning on duplicate addSequence.

Now that duplicates return false, a warning helps avoid silent no-ops when callers ignore the return value.

💡 Suggested tweak
-    if (!emplaceDone)
-    {
-        return false;
-    }
+    if (!emplaceDone)
+    {
+        TLLM_LOG_WARNING("[kv cache manager] addSequence ignored; sequence %d already exists", requestId);
+        return false;
+    }
tests/unittest/_torch/test_connector.py (1)

25-28: Prefer module-level imports to keep namespaces intact.

This repo asks for namespace-preserving imports; consider importing the module and qualifying types to avoid from … import … here.

♻️ Suggested refactor
-from tensorrt_llm._torch.pyexecutor.kv_cache_connector import (
-    AsyncRequests, KvCacheConnectorManager,
-    KvCacheConnectorSchedulerOutputManager)
-from tensorrt_llm._torch.pyexecutor.llm_request import LlmRequestState
+import tensorrt_llm._torch.pyexecutor.kv_cache_connector as kv_cache_connector
+import tensorrt_llm._torch.pyexecutor.llm_request as llm_request
-    req.state = LlmRequestState.GENERATION_IN_PROGRESS
+    req.state = llm_request.LlmRequestState.GENERATION_IN_PROGRESS
...
-    manager = KvCacheConnectorSchedulerOutputManager()
+    manager = kv_cache_connector.KvCacheConnectorSchedulerOutputManager()
...
-    scheduler_output = manager.build_scheduler_output(scheduled_batch,
-                                                      AsyncRequests({}, {}),
-                                                      kv_cache_manager)
+    scheduler_output = manager.build_scheduler_output(
+        scheduled_batch,
+        kv_cache_connector.AsyncRequests({}, {}),
+        kv_cache_manager)

As per coding guidelines, Always maintain the namespace when importing Python modules, even if only one class or function from a module is used.

Comment thread tensorrt_llm/_torch/pyexecutor/kv_cache_connector.py
Comment thread tests/integration/defs/llmapi/test_llm_api_connector.py
@pcastonguay
Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

1 similar comment
@tburt-nv
Copy link
Copy Markdown
Collaborator

tburt-nv commented Feb 3, 2026

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #34516 [ run ] triggered by Bot. Commit: c229b67

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #34516 [ run ] completed with state SUCCESS. Commit: c229b67
/LLM/main/L0_MergeRequest_PR pipeline #26631 completed with status: 'SUCCESS'

Copy link
Copy Markdown
Collaborator

@eopXD eopXD left a comment

Choose a reason for hiding this comment

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

The limited changes compared to #9186 are more clear and concised. Some comments around the semantics and mechanisms.

Comment thread cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
Comment thread tensorrt_llm/_torch/pyexecutor/py_executor.py
Comment thread tensorrt_llm/_torch/pyexecutor/py_executor.py Outdated
Comment thread tensorrt_llm/_torch/pyexecutor/py_executor.py
Comment thread tensorrt_llm/_torch/pyexecutor/py_executor.py Outdated
@jthomson04 jthomson04 force-pushed the jthomson04/kv-connector-cleanup-v2 branch from c229b67 to 5719de3 Compare February 4, 2026 19:51
Comment thread cpp/tensorrt_llm/batch_manager/kvCacheManager.cpp
Comment thread tensorrt_llm/_torch/pyexecutor/resource_manager.py
@jthomson04
Copy link
Copy Markdown
Collaborator Author

jthomson04 commented Feb 8, 2026

Was this change motivated by a need (somebody already calling more than once), or just done to make the code more robust?

@thorjohnsen The primary motivation was to eliminate some additional state tracking login in the KV connector. If the KV connector is loading additional KV cache, after the loading is complete, the request is still in the CONTEXT_INIT state, with is_first_context_chunk=True, which breaks our existing checks to see if the request should be added. Moving this check into add_sequence significantly simplifies this.

@jthomson04 jthomson04 force-pushed the jthomson04/kv-connector-cleanup-v2 branch from 5719de3 to 7e8a096 Compare February 11, 2026 19:25
@pcastonguay
Copy link
Copy Markdown
Collaborator

@thorjohnsen @eopXD can you resolve your threads if you're ok with John's response/changes. Thanks.

Copy link
Copy Markdown
Collaborator

@thorjohnsen thorjohnsen left a comment

Choose a reason for hiding this comment

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

This looks good to me. Let's give Eop some time to review his concerns before merge. Thanks!

Copy link
Copy Markdown
Collaborator

@eopXD eopXD left a comment

Choose a reason for hiding this comment

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

Thank you for patiently addressing my comments John : D

@pcastonguay
Copy link
Copy Markdown
Collaborator

@jthomson04 can you resolve the conflict so we can run CI and get it merged? Thanks.

jthomson04 and others added 2 commits February 24, 2026 13:15
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
@jthomson04 jthomson04 force-pushed the jthomson04/kv-connector-cleanup-v2 branch from 7e8a096 to 500f3f4 Compare February 24, 2026 21:18
@pcastonguay
Copy link
Copy Markdown
Collaborator

/bot run --disable-fail-fast

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #36690 [ run ] triggered by Bot. Commit: 500f3f4 Link to invocation

@tensorrt-cicd
Copy link
Copy Markdown
Collaborator

PR_Github #36690 [ run ] completed with state SUCCESS. Commit: 500f3f4
/LLM/main/L0_MergeRequest_PR pipeline #28408 completed with status: 'SUCCESS'
Pipeline passed with automatic retried tests. Check the rerun report for details.
Pipeline has performance regression cases. Check the performance regression report for details.

Link to invocation

@pcastonguay pcastonguay merged commit 0338bb2 into NVIDIA:main Feb 25, 2026
5 checks passed
jthomson04 added a commit to jthomson04/TensorRT-LLM that referenced this pull request Mar 3, 2026
jthomson04 added a commit to jthomson04/TensorRT-LLM that referenced this pull request Mar 3, 2026
jthomson04 added a commit to jthomson04/TensorRT-LLM that referenced this pull request Mar 6, 2026
dominicshanshan pushed a commit to dominicshanshan/TensorRT-LLM that referenced this pull request Mar 9, 2026
jthomson04 added a commit that referenced this pull request Mar 11, 2026
tianyuz-nv pushed a commit to wanqian-nv/TensorRT-LLM that referenced this pull request Mar 19, 2026
Signed-off-by: jthomson04 <[email protected]>
Signed-off-by: jthomson04 <[email protected]>
limin2021 pushed a commit to limin2021/TensorRT-LLM that referenced this pull request Mar 19, 2026
longcheng-nv pushed a commit to longcheng-nv/TensorRT-LLM that referenced this pull request Mar 31, 2026
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