Prhub

#21413 Api add flush cache timeout

原始 PR 作者 Wenjun7J 合并时间 2026-03-27 05:44 文件变更 6 提交数 4 评论 3 代码增减 +167 / -9

执行摘要

为 flush_cache API 添加超时参数,允许在系统繁忙时等待空闲后刷新缓存。

源自issue #21359,当HiCache异步操作(如GPU kv cache写入Host)进行时,flush_cache会因系统非完全空闲而立即返回400 Bad Request错误。PR body指出:“flush_cache can only be safely applied when is_fully_idle() is true”,客户端需要轮询直到成功,引入超时参数以减少不必要的重试和几乎无额外开销的服务器等待。

建议阅读python/sglang/srt/managers/scheduler.py中的flush_cache_wrapped和_check_pending_flush方法,了解超时队列设计;同时关注单元测试以验证正确性。对于调度器开发者和API用户,此PR提供了处理异步状态等待的参考模式。

讨论亮点

Review中仅有一个来自gemini-code-assist[bot]的总结性评论,概述了变更内容:“introduces a new /flush_cache endpoint with a timeout parameter, allowing for deferred cache flushing”,没有具体争议或深度讨论,变更被顺利合并。

实现拆解

实现分为几个关键模块:

1) API层:在python/sglang/srt/entrypoints/http_server.py中为/flush_cache端点添加timeout查询参数,传递至tokenizer_manager。
2) 数据层:修改python/sglang/srt/managers/io_struct.py中的FlushCacheReqInput类,新增timeout_s字段。
3) 核心逻辑层:在python/sglang/srt/managers/scheduler.py中新增_pending_flush队列、flush_cache_wrapped方法(处理超时逻辑)、_check_pending_flush和_expire_timed_out_pending_flushes方法(每轮事件循环检查待处理请求)。
4) 通信层:更新python/sglang/srt/managers/tokenizer_communicator_mixin.py的flush_cache方法以支持timeout_s参数。
5) 文档与测试:更新docs/basic_usage/native_api.ipynb文档,新增test/registered/unit/managers/test_scheduler_flush_cache.py单元测试验证逻辑。

文件 模块 状态 重要度
python/sglang/srt/managers/scheduler.py 调度器 modified 9.0
test/registered/unit/managers/test_scheduler_flush_cache.py 测试 added 7.0
python/sglang/srt/entrypoints/http_server.py API 端点 modified 6.0
python/sglang/srt/managers/io_struct.py 数据结构 modified 5.0
docs/basic_usage/native_api.ipynb 文档 modified 4.0

关键符号

flush_cache_wrapped _check_pending_flush _expire_timed_out_pending_flushes flush_cache (in tokenizer_communicator_mixin.py)

分析完成后,这里会展示 LLM 生成的相对完整源码片段和详细注释。

评论区精华

变更总结 设计

gemini-code-assist[bot] 总结 PR 引入了带超时参数的 flush_cache 端点,允许延迟缓存刷新。

结论:变更被认可并合并,无争议。 · 已解决

风险与影响

主要风险包括:

1) 调度器复杂度增加:新增_pending_flush队列和检查逻辑可能引入竞态条件,但PR body提到“each scheduler is single-threaded and only handles its own pending flush queue, there should be no thread-safety concerns”,需确保单线程假设成立。
2) 超时处理可能延迟:_check_pending_flush依赖process_input_requests循环,若循环间隔长,超时响应可能不及时。
3) 测试覆盖:新增单元测试覆盖核心场景,但未涉及并发请求或极端超时值,可能遗漏边缘情况。
4) 文档一致性:文档更新了参数说明,但需确认其他相关API文档同步更新。

对用户:API更易用,减少客户端轮询需求,提升用户体验;对系统:轻微性能开销来自队列管理,但无显著影响;对团队:需维护新增的逻辑和测试,文档更新促进开发者理解。影响范围限于flush_cache相关功能,不涉及核心模型推理路径。

核心路径变更 新增队列管理 超时处理复杂度

关联 Issue

未识别关联 Issue

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

完整报告

参与讨论