Skip to content

feat: Session-reference-aware Unified Radix Cache for agentic multi-turn workloads - #29173

Merged
hzh0425 merged 6 commits into
sgl-project:mainfrom
Zhangmj0621:feat/ref_aware_kv_buffer
Aug 2, 2026
Merged

hzh0425 merged 6 commits into
sgl-project:mainfrom
Zhangmj0621:feat/ref_aware_kv_buffer

Conversation

@Zhangmj0621

@Zhangmj0621 Zhangmj0621 commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

In multi-turn inference workloads such as agentic workflows and RL rollouts, active sessions accumulate reusable KV prefixes across turns. Under memory pressure, the standard radix cache evicts entries using only the configured cache policy, without considering whether a prefix is still referenced by an active session.

This may evict an active session's prefix while unrelated, unreferenced KV remains cached, causing unnecessary recomputation in later turns and reducing cache hit rate and throughput.

Design

This PR adds session-aware eviction to UnifiedRadixCache. Applications pass a stable top-level session_id with each request. When a request finishes, SGLang registers its reusable KV under that session. When the session ends, the application calls /close_session to release those references.

                    --enable-session-radix-cache
                                 |
              +------------------+------------------+
              |                                     |
       request finished                       session closed
              |                                     |
   register_session_ref(req)          release_radix_session(id)
              |                                     |
              +------------- session refs ----------+
                                 |
                       UnifiedRadixCache
                                 |
              +------------------+------------------+
              |                  |                  |
            FULL                SWA               MAMBA
     reusable prefix path   sliding window   reusable state leaf
              |                  |                  |
              +------------------+------------------+
                                 |
                    device and host eviction
                                 |
                 UNREFERENCED -> REFERENCED

Each UnifiedRadixCache component tracks the KV region reusable by a session:

  • FULL attention tracks the reusable prefix path. Eviction orders nodes by (is_referenced, session_ref_count, base_eviction_priority).
  • SWA tracks the reusable sliding-window tail. Device and host eviction use two LRU passes: unreferenced nodes first, then referenced nodes if more space is required.
  • Mamba tracks the reusable state at the session frontier. It uses the same two-pass unreferenced-first fallback.

Referenced KV is soft-protected, not pinned. If unreferenced KV is insufficient, referenced entries remain evictable. Closing a session removes its references without immediately freeing its KV, allowing the KV to remain reusable until normal eviction reclaims it.

Session generations and bounded closed-session tombstones prevent stale in-flight requests from reattaching references after close or close/reopen.

This feature is implemented only by UnifiedRadixCache. Ordinary RadixCache and HiRadixCache do not maintain session references.

Storage-backed L3 cache is not included in this PR.

Modifications

  • Add SessionUnifiedRadixCacheMixin for session lifecycle and stale-request protection.
  • Add per-component session leaf indexes and compact reference counts for FULL, SWA, and Mamba.
  • Apply session-aware ordering to both device and host eviction.
  • Register reusable KV when requests finish and release references through /close_session.
  • Support top-level session_id without changing or reconstructing request prompts.
  • Preserve the configured base eviction policy without requiring --radix-eviction-policy priority.
  • Remove session tracking and SessionAwareEvictionStrategy integration from ordinary RadixCache and HiRadixCache.
  • Add focused tests for UnifiedRadixCache ownership, registration, release, stale generations, and unreferenced-first eviction.
  • Add documentation for enablement, request lifecycle, and per-component eviction behavior.
  • Enable the feature with --enable-session-radix-cache; UnifiedRadixCache must also be enabled.

Speed Tests and Profiling

We evaluate session radix cache on a SWE-agent agentic workload using GLM-5.2 (UnifiedRadixCache) under different batch sizes. The cache hit rate breakdown between the original HiCache and session radix cache is shown below.

The results show that session-reference-aware radix cache substantially improves both cache hit rate and end-to-end throughput. By preserving KV cache entries that are still referenced by active multi-turn requests, session radix cache reduces unnecessary prefix recomputation and improves cache residency under memory pressure.

However, we also observe that the cache hit rate still drops at larger batch sizes. This suggests that large batches can still cause KV cache thrashing, even with reference-aware eviction. Addressing this issue may require additional mechanisms such as cache-aware admission control, batch throttling, or concurrency control, similar to the approaches explored in ThunderAgent and Concur.


CI States

Latest PR Test (Base): ✅ Run #30707949357
Latest PR Test (Extra): ✅ Run #30707949287

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request implements a ref-aware KV cache eviction mechanism with two-tier priority, introducing a reusable RefAwareCacheMixin along with RefAwareHiRadixCache and RefAwareRadixCache implementations, new API endpoints, and scheduling integration. The code review identified several critical issues: a runtime NameError in prepare_for_extend due to an undefined reqs variable, a potential bug when modifying the running batch in-place during forward iteration, reference count collisions when req.rid is empty, and bypassed eviction metrics caused by calling the private _evict_tiered method directly instead of using the public interface.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@ishandhanani ishandhanani self-assigned this Jun 24, 2026
@ishandhanani

ishandhanani commented Jun 24, 2026 •

Copy link
Copy Markdown
Collaborator

This is great work! Wanted to flag some similar work that is being done with SGLang session-radix cache. I think there's some easy parallels and wins here.

IIUC the distinction seems to be:

  1. RefAwareCache keeps active session KV resident under pressure.
  2. SessionRadixCache tracks ownership and reclaims KV on session close

I wonder if we can share the existing session_id lifecycle instead of introducing a parallel rid lifecycle? Then we could unify the RefAwareCache with the SessionRadixCache (I am ok with just using RefAwareCache in this cause I think. Do you think we could add a deterministic close rather than just a full reference decrement?). I think using the existing req.session_id machinery could allow us to do this. Happy to co-design I'd love to unify the 2 works :)

@Zhangmj0621

Copy link
Copy Markdown
Contributor Author

This is great work! Wanted to flag some similar work that is being done with SGLang session-radix cache. I think there's some easy parallels and wins here.

IIUC the distinction seems to be:

  1. RefAwareCache keeps active session KV resident under pressure.
  2. SessionRadixCache tracks ownership and reclaims KV on session close

I wonder if we can share the existing session_id lifecycle instead of introducing a parallel rid lifecycle? Then we could unify the RefAwareCache with the SessionRadixCache (I am ok with just using RefAwareCache in this cause I think. Do you think we could add a deterministic close rather than just a full reference decrement?). I think using the existing req.session_id machinery could allow us to do this. Happy to co-design I'd love to unify the 2 works :)

Hi Ishan, thanks for your review! I have seen your message on Slack. Happy to discuss it there.

@ishandhanani ishandhanani left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Narrow review at 67801c4135. I reproduced two blocking correctness issues: (1) current head cannot import/start on supported Python 3.12 because the new stdlib dataclasses subclass msgspec.Struct; (2) after an import-only throwaway patch, a valid low-priority multi-chunk request crashes the scheduler. The added 40 manual RefAware tests and 85 server-argument tests pass but do not exercise either path. I intentionally excluded SessionRadixCache removal, /close_session, and broader conditional concerns from this review.

Note - generated with codex but reviewed by Ishan

Comment thread python/sglang/srt/managers/io_struct.py Resolved
Comment thread python/sglang/srt/managers/scheduler.py Resolved

@ishandhanani ishandhanani left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Follow-up review at b404e169a4. The two previously posted findings are resolved: the server imports and starts on Python 3.12.12, and the exact 200-token low-priority chunked-prefill reproduction now completes with HTTP 200. The refreshed 125-test targeted suite and a 64/64-request AIPerf smoke also pass, but they do not exercise the HTTP control routes or HiCache host-pressure lifecycle below. This review is intentionally limited to four independently reproduced P1 issues; SessionRadixCache removal, /close_session, conditional priority contracts, and broader deep-review notes are excluded.

@Zhangmj0621
Zhangmj0621 force-pushed the feat/ref_aware_kv_buffer branch from 1b8a065 to 92a209a Compare July 1, 2026 12:51
@krishs0404

Copy link
Copy Markdown

Hey wanted to give some of my thoughts on this PR!

Main correctness issue I found: mixed-priority refs can leak within the same session_id.

Repro shape:

  1. session s1 first registers cached nodes as low priority
  2. the same session later extends/registers a high-priority suffix
  3. release_ref("s1")

After release, the suffix can still have high_ref == 1. The reverse high→low case can similarly leak low_ref.

I think the issue is that register_ref() computes the ref class from the current request priority even for an already-tracked session, while release_ref() decrements all nodes using the session’s original RefInfo.is_high. So one session can end up owning nodes in both ref classes, but release assumes one class.

Possible fixes:

  • Simpler invariant: once a session is tracked, all newly registered suffix nodes use ref_info.is_high, not the current request priority.
  • Or stricter lifecycle: require priority-class changes to go through update_ref() before adding new refs, so the session’s existing refs and future refs stay in one class.
  • Or more flexible accounting: track ref class per (session_id, node) instead of one is_high per session. That is more robust but probably more complexity than needed for this PR.

Bigger-picture thoughts:

I like the direction. Agentic workloads are not well served by plain LRU, because useful prefixes can look temporarily cold while the agent is in a tool call, a branch, or a SWE-bench-style edit loop. Treating session_id as a first-class cache identity is a good primitive.

That said, I think the hard part is lifecycle semantics, not only eviction priority. Long term, this probably wants to behave like a session/trajectory lease:

  • refs are acquired when a trajectory produces reusable KV
  • refs are updated when the session priority changes
  • refs are released when the session/task ends
  • abandoned sessions are bounded by TTL or token budget

Things I’d consider next:

  • unify close_session and release_ref, or at least make the relationship explicit
  • add TTL / max protected-token budgets so leaked or abandoned sessions cannot pin KV forever
  • add priority decay so old high-priority sessions eventually become evictable
  • expose metrics: protected tokens by tier, refs by session, release count, stale refs, evictions by tier
  • test against Mooncake toolagent / SWE-bench-like traces with stable session_id per trajectory
  • think about branch-aware caching for agent search/tree-of-thought workloads, where one task may fan out into multiple related continuations

So my take is: the PR is a promising first step toward agent-aware KV management, and the GPU smoke path works, but I’d fix the mixed-priority accounting and clarify the session/ref lifecycle before landing.

@Zhangmj0621

Copy link
Copy Markdown
Contributor Author

@krishs0404 Hi, thanks for review. In fact, the low-priority session should not send high-priority generation request unless calls update_ref. It may need a log here to manage priority mismatch instead of take this case as normal one.

@Zhangmj0621
Zhangmj0621 force-pushed the feat/ref_aware_kv_buffer branch 2 times, most recently from 06c0fe7 to 6090342 Compare July 6, 2026 06:12
@xiezhq-hermann xiezhq-hermann added hicache Hierarchical Caching for SGLang run-ci CI: run the baseline test suite on this PR labels Jul 6, 2026

@ishandhanani ishandhanani left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Some mechanical reviews. Have some questions about some mechanics of the ref aware but i need to deeply understand for a bit longer. Will add that review in very very soon

Comment thread python/sglang/srt/server_args.py Resolved
@ispobock

ispobock commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

@Zhangmj0621

Copy link
Copy Markdown
Contributor Author

https://github.com/sgl-project/sglang/actions/runs/30704732713/job/91381865765?pr=29173#step:12:1165 this cpu ci is failed

I'm taking a look

Track per-session references on UnifiedRadixCache KV so that eviction
consumes unreferenced entries before referenced ones, and closing a
session only dereferences its KV instead of freeing it. Enabled by
--enable-session-radix-cache on top of SGLANG_ENABLE_UNIFIED_RADIX_TREE=1.

Each tree component keeps its own session frontier leaves and per-node
session_ref, over the span it actually owns: Full covers the whole
leaf->root path, SWA one sliding window, Mamba only the leaf. The
per-component LRUs are partitioned by session_ref around a locked `mid`
sentinel, so an eviction walk drains the unreferenced side first, and
SWA/Mamba walk behind a locked cursor sentinel that the list relinks on
its own. Full keeps its heap and orders by (referenced, ref, base
priority) instead.

Registration happens in cache_finished_req after a successful insert
(FINISH_ABORT excluded), guarded by a monotonic session generation so a
request that finishes after a close/reopen of the same session id cannot
tag the new incarnation.

Drops the previous RadixCache-based SessionRadixCacheMixin.
@Zhangmj0621
Zhangmj0621 force-pushed the feat/ref_aware_kv_buffer branch from ab3f0e5 to daf70ab Compare August 1, 2026 16:21
@Zhangmj0621

Copy link
Copy Markdown
Contributor Author

https://github.com/sgl-project/sglang/actions/runs/30704732713/job/91381865765?pr=29173#step:12:1165 this cpu ci is failed

It should be fixed. And i have moved the session-radix-cache test to the registered.

@ispobock

ispobock commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

/rerun-failed-ci

@ispobock

ispobock commented Aug 1, 2026

Copy link
Copy Markdown
Collaborator

/rerun-test test/registered/unit/mem_cache/test_session_unified_radix_cache.py test/registered/unit/mem_cache/test_tree_core_registry.py test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py

@github-actions

github-actions Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Results for /rerun-test test/registered/unit/mem_cache/test_session_unified_radix_cache.py test/registered/unit/mem_cache/test_tree_core_registry.py test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py:

🚀 ubuntu-latest (2 tests): ✅ View workflow run

cd test/ && python3 registered/unit/mem_cache/test_session_unified_radix_cache.py
cd test/ && python3 registered/unit/mem_cache/test_tree_core_registry.py

🚀 1-gpu-5090 (1 test): ✅ View workflow run

cd test/ && python3 registered/unit/mem_cache/test_unified_radix_cache_unittest.py

@hzh0425

hzh0425 commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator
image All ci passed

@@ -0,0 +1,222 @@
"""Tests for session references on UnifiedRadixCache."""

@hzh0425 hzh0425 Aug 2, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

we need to add an e2e test in next pr for session radix tree @Zhangmj0621

refer to test/registered/radix_cache/unified_radix_tree/test_unified_radix_cache_kl_swa.py

@hzh0425
hzh0425 merged commit 056474c into sgl-project:main Aug 2, 2026
248 of 273 checks passed
@ispobock ispobock mentioned this pull request Aug 6, 2026
56 of 66 tasks
saturn-acc pushed a commit to saturn-acc/sglang that referenced this pull request Aug 16, 2026
…urn workloads (sgl-project#29173)

Co-authored-by: Ishan Dhanani <[email protected]>
Co-authored-by: hzh0425 <[email protected]>
Co-authored-by: ispobock <[email protected]>
Atituiset pushed a commit to Atituiset/sglang that referenced this pull request Sep 10, 2026
…urn workloads (sgl-project#29173)

Co-authored-by: Ishan Dhanani <[email protected]>
Co-authored-by: hzh0425 <[email protected]>
Co-authored-by: ispobock <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bypass-fastfail documentation Improvements or additions to documentation hicache Hierarchical Caching for SGLang high priority release-highlight Candidate PR for release note highlight run-ci CI: run the baseline test suite on this PR run-ci-extra CI: also run the extra suite (requires run-ci)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants