Skip to content

[None][chore] KVCacheManagerV2: Python and test preparation for a C++ backend - #16218

Merged
lowsfer merged 1 commit into
NVIDIA:mainfrom
lowsfer:kvCacheManagerV2-py-prep
Jul 15, 2026
Merged

[None][chore] KVCacheManagerV2: Python and test preparation for a C++ backend#16218
lowsfer merged 1 commit into
NVIDIA:mainfrom
lowsfer:kvCacheManagerV2-py-prep

Conversation

@lowsfer

@lowsfer lowsfer commented Jul 10, 2026

Copy link
Copy Markdown
Member

Description

Backend-neutral Python groundwork for the upcoming C++ implementation of KVCacheManagerV2 (the C++ backend and its dispatcher come in a follow-up PR stacked on top). This PR contains no backend-switching code — the pure-Python implementation remains the only backend.

  • Expand the public API of tensorrt_llm.runtime.kv_cache_manager_v2: export layout descriptors (pool_group_descs: PoolDesc, PoolGroupDesc, SlotDesc, CoalescedBuffer, ExpandedBuffer), stats/eventing types, and a backend-neutral _introspection helper module.
  • Use the public layout/introspection APIs in the disaggregation kv_extractor and the DSv4/MiniMax sparse cache managers instead of reaching into implementation internals.
  • Keep vocab_size in the _build_cache_config() virtual-method contract (subclasses override it) but drop it from the generic KVCacheManagerConfig.
  • Add v2_blake3 / v2_blake3_64 KV cache event hash options to KvCacheConfig and regenerate the LLM args golden manifest.
  • Fix StagingBuffer wrap-around when the ring tail cannot satisfy min_size; misc small fixes surfaced while translating the code.
  • Extend unit test coverage (stats API, hash options); route tests through the public API where possible.
  • Fix create_perf_comparison_report.py crash when the only perf test is waived and no CSV is produced (pre-existing main issue).
  • Rename the debug assertion env var to TLLM_DEBUG_MODE.

Test Coverage

  • tests/unittest/kv_cache_manager_v2_tests/ (full directory): 138 passed, 12 skipped.
  • tests/unittest/llmapi/test_llm_args.py hash-algo tests pass.

PR Checklist

  • PR title and description added
  • Test coverage added/updated
  • LLM args golden manifest regenerated

🤖 Generated with Claude Code

@coderabbitai

coderabbitai Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This change adds Python/C++ KV-cache V2 backend selection and introspection, exposes pool layout descriptors, updates lifecycle, statistics, storage, radix-tree, and event handling, and rewrites disaggregation page-table construction. Tests and configuration manifests are updated for the new APIs and Blake3 hash algorithms.

Changes

KV cache V2 platform and storage

Layer / File(s) Summary
Backend, introspection, and public contracts
tensorrt_llm/runtime/kv_cache_manager_v2/..., tensorrt_llm/runtime/kv_cache_hash.py, tensorrt_llm/llmapi/llm_args.py
Adds backend-dependent loading, fallback symbols, introspection helpers, pool descriptors, public cache properties, and Blake3 hash identifiers.
Storage and lifecycle handling
tensorrt_llm/runtime/kv_cache_manager_v2/_core/..., .../_storage/..., .../_block_radix_tree.py, .../_page.py
Updates pool addressing and validation, radix-tree detachment, page unlink cleanup, event reference resolution, and cache lifecycle behavior.
Executor quota and statistics flow
tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
Uses integer tier quotas, removes stored vocabulary size, delegates metadata and statistics through introspection, and supports native peak statistics.
Disaggregation page tables
tensorrt_llm/_torch/disaggregation/resource/...
Builds V2 page tables from public pool descriptors, buffer offsets, native roles, and per-layer window configuration.
Event hashing and validation
tensorrt_llm/runtime/kv_cache_manager_v2/_event_manager.py, tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_event_manager.py
Uses event keys for hashing and adds Python/native backend parity coverage, including Blake3-derived expectations.
Regression and manifest updates
tests/unittest/kv_cache_manager_v2_tests/*, tests/integration/*, tensorrt_llm/usage/llm_args_golden_manifest.json
Migrates tests to public APIs and adds coverage for reuse, quotas, scratch readiness, statistics, type annotations, and new manifest options.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant KVCacheManager
  participant Introspection
  participant CppBackend
  participant Disaggregation
  participant EventManager
  KVCacheManager->>Introspection: request lifecycle and storage metadata
  Introspection->>CppBackend: delegate when native backend is active
  CppBackend-->>Introspection: return statistics and descriptors
  Introspection-->>KVCacheManager: provide backend-independent metadata
  Disaggregation->>KVCacheManager: read pool_group_descs and init_config
  Disaggregation-->>Disaggregation: build page tables from buffer offsets
  EventManager->>KVCacheManager: resolve page references and event keys
Loading

Possibly related PRs

Suggested reviewers: jiaganc, yizhang-nv, QiJune, juney-nvidia, arysef, brb-nv

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 19.60% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title is concise and accurately summarizes the main backend-prep and test changes in the PR.
Description check ✅ Passed The description follows the template with Description, Test Coverage, and PR Checklist sections filled in.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (2)
tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py (1)

100-128: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add type annotations to the new fallback functions.

_load_cpp_module, _RawRef.__init__, _RawRef.__call__, and _RawRef.__class_getitem__ omit parameter and/or return annotations. As per coding guidelines, Python functions must always be annotated.

Also applies to: 205-217

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py` around lines 100 - 128,
Add complete parameter and return type annotations to _load_cpp_module,
_RawRef.__init__, _RawRef.__call__, and _RawRef.__class_getitem__, including
appropriate self, argument, and return types consistent with their existing
behavior and surrounding typing conventions.

Source: Coding guidelines

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

1245-1251: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use an f-string conversion flag.

Ruff reports RUF010 for str(role) inside the f-string.

Proposed fix
-                f"role={str(role)}, lifecycle_id={int(lifecycle_id)}, "
+                f"role={role!s}, lifecycle_id={int(lifecycle_id)}, "
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py` around lines 1245 -
1251, Replace str(role) in the return expression of the relevant KV cache
manager method with the f-string conversion flag !s, preserving the existing
output while resolving Ruff RUF010.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py`:
- Around line 860-870: Preserve the configured disk cache tier when host
registration falls back to GPU-only tiers. Update the retry/filter logic in the
KV cache manager initialization, near the host registration handling, to retain
both GPU and disk tiers while excluding only the failed host tier; ensure the
existing DiskCacheTierConfig created from disk_cache_size and disk_cache_path
remains available for suspended request resumption.

In `@tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py`:
- Around line 119-128: In the backend-loading function containing the
kv_cache_manager_v2 import, replace the assert validating
find_spec("kv_cache_manager_v2") with an explicit check for a missing spec or
origin, and raise a descriptive ImportError before constructing
Path(spec.origin). Preserve the existing path setup and cleanup for valid specs.
- Line 166: Guard the stats helpers that use `_cpp_introspection` so native
`KVCacheManager` does not fall back to the private `self.impl._storage`
contract. Update the relevant methods in `KVCacheManager` to gate storage-based
paths by backend or fail fast when native introspection is unavailable, while
preserving the Python manager fallback.

In `@tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py`:
- Around line 2648-2686: Make
test_excess_scratch_slot_waits_for_ready_event_on_new_stream deterministic by
gating producer completion after its work is enqueued, then assert
consumer_marker does not complete while that gate is held and does complete
after releasing it. Replace the current producer_marker.query_complete assertion
with explicit producer-side synchronization/control that proves the consumer
waits for the producer’s ready event across streams.

In `@tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_api.py`:
- Around line 90-117: Extend test_manager_stats_config_and_api to exercise both
collection modes: after creating the cache, resume it, resize it, and commit it,
then assert enable_stats=True produces non-empty allocation/reuse counters in
the committed or iteration stats, while enable_stats=False keeps those stats
empty. Retain the existing configuration and dirty/excluded-state assertions,
and use the cache lifecycle methods exposed by the test fixture.

---

Nitpick comments:
In `@tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py`:
- Around line 1245-1251: Replace str(role) in the return expression of the
relevant KV cache manager method with the f-string conversion flag !s,
preserving the existing output while resolving Ruff RUF010.

In `@tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py`:
- Around line 100-128: Add complete parameter and return type annotations to
_load_cpp_module, _RawRef.__init__, _RawRef.__call__, and
_RawRef.__class_getitem__, including appropriate self, argument, and return
types consistent with their existing behavior and surrounding typing
conventions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 97de4c46-d2af-46d1-b2e9-4872b9a0986f

📥 Commits

Reviewing files that changed from the base of the PR and between b5a085a and acb5620.

📒 Files selected for processing (36)
  • tensorrt_llm/_torch/attention_backend/sparse/deepseek_v4/cache_manager.py
  • tensorrt_llm/_torch/disaggregation/resource/kv_extractor.py
  • tensorrt_llm/_torch/disaggregation/resource/utils.py
  • tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
  • tensorrt_llm/llmapi/llm_args.py
  • tensorrt_llm/runtime/kv_cache_hash.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/AGENTS.md
  • tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/__init__.pyi
  • tensorrt_llm/runtime/kv_cache_manager_v2/_block_radix_tree.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_common.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_config.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_copy_engine.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_core/__init__.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_core/_kv_cache.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_core/_kv_cache_manager.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_event_manager.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_eviction_controller/_eviction_controller.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_introspection.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_page.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_stats.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_storage/_core.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_storage_manager.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/_utils.py
  • tensorrt_llm/runtime/kv_cache_manager_v2/setup_mypyc.py
  • tensorrt_llm/usage/llm_args_golden_manifest.json
  • tests/integration/defs/accuracy/test_kv_pool_rebalance_accuracy.py
  • tests/integration/defs/perf/create_perf_comparison_report.py
  • tests/unittest/_torch/attention/sparse/deepseek_v4/test_deepseek_v4_cache_manager.py
  • tests/unittest/disaggregated/test_kv_transfer.py
  • tests/unittest/kv_cache_manager_v2_tests/fake_engine.py
  • tests/unittest/kv_cache_manager_v2_tests/test_branch_reuse.py
  • tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_event_manager.py
  • tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_manager_v2.py
  • tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_api.py
  • tests/unittest/llmapi/test_llm_args.py
💤 Files with no reviewable changes (1)
  • tensorrt_llm/runtime/kv_cache_manager_v2/_config.py

Comment thread tensorrt_llm/_torch/pyexecutor/kv_cache_manager_v2.py
Comment thread tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py Outdated
Comment thread tensorrt_llm/runtime/kv_cache_manager_v2/__init__.py Outdated
Comment thread tests/unittest/kv_cache_manager_v2_tests/test_kv_cache_stats_api.py
@lowsfer
lowsfer force-pushed the kvCacheManagerV2-py-prep branch from acb5620 to fa5ef6d Compare July 10, 2026 06:52
@lowsfer lowsfer changed the title [None][chore] KVCacheManagerV2: backend-neutral Python and test preparation [None][chore] KVCacheManagerV2: Python and test preparation for a C++ backend Jul 10, 2026
@lowsfer lowsfer added the api-compatible Accepted LLM API contract change that is backwards-compatible label Jul 10, 2026
@lowsfer
lowsfer force-pushed the kvCacheManagerV2-py-prep branch from 8645d9f to d9b0aa9 Compare July 10, 2026 10:10
@lowsfer

lowsfer commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58657 [ run ] triggered by Bot. Commit: d9b0aa9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58657 [ run ] completed with state SUCCESS. Commit: d9b0aa9
/LLM/main/L0_MergeRequest_PR pipeline #47243 completed with status: 'FAILURE'

CI Report

⚠️ 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

CI Agent Failure Analysis

Link to invocation

@lowsfer

lowsfer commented Jul 10, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58713 [ run ] triggered by Bot. Commit: d9b0aa9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58713 [ run ] completed with state FAILURE. Commit: d9b0aa9
/LLM/main/L0_MergeRequest_PR pipeline #47296 completed with status: 'FAILURE'

CI Report

⚠️ 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

CI Agent Failure Analysis

Link to invocation

@lowsfer

lowsfer commented Jul 11, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58747 [ run ] triggered by Bot. Commit: d9b0aa9 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #58747 [ run ] completed with state SUCCESS. Commit: d9b0aa9
/LLM/main/L0_MergeRequest_PR pipeline #47330 completed with status: 'SUCCESS'

CI Report

Link to invocation

@fredricz-20070104

Copy link
Copy Markdown
Collaborator

Merge conflict — how to resolve

This PR is currently in a CONFLICTING / DIRTY state, which is a hard merge blocker. The good news: the conflict is confined to one file and is trivial to resolve.

File: tensorrt_llm/runtime/kv_cache_manager_v2/_storage_manager.py (import block, ~lines 47-58)

What conflicts:

  • This PR introduces LogicError (used at lines 336, 371).
  • main added AttnLifeCycle (used at lines 922, 935).

Both symbols are genuinely in use, so there is no logical conflict — just keep both sides' imports:

  • Keep LogicError, OutOfPagesError (from this PR)
  • Keep AttnLifeCycle, LifeCycleId, LifeCycleRegistry, compute_scratch_range (from main)

After rebasing / merging main, resolving this single import block is all that's needed. Verified locally: merging main produces exactly one conflict, in this file's import block only.

… backend

Backend-neutral Python groundwork for the upcoming C++ implementation
of KVCacheManagerV2 (introduced in a follow-up PR):

- Expand the public API of tensorrt_llm.runtime.kv_cache_manager_v2:
  export layout descriptors (pool_group_descs: PoolDesc, PoolGroupDesc,
  SlotDesc, CoalescedBuffer, ExpandedBuffer), stats/eventing types, and
  a backend-neutral _introspection helper module.
- Use the public layout/introspection APIs in the disaggregation
  kv_extractor and the DSv4/MiniMax sparse cache managers instead of
  reaching into implementation internals.
- Keep vocab_size in the _build_cache_config() virtual-method contract
  but drop it from the generic KVCacheManagerConfig.
- Add v2_blake3 / v2_blake3_64 KV cache event hash options to llm_args
  and regenerate the LLM args golden manifest.
- Fix StagingBuffer wrap-around when the ring tail cannot satisfy
  min_size; misc small fixes surfaced while translating the code.
- Extend unit test coverage (stats API, hash options); route tests
  through the public API where possible.
- Fix create_perf_comparison_report.py crash when the only perf test is
  waived and no CSV is produced (pre-existing main issue).
- Rename debug assertion env var to TLLM_DEBUG_MODE.

Signed-off-by: Yao Yao <lowsfer@users.noreply.github.com>
@lowsfer
lowsfer force-pushed the kvCacheManagerV2-py-prep branch from d9b0aa9 to 5588af1 Compare July 14, 2026 08:39
@lowsfer
lowsfer requested review from a team as code owners July 14, 2026 08:39
@tburt-nv
tburt-nv removed the request for review from a team July 14, 2026 15:03
@lowsfer

lowsfer commented Jul 14, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59222 [ run ] triggered by Bot. Commit: 5588af1 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59222 [ run ] completed with state SUCCESS. Commit: 5588af1
/LLM/main/L0_MergeRequest_PR pipeline #47719 completed with status: 'FAILURE'

CI Report

⚠️ 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

CI Agent Failure Analysis

Link to invocation

Comment thread tensorrt_llm/_torch/disaggregation/resource/utils.py
@lowsfer

lowsfer commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59350 [ run ] triggered by Bot. Commit: 5588af1 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59350 [ run ] completed with state SUCCESS. Commit: 5588af1
/LLM/main/L0_MergeRequest_PR pipeline #47828 completed with status: 'FAILURE'

CI Report

⚠️ 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

CI Agent Failure Analysis

Link to invocation

@lowsfer

lowsfer commented Jul 15, 2026

Copy link
Copy Markdown
Member Author

/bot run --disable-fail-fast

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59400 [ run ] triggered by Bot. Commit: 5588af1 Link to invocation

@tensorrt-cicd

Copy link
Copy Markdown
Collaborator

PR_Github #59400 [ run ] completed with state SUCCESS. Commit: 5588af1
/LLM/main/L0_MergeRequest_PR pipeline #47876 completed with status: 'SUCCESS'

CI Report

Link to invocation

@lowsfer
lowsfer merged commit 0846183 into NVIDIA:main Jul 15, 2026
7 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api-compatible Accepted LLM API contract change that is backwards-compatible

Projects

None yet

Development

Successfully merging this pull request may close these issues.

9 participants