Prhub

#25991 [HiCache] fix: truncate prefetch key on degraded allocation

原始 PR 作者 alphabetc1 合并时间 2026-06-03 22:06 文件变更 1 提交数 6 评论 2 代码增减 +6 / -3

执行摘要

修复 HiCache 降级分配时 prefetch 键截断错误

当主机内存不足、prefetch_length 被迫缩小后,原代码截断原始 new_input_tokens 而非 prefetch_key,导致后续使用错误的键进行预取,可能触发键长度不匹配或无效查找。PR 描述指出“Crop prefetch_key when HiRadixCache falls back to a smaller host allocation for L3 prefetch”正是该修复的核心动机。

值得精读,因其展示了退化路径中细微但关键的 Bug 修复模式。鼓励为此分支编写单元测试。

讨论亮点

作者 alphabetc1 在自评中指出:“RadixKey supports truncation, so writing it this way is OK.” 确认了使用 [:prefetch_length] 截断 prefetch_key 的可行性。审核者 xiezhq-hermann 批准了该 PR,未提出异议。

实现拆解

  1. 变量修正:将 avaliable_size 拼写修正为 available_size(改进可读性)。
  2. 截断对象调整:在退化分配分支(if host_indices is None)中,将 new_input_tokens = new_input_tokens[:prefetch_length] 改为 prefetch_key = prefetch_key[:prefetch_length],因为 RadixKey 支持截断操作,且后续使用的都是 prefetch_key
  3. 空指针防御:在 host_indices = self.cache_controller.mem_pool_host.alloc(prefetch_length) 之后检查返回是否为 None,若是则释放保护、提前返回,防止空索引导致崩溃。
  4. 文件:仅修改了 python/sglang/srt/mem_cache/hiradix_cache.py 中的 prefetch_from_storage 方法,无其他文件变更。
文件 模块 状态 重要度
python/sglang/srt/mem_cache/hiradix_cache.py 缓存层 modified 5.8

关键符号

prefetch_from_storage

关键源码片段

python/sglang/srt/mem_cache/hiradix_cache.py core-logic

唯一变更文件,核心预取逻辑所在,修复退化分配中键截断 Bug。

# python/sglang/srt/mem_cache/hiradix_cache.py
# 方法内退化分配分支(host_indices is None 后的降级路径)
if host_indices is None:
    # 修正前:`new_input_tokens = new_input_tokens[:prefetch_length]`
    # 修正后:直接截断 `prefetch_key`,因为 RadixKey 支持切片
    available_size = self.cache_controller.mem_pool_host.available_size()
    prefetch_length = available_size - (available_size % self.page_size)
    if prefetch_length >= self.prefetch_threshold:
        prefetch_key = prefetch_key[:prefetch_length]
        host_indices = self.cache_controller.mem_pool_host.alloc(
            prefetch_length
        )
        # 新增空指针检查:若仍分配失败则释放并返回
        if host_indices is None:
            last_host_node.release_host()
            return
    else:
        last_host_node.release_host()
        return

评论区精华

RadixKey 截断可行性确认 设计

作者 alphabetc1 在自评中说明 `RadixKey` 支持截断切片操作,使用 `[:prefetch_length]` 是安全的。

结论:确认方法可行,无需额外转换。 · 已解决

风险与影响

变更范围很小(+6/-3),仅影响主机内存不足时的降级预取路径,回归风险低。但缺乏对应的单元测试覆盖该退化分支,若未来 RadixKey 的切片语义发生变化,此代码可能静默失效。

对用户无直接可感知影响,但可避免在主机内存紧张场景下的预取键长度错误,提升 HiCache 的健壮性。影响范围限定于启用了 HiCache 且主机内存分配可能失败的部署环境。

缺少测试覆盖

关联 Issue

未识别关联 Issue

当前没有检测到明确关联的 Issue 链接,后续同步到相关引用后会出现在这里。

完整报告

参与讨论