Skip to content

FreeToken brings datacenter-scale model serving to your desktop. Run massive models locally, fast and efficiently.

feat(server): add /v1/cache/flush to drop the prefix cache when idle (#811)

Xiaoze Fane0a7e23c9d2b
diff --git a/python/freetoken/message/__init__.py b/python/freetoken/message/__init__.py
index c22cb70d..531fb52f 100644
--- a/python/freetoken/message/__init__.py
+++ b/python/freetoken/message/__init__.py
@@ -4,10 +4,17 @@ from .backend import (
BatchBackendMsg,
CacheRebuildBackendMsg,
ExitMsg,
+ FlushCacheBackendMsg,
MMItem,
UserMsg,
)
-from .frontend import BaseFrontendMsg, BatchFrontendMsg, CacheRebuildReply, UserReply
+from .frontend import (
+ BaseFrontendMsg,
+ BatchFrontendMsg,
+ CacheRebuildReply,
+ FlushCacheReply,
+ UserReply,
+)
from .tokenizer import (
AbortMsg,
BaseTokenizerMsg,
@@ -16,6 +23,8 @@ from .tokenizer import (
CacheRebuildResultMsg,
DetokenizeMsg,
ErrorReplyMsg,
+ FlushCacheMsg,
+ FlushCacheResultMsg,
PromptAdmittedMsg,
TokenizeMsg,
)
@@ -27,6 +36,7 @@ __all__ = [
"BatchBackendMsg",
"CacheRebuildBackendMsg",
"ExitMsg",
+ "FlushCacheBackendMsg",
"MMItem",
"UserMsg",
"BaseTokenizerMsg",
@@ -35,10 +45,13 @@ __all__ = [
"CacheRebuildResultMsg",
"DetokenizeMsg",
"ErrorReplyMsg",
+ "FlushCacheMsg",
+ "FlushCacheResultMsg",
"PromptAdmittedMsg",
"TokenizeMsg",
"BaseFrontendMsg",
"BatchFrontendMsg",
"CacheRebuildReply",
+ "FlushCacheReply",
"UserReply",
]
diff --git a/python/freetoken/message/backend.py b/python/freetoken/message/backend.py
index ccc1d792..632802a4 100644
--- a/python/freetoken/message/backend.py
+++ b/python/freetoken/message/backend.py
@@ -95,3 +95,10 @@ class CacheRebuildBackendMsg(BaseBackendMsg):
num_mamba_slots: int | None = None
num_swa_pages: int | None = None
mode: str = "if_idle" # only "if_idle" is supported; "drain" is deferred (rejected)
+
+
+@dataclass
+class FlushCacheBackendMsg(BaseBackendMsg):
+ # tokenizer worker -> scheduler: drop every unlocked prefix-cache entry. timeout > 0 waits that many seconds for the scheduler to go idle.
+ request_id: str
+ timeout: float = 0.0
diff --git a/python/freetoken/message/frontend.py b/python/freetoken/message/frontend.py
index 24725567..abf69264 100644
--- a/python/freetoken/message/frontend.py
+++ b/python/freetoken/message/frontend.py
@@ -68,3 +68,11 @@ class CacheRebuildReply(BaseFrontendMsg):
mamba_slots: int = 0
num_swa_pages: int = 0
error: str | None = None
+
+
+@dataclass
+class FlushCacheReply(BaseFrontendMsg):
+ # detokenizer worker -> api server: result of a /v1/cache/flush request.
+ request_id: str
+ status: str # "ok" | "busy" | "timeout" | "unsupported" | "failed"
+ error: str | None = None
diff --git a/python/freetoken/message/tokenizer.py b/python/freetoken/message/tokenizer.py
index d52d658e..f091d0d3 100644
--- a/python/freetoken/message/tokenizer.py
+++ b/python/freetoken/message/tokenizer.py
@@ -104,6 +104,21 @@ class CacheRebuildResultMsg(BaseTokenizerMsg):
error: str | None = None
+@dataclass
+class FlushCacheMsg(BaseTokenizerMsg):
+ # api server -> tokenizer worker (pure passthrough to FlushCacheBackendMsg).
+ request_id: str
+ timeout: float = 0.0
+
+
+@dataclass
+class FlushCacheResultMsg(BaseTokenizerMsg):
+ # scheduler -> detokenizer worker (passthrough to FlushCacheReply).
+ request_id: str
+ status: str # "ok" | "busy" | "timeout" | "unsupported"
+ error: str | None = None
+
+
@dataclass
class ErrorReplyMsg(BaseTokenizerMsg):
# scheduler -> tokenizer/detokenizer worker -> frontend: a request the scheduler cannot
diff --git a/python/freetoken/scheduler/cache.py b/python/freetoken/scheduler/cache.py
index 772297e0..bd675d72 100644
--- a/python/freetoken/scheduler/cache.py
+++ b/python/freetoken/scheduler/cache.py
@@ -588,22 +588,31 @@ class CacheManager:
del self._free
self.free_slots = torch.cat([self.free_slots] + lazy_free_list)
+ def flush(self) -> int:
+ """Evict every unlocked prefix-cache entry and return the number of tokens freed."""
+ evictable = (self.prefix_cache.full_evictable_size if (self.is_hybrid or self.is_swa)
+ else self.prefix_cache.size_info.evictable_size)
+ evicted = self._evict(evictable)
+ self._free(evicted)
+ return len(evicted)
+
+ def _evict(self, need: int) -> torch.Tensor:
+ if self.is_swa:
+ # Evicting KV leaf nodes drops their swa slots too -> return both pools.
+ ev = self.prefix_cache.evict_full(need)
+ self._free_swa(ev.swa_indices)
+ return ev.kv_indices
+ if self.is_hybrid:
+ # Evicting KV leaf nodes drops their GDN snapshots too -> return both pools.
+ er = self.prefix_cache.evict_full(need)
+ if er.mamba_slots:
+ self.linear_state_pool.free(er.mamba_slots)
+ return er.kv_indices
+ return self.prefix_cache.evict(need)
+
def _allocate(self, needed_pages: int) -> torch.Tensor:
if needed_pages > (free_pages := len(self.free_slots)):
- need = (needed_pages - free_pages) * self.page_size
- if self.is_swa:
- # Evicting KV leaf nodes drops their swa slots too -> return both pools.
- ev = self.prefix_cache.evict_full(need)
- evicted = ev.kv_indices
- self._free_swa(ev.swa_indices)
- elif self.is_hybrid:
- # Evicting KV leaf nodes drops their GDN snapshots too -> return both pools.
- er = self.prefix_cache.evict_full(need)
- evicted = er.kv_indices
- if er.mamba_slots:
- self.linear_state_pool.free(er.mamba_slots)
- else:
- evicted = self.prefix_cache.evict(need)
+ evicted = self._evict((needed_pages - free_pages) * self.page_size)
self.free_slots = torch.cat([self.free_slots, evicted[:: self.page_size]])
assert len(self.free_slots) >= needed_pages, "Eviction did not free enough space."
allocated = self.free_slots[:needed_pages]
diff --git a/python/freetoken/scheduler/scheduler.py b/python/freetoken/scheduler/scheduler.py
index 220fa090..f16608cc 100644
--- a/python/freetoken/scheduler/scheduler.py
+++ b/python/freetoken/scheduler/scheduler.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import os
+import time
from typing import TYPE_CHECKING, List, NamedTuple, NoReturn, Set, Tuple, TypeAlias
@@ -18,6 +19,8 @@ from freetoken.message import (
DetokenizeMsg,
ErrorReplyMsg,
ExitMsg,
+ FlushCacheBackendMsg,
+ FlushCacheResultMsg,
PromptAdmittedMsg,
UserMsg,
)
@@ -120,6 +123,8 @@ class Scheduler(SchedulerIOMixin):
# A received-but-not-yet-executed runtime cache rebuild (CacheRebuildBackendMsg),
# run at the next idle safe point in overlap_loop. None when no rebuild is pending.
self._pending_rebuild: CacheRebuildBackendMsg | None = None
+ # A /v1/cache/flush waiting for the idle safe point, with its time.monotonic() deadline.
+ self._pending_flush: Tuple[FlushCacheBackendMsg, float] | None = None
self.tokenizer = load_tokenizer(config.model_path)
self.eos_token_ids = load_eos_token_ids(config.model_path, self.tokenizer)
self.toolcall_anchor_id = None
@@ -227,6 +232,7 @@ class Scheduler(SchedulerIOMixin):
or self.prefill_manager.runnable
or self.decode_manager.runnable
or self._pending_rebuild is not None # a queued rebuild to drain toward + execute
+ or self._pending_flush is not None # a deferred flush to run at idle or time out
)
for msg in self.receive_msg(blocking=blocking):
self._process_one_msg(msg)
@@ -238,6 +244,7 @@ class Scheduler(SchedulerIOMixin):
self.prefill_manager.runnable or self.decode_manager.runnable
):
self._execute_pending_rebuild()
+ self._check_pending_flush()
# Order this iteration's host->device token_pool copies (issued on ``self.stream``
# during scheduling) after the previous batch's sampled-token writes (issued on the
@@ -272,6 +279,7 @@ class Scheduler(SchedulerIOMixin):
self.prefill_manager.runnable
or self.decode_manager.runnable
or self._pending_rebuild is not None # a queued rebuild to execute at idle
+ or self._pending_flush is not None # a deferred flush to run at idle or time out
)
for msg in self.receive_msg(blocking=blocking):
self._process_one_msg(msg)
@@ -283,6 +291,7 @@ class Scheduler(SchedulerIOMixin):
self.prefill_manager.runnable or self.decode_manager.runnable
):
self._execute_pending_rebuild()
+ self._check_pending_flush()
forward_input = self._schedule_next_batch()
ongoing_data = None
@@ -616,6 +625,8 @@ class Scheduler(SchedulerIOMixin):
self._reply_rebuild(msg.request_id, "busy")
else:
self._pending_rebuild = msg
+ elif isinstance(msg, FlushCacheBackendMsg):
+ self._handle_flush(msg)
else:
logger.error(f"Unknown message type: {type(msg)}")
raise NotImplementedError
@@ -737,6 +748,43 @@ class Scheduler(SchedulerIOMixin):
self._log_cache_geometry("Cache rebuilt")
self._reply_rebuild(msg.request_id, "ok")
+ def _handle_flush(self, msg: FlushCacheBackendMsg) -> None:
+ # Same idle/timeout contract as sglang's /flush_cache. Even timeout=0 waits for this iteration's safe point.
+ if self.config.tp_info.size > 1:
+ # each rank checks the deadline on its own clock, so a deferred flush could run on only some ranks
+ self._reply_flush(msg.request_id, "unsupported", "cache flush unsupported under TP > 1")
+ elif self._pending_flush is not None:
+ self._reply_flush(msg.request_id, "busy", "another cache flush is already waiting")
+ else:
+ self._pending_flush = (msg, time.monotonic() + msg.timeout)
+
+ def _check_pending_flush(self) -> None:
+ """Run the pending flush once the scheduler is fully idle, or fail it at its deadline."""
+ if self._pending_flush is None:
+ return
+ msg, deadline = self._pending_flush
+ if self._last_data is None and not (
+ self.prefill_manager.runnable or self.decode_manager.runnable
+ ):
+ self._pending_flush = None
+ freed = self.cache_manager.flush()
+ self.cache_manager.check_integrity()
+ logger.info_rank0(f"Cache flushed: {freed} prefix-cache tokens freed")
+ self._reply_flush(msg.request_id, "ok")
+ elif time.monotonic() >= deadline:
+ self._pending_flush = None
+ error = (
+ "scheduler is not idle: "
+ f"{len(self.prefill_manager.pending_list)} queued, "
+ f"{len(self.decode_manager.running_reqs)} running"
+ + (", last batch still in flight" if self._last_data is not None else "")
+ )
+ logger.warning_rank0(f"Cache not flushed, {error}")
+ self._reply_flush(msg.request_id, "timeout" if msg.timeout > 0 else "busy", error)
+
+ def _reply_flush(self, request_id: str, status: str, error: str | None = None) -> None:
+ self.send_result([FlushCacheResultMsg(request_id=request_id, status=status, error=error)])
+
def _current_cache_geometry(self) -> dict:
"""The pools' current (serving) sizes as rebuild_cache kwargs — the rollback snapshot and
the single source for _reply_rebuild's readout. None for a pool this model lacks
diff --git a/python/freetoken/server/api_server.py b/python/freetoken/server/api_server.py
index a9b16adf..ce04b341 100644
--- a/python/freetoken/server/api_server.py
+++ b/python/freetoken/server/api_server.py
@@ -15,7 +15,7 @@ from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Literal
import uvicorn
-from fastapi import FastAPI, Request
+from fastapi import FastAPI, Query, Request
from fastapi.responses import JSONResponse, StreamingResponse
from freetoken import __version__
from freetoken.core import SamplingParams
@@ -26,6 +26,8 @@ from freetoken.message import (
BatchFrontendMsg,
CacheRebuildMsg,
CacheRebuildReply,
+ FlushCacheMsg,
+ FlushCacheReply,
TokenizeMsg,
UserReply,
)
@@ -146,6 +148,8 @@ class FrontendManager:
# Runtime cache-rebuild control plane (correlated by uuid request_id, separate from
# the int-uid generation ack machinery).
rebuild_futures: Dict[str, asyncio.Future] = field(default_factory=dict)
+ # /v1/cache/flush waiters by request_id; the scheduler owns the deadline, so there is no HTTP timeout.
+ flush_futures: Dict[str, asyncio.Future] = field(default_factory=dict)
# Lifecycle gate. Starts "loading" (uvicorn binds before weights finish; the three
# API adapters 503 until this flips) -> "serving" once all workers ack ready ->
# "rebuilding"/"failed" for runtime cache rebuilds.
@@ -252,6 +256,11 @@ class FrontendManager:
if isinstance(msg, CacheRebuildReply):
self._resolve_rebuild(msg)
continue
+ if isinstance(msg, FlushCacheReply):
+ fut = self.flush_futures.pop(msg.request_id, None)
+ if fut is not None and not fut.done():
+ fut.set_result(msg)
+ continue
for msg in _unwrap_msg(msg):
# Global accounting follows actual admitted/sampled work even after the HTTP
# client disconnects and abort_user removes its ack queue. Delivery to a live
@@ -300,7 +309,8 @@ class FrontendManager:
caller blocked in dispatch_rebuild's ``await`` would otherwise hang until its full
timeout (up to 300s). Runs the resolution ON the event loop via call_soon_threadsafe —
asyncio Futures are not thread-safe, and _resolve_rebuild only ever calls set_result
- from the loop thread (the listen() task), so we mirror that here from off-thread."""
+ from the loop thread (the listen() task), so we mirror that here from off-thread.
+ Pending /v1/cache/flush waiters fail the same way."""
loop = self._loop
if loop is None:
return # listener never started -> no futures could be pending
@@ -311,6 +321,10 @@ class FrontendManager:
fut = self.rebuild_futures.pop(request_id, None)
if fut is not None and not fut.done():
fut.set_result(dict(result))
+ for request_id in list(self.flush_futures):
+ fut = self.flush_futures.pop(request_id, None)
+ if fut is not None and not fut.done():
+ fut.set_result(FlushCacheReply(request_id=request_id, status="failed", error=message))
try:
loop.call_soon_threadsafe(_resolve_all)
@@ -609,14 +623,11 @@ def _resolve_num_swa_pages(state: FrontendManager, req: CacheRebuildRequest) ->
return max(1, -(-window_tokens // swa_page_size)) # ceil-div to the pool's page unit
[email protected]("/v1/cache/rebuild")
-async def cache_rebuild(req: CacheRebuildRequest):
- """Trigger a runtime KV/MoE cache resize. Blocks until the scheduler reports a result
- (or timeout). New generation is gated (503) while a rebuild is in flight."""
- state = get_global_state()
+def _maintenance_rejection(state: FrontendManager, action: str) -> JSONResponse | None:
+ """The /v1/cache/* refusal while the engine is not serving, or None to proceed."""
if state.maintenance_state == "loading":
return JSONResponse(
- {"status": "loading", "error": "model is still loading; cannot rebuild cache yet"},
+ {"status": "loading", "error": f"model is still loading; cannot {action} yet"},
status_code=503,
)
if state.maintenance_state == "failed":
@@ -634,6 +645,16 @@ async def cache_rebuild(req: CacheRebuildRequest):
{"status": "busy", "error": "engine stop is in progress"},
status_code=409,
)
+ return None
+
+
[email protected]("/v1/cache/rebuild")
+async def cache_rebuild(req: CacheRebuildRequest):
+ """Trigger a runtime KV/MoE cache resize. Blocks until the scheduler reports a result
+ (or timeout). New generation is gated (503) while a rebuild is in flight."""
+ state = get_global_state()
+ if (rejection := _maintenance_rejection(state, "rebuild cache")) is not None:
+ return rejection
if req.num_swa_pages is not None and req.swa_full_tokens_ratio is not None:
return JSONResponse(
{"status": "failed", "error": "pass num_swa_pages OR swa_full_tokens_ratio, not both"},
@@ -662,6 +683,33 @@ async def cache_rebuild(req: CacheRebuildRequest):
return JSONResponse(result, status_code=200 if result["status"] == "ok" else 503)
[email protected]_route("/v1/cache/flush", methods=["GET", "POST"])
+async def cache_flush(timeout: float = Query(0.0, ge=0.0)):
+ """Drop every prefix-cache entry once the scheduler is idle, waiting up to ``timeout`` seconds."""
+ state = get_global_state()
+ if (rejection := _maintenance_rejection(state, "flush cache")) is not None:
+ return rejection
+ request_id = str(uuid.uuid4())
+ fut = asyncio.get_running_loop().create_future()
+ state.flush_futures[request_id] = fut
+ try:
+ await state.send_one(FlushCacheMsg(request_id=request_id, timeout=timeout))
+ except Exception as e: # noqa: BLE001
+ state.flush_futures.pop(request_id, None)
+ return JSONResponse(
+ {"status": "failed", "error": f"failed to dispatch flush: {e!r}"}, status_code=503
+ )
+ try:
+ reply = await fut
+ finally:
+ state.flush_futures.pop(request_id, None)
+ body = {"status": reply.status}
+ if reply.error is not None:
+ body["error"] = reply.error
+ status_code = {"ok": 200, "timeout": 504}.get(reply.status, 503)
+ return JSONResponse(body, status_code=status_code)
+
+
def _cache_limits(geo: dict, unit_bytes: dict, pool_budget: int, floors: dict) -> dict:
"""Per-pool adjustable {min, max} bounds for the desktop cache sliders, so their ranges stay
sensible instead of spanning the whole theoretical space:
diff --git a/python/freetoken/tokenizer/server.py b/python/freetoken/tokenizer/server.py
index d3365bfe..fad66d74 100644
--- a/python/freetoken/tokenizer/server.py
+++ b/python/freetoken/tokenizer/server.py
@@ -19,6 +19,10 @@ from freetoken.message import (
CacheRebuildResultMsg,
DetokenizeMsg,
ErrorReplyMsg,
+ FlushCacheBackendMsg,
+ FlushCacheMsg,
+ FlushCacheReply,
+ FlushCacheResultMsg,
PromptAdmittedMsg,
TokenizeMsg,
UserMsg,
@@ -196,10 +200,25 @@ def tokenize_worker(
error=m.error,
)
)
+ elif isinstance(m, FlushCacheMsg):
+ send_backend.put(
+ FlushCacheBackendMsg(request_id=m.request_id, timeout=m.timeout)
+ )
+ elif isinstance(m, FlushCacheResultMsg):
+ send_frontend.put(
+ FlushCacheReply(request_id=m.request_id, status=m.status, error=m.error)
+ )
n_control = sum(
isinstance(
m,
- (CacheRebuildMsg, CacheRebuildResultMsg, ErrorReplyMsg, PromptAdmittedMsg),
+ (
+ CacheRebuildMsg,
+ CacheRebuildResultMsg,
+ FlushCacheMsg,
+ FlushCacheResultMsg,
+ ErrorReplyMsg,
+ PromptAdmittedMsg,
+ ),
)
for m in pending_msg
)
diff --git a/tests/e2e/test_cache_rebuild.py b/tests/e2e/test_cache_rebuild.py
index ed17e240..b17fc28b 100644
--- a/tests/e2e/test_cache_rebuild.py
+++ b/tests/e2e/test_cache_rebuild.py
@@ -2,7 +2,8 @@
Boots ``ft serve`` on a small checkpoint and drives POST /v1/cache/rebuild for real: the whole
chain of HTTP route -> control message -> scheduler idle gate -> engine teardown -> pool resize
--> page-table refresh -> CUDA-graph re-capture, then checks the server still generates.
+-> page-table refresh -> CUDA-graph re-capture, then checks the server still generates. The same
+boot also drives /v1/cache/flush, which drops the prefix cache without touching the pools.
This is the primary gate for the rebuild path. The destructive orchestration has no in-process
seam worth stubbing -- what matters is that a rebuild lands on a live engine and the server keeps
@@ -131,6 +132,7 @@ def test_cache_rebuild_resizes_a_live_engine_and_keeps_serving(tmp_path):
"--host", "127.0.0.1",
"--port", str(port),
"--num-pages", str(BOOT_PAGES),
+ "--enable-cache-report",
],
stdout=log,
stderr=subprocess.STDOUT,
@@ -144,6 +146,27 @@ def test_cache_rebuild_resizes_a_live_engine_and_keeps_serving(tmp_path):
assert geometry["num_pages"] == BOOT_PAGES
assert _generate(base) # a baseline generation, before anything is torn down
+ # 0. Flush the prefix cache. Long enough for a hybrid model to snapshot a reusable prefix.
+ chat = {
+ "model": "rebuild-test",
+ "messages": [{"role": "user", "content": "Summarize in one word: " + "the cache keeps every prompt it has seen. " * 40}],
+ "max_tokens": 16,
+ "temperature": 0.0,
+ "chat_template_kwargs": {"enable_thinking": False},
+ }
+ code, cold = _post(base, "/v1/chat/completions", chat)
+ assert code == 200, cold
+ code, warm = _post(base, "/v1/chat/completions", chat)
+ assert code == 200, warm
+ assert warm["usage"]["prompt_tokens_details"]["cached_tokens"] > 0
+ code, reply = _post(base, "/v1/cache/flush", {})
+ assert (code, reply["status"]) == (200, "ok"), reply
+ code, flushed = _post(base, "/v1/chat/completions", chat)
+ assert code == 200, flushed
+ assert "prompt_tokens_details" not in flushed["usage"] # nothing left to hit
+ # A cold run after the flush computes exactly what the cold run before it did.
+ assert flushed["choices"][0]["message"]["content"] == cold["choices"][0]["message"]["content"]
+
# 1. Grow the KV pool. The reply carries the geometry the engine actually landed on.
code, reply = _post(base, "/v1/cache/rebuild", {"num_pages": GROWN_PAGES})
assert (code, reply["status"]) == (200, "ok"), reply
diff --git a/tests/scheduler/test_cache_rebuild.py b/tests/scheduler/test_cache_rebuild.py
index 0c058070..0c9560b6 100644
--- a/tests/scheduler/test_cache_rebuild.py
+++ b/tests/scheduler/test_cache_rebuild.py
@@ -2,10 +2,14 @@
pool/table re-point it performs. The destructive orchestration underneath (graph teardown, pool
resize, page-table refresh, graph re-capture) has no seam worth stubbing and is covered against a
real server by tests/e2e/test_cache_rebuild.py; the maintenance state machine the HTTP layer runs
-on top lives in tests/server/test_rebuild_maintenance.py."""
+on top lives in tests/server/test_rebuild_maintenance.py. Also the /v1/cache/flush path:
+CacheManager.flush and the scheduler's deferred-flush gate."""
from __future__ import annotations
+from types import SimpleNamespace
+
+import pytest
import torch
@@ -71,6 +75,7 @@ def _stub_scheduler(*, prefill_runnable: bool, decode_runnable: bool, pending: o
sched.prefill_manager = SimpleNamespace(runnable=prefill_runnable)
sched.decode_manager = SimpleNamespace(runnable=decode_runnable)
sched._pending_rebuild = pending
+ sched._pending_flush = None
sched.receive_msg = lambda blocking: []
sched._schedule_next_batch = lambda: None
sched._process_last_data = lambda data: None
@@ -168,3 +173,139 @@ def test_rebuild_cache_refreshes_prefill_budget(monkeypatch):
cache_manager.prefill_chunk_budget = 1000 # the (stubbed) engine rebuild shrank the pool
Scheduler.rebuild_cache(sched, num_pages=16)
assert sched.prefill_budget == 1000 # tracks the shrunk cap, not the stale 5000
+
+
+def _flush_manager(cache_type: str):
+ from freetoken.scheduler.cache import CacheManager
+
+ ps, num_pages = 2, 16
+ pt = _page_table(4, num_pages * ps)
+ if cache_type == "hybrid_radix":
+ from freetoken.kvcache.linear_state_pool import LinearStatePool
+ from freetoken.models.config import LinearGatedDeltaGroupConfig
+
+ g = LinearGatedDeltaGroupConfig(
+ name="linear", layer_ids=(0,), num_key_heads=2, num_value_heads=4,
+ key_head_dim=16, value_head_dim=16, conv_kernel_dim=4, output_gate="silu",
+ )
+ pool = LinearStatePool(group=g, num_slots=8, dtype=torch.bfloat16,
+ device=torch.device("cpu"), tp_size=1)
+ return CacheManager(num_pages, ps, pt, cache_type, linear_state_pool=pool)
+ if cache_type == "swa_radix":
+ from freetoken.distributed import set_tp_info, try_get_tp_info
+ from freetoken.kvcache.hybrid_swa_pool import HybridSWAKVCache
+ from freetoken.models.config import KVCacheGroupSpec
+
+ if try_get_tp_info() is None:
+ set_tp_info(rank=0, size=1)
+
+ groups = (
+ KVCacheGroupSpec(name="full", layer_ids=(1,), num_kv_heads=1, head_dim=8,
+ sliding_window=None),
+ KVCacheGroupSpec(name="swa", layer_ids=(0,), num_kv_heads=1, head_dim=8,
+ sliding_window=ps),
+ )
+ pool = HybridSWAKVCache(
+ groups=groups, num_layers=2, num_full_pages=num_pages, page_size=ps,
+ dtype=torch.bfloat16, device=torch.device("cpu"), num_swa_tokens=num_pages * ps,
+ )
+ return CacheManager(num_pages, ps, pt, cache_type, swa_pool=pool, sliding_window_size=ps)
+ return CacheManager(num_pages, ps, pt, cache_type)
+
+
+def _insert(cm, ids: list[int]) -> None:
+ """Commit ``ids`` to the tree through the tree's own insert, returning duplicate slots like cache_req does."""
+ ids = torch.tensor(ids, dtype=torch.int32)
+ kv = cm._page_to_token(cm._allocate(len(ids) // cm.page_size))
+ if cm.is_swa:
+ cm.swa_pool.alloc_swa(kv)
+ _, dup = cm.prefix_cache.insert(ids, kv)
+ cm._free_swa(dup)
+ cm._free(dup)
+ elif cm.is_hybrid:
+ matched, _ = cm.prefix_cache.insert(ids, kv, cm.linear_state_pool.alloc(1)[0])
+ cm._free(kv[:matched])
+ else:
+ cm._free(kv[: cm.prefix_cache.insert_prefix(ids, kv).cached_len])
+
+
[email protected]("cache_type", ["radix", "hybrid_radix", "swa_radix"])
+def test_cache_manager_flush_returns_every_pool_slot(cache_type):
+ _setup_context(page_size=2)
+ cm = _flush_manager(cache_type)
+ # The shared [1..4] prefix becomes an internal node, so flush must also evict a parent left childless.
+ _insert(cm, [1, 2, 3, 4, 5, 6, 7, 8])
+ _insert(cm, [1, 2, 3, 4, 20, 21, 22, 23])
+ _insert(cm, [30, 31])
+ cm.check_integrity()
+
+ assert cm.flush() == 14
+ assert len(cm.free_slots) == cm.num_pages
+ if cm.is_hybrid:
+ assert cm.linear_state_pool.num_free_slots == 8 - 1 # slot 0 is padding
+ if cm.is_swa:
+ assert cm.swa_pool.swa_available_size() == cm.swa_pool.swa_num_tokens - 1 # slot 0 is the sentinel
+ cm.check_integrity()
+ pending = SimpleNamespace(input_ids=torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=torch.int32), input_len=9)
+ assert cm.match_req(pending).cuda_handle.cached_len == 0
+
+
[email protected]("loop", ["normal", "overlap"])
+def test_deferred_flush_runs_at_idle_and_times_out_while_busy(monkeypatch, loop):
+ from freetoken.message import FlushCacheBackendMsg
+ from freetoken.scheduler import scheduler as scheduler_mod
+ from freetoken.scheduler.scheduler import Scheduler
+
+ clock = [0.0]
+ monkeypatch.setattr(scheduler_mod, "time", SimpleNamespace(monotonic=lambda: clock[0]))
+ sched, _ = _stub_scheduler(prefill_runnable=False, decode_runnable=False, pending=None)
+ sched.prefill_manager.pending_list = []
+ sched.decode_manager.running_reqs = set()
+ sched.config = SimpleNamespace(tp_info=SimpleNamespace(size=1))
+ sched._last_data = None
+ sched.stream = SimpleNamespace(wait_stream=lambda stream: None)
+ sched.engine = SimpleNamespace(stream=None)
+ flushed = []
+ sched.cache_manager = SimpleNamespace(flush=lambda: flushed.append(True) or 0, check_integrity=lambda: None)
+ sent = []
+ sched.send_result = lambda msgs: sent.extend((m.request_id, m.status) for m in msgs)
+ blocked = []
+ sched.receive_msg = lambda blocking: blocked.append(blocking) or []
+
+ def step(busy: bool) -> None:
+ if loop == "normal":
+ sched.decode_manager.runnable = busy
+ Scheduler.normal_loop(sched)
+ else:
+ # Only the in-flight batch keeps the overlap scheduler busy here.
+ Scheduler.overlap_loop(sched, object() if busy else None)
+
+ Scheduler._process_one_msg(sched, FlushCacheBackendMsg(request_id="a", timeout=10.0))
+ Scheduler._process_one_msg(sched, FlushCacheBackendMsg(request_id="b", timeout=10.0))
+ assert sent == [("b", "busy")]
+
+ # Busy before the deadline: still waiting.
+ clock[0] = 5.0
+ step(busy=True)
+ assert len(sent) == 1 and not flushed
+
+ # Idle: runs without new traffic, so the loop must not block on receive.
+ step(busy=False)
+ assert blocked[-1] is False
+ assert flushed == [True] and sent[-1] == ("a", "ok")
+ assert sched._pending_flush is None
+
+ # Busy past the deadline: fails and clears the slot.
+ Scheduler._process_one_msg(sched, FlushCacheBackendMsg(request_id="c", timeout=10.0))
+ clock[0] = 15.0
+ step(busy=True)
+ assert sent[-1] == ("c", "timeout")
+ assert flushed == [True] and sched._pending_flush is None
+
+ # timeout=0 never waits: busy fails in the same iteration, idle flushes in the same iteration.
+ Scheduler._process_one_msg(sched, FlushCacheBackendMsg(request_id="d", timeout=0.0))
+ step(busy=True)
+ assert sent[-1] == ("d", "busy") and sched._pending_flush is None
+ Scheduler._process_one_msg(sched, FlushCacheBackendMsg(request_id="e", timeout=0.0))
+ step(busy=False)
+ assert sent[-1] == ("e", "ok") and flushed == [True, True]
diff --git a/tests/scheduler/test_cost_accounting_core.py b/tests/scheduler/test_cost_accounting_core.py
index 045010c6..ed741ef8 100644
--- a/tests/scheduler/test_cost_accounting_core.py
+++ b/tests/scheduler/test_cost_accounting_core.py
@@ -204,6 +204,7 @@ def test_normal_loop_sends_prior_sample_before_abort_terminal():
scheduler.decode_manager = SimpleNamespace(runnable=False, abort_req=lambda uid: None)
scheduler._pending_abort_acks = set()
scheduler._pending_rebuild = None
+ scheduler._pending_flush = None
scheduler.receive_msg = lambda blocking: [AbortBackendMsg(uid=5)]
scheduler._schedule_next_batch = lambda: None
sent = []
diff --git a/tests/server/test_rebuild_maintenance.py b/tests/server/test_rebuild_maintenance.py
index a1d10a7e..44077159 100644
--- a/tests/server/test_rebuild_maintenance.py
+++ b/tests/server/test_rebuild_maintenance.py
@@ -35,12 +35,13 @@ from freetoken.server.supervisor import (
class _FakeState:
"""Stand-in for FrontendManager exposing exactly what dispatch_rebuild / _resolve_rebuild /
- fail_pending_rebuilds read: rebuild_futures, maintenance_state, fatal_error, last_rebuild,
+ fail_pending_rebuilds read: rebuild_futures, flush_futures, maintenance_state, fatal_error, last_rebuild,
the event loop (_loop, for cross-thread future resolution), and an async send_one delegating
to an injected impl (so a test can make the enqueue succeed or raise)."""
def __init__(self, send_impl, *, maintenance_state="serving", fatal_error=None):
self.rebuild_futures: dict = {}
+ self.flush_futures: dict = {}
self.maintenance_state = maintenance_state
self.fatal_error = fatal_error
self.last_rebuild = None
@@ -204,6 +205,8 @@ def test_crash_during_rebuild_latches_failed_via_watchdog():
await asyncio.sleep(0)
assert state.rebuild_futures # a waiter is parked
assert state.maintenance_state == "rebuilding"
+ flush_fut = asyncio.get_running_loop().create_future()
+ state.flush_futures["flush"] = flush_fut # a /v1/cache/flush waiter has no HTTP timeout either
proc._alive = False # …and the scheduler crashes mid-rebuild
@@ -214,6 +217,8 @@ def test_crash_during_rebuild_latches_failed_via_watchdog():
assert state.maintenance_state == "failed" # escaped "rebuilding" to a definite state
assert "scheduler" in state.fatal_error
assert state.rebuild_futures == {} # waiter resolved and cleared, not leaked
+ assert (await asyncio.wait_for(flush_fut, timeout=5.0)).status == "failed"
+ assert state.flush_futures == {}
sup.join(timeout=1.0)
asyncio.run(_run())