# PR #25085 完整报告

- 仓库：`sgl-project/sglang`
- 标题：Fix swa component host hit
- 合并时间：2026-05-12 21:03
- 原文链接：http://prhub.com.cn/sgl-project/sglang/pull/25085

---

# 执行摘要

- 一句话：修复 SWA 组件 host hit 计数起点错误
- 推荐动作：该 PR 修复了具体的计数问题，值得关注；建议后续结合 review 反馈评估是否需要进一步优化以处理 device-only 节点场景。

# 功能与动机

在 Unified HiCache 的 SWA 组件中，`finalize_match_result` 原先从 `last_device_node` 开始遍历，当匹配结果包含仅存在于 host 的节点时，无法正确识别 host hit，导致 `host_hit_length` 未被更新。

# 实现拆解

1. **定位问题**：在 `python/sglang/srt/mem_cache/unified_cache_components/swa_component.py` 的 `finalize_match_result` 方法中，原先使用 `result.last_device_node` 作为遍历起点。
2. **修复**：将第 98 行 `node = result.last_device_node` 改为 `node = result.last_host_node`，确保遍历从最深的 host 节点开始，以正确检查 host-only 模板。

关键文件：
- `python/sglang/srt/mem_cache/unified_cache_components/swa_component.py`（模块 缓存层；类别 source；类型 core-logic；符号 finalize_match_result）: 核心修复文件，修改 `finalize_match_result` 方法中的遍历起点，影响 host hit 检测逻辑。

关键符号：finalize_match_result

## 关键源码片段

### `python/sglang/srt/mem_cache/unified_cache_components/swa_component.py`

核心修复文件，修改 `finalize_match_result` 方法中的遍历起点，影响 host hit 检测逻辑。

```python
# python/sglang/srt/mem_cache/unified_cache_components/swa_component.py

def finalize_match_result(self, result, params, value_chunks, best_value_len):
    ct = self.component_type
    n_swa = 0
    # 关键修复：从 last_host_node 开始遍历，确保能检测到 host-only 模板
    node = result.last_host_node
    root = self.cache.root_node
    while node is not root and n_swa < self.sliding_window_size:
        cd = node.component_data[ct]
        if cd.value is None and cd.host_value is not None:
            return result._replace(host_hit_length=max(result.host_hit_length, 1))
        if cd.value is not None:
            n_swa += len(cd.value)
        elif cd.host_value is not None:
            n_swa += len(cd.host_value)
        else:
            break
        node = node.parent
    return result

```

# 评论区精华

Review 中指出使用 `last_host_node` 可能跳过 device-only 节点，导致滑动窗口计数偏低。但该 PR 仅有一行改动，且作者已合并，未展开进一步讨论。

- 遍历起点选择可能导致 device-only 节点被跳过 (correctness): 作者未回应并直接合并，但当前修复解决了 host hit 检测问题，device 场景需后续评估。

# 风险与影响

- 风险：当匹配结束于纯 device 节点时（如新插入未备份的 token），`last_host_node` 是 `last_device_node` 的祖先，从较浅的节点开始遍历会跳过设备部分，可能导致 `n_swa` 低估。Review 已指出此风险，但 PR 作者认为当前场景下 host hit 检测更重要。
- 影响：仅影响 SWA 组件的 host hit 检测路径，对非 SWA 组件无影响。改动极小，风险可控。
- 风险标记：潜在低估滑动窗口计数

# 关联脉络

- PR #24972 [UnifiedTree]: Fix Unified HiCache tombstone lock release replay: 均涉及 Unified HiCache 的 SWA 组件修复，属于同一功能模块。