From e239f9ebe1bb0413dd4a66663784cfe743104a46 Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 11:51:38 +0800 Subject: [PATCH 1/7] fix(pd): keep master control traffic responsive under CPU pressure --- lightllm/server/api_anthropic.py | 5 +- lightllm/server/api_http.py | 78 ++++++++++- lightllm/server/api_http_pd.py | 67 ++++++++-- lightllm/server/build_prompt.py | 15 ++- .../httpserver_for_pd_master/manager.py | 8 +- .../prompt_processing.py | 61 +++++++++ .../httpserver/test_pd_request_admission.py | 125 ++++++++++++++++++ .../httpserver/test_pd_websocket_lifecycle.py | 62 ++++++++- unit_tests/server/test_pd_master_mode.py | 4 +- 9 files changed, 400 insertions(+), 25 deletions(-) create mode 100644 lightllm/server/httpserver_for_pd_master/prompt_processing.py create mode 100644 unit_tests/server/httpserver/test_pd_request_admission.py diff --git a/lightllm/server/api_anthropic.py b/lightllm/server/api_anthropic.py index 299fd524de..c978f07601 100644 --- a/lightllm/server/api_anthropic.py +++ b/lightllm/server/api_anthropic.py @@ -1323,7 +1323,7 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response: from .api_http import g_objs from .api_models import ChatCompletionRequest from .api_openai import _build_multimodal_params, _select_chat_template_tools - from .build_prompt import build_prompt + from .build_prompt import build_prompt, run_tokenizer_work from .core.objs.sampling_params import SamplingParams raw_body = await raw_request.json() @@ -1340,7 +1340,8 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response: sampling_params = SamplingParams() sampling_params.init(tokenizer=g_objs.httpserver_manager.tokenizer, add_special_tokens=False) - input_tokens = g_objs.httpserver_manager.tokens( + input_tokens = await run_tokenizer_work( + g_objs.httpserver_manager.tokens, prompt, multimodal_params, sampling_params, diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index 8c8ed804ab..b2bed6f93c 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -68,7 +68,8 @@ ModelCard, ModelListResponse, ) -from .build_prompt import build_prompt, init_tokenizer +from .build_prompt import build_prompt, init_tokenizer, run_tokenizer_work +from .api_http_pd import PDHeartbeatMonitor, router as pd_router logger = init_logger(__name__) @@ -76,6 +77,8 @@ @dataclass class G_Objs: app: FastAPI = None + pd_heartbeat_monitor: PDHeartbeatMonitor = None + pd_heartbeat_task: asyncio.Task = None metric_client: MetricClient = None args: StartArgs = None g_generate_func: Callable = None @@ -155,6 +158,66 @@ async def send_wrapper(message): logger.info(msg) +class _PDRequestAdmission: + # Reserve before FastAPI parses the body. The ASGI application returns only after + # the response (including SSE) finishes or the request is cancelled. + paths = frozenset( + { + "/", + "/generate", + "/generate_stream", + "/get_score", + "/v1/chat/completions", + "/v1/completions", + "/v1/responses", + "/v1/messages", + "/v1/messages/count_tokens", + "/tokens", + } + ) + + def __init__(self, app): + self.app = app + self.in_flight = 0 + + async def __call__(self, scope, receive, send): + if ( + scope["type"] != "http" + or scope["path"] not in self.paths + or (scope["method"] != "POST" and not (scope["path"] == "/tokens" and scope["method"] == "GET")) + or g_objs.args is None + or g_objs.args.run_mode != "pd_master" + ): + return await self.app(scope, receive, send) + + if self.in_flight >= g_objs.args.running_max_req_size: + # Finishing an HTTP/1 response while the client is still uploading can + # reset the connection and lose the 429. Discard chunks without parsing + # JSON or buffering the request body. + if scope.get("http_version", "1.1").startswith("1") and scope["method"] == "POST": + while True: + message = await receive() + if message["type"] == "http.disconnect": + return + if not message.get("more_body", False): + break + if scope["path"].startswith("/v1/messages"): + from .api_anthropic import _anthropic_error_response + + g_objs.metric_client.counter_inc("lightllm_request_failure") + response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE) + else: + response = create_server_busy_response(ServerBusyError("PD master request limit reached")) + return await response(scope, receive, send) + + self.in_flight += 1 + try: + return await self.app(scope, receive, send) + finally: + self.in_flight -= 1 + + +app.add_middleware(_PDRequestAdmission) app.add_middleware(_AccessLogMiddleware) @@ -192,7 +255,7 @@ async def generation_exception_handler(request: Request, exc: GenerationError) - @app.get("/liveness") @app.post("/liveness") -def liveness(): +async def liveness(): return {"status": "ok"} @@ -522,8 +585,8 @@ async def tokens(request: Request): await multimodal_params.verify_and_preload(request) return JSONResponse( { - "ntokens": g_objs.httpserver_manager.tokens( - prompt, multimodal_params, sampling_params, sample_params_dict + "ntokens": await run_tokenizer_work( + g_objs.httpserver_manager.tokens, prompt, multimodal_params, sampling_params, sample_params_dict ) }, status_code=200, @@ -551,7 +614,6 @@ async def metrics() -> Response: app.include_router(rl_router) # PD 分离控制面接口(worker 发现、P/D 注册与 KV 状态上报),见 api_http_pd.py -from .api_http_pd import router as pd_router app.include_router(pd_router) @@ -577,6 +639,9 @@ async def profiler_stop() -> Response: @app.on_event("shutdown") async def shutdown(): logger.info("Received signal to shutdown. Performing graceful shutdown...") + if g_objs.pd_heartbeat_task is not None: + g_objs.pd_heartbeat_task.cancel() + await asyncio.gather(g_objs.pd_heartbeat_task, return_exceptions=True) await asyncio.sleep(3) # 杀掉所有子进程 @@ -596,6 +661,9 @@ async def startup_event(): logger.info("server start up") loop = asyncio.get_event_loop() g_objs.set_args(get_env_start_args()) + if g_objs.args.run_mode == "pd_master": + g_objs.pd_heartbeat_monitor = PDHeartbeatMonitor() + g_objs.pd_heartbeat_task = loop.create_task(g_objs.pd_heartbeat_monitor.run()) loop.create_task(g_objs.httpserver_manager.handle_loop()) logger.info(f"server start up ok, loop use is {asyncio.get_event_loop()}") return diff --git a/lightllm/server/api_http_pd.py b/lightllm/server/api_http_pd.py index 9be49735e1..10d5af3159 100644 --- a/lightllm/server/api_http_pd.py +++ b/lightllm/server/api_http_pd.py @@ -8,7 +8,9 @@ ``g_objs`` 在 handler 内懒导入,避免与 api_http 循环依赖。 """ +import asyncio import pickle +import time import ujson as json from anyio import fail_after @@ -23,6 +25,49 @@ router = APIRouter() +_PD_HEARTBEAT_TIMEOUT = 30 +_PD_HEARTBEAT_INTERVAL = 15 + + +class PDHeartbeatMonitor: + """One monotonic scheduling sample per second for all registrations on this worker.""" + + def __init__(self): + self.last_sample = time.monotonic() + self.last_stall_end = float("-inf") + + async def run(self): + while True: + await asyncio.sleep(1) + now = time.monotonic() + # A peer normally sends at least once every 15 seconds. + if now - self.last_sample >= _PD_HEARTBEAT_INTERVAL: + self.last_stall_end = now + self.last_sample = now + + def stalled_since(self, started): + # The receive deadline can run before the overdue sampler on the same loop turn. + return ( + self.last_stall_end > started or time.monotonic() - max(started, self.last_sample) >= _PD_HEARTBEAT_INTERVAL + ) + + +async def _receive_pd_frame(websocket, monitor): + # Keep a single reader and avoid creating a task for every token frame. + started = time.monotonic() + try: + with fail_after(_PD_HEARTBEAT_TIMEOUT): + return await websocket.receive_bytes() + except TimeoutError: + if not monitor.stalled_since(started): + raise + # Local scheduling delay made the deadline inconclusive. Give the same socket + # one fresh read; even repeated local stalls cannot extend it indefinitely. + logger.warning("PD registration read timed out during local event loop lag, rechecking %s", websocket.client) + with fail_after(_PD_HEARTBEAT_TIMEOUT): + return await websocket.receive_bytes() + + @router.websocket("/pd_register") async def register_and_keep_alive(websocket: WebSocket): from .api_http import g_objs @@ -36,12 +81,16 @@ async def register_and_keep_alive(websocket: WebSocket): pd_client = await g_objs.httpserver_manager.register_pd(regist_json, websocket) try: - heartbeat_timeout_seconds = 30 while True: - # Avoid creating a new Task per message so queued PD token packs - # can be drained without extra event-loop scheduling. - with fail_after(heartbeat_timeout_seconds): - data = await websocket.receive_bytes() + try: + data = await _receive_pd_frame(websocket, g_objs.pd_heartbeat_monitor) + except TimeoutError: + logger.warning(f"client {regist_json} heartbeat timed out after {_PD_HEARTBEAT_TIMEOUT} seconds") + try: + await websocket.close(code=1011, reason="PD heartbeat timed out") + except Exception: + logger.debug("failed to close timed-out client %s", regist_json, exc_info=True) + break obj = pickle.loads(data) if isinstance(obj, tuple) and obj and obj[0] == ObjType.HEARTBEAT: if len(obj) == 2: @@ -49,12 +98,8 @@ async def register_and_keep_alive(websocket: WebSocket): continue await g_objs.httpserver_manager.put_to_handle_queue(obj) - except TimeoutError: - logger.warning(f"client {regist_json} heartbeat timed out after {heartbeat_timeout_seconds} seconds") - try: - await websocket.close(code=1011, reason="PD heartbeat timed out") - except BaseException: - logger.debug(f"failed to close timed-out client {regist_json}", exc_info=True) + except asyncio.CancelledError: + raise except WebSocketDisconnect as e: logger.info(f"client {regist_json} disconnected: {str(e)}") except BaseException as e: diff --git a/lightllm/server/build_prompt.py b/lightllm/server/build_prompt.py index 1ee9994643..fda3430c7c 100644 --- a/lightllm/server/build_prompt.py +++ b/lightllm/server/build_prompt.py @@ -1,5 +1,6 @@ import os import json +from lightllm.server.httpserver_for_pd_master.prompt_processing import run_pd_prompt_work from lightllm.server.tokenizer import get_tokenizer from lightllm.utils.log_utils import init_logger from functools import lru_cache @@ -8,10 +9,12 @@ logger = init_logger(__name__) tokenizer = None +_pd_master = False def init_tokenizer(args): - global tokenizer + global tokenizer, _pd_master + _pd_master = args.run_mode == "pd_master" tokenizer = get_tokenizer(args.model_dir, args.tokenizer_mode, trust_remote_code=args.trust_remote_code) chat_path = args.chat_template @@ -150,7 +153,17 @@ def _redact_message_image_data_in_place(messages: list) -> None: image_url["url"] = f"{media_type}{separator}" if separator else "" +async def run_tokenizer_work(function, *args): + if _pd_master: + return await run_pd_prompt_work(function, *args) + return function(*args) + + async def build_prompt(request, tools) -> str: + return await run_tokenizer_work(_render_prompt, request, tools) + + +def _render_prompt(request, tools) -> str: # pydantic格式转成dict, 否则,当根据tokenizer_config.json拼template时,Jinja判断无法识别 messages = [m.model_dump(by_alias=True, exclude_none=True) for m in request.messages] _normalize_tool_call_arguments(messages) diff --git a/lightllm/server/httpserver_for_pd_master/manager.py b/lightllm/server/httpserver_for_pd_master/manager.py index 3dab0526fd..13ff1dbd49 100644 --- a/lightllm/server/httpserver_for_pd_master/manager.py +++ b/lightllm/server/httpserver_for_pd_master/manager.py @@ -47,6 +47,7 @@ ) from lightllm.utils.shm_port_args import get_shm_port_args from lightllm.utils.pd_timeout_utils import get_pd_handshake_timeout_seconds +from .prompt_processing import run_pd_prompt_work from .pd_selector import PDSelectionExtraInfo, create_selector logger = init_logger(__name__) @@ -240,7 +241,7 @@ async def _generate_choices( await multimodal_params.verify_and_preload(request) # 计算输入的 input_token_num, 进行校验,如果输入+输出参数设置太长,则将 # sampling_params 的参数进行修正。 - input_token_num, prefill_prompt_ids = await asyncio.to_thread( + input_token_num, prefill_prompt_ids = await run_pd_prompt_work( self._prepare_prefill_prompt, prompt, multimodal_params, sampling_params ) from lightllm.server.httpserver.manager import HttpServerManager @@ -465,7 +466,7 @@ async def _generate_one_attempt( ) sampling_params.constraint_out_params.pd_previous_output_len = 0 if history_gen_token_strs and sampling_params.constraint_out_params.has_constraint(): - block_token_num = await asyncio.to_thread( + block_token_num = await run_pd_prompt_work( self.tokens, block_prompt, multimodal_params, sampling_params ) # 原始输入长度已在准入时计算;长度差作为重新编码后的历史输出长度。 @@ -1157,7 +1158,8 @@ def is_pd_nodes_ready(self): return False async def check_pd_nodes_health(self): - pd_nodes = [*self.prefill_nodes, *self.decode_nodes] + # Prefill DP slots on the same HTTP endpoint share one health response. + pd_nodes = list({node.client_ip_port: node for node in (*self.prefill_nodes, *self.decode_nodes)}.values()) if not pd_nodes: return True diff --git a/lightllm/server/httpserver_for_pd_master/prompt_processing.py b/lightllm/server/httpserver_for_pd_master/prompt_processing.py new file mode 100644 index 0000000000..bdd3bf070b --- /dev/null +++ b/lightllm/server/httpserver_for_pd_master/prompt_processing.py @@ -0,0 +1,61 @@ +"""Bound CPU-heavy prompt work separately from the HTTP worker's default executor.""" + +import asyncio +import os +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context +from functools import lru_cache, partial +from pathlib import Path + + +def _cpu_quota(directory, unified): + try: + if unified: + quota, period = (directory / "cpu.max").read_text().split() + else: + quota = (directory / "cpu.cfs_quota_us").read_text() + period = (directory / "cpu.cfs_period_us").read_text() + quota, period = int(quota), int(period) + except (OSError, ValueError): + return None + return max(1, quota // period) if quota > 0 and period > 0 else None + + +def _prompt_workers(cgroups=Path("/sys/fs/cgroup"), membership=Path("/proc/self/cgroup")): + available = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() or 1 + try: + entries = membership.read_text().splitlines() + except OSError: + entries = [] + for entry in entries: + _, controllers, group = entry.split(":", 2) + if controllers and "cpu" not in controllers.split(","): + continue + unified = not controllers + roots = (cgroups,) if unified else (cgroups / "cpu", cgroups / "cpu,cpuacct", cgroups / "cpuacct,cpu") + for root in roots: + if not root.is_dir(): + continue + # Containers may expose just their subtree at the mount root. On a + # host mount the process can also inherit a tighter parent quota. + relative = Path(group.lstrip("/")) + directory = root if ".." in relative.parts else root / relative + while True: + quota = _cpu_quota(directory, unified) + if quota is not None: + available = min(available, quota) + if directory == root: + break + directory = directory.parent + # Leave room for control-plane I/O when multiple CPUs are available. + return max(1, min(4, available - 1)) + + +@lru_cache(maxsize=1) +def _prompt_executor(): + return ThreadPoolExecutor(max_workers=_prompt_workers(), thread_name_prefix="pd-prompt") + + +async def run_pd_prompt_work(function, *args): + call = partial(copy_context().run, function, *args) + return await asyncio.get_running_loop().run_in_executor(_prompt_executor(), call) diff --git a/unit_tests/server/httpserver/test_pd_request_admission.py b/unit_tests/server/httpserver/test_pd_request_admission.py new file mode 100644 index 0000000000..8d8d5144c3 --- /dev/null +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -0,0 +1,125 @@ +import asyncio +import json +import threading +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +from lightllm.server import api_http, build_prompt + + +@pytest.mark.parametrize("finish", ["complete", "cancel", "error"]) +def test_admission_covers_the_entire_response_and_releases_capacity(monkeypatch, finish): + async def run(): + started = asyncio.Event() + release = asyncio.Event() + + async def app(scope, receive, send): + if scope["path"] == "/health": + return + await receive() + started.set() + await release.wait() + if finish == "error": + raise ValueError("failed") + + gate = api_http._PDRequestAdmission(app) + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), + ) + chat = dict(type="http", method="POST", path="/v1/chat/completions") + task = asyncio.create_task(gate(chat, AsyncMock(), AsyncMock())) + await asyncio.wait_for(started.wait(), 1) + incoming = AsyncMock(side_effect=[dict(type="http.request", more_body=True), dict(type="http.request")]) + send = AsyncMock() + await gate(chat, incoming, send) + assert incoming.await_count == 2 + assert send.await_args_list[0].args[0]["status"] == 429 + assert json.loads(send.await_args_list[1].args[0]["body"])["error"]["type"] == "RateLimitError" + await gate(dict(chat, method="GET", path="/health"), incoming, send) + if finish == "cancel": + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + elif finish == "error": + release.set() + with pytest.raises(ValueError): + await task + else: + release.set() + await task + assert gate.in_flight == 0 + + asyncio.run(run()) + + +def test_pd_template_render_runs_outside_the_event_loop(monkeypatch): + monkeypatch.setattr(build_prompt, "_pd_master", True) + monkeypatch.setattr(build_prompt, "_render_prompt", lambda *_: threading.get_ident()) + assert asyncio.run(build_prompt.build_prompt(None, None)) != threading.get_ident() + + +def test_http1_client_disconnect_while_shedding_returns_without_response(monkeypatch): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + monkeypatch.setattr( + api_http, "g_objs", SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1)) + ) + send = AsyncMock() + receive = AsyncMock(return_value={"type": "http.disconnect"}) + asyncio.run(gate(dict(type="http", path="/v1/chat/completions", method="POST"), receive, send)) + gate.app.assert_not_awaited() + send.assert_not_awaited() + assert gate.in_flight == 1 + + +def test_anthropic_overload_keeps_native_error_and_counts_it_once(monkeypatch): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + metric_client = Mock() + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace( + args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=metric_client + ), + ) + send = AsyncMock() + receive = AsyncMock(return_value={"type": "http.request"}) + asyncio.run(gate(dict(type="http", path="/v1/messages", method="POST"), receive, send)) + assert send.await_args_list[0].args[0]["status"] == 429 + body = json.loads(send.await_args_list[1].args[0]["body"]) + assert body["type"] == "error" and body["error"]["type"] == "rate_limit_error" + metric_client.counter_inc.assert_called_once_with("lightllm_request_failure") + + +@pytest.mark.parametrize("unified", [True, False]) +def test_prompt_executor_obeys_leaf_parent_and_mount_root_quotas(monkeypatch, tmp_path, unified): + from lightllm.server.httpserver_for_pd_master import prompt_processing + + monkeypatch.setattr(prompt_processing.os, "sched_getaffinity", lambda _: set(range(16)), raising=False) + membership = tmp_path / "membership" + membership.write_text("0::/pod/server\n" if unified else "2:cpu,cpuacct:/pod/server\n") + mount = tmp_path if unified else tmp_path / "cpu" + leaf = mount / "pod" / "server" + leaf.mkdir(parents=True) + + def set_quota(directory, value): + if unified: + (directory / "cpu.max").write_text(f"{value} 100000") + else: + (directory / "cpu.cfs_quota_us").write_text(str(value)) + (directory / "cpu.cfs_period_us").write_text("100000") + + set_quota(leaf, "max" if unified else -1) + assert prompt_processing._prompt_workers(tmp_path, membership) == 4 + set_quota(mount / "pod", 300000) + assert prompt_processing._prompt_workers(tmp_path, membership) == 2 + set_quota(leaf, 7500) + assert prompt_processing._prompt_workers(tmp_path, membership) == 1 + leaf.rename(mount / "pod" / "hidden") + set_quota(mount, 5000) + assert prompt_processing._prompt_workers(tmp_path, membership) == 1 diff --git a/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py index e3b8c322f4..c3348f1d3f 100644 --- a/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py +++ b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py @@ -4,7 +4,7 @@ import json import pickle from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import pytest @@ -34,7 +34,8 @@ def _manager(monkeypatch, **overrides): ) values.update(overrides) manager = SimpleNamespace(**values) - monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(httpserver_manager=manager)) + monitor = api_http_pd.PDHeartbeatMonitor() + monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(httpserver_manager=manager, pd_heartbeat_monitor=monitor)) return manager @@ -84,3 +85,60 @@ def test_kv_status_is_forwarded_without_registration_or_reply(monkeypatch): asyncio.run(api_http_pd.kv_move_status(websocket)) manager.update_req_status.assert_awaited_once_with(status) websocket.send_bytes.assert_not_awaited() + + +def test_local_lag_only_extends_the_pending_read_once(monkeypatch): + manager = _manager(monkeypatch) + monitor = api_http.g_objs.pd_heartbeat_monitor + monkeypatch.setattr(monitor, "stalled_since", Mock(return_value=True)) + websocket = _websocket(receive_bytes=AsyncMock(side_effect=[TimeoutError(), TimeoutError()])) + + asyncio.run(api_http_pd.register_and_keep_alive(websocket)) + assert websocket.receive_bytes.await_count == 2 + websocket.close.assert_awaited_once_with(code=1011, reason="PD heartbeat timed out") + manager.remove_pd.assert_awaited_once() + + +def test_frame_after_local_lag_is_delivered_once(monkeypatch): + from fastapi import WebSocketDisconnect + + manager = _manager(monkeypatch) + monitor = api_http.g_objs.pd_heartbeat_monitor + monkeypatch.setattr(monitor, "stalled_since", Mock(return_value=True)) + frame = ("test frame", 1) + websocket = _websocket( + receive_bytes=AsyncMock(side_effect=[TimeoutError(), pickle.dumps(frame), WebSocketDisconnect()]) + ) + + asyncio.run(api_http_pd.register_and_keep_alive(websocket)) + manager.put_to_handle_queue.assert_awaited_once_with(frame) + websocket.close.assert_not_awaited() + manager.remove_pd.assert_awaited_once() + + +def test_stall_detection_handles_sampler_and_timeout_in_either_order(monkeypatch): + clock = Mock(return_value=10.0) + monkeypatch.setattr(api_http_pd, "time", SimpleNamespace(monotonic=clock)) + monitor = api_http_pd.PDHeartbeatMonitor() + clock.return_value = 35.0 + assert monitor.stalled_since(10.0) + assert not monitor.stalled_since(34.0) + + async def sample(_): + if monitor.last_sample == 35.0: + raise asyncio.CancelledError + + monkeypatch.setattr(api_http_pd.asyncio, "sleep", sample) + with pytest.raises(asyncio.CancelledError): + asyncio.run(monitor.run()) + assert monitor.stalled_since(10.0) + assert not monitor.stalled_since(35.0) + + +def test_cancelled_registration_is_removed_without_closing_as_stale(monkeypatch): + manager = _manager(monkeypatch) + websocket = _websocket(receive_bytes=AsyncMock(side_effect=asyncio.CancelledError)) + with pytest.raises(asyncio.CancelledError): + asyncio.run(api_http_pd.register_and_keep_alive(websocket)) + websocket.close.assert_not_awaited() + manager.remove_pd.assert_awaited_once() diff --git a/unit_tests/server/test_pd_master_mode.py b/unit_tests/server/test_pd_master_mode.py index c1fb93afa1..67ea907419 100644 --- a/unit_tests/server/test_pd_master_mode.py +++ b/unit_tests/server/test_pd_master_mode.py @@ -370,10 +370,12 @@ async def get(self, url): manager = PDManager(StartArgs()) manager.prefill_nodes = [SimpleNamespace(mode="prefill", client_ip_port="10.0.0.1:8000")] + # Two Prefill DP slots share one HTTP endpoint. + manager.prefill_nodes.append(SimpleNamespace(mode="prefill", client_ip_port="10.0.0.1:8000")) manager.decode_nodes = [SimpleNamespace(mode="decode", client_ip_port="10.0.0.2:8000")] assert asyncio.run(manager.check_pd_nodes_health()) is True - assert set(requested_urls) == set(responses) + assert sorted(requested_urls) == sorted(responses) responses["http://10.0.0.2:8000/health"] = SimpleNamespace(status_code=503) assert asyncio.run(manager.check_pd_nodes_health()) is False From d5611964007729e8a628ba7a5599799d057b73c4 Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 11:57:00 +0800 Subject: [PATCH 2/7] fix(pd): shed new work when the prompt queue stays backed up --- lightllm/server/api_http.py | 5 +-- lightllm/server/build_prompt.py | 4 +-- .../httpserver_for_pd_master/manager.py | 6 ++-- .../prompt_processing.py | 31 +++++++++++++---- .../httpserver/test_pd_request_admission.py | 33 +++++++++++++++++++ 5 files changed, 66 insertions(+), 13 deletions(-) diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index b2bed6f93c..8ab9c2ed0d 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -43,6 +43,7 @@ from .multimodal_params import MultimodalParams from .httpserver.manager import HttpServerManager from .httpserver_for_pd_master.manager import HttpServerManagerForPDMaster +from .httpserver_for_pd_master.prompt_processing import get_pd_prompt_pool from .api_lightllm import lightllm_get_score from lightllm.utils.envs_utils import get_env_start_args from lightllm.utils.log_utils import init_logger @@ -190,7 +191,7 @@ async def __call__(self, scope, receive, send): ): return await self.app(scope, receive, send) - if self.in_flight >= g_objs.args.running_max_req_size: + if self.in_flight >= g_objs.args.running_max_req_size or get_pd_prompt_pool().backed_up(): # Finishing an HTTP/1 response while the client is still uploading can # reset the connection and lose the 429. Discard chunks without parsing # JSON or buffering the request body. @@ -207,7 +208,7 @@ async def __call__(self, scope, receive, send): g_objs.metric_client.counter_inc("lightllm_request_failure") response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE) else: - response = create_server_busy_response(ServerBusyError("PD master request limit reached")) + response = create_server_busy_response(ServerBusyError("PD master request or prompt capacity reached")) return await response(scope, receive, send) self.in_flight += 1 diff --git a/lightllm/server/build_prompt.py b/lightllm/server/build_prompt.py index fda3430c7c..94ad05e999 100644 --- a/lightllm/server/build_prompt.py +++ b/lightllm/server/build_prompt.py @@ -1,6 +1,6 @@ import os import json -from lightllm.server.httpserver_for_pd_master.prompt_processing import run_pd_prompt_work +from lightllm.server.httpserver_for_pd_master.prompt_processing import get_pd_prompt_pool from lightllm.server.tokenizer import get_tokenizer from lightllm.utils.log_utils import init_logger from functools import lru_cache @@ -155,7 +155,7 @@ def _redact_message_image_data_in_place(messages: list) -> None: async def run_tokenizer_work(function, *args): if _pd_master: - return await run_pd_prompt_work(function, *args) + return await get_pd_prompt_pool().run(function, *args) return function(*args) diff --git a/lightllm/server/httpserver_for_pd_master/manager.py b/lightllm/server/httpserver_for_pd_master/manager.py index 13ff1dbd49..b8fc7e097c 100644 --- a/lightllm/server/httpserver_for_pd_master/manager.py +++ b/lightllm/server/httpserver_for_pd_master/manager.py @@ -47,7 +47,7 @@ ) from lightllm.utils.shm_port_args import get_shm_port_args from lightllm.utils.pd_timeout_utils import get_pd_handshake_timeout_seconds -from .prompt_processing import run_pd_prompt_work +from .prompt_processing import get_pd_prompt_pool from .pd_selector import PDSelectionExtraInfo, create_selector logger = init_logger(__name__) @@ -241,7 +241,7 @@ async def _generate_choices( await multimodal_params.verify_and_preload(request) # 计算输入的 input_token_num, 进行校验,如果输入+输出参数设置太长,则将 # sampling_params 的参数进行修正。 - input_token_num, prefill_prompt_ids = await run_pd_prompt_work( + input_token_num, prefill_prompt_ids = await get_pd_prompt_pool().run( self._prepare_prefill_prompt, prompt, multimodal_params, sampling_params ) from lightllm.server.httpserver.manager import HttpServerManager @@ -466,7 +466,7 @@ async def _generate_one_attempt( ) sampling_params.constraint_out_params.pd_previous_output_len = 0 if history_gen_token_strs and sampling_params.constraint_out_params.has_constraint(): - block_token_num = await run_pd_prompt_work( + block_token_num = await get_pd_prompt_pool().run( self.tokens, block_prompt, multimodal_params, sampling_params ) # 原始输入长度已在准入时计算;长度差作为重新编码后的历史输出长度。 diff --git a/lightllm/server/httpserver_for_pd_master/prompt_processing.py b/lightllm/server/httpserver_for_pd_master/prompt_processing.py index bdd3bf070b..32cf9e576a 100644 --- a/lightllm/server/httpserver_for_pd_master/prompt_processing.py +++ b/lightllm/server/httpserver_for_pd_master/prompt_processing.py @@ -2,9 +2,11 @@ import asyncio import os +import time from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context from functools import lru_cache, partial +from itertools import islice from pathlib import Path @@ -51,11 +53,28 @@ def _prompt_workers(cgroups=Path("/sys/fs/cgroup"), membership=Path("/proc/self/ return max(1, min(4, available - 1)) -@lru_cache(maxsize=1) -def _prompt_executor(): - return ThreadPoolExecutor(max_workers=_prompt_workers(), thread_name_prefix="pd-prompt") +class PDPromptPool: + def __init__(self, workers): + self.workers = workers + self.executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="pd-prompt") + self.pending = {} + + def backed_up(self): + # At most 'workers' jobs can be executing. Allow one more per worker + # to absorb bursts. Shed new HTTP requests if the excess persists for a second. + if len(self.pending) <= 2 * self.workers: + return False + excess_since = next(islice(self.pending.values(), 2 * self.workers, None)) + return time.monotonic() - excess_since >= 1 + async def run(self, function, *args): + call = partial(copy_context().run, function, *args) + future = asyncio.get_running_loop().run_in_executor(self.executor, call) + self.pending[future] = time.monotonic() + future.add_done_callback(self.pending.pop) + return await future -async def run_pd_prompt_work(function, *args): - call = partial(copy_context().run, function, *args) - return await asyncio.get_running_loop().run_in_executor(_prompt_executor(), call) + +@lru_cache(maxsize=1) +def get_pd_prompt_pool(): + return PDPromptPool(_prompt_workers()) diff --git a/unit_tests/server/httpserver/test_pd_request_admission.py b/unit_tests/server/httpserver/test_pd_request_admission.py index 8d8d5144c3..bfdc495b24 100644 --- a/unit_tests/server/httpserver/test_pd_request_admission.py +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -123,3 +123,36 @@ def set_quota(directory, value): leaf.rename(mount / "pod" / "hidden") set_quota(mount, 5000) assert prompt_processing._prompt_workers(tmp_path, membership) == 1 + + +def test_preprocessing_backpressure_ignores_bursts_and_clears_after_drain(monkeypatch): + from lightllm.server.httpserver_for_pd_master import prompt_processing + + pool = prompt_processing.PDPromptPool(1) + monkeypatch.setattr(prompt_processing, "time", SimpleNamespace(monotonic=lambda: 10)) + pool.pending = {"executing": 1, "buffered": 2, "excess": 9.5} + assert not pool.backed_up() + pool.pending["excess"] = 8 + assert pool.backed_up() + del pool.pending["executing"] + assert not pool.backed_up() + + +def test_backed_up_prompt_pool_rejects_before_dispatch(monkeypatch): + gate = api_http._PDRequestAdmission(AsyncMock()) + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=128), metric_client=Mock()), + ) + monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True)) + send = AsyncMock() + asyncio.run( + gate( + dict(type="http", method="POST", path="/v1/completions"), + AsyncMock(return_value={"type": "http.request"}), + send, + ) + ) + assert send.await_args_list[0].args[0]["status"] == 429 + gate.app.assert_not_awaited() From d213de6e58054709131b0ab6ffa9fe0b40215ee7 Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 12:02:20 +0800 Subject: [PATCH 3/7] fix(pd): revalidate probe state and preserve healthy burst capacity --- lightllm/server/api_http.py | 22 +++++++++--- lightllm/server/api_http_pd.py | 7 ++++ .../prompt_processing.py | 17 ++++----- .../httpserver/test_pd_request_admission.py | 36 ++++++++++++++++--- .../server/test_pd_master_topology_api.py | 22 ++++++++++++ 5 files changed, 87 insertions(+), 17 deletions(-) diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index 8ab9c2ed0d..597b045653 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -191,7 +191,10 @@ async def __call__(self, scope, receive, send): ): return await self.app(scope, receive, send) - if self.in_flight >= g_objs.args.running_max_req_size or get_pd_prompt_pool().backed_up(): + pool = get_pd_prompt_pool() + if self.in_flight >= g_objs.args.running_max_req_size or ( + pool.backed_up() and (pool.subcore or g_objs.pd_heartbeat_monitor.recently_delayed()) + ): # Finishing an HTTP/1 response while the client is still uploading can # reset the connection and lose the 429. Discard chunks without parsing # JSON or buffering the request body. @@ -322,9 +325,20 @@ async def healthcheck(request: Request): else: inference_is_healthy = httpserver_manager.is_healthy() pd_nodes_are_ready = pd_manager.is_pd_nodes_ready() - pd_nodes_are_healthy = ( - inference_is_healthy and pd_nodes_are_ready and await pd_manager.check_pd_nodes_health() - ) + pd_nodes_are_healthy = False + if inference_is_healthy and pd_nodes_are_ready: + checked = (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) + reachable = await pd_manager.check_pd_nodes_health() + # Registration changes while the downstream HTTP requests are in flight. + # Report the current snapshot, and only certify peers we actually checked. + inference_is_healthy = httpserver_manager.is_healthy() + pd_nodes_are_ready = pd_manager.is_pd_nodes_ready() + pd_nodes_are_healthy = ( + reachable + and inference_is_healthy + and pd_nodes_are_ready + and checked == (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) + ) is_healthy = pd_nodes_are_healthy health_info = { "inference_healthy": inference_is_healthy, diff --git a/lightllm/server/api_http_pd.py b/lightllm/server/api_http_pd.py index 10d5af3159..1d2d68dfa1 100644 --- a/lightllm/server/api_http_pd.py +++ b/lightllm/server/api_http_pd.py @@ -35,16 +35,23 @@ class PDHeartbeatMonitor: def __init__(self): self.last_sample = time.monotonic() self.last_stall_end = float("-inf") + self.last_slow_sample = float("-inf") async def run(self): while True: await asyncio.sleep(1) now = time.monotonic() + if now - self.last_sample >= 1.5: + self.last_slow_sample = now # A peer normally sends at least once every 15 seconds. if now - self.last_sample >= _PD_HEARTBEAT_INTERVAL: self.last_stall_end = now self.last_sample = now + def recently_delayed(self): + now = time.monotonic() + return now - self.last_slow_sample < 5 or now - self.last_sample >= 1.5 + def stalled_since(self, started): # The receive deadline can run before the overdue sampler on the same loop turn. return ( diff --git a/lightllm/server/httpserver_for_pd_master/prompt_processing.py b/lightllm/server/httpserver_for_pd_master/prompt_processing.py index 32cf9e576a..9e16e9476e 100644 --- a/lightllm/server/httpserver_for_pd_master/prompt_processing.py +++ b/lightllm/server/httpserver_for_pd_master/prompt_processing.py @@ -20,10 +20,10 @@ def _cpu_quota(directory, unified): quota, period = int(quota), int(period) except (OSError, ValueError): return None - return max(1, quota // period) if quota > 0 and period > 0 else None + return quota / period if quota > 0 and period > 0 else None -def _prompt_workers(cgroups=Path("/sys/fs/cgroup"), membership=Path("/proc/self/cgroup")): +def _cpu_budget(cgroups=Path("/sys/fs/cgroup"), membership=Path("/proc/self/cgroup")): available = len(os.sched_getaffinity(0)) if hasattr(os, "sched_getaffinity") else os.cpu_count() or 1 try: entries = membership.read_text().splitlines() @@ -49,14 +49,15 @@ def _prompt_workers(cgroups=Path("/sys/fs/cgroup"), membership=Path("/proc/self/ if directory == root: break directory = directory.parent - # Leave room for control-plane I/O when multiple CPUs are available. - return max(1, min(4, available - 1)) + return available class PDPromptPool: - def __init__(self, workers): - self.workers = workers - self.executor = ThreadPoolExecutor(max_workers=workers, thread_name_prefix="pd-prompt") + def __init__(self, cpu_budget): + self.subcore = cpu_budget < 1 + # Leave room for HTTP and socket callbacks when multiple CPUs are available. + self.workers = max(1, min(4, int(cpu_budget) - 1)) + self.executor = ThreadPoolExecutor(max_workers=self.workers, thread_name_prefix="pd-prompt") self.pending = {} def backed_up(self): @@ -77,4 +78,4 @@ async def run(self, function, *args): @lru_cache(maxsize=1) def get_pd_prompt_pool(): - return PDPromptPool(_prompt_workers()) + return PDPromptPool(_cpu_budget()) diff --git a/unit_tests/server/httpserver/test_pd_request_admission.py b/unit_tests/server/httpserver/test_pd_request_admission.py index bfdc495b24..a574e70f4c 100644 --- a/unit_tests/server/httpserver/test_pd_request_admission.py +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -115,14 +115,14 @@ def set_quota(directory, value): (directory / "cpu.cfs_period_us").write_text("100000") set_quota(leaf, "max" if unified else -1) - assert prompt_processing._prompt_workers(tmp_path, membership) == 4 + assert prompt_processing._cpu_budget(tmp_path, membership) == 16 set_quota(mount / "pod", 300000) - assert prompt_processing._prompt_workers(tmp_path, membership) == 2 + assert prompt_processing._cpu_budget(tmp_path, membership) == 3 set_quota(leaf, 7500) - assert prompt_processing._prompt_workers(tmp_path, membership) == 1 + assert prompt_processing._cpu_budget(tmp_path, membership) == 0.075 leaf.rename(mount / "pod" / "hidden") set_quota(mount, 5000) - assert prompt_processing._prompt_workers(tmp_path, membership) == 1 + assert prompt_processing._cpu_budget(tmp_path, membership) == 0.05 def test_preprocessing_backpressure_ignores_bursts_and_clears_after_drain(monkeypatch): @@ -145,7 +145,7 @@ def test_backed_up_prompt_pool_rejects_before_dispatch(monkeypatch): "g_objs", SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=128), metric_client=Mock()), ) - monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True)) + monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=True)) send = AsyncMock() asyncio.run( gate( @@ -156,3 +156,29 @@ def test_backed_up_prompt_pool_rejects_before_dispatch(monkeypatch): ) assert send.await_args_list[0].args[0]["status"] == 429 gate.app.assert_not_awaited() + + +@pytest.mark.parametrize("delayed", [False, True]) +def test_full_cpu_worker_sheds_backlog_only_when_scheduling_is_delayed(monkeypatch, delayed): + app, send = AsyncMock(), AsyncMock() + gate = api_http._PDRequestAdmission(app) + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace( + args=SimpleNamespace(run_mode="pd_master", running_max_req_size=128), + metric_client=Mock(), + pd_heartbeat_monitor=SimpleNamespace(recently_delayed=lambda: delayed), + ), + ) + monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=False)) + asyncio.run( + gate( + dict(type="http", method="POST", path="/v1/completions"), + AsyncMock(return_value={"type": "http.request"}), + send, + ) + ) + assert app.await_count == int(not delayed) + if delayed: + assert send.await_args_list[0].args[0]["status"] == 429 diff --git a/unit_tests/server/test_pd_master_topology_api.py b/unit_tests/server/test_pd_master_topology_api.py index de92995ddc..ada7487f3c 100644 --- a/unit_tests/server/test_pd_master_topology_api.py +++ b/unit_tests/server/test_pd_master_topology_api.py @@ -94,3 +94,25 @@ def test_kv_status_keeps_existing_wire_protocol(monkeypatch): with client.websocket_connect("/kv_move_status") as websocket: websocket.send_bytes(pickle.dumps(PDUpKVStatus(8, 100, b"metadata"))) client.portal.call(_wait_until, lambda: manager.update_req_status.await_count == 1) + + +@pytest.mark.parametrize("replace", [False, True]) +def test_health_rechecks_registration_after_downstream_io(monkeypatch, replace): + args, manager = _install(monkeypatch, ready=True, healthy=True) + args.pd_master_mode = "1p1d" + pd = manager.pd_manager + + async def check_old_peers(): + pd.decode_nodes.clear() + if replace: + pd.decode_nodes.append(SimpleNamespace(node_id=201)) + pd.is_pd_nodes_ready.return_value = replace + return True + + pd.check_pd_nodes_health = check_old_peers + response = asyncio.run(api_http.healthcheck(None)) + body = json.loads(response.body) + assert response.status_code == 503 + assert body["pd_nodes_ready"] is replace + assert not body["pd_nodes_healthy"] + assert body["registered_decode_nodes"] == int(replace) From 953220324f1de3f99c9fdb871a5a07fb20957f7d Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 13:35:46 +0800 Subject: [PATCH 4/7] fix(pd): preserve connections when rejecting request bodies --- docker/Dockerfile | 5 +- docker/Dockerfile.glm53_flashkda_megamoe | 2 + docker/Dockerfile.glm53_optim | 2 + docker/requirements.hypercorn.txt | 2 + docker/verify_hypercorn.py | 14 ++++ lightllm/server/api_http.py | 28 +++++-- requirements.txt | 2 +- .../httpserver/test_pd_request_admission.py | 81 ++++++++++++++++++- 8 files changed, 125 insertions(+), 11 deletions(-) create mode 100644 docker/requirements.hypercorn.txt create mode 100644 docker/verify_hypercorn.py diff --git a/docker/Dockerfile b/docker/Dockerfile index e597a7de1f..448d90c96b 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -50,6 +50,7 @@ RUN case ${TARGETPLATFORM} in \ WORKDIR /lightllm COPY ./requirements.txt /lightllm/requirements.txt +COPY docker/requirements.hypercorn.txt /lightllm/docker/requirements.hypercorn.txt RUN pip install -U pip RUN pip install --no-cache-dir \ -i https://pypi.org/simple \ @@ -145,4 +146,6 @@ RUN if [ "${ENABLE_NIXL}" = "1" ]; then \ fi COPY . /lightllm -RUN pip install -e /lightllm --no-cache-dir +RUN pip install -e /lightllm --no-cache-dir \ + && python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ + && python docker/verify_hypercorn.py diff --git a/docker/Dockerfile.glm53_flashkda_megamoe b/docker/Dockerfile.glm53_flashkda_megamoe index 8e686d0c22..c30ca20a21 100644 --- a/docker/Dockerfile.glm53_flashkda_megamoe +++ b/docker/Dockerfile.glm53_flashkda_megamoe @@ -11,6 +11,8 @@ RUN test -n "${VCS_REF}" \ && test "$(git rev-parse HEAD)" = "${VCS_REF}" \ && test -z "$(git status --porcelain)" \ && /opt/conda/bin/python -m pip install --no-cache-dir --no-deps --no-build-isolation -e /lightllm \ + && /opt/conda/bin/python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ + && /opt/conda/bin/python docker/verify_hypercorn.py \ && ln -s /lightllm/test/start_scripts/glm53/glm53_pd_kernels.sh /usr/local/bin/glm53-pd-kernels \ && printf '%s\n' "${VCS_REF}" > /opt/lightllm-build/source_revision \ && /opt/conda/bin/python /lightllm/docker/validate_glm53_kernels.py diff --git a/docker/Dockerfile.glm53_optim b/docker/Dockerfile.glm53_optim index b1728117ff..c96bbb47a2 100644 --- a/docker/Dockerfile.glm53_optim +++ b/docker/Dockerfile.glm53_optim @@ -35,6 +35,8 @@ RUN test -n "${VCS_REF}" \ && test "$(git rev-parse HEAD)" = "${VCS_REF}" \ && test -z "$(git status --porcelain)" \ && /opt/conda/bin/python -m pip install --no-cache-dir --no-deps --no-build-isolation -e /lightllm \ + && /opt/conda/bin/python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ + && /opt/conda/bin/python docker/verify_hypercorn.py \ && ln -s /lightllm/test/start_scripts/glm53/glm53_pd_2p2d.sh /usr/local/bin/glm53-pd \ && mkdir -p /opt/lightllm-build \ && printf '%s\n' "${VCS_REF}" > /opt/lightllm-build/source_revision diff --git a/docker/requirements.hypercorn.txt b/docker/requirements.hypercorn.txt new file mode 100644 index 0000000000..1e7d2f52cf --- /dev/null +++ b/docker/requirements.hypercorn.txt @@ -0,0 +1,2 @@ +# Hypercorn PR 391. The patched distribution also reports version 0.18.0. +hypercorn @ https://codeload.github.com/mayuriphad/hypercorn/tar.gz/52f4134ec2c1366b36246f5a01b219136d1ec454#sha256=ed82db9986a45b422a0d11d497f38a6a282840df3648ec080dc208cf3e1d7534 diff --git a/docker/verify_hypercorn.py b/docker/verify_hypercorn.py new file mode 100644 index 0000000000..ac3e0c7e68 --- /dev/null +++ b/docker/verify_hypercorn.py @@ -0,0 +1,14 @@ +"""Verify the HTTP/2 handler imported by the image's serving interpreter.""" + +import hashlib +from pathlib import Path + +from hypercorn.protocol import h2 + +# src/hypercorn/protocol/h2.py at upstream PR 391, commit 52f4134. +expected = "b34be8aa7bc9e4c448e438a6caf904704c1f3d45df374bd45642eb1ef1ba1a0b" +path = Path(h2.__file__) +actual = hashlib.sha256(path.read_bytes()).hexdigest() +if actual != expected: + raise SystemExit(f"Unexpected Hypercorn HTTP/2 handler at {path}: {actual} (expected {expected})") +print(f"Hypercorn HTTP/2 handler {path} sha256={actual}") diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index 597b045653..9b690615ad 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -21,6 +21,7 @@ import time import uvloop +from anyio import create_task_group import requests import base64 import os @@ -159,6 +160,16 @@ async def send_wrapper(message): logger.info(msg) +async def _discard_request_body(receive): + """Release request chunks as they arrive. Return False on disconnect.""" + while True: + message = await receive() + if message["type"] == "http.disconnect": + return False + if not message.get("more_body", False): + return True + + class _PDRequestAdmission: # Reserve before FastAPI parses the body. The ASGI application returns only after # the response (including SSE) finishes or the request is cancelled. @@ -198,13 +209,9 @@ async def __call__(self, scope, receive, send): # Finishing an HTTP/1 response while the client is still uploading can # reset the connection and lose the 429. Discard chunks without parsing # JSON or buffering the request body. - if scope.get("http_version", "1.1").startswith("1") and scope["method"] == "POST": - while True: - message = await receive() - if message["type"] == "http.disconnect": - return - if not message.get("more_body", False): - break + http_version = scope.get("http_version", "1.1") + if http_version.startswith("1") and not await _discard_request_body(receive): + return if scope["path"].startswith("/v1/messages"): from .api_anthropic import _anthropic_error_response @@ -212,6 +219,13 @@ async def __call__(self, scope, receive, send): response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE) else: response = create_server_busy_response(ServerBusyError("PD master request or prompt capacity reached")) + if http_version == "2": + # Hypercorn can block its connection reader on a full ASGI input + # queue. Drain it while sending the 429, until EOF or disconnect. + async with create_task_group() as tasks: + tasks.start_soon(_discard_request_body, receive) + await response(scope, receive, send) + return return await response(scope, receive, send) self.in_flight += 1 diff --git a/requirements.txt b/requirements.txt index eb5d3b3b28..8c75990497 100644 --- a/requirements.txt +++ b/requirements.txt @@ -83,7 +83,7 @@ ujson==5.10.0 frozendict==2.4.6 atomics==1.0.3 easydict==1.13 -hypercorn==0.18.0 +-r docker/requirements.hypercorn.txt # Native HTTP/SSE entry point for multiprocess PD master, bundled with its shared libraries. ray-haproxy==2.8.25; sys_platform == "linux" and (platform_machine == "x86_64" or platform_machine == "aarch64") # SM90 NoPE MLA (512 latent dimensions, zero RoPE dimensions). diff --git a/unit_tests/server/httpserver/test_pd_request_admission.py b/unit_tests/server/httpserver/test_pd_request_admission.py index a574e70f4c..c74b8db782 100644 --- a/unit_tests/server/httpserver/test_pd_request_admission.py +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -62,7 +62,84 @@ def test_pd_template_render_runs_outside_the_event_loop(monkeypatch): assert asyncio.run(build_prompt.build_prompt(None, None)) != threading.get_ident() -def test_http1_client_disconnect_while_shedding_returns_without_response(monkeypatch): +@pytest.mark.parametrize("method", ["GET", "POST"]) +def test_http1_rejected_tokens_upload_finishes_before_429(monkeypatch, method): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), + ) + body = json.dumps({"text": "a" * (65536 - len('{"text": ""}'))}).encode() + remaining = [ + {"type": "http.request", "body": body[i : i + 4096], "more_body": i + 4096 < len(body)} + for i in range(0, len(body), 4096) + ] + + async def receive(): + return remaining.pop(0) + + sent = [] + + async def send(message): + sent.append(message["type"]) + assert not remaining + if message["type"] == "http.response.start": + assert message["status"] == 429 + else: + assert json.loads(message["body"])["error"]["type"] == "RateLimitError" + + asyncio.run(gate(dict(type="http", http_version="1.1", path="/tokens", method=method), receive, send)) + assert sent == ["http.response.start", "http.response.body"] + gate.app.assert_not_awaited() + + +@pytest.mark.parametrize("last", [{"type": "http.disconnect"}, {"type": "http.request", "more_body": False}]) +def test_http2_rejection_releases_input_queue_and_sibling_before_upload_finishes(monkeypatch, last): + async def run(): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + monkeypatch.setattr( + api_http, + "g_objs", + SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), + ) + queue = asyncio.Queue(maxsize=1) + chunk = {"type": "http.request", "body": b"part", "more_body": True} + queue.put_nowait(chunk) + replied = asyncio.Event() + sibling_done = asyncio.Event() + scope = dict(type="http", http_version="2", method="POST", path="/tokens") + + async def deliver(): + # A single connection reader must deliver this chunk before it can + # dispatch the next stream. The rejected upload is still open. + await queue.put(chunk) + await gate(dict(scope, method="GET", path="/liveness"), AsyncMock(), AsyncMock()) + sibling_done.set() + await replied.wait() + await queue.put(last) + + async def send(message): + if message["type"] == "http.response.start": + assert message["status"] == 429 + else: + assert json.loads(message["body"])["error"]["type"] == "RateLimitError" + replied.set() + await sibling_done.wait() + + await asyncio.gather(deliver(), gate(scope, queue.get, send)) + assert replied.is_set() and queue.empty() + gate.app.assert_awaited_once() + assert gate.app.await_args.args[0]["path"] == "/liveness" + assert gate.in_flight == 1 + + asyncio.run(asyncio.wait_for(run(), timeout=2)) + + +@pytest.mark.parametrize("method", ["GET", "POST"]) +def test_http1_client_disconnect_while_shedding_returns_without_response(monkeypatch, method): gate = api_http._PDRequestAdmission(AsyncMock()) gate.in_flight = 1 monkeypatch.setattr( @@ -70,7 +147,7 @@ def test_http1_client_disconnect_while_shedding_returns_without_response(monkeyp ) send = AsyncMock() receive = AsyncMock(return_value={"type": "http.disconnect"}) - asyncio.run(gate(dict(type="http", path="/v1/chat/completions", method="POST"), receive, send)) + asyncio.run(gate(dict(type="http", path="/tokens", method=method), receive, send)) gate.app.assert_not_awaited() send.assert_not_awaited() assert gate.in_flight == 1 From f3a36f0968667f1e1051c95c93d294879315101d Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 13:38:33 +0800 Subject: [PATCH 5/7] test(pd): provide worker heartbeat monitor in split registration fixture --- unit_tests/server/httpserver/test_pd_split_connections.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/unit_tests/server/httpserver/test_pd_split_connections.py b/unit_tests/server/httpserver/test_pd_split_connections.py index d95cf05a36..3d276e19df 100644 --- a/unit_tests/server/httpserver/test_pd_split_connections.py +++ b/unit_tests/server/httpserver/test_pd_split_connections.py @@ -278,11 +278,12 @@ async def handle(obj): api_http, "g_objs", SimpleNamespace( + pd_heartbeat_monitor=api_http_pd.PDHeartbeatMonitor(), httpserver_manager=SimpleNamespace( register_pd=AsyncMock(side_effect=manager.register_pd), remove_pd=AsyncMock(side_effect=manager.remove_pd), put_to_handle_queue=handle, - ) + ), ), ) asyncio.run(api_http_pd.register_and_keep_alive(websocket)) From aab67f60d31550d3408086b0a33a135439a26acc Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 14:25:23 +0800 Subject: [PATCH 6/7] fix(pd): verify Hypercorn at startup and isolate worker tokenizers --- docker/Dockerfile | 2 +- docker/Dockerfile.glm53_flashkda_megamoe | 2 +- docker/Dockerfile.glm53_optim | 2 +- docker/requirements.hypercorn.txt | 2 +- docker/verify_hypercorn.py | 14 ---- .../source/getting_started/installation.rst | 11 +++ .../tutorial/pd_master_multiprocess.rst | 2 + .../source/getting_started/installation.rst | 11 +++ .../tutorial/pd_master_multiprocess.rst | 2 + lightllm/server/api_http.py | 3 + .../httpserver_for_pd_master/manager.py | 26 +++++-- lightllm/utils/verify_hypercorn.py | 26 +++++++ .../test_pd_tokenizer_concurrency.py | 68 +++++++++++++++++++ unit_tests/server/test_hypercorn_config.py | 19 ++++++ 14 files changed, 167 insertions(+), 23 deletions(-) delete mode 100644 docker/verify_hypercorn.py create mode 100644 lightllm/utils/verify_hypercorn.py create mode 100644 unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py diff --git a/docker/Dockerfile b/docker/Dockerfile index 448d90c96b..0d4745f91a 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -148,4 +148,4 @@ RUN if [ "${ENABLE_NIXL}" = "1" ]; then \ COPY . /lightllm RUN pip install -e /lightllm --no-cache-dir \ && python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ - && python docker/verify_hypercorn.py + && python lightllm/utils/verify_hypercorn.py diff --git a/docker/Dockerfile.glm53_flashkda_megamoe b/docker/Dockerfile.glm53_flashkda_megamoe index c30ca20a21..460730cea2 100644 --- a/docker/Dockerfile.glm53_flashkda_megamoe +++ b/docker/Dockerfile.glm53_flashkda_megamoe @@ -12,7 +12,7 @@ RUN test -n "${VCS_REF}" \ && test -z "$(git status --porcelain)" \ && /opt/conda/bin/python -m pip install --no-cache-dir --no-deps --no-build-isolation -e /lightllm \ && /opt/conda/bin/python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ - && /opt/conda/bin/python docker/verify_hypercorn.py \ + && /opt/conda/bin/python lightllm/utils/verify_hypercorn.py \ && ln -s /lightllm/test/start_scripts/glm53/glm53_pd_kernels.sh /usr/local/bin/glm53-pd-kernels \ && printf '%s\n' "${VCS_REF}" > /opt/lightllm-build/source_revision \ && /opt/conda/bin/python /lightllm/docker/validate_glm53_kernels.py diff --git a/docker/Dockerfile.glm53_optim b/docker/Dockerfile.glm53_optim index c96bbb47a2..4858a47e3a 100644 --- a/docker/Dockerfile.glm53_optim +++ b/docker/Dockerfile.glm53_optim @@ -36,7 +36,7 @@ RUN test -n "${VCS_REF}" \ && test -z "$(git status --porcelain)" \ && /opt/conda/bin/python -m pip install --no-cache-dir --no-deps --no-build-isolation -e /lightllm \ && /opt/conda/bin/python -m pip install --no-cache-dir --force-reinstall --no-deps -r docker/requirements.hypercorn.txt \ - && /opt/conda/bin/python docker/verify_hypercorn.py \ + && /opt/conda/bin/python lightllm/utils/verify_hypercorn.py \ && ln -s /lightllm/test/start_scripts/glm53/glm53_pd_2p2d.sh /usr/local/bin/glm53-pd \ && mkdir -p /opt/lightllm-build \ && printf '%s\n' "${VCS_REF}" > /opt/lightllm-build/source_revision diff --git a/docker/requirements.hypercorn.txt b/docker/requirements.hypercorn.txt index 1e7d2f52cf..0dc4443ba7 100644 --- a/docker/requirements.hypercorn.txt +++ b/docker/requirements.hypercorn.txt @@ -1,2 +1,2 @@ # Hypercorn PR 391. The patched distribution also reports version 0.18.0. -hypercorn @ https://codeload.github.com/mayuriphad/hypercorn/tar.gz/52f4134ec2c1366b36246f5a01b219136d1ec454#sha256=ed82db9986a45b422a0d11d497f38a6a282840df3648ec080dc208cf3e1d7534 +hypercorn @ https://github.com/mayuriphad/hypercorn/archive/52f4134ec2c1366b36246f5a01b219136d1ec454.tar.gz?download=1#sha256=ed82db9986a45b422a0d11d497f38a6a282840df3648ec080dc208cf3e1d7534 diff --git a/docker/verify_hypercorn.py b/docker/verify_hypercorn.py deleted file mode 100644 index ac3e0c7e68..0000000000 --- a/docker/verify_hypercorn.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Verify the HTTP/2 handler imported by the image's serving interpreter.""" - -import hashlib -from pathlib import Path - -from hypercorn.protocol import h2 - -# src/hypercorn/protocol/h2.py at upstream PR 391, commit 52f4134. -expected = "b34be8aa7bc9e4c448e438a6caf904704c1f3d45df374bd45642eb1ef1ba1a0b" -path = Path(h2.__file__) -actual = hashlib.sha256(path.read_bytes()).hexdigest() -if actual != expected: - raise SystemExit(f"Unexpected Hypercorn HTTP/2 handler at {path}: {actual} (expected {expected})") -print(f"Hypercorn HTTP/2 handler {path} sha256={actual}") diff --git a/docs/CN/source/getting_started/installation.rst b/docs/CN/source/getting_started/installation.rst index bf96a9eee7..0f974c11f8 100755 --- a/docs/CN/source/getting_started/installation.rst +++ b/docs/CN/source/getting_started/installation.rst @@ -82,6 +82,13 @@ Lightllm 是一个纯python开发的推理框架,其中的算子使用triton $ # 安装lightllm的依赖 (摩尔线程 GPU) $ ./generate_requirements_musa.sh $ pip install -r requirements-musa.txt + +CUDA 与摩尔线程环境均需执行下面的安装或升级步骤。补丁版 Hypercorn 与原版的版本号相同。 + +.. code-block:: console + + $ python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt + $ python lightllm/utils/verify_hypercorn.py $ $ # 安装lightllm $ python setup.py install @@ -100,5 +107,9 @@ Lightllm 是一个纯python开发的推理框架,其中的算子使用triton $ # 安装 Lightllm 依赖 (CUDA 13.0) $ uv pip install -r requirements.txt --torch-backend=cu130 $ + $ # 补丁版和原版 Hypercorn 都使用 0.18.0 版本号,源码安装或升级时需替换并校验 HTTP/2 处理模块。 + $ uv pip install --reinstall --no-deps -r docker/requirements.hypercorn.txt + $ python lightllm/utils/verify_hypercorn.py + $ $ # 安装 Lightllm $ uv pip install -e . diff --git a/docs/CN/source/tutorial/pd_master_multiprocess.rst b/docs/CN/source/tutorial/pd_master_multiprocess.rst index 37070ae93f..4df587f228 100644 --- a/docs/CN/source/tutorial/pd_master_multiprocess.rst +++ b/docs/CN/source/tutorial/pd_master_multiprocess.rst @@ -142,6 +142,8 @@ HAProxy。依赖已固定在 ``requirements.txt``: .. code-block:: bash pip install -r requirements.txt + python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt + python lightllm/utils/verify_hypercorn.py .. code-block:: bash diff --git a/docs/EN/source/getting_started/installation.rst b/docs/EN/source/getting_started/installation.rst index 6627a9940b..6c7a2b800b 100755 --- a/docs/EN/source/getting_started/installation.rst +++ b/docs/EN/source/getting_started/installation.rst @@ -84,6 +84,13 @@ You can also install Lightllm from source: $ # Install Lightllm dependencies (Moore Threads GPU) $ ./generate_requirements_musa.sh $ pip install -r requirements-musa.txt + +For both CUDA and Moore Threads, finish the installation or upgrade with the following commands. The patched and stock Hypercorn distributions have the same version. + +.. code-block:: console + + $ python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt + $ python lightllm/utils/verify_hypercorn.py $ $ # Install Lightllm $ python setup.py install @@ -102,5 +109,9 @@ You can also install Lightllm with `uv `_: $ # Install Lightllm dependencies (CUDA 13.0) $ uv pip install -r requirements.txt --torch-backend=cu130 $ + $ # Replace and verify the HTTP/2 handler on source installs and upgrades. Both Hypercorn builds report 0.18.0. + $ uv pip install --reinstall --no-deps -r docker/requirements.hypercorn.txt + $ python lightllm/utils/verify_hypercorn.py + $ $ # Install Lightllm $ uv pip install -e . diff --git a/docs/EN/source/tutorial/pd_master_multiprocess.rst b/docs/EN/source/tutorial/pd_master_multiprocess.rst index b974e4b398..0bb21fdbf7 100644 --- a/docs/EN/source/tutorial/pd_master_multiprocess.rst +++ b/docs/EN/source/tutorial/pd_master_multiprocess.rst @@ -151,6 +151,8 @@ The entry point uses the native HAProxy bundled in the .. code-block:: bash pip install -r requirements.txt + python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt + python lightllm/utils/verify_hypercorn.py .. code-block:: bash diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index 9b690615ad..e3831a4f45 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -58,6 +58,7 @@ from lightllm.server.metrics.manager import MetricClient from lightllm.utils.envs_utils import get_unique_server_name from lightllm.utils.shm_port_args import get_shm_port_args +from lightllm.utils.verify_hypercorn import verify_hypercorn from dataclasses import asdict, dataclass, is_dataclass from .api_errors import create_error_response, create_server_busy_response @@ -92,6 +93,8 @@ class G_Objs: model_created: int = None def set_args(self, args: StartArgs): + if args.run_mode == "pd_master": + verify_hypercorn() self.args = args from .api_lightllm import lightllm_generate, lightllm_generate_stream from .api_tgi import tgi_generate_impl, tgi_generate_stream_impl diff --git a/lightllm/server/httpserver_for_pd_master/manager.py b/lightllm/server/httpserver_for_pd_master/manager.py index b8fc7e097c..9dd43dfbcc 100644 --- a/lightllm/server/httpserver_for_pd_master/manager.py +++ b/lightllm/server/httpserver_for_pd_master/manager.py @@ -1,6 +1,7 @@ import sys import os import asyncio +import threading import uvloop import time import datetime @@ -53,7 +54,26 @@ logger = init_logger(__name__) +class _PDTokenizer: + """Resolve a model-specific tokenizer on the thread actually using it.""" + + def __get__(self, manager, owner=None): + if manager is None: + return self + local = manager._thread_local + if not hasattr(local, "tokenizer"): + args = manager.args + local.tokenizer = get_tokenizer( + args.model_dir, args.tokenizer_mode, trust_remote_code=args.trust_remote_code + ) + return local.tokenizer + + class HttpServerManagerForPDMaster: + # Fast tokenizers change padding/truncation state during encode. The event + # loop and each prompt worker own separate backends, including multimodal wrappers. + tokenizer = _PDTokenizer() + def __init__( self, args: StartArgs, @@ -88,11 +108,7 @@ def __init__( self.pd_cache_high_priority_min_prompt_tokens = get_pd_cache_high_priority_min_prompt_tokens() self.disable_pd_cache_high_priority = args.disable_pd_cache_high_priority - self.tokenizer = get_tokenizer( - args.model_dir, - args.tokenizer_mode, - trust_remote_code=args.trust_remote_code, - ) + self._thread_local = threading.local() self.output_grammar_compiler = create_output_grammar_compiler(args, self.tokenizer) self.first_time_costs = MovingAverage() diff --git a/lightllm/utils/verify_hypercorn.py b/lightllm/utils/verify_hypercorn.py new file mode 100644 index 0000000000..0b43f0d649 --- /dev/null +++ b/lightllm/utils/verify_hypercorn.py @@ -0,0 +1,26 @@ +"""Check the Hypercorn HTTP/2 handler before enabling PD master early responses.""" + +import hashlib +from pathlib import Path + + +# src/hypercorn/protocol/h2.py at upstream PR 391, commit 52f4134. +EXPECTED_SHA256 = "b34be8aa7bc9e4c448e438a6caf904704c1f3d45df374bd45642eb1ef1ba1a0b" + + +def verify_hypercorn(): + from hypercorn.protocol import h2 + + path = Path(h2.__file__) + actual = hashlib.sha256(path.read_bytes()).hexdigest() + if actual != EXPECTED_SHA256: + raise RuntimeError( + f"Unexpected Hypercorn HTTP/2 handler at {path}: {actual} (expected {EXPECTED_SHA256}). " + "From the LightLLM checkout run " + "python -m pip install --force-reinstall --no-deps -r docker/requirements.hypercorn.txt" + ) + return path + + +if __name__ == "__main__": + print(f"Hypercorn HTTP/2 handler {verify_hypercorn()} sha256={EXPECTED_SHA256}") diff --git a/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py b/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py new file mode 100644 index 0000000000..a62df20627 --- /dev/null +++ b/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py @@ -0,0 +1,68 @@ +import asyncio +import json +import threading +from types import SimpleNamespace +from unittest.mock import Mock + +import httpx +from tokenizers import Tokenizer, models, pre_tokenizers +from transformers import PreTrainedTokenizerFast + +from lightllm.server import api_http, build_prompt +from lightllm.server.core.objs import StartArgs +from lightllm.server.httpserver_for_pd_master import manager as pd_manager +from lightllm.server.httpserver_for_pd_master.prompt_processing import PDPromptPool + + +def test_concurrent_token_counts_keep_truncation_local_to_the_worker(monkeypatch, tmp_path): + backend = Tokenizer(models.WordLevel({"[UNK]": 0, "hello": 1}, unk_token="[UNK]")) + backend.pre_tokenizer = pre_tokenizers.Whitespace() + PreTrainedTokenizerFast(tokenizer_object=backend, unk_token="[UNK]").save_pretrained(tmp_path) + (tmp_path / "config.json").write_text(json.dumps({"model_type": "bert", "architectures": ["BertModel"]})) + args = StartArgs(model_dir=str(tmp_path), run_mode="pd_master", max_req_total_len=250000, running_max_req_size=4) + monkeypatch.setattr(pd_manager, "get_shm_port_args", lambda: SimpleNamespace(metric_port=0)) + for service in ("MetricClient", "PDManager", "ReqIDGenerator", "create_output_grammar_compiler"): + monkeypatch.setattr(pd_manager, service, Mock()) + manager = pd_manager.HttpServerManagerForPDMaster(args) + monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(args=args, httpserver_manager=manager)) + pool = PDPromptPool(cpu_budget=3) + monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: pool) + monkeypatch.setattr(build_prompt, "get_pd_prompt_pool", lambda: pool) + monkeypatch.setattr(build_prompt, "_pd_master", True) + + # Rendezvous at the real encode call so both pool threads are exercised + # even when one request could otherwise finish before the other starts. + rendezvous = threading.Barrier(2) + backends = {} + tokenizer_type = type(manager.tokenizer) + encode = tokenizer_type.encode + + def concurrent_encode(tokenizer, *args, **kwargs): + backends[threading.get_ident()] = tokenizer.backend_tokenizer + rendezvous.wait(timeout=10) + return encode(tokenizer, *args, **kwargs) + + monkeypatch.setattr(tokenizer_type, "encode", concurrent_encode) + + async def run(): + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=api_http.app), base_url="http://worker" + ) as client: + full, truncated = await asyncio.gather( + client.post("/tokens", json={"text": "hello " * 200000}), + client.post( + "/tokens", json={"text": "hello " * 32, "parameters": {"truncation": True, "max_length": 8}} + ), + ) + assert (full.status_code, truncated.status_code) == (200, 200), (full.text, truncated.text) + assert (full.json()["ntokens"], truncated.json()["ntokens"]) == (200000, 8) + + try: + asyncio.run(run()) + finally: + pool.executor.shutdown() + assert threading.get_ident() not in backends + assert len(backends) == 2 + first, second = backends.values() + assert first is not second + assert all(backend is not manager.tokenizer.backend_tokenizer for backend in backends.values()) diff --git a/unit_tests/server/test_hypercorn_config.py b/unit_tests/server/test_hypercorn_config.py index 46ee8b7e7a..304476c0e3 100644 --- a/unit_tests/server/test_hypercorn_config.py +++ b/unit_tests/server/test_hypercorn_config.py @@ -24,3 +24,22 @@ def test_hypercorn_args_do_not_set_keep_alive_with_config(): args = make_argument_parser().parse_args(["--hypercorn_config", "hypercorn.toml"]) assert _hypercorn_config_args(args) == ["--config", "hypercorn.toml"] + + +def test_pd_worker_rejects_unpatched_handler_before_initializing(monkeypatch, tmp_path): + import asyncio + + import pytest + from hypercorn.protocol import h2 + from lightllm.server import api_http + from lightllm.server.core.objs import StartArgs + + stale = tmp_path / "h2.py" + stale.write_text("# stale handler") + monkeypatch.setattr(h2, "__file__", str(stale)) + state = api_http.G_Objs() + monkeypatch.setattr(api_http, "g_objs", state) + monkeypatch.setattr(api_http, "get_env_start_args", lambda: StartArgs(run_mode="pd_master")) + with pytest.raises(RuntimeError, match="--force-reinstall"): + asyncio.run(api_http.startup_event()) + assert state.args is None and state.httpserver_manager is None From 6007dc88c56c25a222c5cf86c14d201c3c28c8d4 Mon Sep 17 00:00:00 2001 From: sufubao Date: Thu, 3 Dec 2026 15:15:00 +0800 Subject: [PATCH 7/7] refactor(pd): centralize prompt scheduling and track work through cancellation --- lightllm/server/api_anthropic.py | 5 +- lightllm/server/api_http.py | 155 ++++++++---------- lightllm/server/api_http_pd.py | 19 ++- lightllm/server/build_prompt.py | 14 +- .../prompt_processing.py | 42 ++++- .../httpserver/test_pd_prompt_processing.py | 91 ++++++++++ .../httpserver/test_pd_request_admission.py | 123 +++----------- .../test_pd_tokenizer_concurrency.py | 11 +- .../httpserver/test_pd_websocket_lifecycle.py | 4 +- .../server/test_pd_master_topology_api.py | 13 +- 10 files changed, 255 insertions(+), 222 deletions(-) create mode 100644 unit_tests/server/httpserver/test_pd_prompt_processing.py diff --git a/lightllm/server/api_anthropic.py b/lightllm/server/api_anthropic.py index c978f07601..d8d48e611f 100644 --- a/lightllm/server/api_anthropic.py +++ b/lightllm/server/api_anthropic.py @@ -1323,8 +1323,9 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response: from .api_http import g_objs from .api_models import ChatCompletionRequest from .api_openai import _build_multimodal_params, _select_chat_template_tools - from .build_prompt import build_prompt, run_tokenizer_work + from .build_prompt import build_prompt from .core.objs.sampling_params import SamplingParams + from .httpserver_for_pd_master.prompt_processing import run_prompt_work raw_body = await raw_request.json() # LiteLLM validates the body as a Messages creation request, where @@ -1340,7 +1341,7 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response: sampling_params = SamplingParams() sampling_params.init(tokenizer=g_objs.httpserver_manager.tokenizer, add_special_tokens=False) - input_tokens = await run_tokenizer_work( + input_tokens = await run_prompt_work( g_objs.httpserver_manager.tokens, prompt, multimodal_params, diff --git a/lightllm/server/api_http.py b/lightllm/server/api_http.py index e3831a4f45..39fb98bd53 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -26,6 +26,7 @@ import base64 import os from io import BytesIO +from itertools import zip_longest import setproctitle asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) @@ -44,7 +45,7 @@ from .multimodal_params import MultimodalParams from .httpserver.manager import HttpServerManager from .httpserver_for_pd_master.manager import HttpServerManagerForPDMaster -from .httpserver_for_pd_master.prompt_processing import get_pd_prompt_pool +from .httpserver_for_pd_master import prompt_processing from .api_lightllm import lightllm_get_score from lightllm.utils.envs_utils import get_env_start_args from lightllm.utils.log_utils import init_logger @@ -71,7 +72,7 @@ ModelCard, ModelListResponse, ) -from .build_prompt import build_prompt, init_tokenizer, run_tokenizer_work +from .build_prompt import build_prompt, init_tokenizer from .api_http_pd import PDHeartbeatMonitor, router as pd_router logger = init_logger(__name__) @@ -95,6 +96,7 @@ class G_Objs: def set_args(self, args: StartArgs): if args.run_mode == "pd_master": verify_hypercorn() + prompt_processing.configure_prompt_processing(args.run_mode) self.args = args from .api_lightllm import lightllm_generate, lightllm_generate_stream from .api_tgi import tgi_generate_impl, tgi_generate_stream_impl @@ -173,21 +175,46 @@ async def _discard_request_body(receive): return True +async def _reject_pd_request(scope, receive, send): + # Finishing an HTTP/1 response while the client is still uploading can + # reset the connection and lose the 429. Discard chunks without parsing + # JSON or buffering the request body. + http_version = scope.get("http_version", "1.1") + if http_version.startswith("1") and not await _discard_request_body(receive): + return + if scope["path"].startswith("/v1/messages"): + from .api_anthropic import _anthropic_error_response + + g_objs.metric_client.counter_inc("lightllm_request_failure") + response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE) + else: + response = create_server_busy_response(ServerBusyError("PD master request or prompt capacity reached")) + if http_version == "2": + # Hypercorn can block its connection reader on a full ASGI input + # queue. Drain it while sending the 429, until EOF or disconnect. + async with create_task_group() as tasks: + tasks.start_soon(_discard_request_body, receive) + await response(scope, receive, send) + return + return await response(scope, receive, send) + + class _PDRequestAdmission: # Reserve before FastAPI parses the body. The ASGI application returns only after # the response (including SSE) finishes or the request is cancelled. - paths = frozenset( + routes = frozenset( { - "/", - "/generate", - "/generate_stream", - "/get_score", - "/v1/chat/completions", - "/v1/completions", - "/v1/responses", - "/v1/messages", - "/v1/messages/count_tokens", - "/tokens", + ("POST", "/"), + ("POST", "/generate"), + ("POST", "/generate_stream"), + ("POST", "/get_score"), + ("POST", "/v1/chat/completions"), + ("POST", "/v1/completions"), + ("POST", "/v1/responses"), + ("POST", "/v1/messages"), + ("POST", "/v1/messages/count_tokens"), + ("POST", "/tokens"), + ("GET", "/tokens"), } ) @@ -198,38 +225,17 @@ def __init__(self, app): async def __call__(self, scope, receive, send): if ( scope["type"] != "http" - or scope["path"] not in self.paths - or (scope["method"] != "POST" and not (scope["path"] == "/tokens" and scope["method"] == "GET")) + or (scope["method"], scope["path"]) not in self.routes or g_objs.args is None or g_objs.args.run_mode != "pd_master" ): return await self.app(scope, receive, send) - pool = get_pd_prompt_pool() + pool = prompt_processing.get_pd_prompt_pool() if self.in_flight >= g_objs.args.running_max_req_size or ( pool.backed_up() and (pool.subcore or g_objs.pd_heartbeat_monitor.recently_delayed()) ): - # Finishing an HTTP/1 response while the client is still uploading can - # reset the connection and lose the 429. Discard chunks without parsing - # JSON or buffering the request body. - http_version = scope.get("http_version", "1.1") - if http_version.startswith("1") and not await _discard_request_body(receive): - return - if scope["path"].startswith("/v1/messages"): - from .api_anthropic import _anthropic_error_response - - g_objs.metric_client.counter_inc("lightllm_request_failure") - response = _anthropic_error_response(HTTPStatus.TOO_MANY_REQUESTS, SERVER_BUSY_MESSAGE) - else: - response = create_server_busy_response(ServerBusyError("PD master request or prompt capacity reached")) - if http_version == "2": - # Hypercorn can block its connection reader on a full ASGI input - # queue. Drain it while sending the 429, until EOF or disconnect. - async with create_task_group() as tasks: - tasks.start_soon(_discard_request_body, receive) - await response(scope, receive, send) - return - return await response(scope, receive, send) + return await _reject_pd_request(scope, receive, send) self.in_flight += 1 try: @@ -331,46 +337,31 @@ async def healthcheck(request: Request): if g_objs.args.run_mode == "pd_master": httpserver_manager = g_objs.httpserver_manager pd_manager = httpserver_manager.pd_manager - if g_objs.args.pd_master_mode == "elastic": - inference_is_healthy = httpserver_manager.is_healthy() - pd_nodes_are_ready = pd_manager.is_pd_nodes_ready() - is_healthy = inference_is_healthy and pd_nodes_are_ready - health_info = { - "inference_healthy": inference_is_healthy, - "pd_nodes_ready": pd_nodes_are_ready, - } - else: - inference_is_healthy = httpserver_manager.is_healthy() - pd_nodes_are_ready = pd_manager.is_pd_nodes_ready() - pd_nodes_are_healthy = False - if inference_is_healthy and pd_nodes_are_ready: - checked = (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) - reachable = await pd_manager.check_pd_nodes_health() - # Registration changes while the downstream HTTP requests are in flight. - # Report the current snapshot, and only certify peers we actually checked. - inference_is_healthy = httpserver_manager.is_healthy() - pd_nodes_are_ready = pd_manager.is_pd_nodes_ready() - pd_nodes_are_healthy = ( - reachable - and inference_is_healthy - and pd_nodes_are_ready - and checked == (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) - ) - is_healthy = pd_nodes_are_healthy - health_info = { - "inference_healthy": inference_is_healthy, - "pd_nodes_ready": pd_nodes_are_ready, - "pd_nodes_healthy": pd_nodes_are_healthy, - } - - health_info.update( - { - "message": "Ok" if is_healthy else "Error", - "pd_master_mode": g_objs.args.pd_master_mode, - "registered_prefill_nodes": len(pd_manager.prefill_nodes), - "registered_decode_nodes": len(pd_manager.decode_nodes), - } - ) + mode = g_objs.args.pd_master_mode + inference_healthy = httpserver_manager.is_healthy() + nodes_ready = pd_manager.is_pd_nodes_ready() + is_healthy = inference_healthy and nodes_ready + if is_healthy and mode != "elastic": + checked = (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) + reachable = await pd_manager.check_pd_nodes_health() + # A new registration at the same address has a different socket. + # Only report success for the registrations we actually probed. + current = (*pd_manager.prefill_nodes, *pd_manager.decode_nodes) + same_nodes = all(old is new for old, new in zip_longest(checked, current)) + inference_healthy = httpserver_manager.is_healthy() + nodes_ready = pd_manager.is_pd_nodes_ready() + is_healthy = reachable and same_nodes and inference_healthy and nodes_ready + + health_info = { + "inference_healthy": inference_healthy, + "pd_nodes_ready": nodes_ready, + "message": "Ok" if is_healthy else "Error", + "pd_master_mode": mode, + "registered_prefill_nodes": len(pd_manager.prefill_nodes), + "registered_decode_nodes": len(pd_manager.decode_nodes), + } + if mode != "elastic": + health_info["pd_nodes_healthy"] = is_healthy return JSONResponse(health_info, status_code=200 if is_healthy else 503) from lightllm.utils.health_check import health_check @@ -615,14 +606,10 @@ async def tokens(request: Request): multimodal_params_dict = request_dict.get("multimodal_params", {}) multimodal_params = MultimodalParams(**multimodal_params_dict) await multimodal_params.verify_and_preload(request) - return JSONResponse( - { - "ntokens": await run_tokenizer_work( - g_objs.httpserver_manager.tokens, prompt, multimodal_params, sampling_params, sample_params_dict - ) - }, - status_code=200, + ntokens = await prompt_processing.run_prompt_work( + g_objs.httpserver_manager.tokens, prompt, multimodal_params, sampling_params, sample_params_dict ) + return JSONResponse({"ntokens": ntokens}) except ValueError as e: return create_error_response(HTTPStatus.BAD_REQUEST, str(e)) except ClientDisconnected as e: diff --git a/lightllm/server/api_http_pd.py b/lightllm/server/api_http_pd.py index 1d2d68dfa1..9d9afbd9ef 100644 --- a/lightllm/server/api_http_pd.py +++ b/lightllm/server/api_http_pd.py @@ -27,6 +27,9 @@ _PD_HEARTBEAT_TIMEOUT = 30 _PD_HEARTBEAT_INTERVAL = 15 +_SAMPLE_INTERVAL = 1 +_SLOW_SAMPLE_INTERVAL = 1.5 +_RECENT_DELAY_WINDOW = 5 class PDHeartbeatMonitor: @@ -39,18 +42,19 @@ def __init__(self): async def run(self): while True: - await asyncio.sleep(1) + await asyncio.sleep(_SAMPLE_INTERVAL) now = time.monotonic() - if now - self.last_sample >= 1.5: + elapsed = now - self.last_sample + if elapsed >= _SLOW_SAMPLE_INTERVAL: self.last_slow_sample = now # A peer normally sends at least once every 15 seconds. - if now - self.last_sample >= _PD_HEARTBEAT_INTERVAL: + if elapsed >= _PD_HEARTBEAT_INTERVAL: self.last_stall_end = now self.last_sample = now def recently_delayed(self): now = time.monotonic() - return now - self.last_slow_sample < 5 or now - self.last_sample >= 1.5 + return now - self.last_slow_sample < _RECENT_DELAY_WINDOW or now - self.last_sample >= _SLOW_SAMPLE_INTERVAL def stalled_since(self, started): # The receive deadline can run before the overdue sampler on the same loop turn. @@ -105,13 +109,10 @@ async def register_and_keep_alive(websocket: WebSocket): continue await g_objs.httpserver_manager.put_to_handle_queue(obj) - except asyncio.CancelledError: - raise except WebSocketDisconnect as e: logger.info(f"client {regist_json} disconnected: {str(e)}") - except BaseException as e: - logger.error(f"client {regist_json} has error {str(e)}") - logger.exception(str(e)) + except Exception: + logger.exception("PD registration failed for %s", regist_json) finally: logger.error(f"client {regist_json} removed") await g_objs.httpserver_manager.remove_pd(pd_client) diff --git a/lightllm/server/build_prompt.py b/lightllm/server/build_prompt.py index 94ad05e999..cc2edb1913 100644 --- a/lightllm/server/build_prompt.py +++ b/lightllm/server/build_prompt.py @@ -1,6 +1,6 @@ import os import json -from lightllm.server.httpserver_for_pd_master.prompt_processing import get_pd_prompt_pool +from lightllm.server.httpserver_for_pd_master.prompt_processing import run_prompt_work from lightllm.server.tokenizer import get_tokenizer from lightllm.utils.log_utils import init_logger from functools import lru_cache @@ -9,12 +9,10 @@ logger = init_logger(__name__) tokenizer = None -_pd_master = False def init_tokenizer(args): - global tokenizer, _pd_master - _pd_master = args.run_mode == "pd_master" + global tokenizer tokenizer = get_tokenizer(args.model_dir, args.tokenizer_mode, trust_remote_code=args.trust_remote_code) chat_path = args.chat_template @@ -153,14 +151,8 @@ def _redact_message_image_data_in_place(messages: list) -> None: image_url["url"] = f"{media_type}{separator}" if separator else "" -async def run_tokenizer_work(function, *args): - if _pd_master: - return await get_pd_prompt_pool().run(function, *args) - return function(*args) - - async def build_prompt(request, tools) -> str: - return await run_tokenizer_work(_render_prompt, request, tools) + return await run_prompt_work(_render_prompt, request, tools) def _render_prompt(request, tools) -> str: diff --git a/lightllm/server/httpserver_for_pd_master/prompt_processing.py b/lightllm/server/httpserver_for_pd_master/prompt_processing.py index 9e16e9476e..aae26a8fcb 100644 --- a/lightllm/server/httpserver_for_pd_master/prompt_processing.py +++ b/lightllm/server/httpserver_for_pd_master/prompt_processing.py @@ -5,9 +5,10 @@ import time from concurrent.futures import ThreadPoolExecutor from contextvars import copy_context -from functools import lru_cache, partial +from functools import lru_cache from itertools import islice from pathlib import Path +from threading import Lock def _cpu_quota(directory, unified): @@ -59,23 +60,46 @@ def __init__(self, cpu_budget): self.workers = max(1, min(4, int(cpu_budget) - 1)) self.executor = ThreadPoolExecutor(max_workers=self.workers, thread_name_prefix="pd-prompt") self.pending = {} + self._pending_lock = Lock() def backed_up(self): # At most 'workers' jobs can be executing. Allow one more per worker # to absorb bursts. Shed new HTTP requests if the excess persists for a second. - if len(self.pending) <= 2 * self.workers: - return False - excess_since = next(islice(self.pending.values(), 2 * self.workers, None)) + with self._pending_lock: + if len(self.pending) <= 2 * self.workers: + return False + excess_since = next(islice(self.pending.values(), 2 * self.workers, None)) return time.monotonic() - excess_since >= 1 + def _finished(self, job): + with self._pending_lock: + del self.pending[job] + async def run(self, function, *args): - call = partial(copy_context().run, function, *args) - future = asyncio.get_running_loop().run_in_executor(self.executor, call) - self.pending[future] = time.monotonic() - future.add_done_callback(self.pending.pop) - return await future + # Cancelling the HTTP task can cancel a queued job. A running thread + # still occupies capacity until its executor future actually finishes. + job = self.executor.submit(copy_context().run, function, *args) + with self._pending_lock: + self.pending[job] = time.monotonic() + job.add_done_callback(self._finished) + return await asyncio.wrap_future(job) @lru_cache(maxsize=1) def get_pd_prompt_pool(): return PDPromptPool(_cpu_budget()) + + +_use_pd_prompt_pool = False + + +def configure_prompt_processing(run_mode): + global _use_pd_prompt_pool + _use_pd_prompt_pool = run_mode == "pd_master" + + +async def run_prompt_work(function, *args): + """Run synchronous prompt work in the PD worker's pool when configured.""" + if _use_pd_prompt_pool: + return await get_pd_prompt_pool().run(function, *args) + return function(*args) diff --git a/unit_tests/server/httpserver/test_pd_prompt_processing.py b/unit_tests/server/httpserver/test_pd_prompt_processing.py new file mode 100644 index 0000000000..ae618c6bcf --- /dev/null +++ b/unit_tests/server/httpserver/test_pd_prompt_processing.py @@ -0,0 +1,91 @@ +import asyncio +import threading +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from lightllm.server import build_prompt +from lightllm.server.httpserver_for_pd_master import prompt_processing + + +@pytest.mark.parametrize("mode", [None, "normal", "pd_master"]) +def test_template_render_uses_the_configured_worker(mode, monkeypatch): + monkeypatch.setattr(prompt_processing, "_use_pd_prompt_pool", False) + if mode is not None: + prompt_processing.configure_prompt_processing(mode) + monkeypatch.setattr(build_prompt, "_render_prompt", lambda *_: threading.get_ident()) + render_thread = asyncio.run(build_prompt.build_prompt(None, None)) + assert (render_thread != threading.get_ident()) == (mode == "pd_master") + + +@pytest.mark.parametrize("unified", [True, False]) +def test_prompt_executor_obeys_leaf_parent_and_mount_root_quotas(monkeypatch, tmp_path, unified): + monkeypatch.setattr(prompt_processing.os, "sched_getaffinity", lambda _: set(range(16)), raising=False) + membership = tmp_path / "membership" + membership.write_text("0::/pod/server\n" if unified else "2:cpu,cpuacct:/pod/server\n") + mount = tmp_path if unified else tmp_path / "cpu" + leaf = mount / "pod" / "server" + leaf.mkdir(parents=True) + + def set_quota(directory, value): + if unified: + (directory / "cpu.max").write_text(f"{value} 100000") + else: + (directory / "cpu.cfs_quota_us").write_text(str(value)) + (directory / "cpu.cfs_period_us").write_text("100000") + + set_quota(leaf, "max" if unified else -1) + assert prompt_processing._cpu_budget(tmp_path, membership) == 16 + set_quota(mount / "pod", 300000) + assert prompt_processing._cpu_budget(tmp_path, membership) == 3 + set_quota(leaf, 7500) + assert prompt_processing._cpu_budget(tmp_path, membership) == 0.075 + leaf.rename(mount / "pod" / "hidden") + set_quota(mount, 5000) + assert prompt_processing._cpu_budget(tmp_path, membership) == 0.05 + + +def test_preprocessing_backpressure_ignores_bursts_and_clears_after_drain(monkeypatch): + pool = prompt_processing.PDPromptPool(1) + monkeypatch.setattr(prompt_processing, "time", SimpleNamespace(monotonic=lambda: 10)) + pool.pending = {"executing": 1, "buffered": 2, "excess": 9.5} + assert not pool.backed_up() + pool.pending["excess"] = 8 + assert pool.backed_up() + del pool.pending["executing"] + assert not pool.backed_up() + + +def test_cancelled_request_tracks_running_work_and_drops_queued_work(): + pool = prompt_processing.PDPromptPool(cpu_budget=1) + release = threading.Event() + queued_call = Mock() + + async def run(): + loop = asyncio.get_running_loop() + started = asyncio.Event() + + def hold_worker(): + loop.call_soon_threadsafe(started.set) + assert release.wait(timeout=5) + + running = asyncio.create_task(pool.run(hold_worker)) + await asyncio.wait_for(started.wait(), timeout=2) + queued = asyncio.create_task(pool.run(queued_call)) + await asyncio.sleep(0) + assert len(pool.pending) == 2 + queued.cancel() + running.cancel() + for task in (queued, running): + with pytest.raises(asyncio.CancelledError): + await task + assert len(pool.pending) == 1 + + try: + asyncio.run(run()) + finally: + release.set() + pool.executor.shutdown() + queued_call.assert_not_called() + assert not pool.pending diff --git a/unit_tests/server/httpserver/test_pd_request_admission.py b/unit_tests/server/httpserver/test_pd_request_admission.py index c74b8db782..736b49d8b4 100644 --- a/unit_tests/server/httpserver/test_pd_request_admission.py +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -1,16 +1,27 @@ import asyncio import json -import threading from types import SimpleNamespace from unittest.mock import AsyncMock, Mock import pytest -from lightllm.server import api_http, build_prompt +from lightllm.server import api_http +from lightllm.server.httpserver_for_pd_master import prompt_processing + + +@pytest.fixture +def worker(monkeypatch): + state = SimpleNamespace( + args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), + metric_client=Mock(), + pd_heartbeat_monitor=Mock(), + ) + monkeypatch.setattr(api_http, "g_objs", state) + return state @pytest.mark.parametrize("finish", ["complete", "cancel", "error"]) -def test_admission_covers_the_entire_response_and_releases_capacity(monkeypatch, finish): +def test_admission_covers_the_entire_response_and_releases_capacity(worker, finish): async def run(): started = asyncio.Event() release = asyncio.Event() @@ -25,11 +36,6 @@ async def app(scope, receive, send): raise ValueError("failed") gate = api_http._PDRequestAdmission(app) - monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), - ) chat = dict(type="http", method="POST", path="/v1/chat/completions") task = asyncio.create_task(gate(chat, AsyncMock(), AsyncMock())) await asyncio.wait_for(started.wait(), 1) @@ -56,21 +62,10 @@ async def app(scope, receive, send): asyncio.run(run()) -def test_pd_template_render_runs_outside_the_event_loop(monkeypatch): - monkeypatch.setattr(build_prompt, "_pd_master", True) - monkeypatch.setattr(build_prompt, "_render_prompt", lambda *_: threading.get_ident()) - assert asyncio.run(build_prompt.build_prompt(None, None)) != threading.get_ident() - - @pytest.mark.parametrize("method", ["GET", "POST"]) -def test_http1_rejected_tokens_upload_finishes_before_429(monkeypatch, method): +def test_http1_rejected_tokens_upload_finishes_before_429(worker, method): gate = api_http._PDRequestAdmission(AsyncMock()) gate.in_flight = 1 - monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), - ) body = json.dumps({"text": "a" * (65536 - len('{"text": ""}'))}).encode() remaining = [ {"type": "http.request", "body": body[i : i + 4096], "more_body": i + 4096 < len(body)} @@ -96,15 +91,10 @@ async def send(message): @pytest.mark.parametrize("last", [{"type": "http.disconnect"}, {"type": "http.request", "more_body": False}]) -def test_http2_rejection_releases_input_queue_and_sibling_before_upload_finishes(monkeypatch, last): +def test_http2_rejection_releases_input_queue_and_sibling_before_upload_finishes(worker, last): async def run(): gate = api_http._PDRequestAdmission(AsyncMock()) gate.in_flight = 1 - monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=Mock()), - ) queue = asyncio.Queue(maxsize=1) chunk = {"type": "http.request", "body": b"part", "more_body": True} queue.put_nowait(chunk) @@ -139,12 +129,9 @@ async def send(message): @pytest.mark.parametrize("method", ["GET", "POST"]) -def test_http1_client_disconnect_while_shedding_returns_without_response(monkeypatch, method): +def test_http1_client_disconnect_while_shedding_returns_without_response(worker, method): gate = api_http._PDRequestAdmission(AsyncMock()) gate.in_flight = 1 - monkeypatch.setattr( - api_http, "g_objs", SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1)) - ) send = AsyncMock() receive = AsyncMock(return_value={"type": "http.disconnect"}) asyncio.run(gate(dict(type="http", path="/tokens", method=method), receive, send)) @@ -153,76 +140,24 @@ def test_http1_client_disconnect_while_shedding_returns_without_response(monkeyp assert gate.in_flight == 1 -def test_anthropic_overload_keeps_native_error_and_counts_it_once(monkeypatch): +@pytest.mark.parametrize("path", ["/v1/messages", "/v1/messages/count_tokens"]) +def test_anthropic_overload_keeps_native_error_and_counts_it_once(worker, path): gate = api_http._PDRequestAdmission(AsyncMock()) gate.in_flight = 1 - metric_client = Mock() - monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace( - args=SimpleNamespace(run_mode="pd_master", running_max_req_size=1), metric_client=metric_client - ), - ) send = AsyncMock() receive = AsyncMock(return_value={"type": "http.request"}) - asyncio.run(gate(dict(type="http", path="/v1/messages", method="POST"), receive, send)) + asyncio.run(gate(dict(type="http", path=path, method="POST"), receive, send)) assert send.await_args_list[0].args[0]["status"] == 429 body = json.loads(send.await_args_list[1].args[0]["body"]) assert body["type"] == "error" and body["error"]["type"] == "rate_limit_error" - metric_client.counter_inc.assert_called_once_with("lightllm_request_failure") - - -@pytest.mark.parametrize("unified", [True, False]) -def test_prompt_executor_obeys_leaf_parent_and_mount_root_quotas(monkeypatch, tmp_path, unified): - from lightllm.server.httpserver_for_pd_master import prompt_processing - - monkeypatch.setattr(prompt_processing.os, "sched_getaffinity", lambda _: set(range(16)), raising=False) - membership = tmp_path / "membership" - membership.write_text("0::/pod/server\n" if unified else "2:cpu,cpuacct:/pod/server\n") - mount = tmp_path if unified else tmp_path / "cpu" - leaf = mount / "pod" / "server" - leaf.mkdir(parents=True) - - def set_quota(directory, value): - if unified: - (directory / "cpu.max").write_text(f"{value} 100000") - else: - (directory / "cpu.cfs_quota_us").write_text(str(value)) - (directory / "cpu.cfs_period_us").write_text("100000") - - set_quota(leaf, "max" if unified else -1) - assert prompt_processing._cpu_budget(tmp_path, membership) == 16 - set_quota(mount / "pod", 300000) - assert prompt_processing._cpu_budget(tmp_path, membership) == 3 - set_quota(leaf, 7500) - assert prompt_processing._cpu_budget(tmp_path, membership) == 0.075 - leaf.rename(mount / "pod" / "hidden") - set_quota(mount, 5000) - assert prompt_processing._cpu_budget(tmp_path, membership) == 0.05 - - -def test_preprocessing_backpressure_ignores_bursts_and_clears_after_drain(monkeypatch): - from lightllm.server.httpserver_for_pd_master import prompt_processing - - pool = prompt_processing.PDPromptPool(1) - monkeypatch.setattr(prompt_processing, "time", SimpleNamespace(monotonic=lambda: 10)) - pool.pending = {"executing": 1, "buffered": 2, "excess": 9.5} - assert not pool.backed_up() - pool.pending["excess"] = 8 - assert pool.backed_up() - del pool.pending["executing"] - assert not pool.backed_up() + worker.metric_client.counter_inc.assert_called_once_with("lightllm_request_failure") -def test_backed_up_prompt_pool_rejects_before_dispatch(monkeypatch): +def test_backed_up_prompt_pool_rejects_before_dispatch(worker, monkeypatch): gate = api_http._PDRequestAdmission(AsyncMock()) monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace(args=SimpleNamespace(run_mode="pd_master", running_max_req_size=128), metric_client=Mock()), + prompt_processing, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=True) ) - monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=True)) send = AsyncMock() asyncio.run( gate( @@ -236,19 +171,13 @@ def test_backed_up_prompt_pool_rejects_before_dispatch(monkeypatch): @pytest.mark.parametrize("delayed", [False, True]) -def test_full_cpu_worker_sheds_backlog_only_when_scheduling_is_delayed(monkeypatch, delayed): +def test_full_cpu_worker_sheds_backlog_only_when_scheduling_is_delayed(worker, monkeypatch, delayed): + worker.pd_heartbeat_monitor.recently_delayed.return_value = delayed app, send = AsyncMock(), AsyncMock() gate = api_http._PDRequestAdmission(app) monkeypatch.setattr( - api_http, - "g_objs", - SimpleNamespace( - args=SimpleNamespace(run_mode="pd_master", running_max_req_size=128), - metric_client=Mock(), - pd_heartbeat_monitor=SimpleNamespace(recently_delayed=lambda: delayed), - ), + prompt_processing, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=False) ) - monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=False)) asyncio.run( gate( dict(type="http", method="POST", path="/v1/completions"), diff --git a/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py b/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py index a62df20627..5c00fe054e 100644 --- a/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py +++ b/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py @@ -8,10 +8,10 @@ from tokenizers import Tokenizer, models, pre_tokenizers from transformers import PreTrainedTokenizerFast -from lightllm.server import api_http, build_prompt +from lightllm.server import api_http from lightllm.server.core.objs import StartArgs from lightllm.server.httpserver_for_pd_master import manager as pd_manager -from lightllm.server.httpserver_for_pd_master.prompt_processing import PDPromptPool +from lightllm.server.httpserver_for_pd_master import prompt_processing def test_concurrent_token_counts_keep_truncation_local_to_the_worker(monkeypatch, tmp_path): @@ -25,10 +25,9 @@ def test_concurrent_token_counts_keep_truncation_local_to_the_worker(monkeypatch monkeypatch.setattr(pd_manager, service, Mock()) manager = pd_manager.HttpServerManagerForPDMaster(args) monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(args=args, httpserver_manager=manager)) - pool = PDPromptPool(cpu_budget=3) - monkeypatch.setattr(api_http, "get_pd_prompt_pool", lambda: pool) - monkeypatch.setattr(build_prompt, "get_pd_prompt_pool", lambda: pool) - monkeypatch.setattr(build_prompt, "_pd_master", True) + pool = prompt_processing.PDPromptPool(cpu_budget=3) + monkeypatch.setattr(prompt_processing, "get_pd_prompt_pool", lambda: pool) + monkeypatch.setattr(prompt_processing, "_use_pd_prompt_pool", True) # Rendezvous at the real encode call so both pool threads are exercised # even when one request could otherwise finish before the other starts. diff --git a/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py index c3348f1d3f..77b6c7dafd 100644 --- a/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py +++ b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py @@ -52,10 +52,8 @@ def test_rejected_registration_does_not_remove_an_existing_connection(monkeypatc def test_heartbeat_wait_is_bounded(monkeypatch): async def run(): - original_wait_for = asyncio.wait_for original_fail_after = api_http_pd.fail_after timeouts = [] - from anyio import fail_after async def wait_forever(): await asyncio.Event().wait() @@ -67,7 +65,7 @@ def short_heartbeat_wait(timeout): manager = _manager(monkeypatch) monkeypatch.setattr(api_http_pd, "fail_after", short_heartbeat_wait) websocket = _websocket(receive_bytes=wait_forever) - await original_wait_for(api_http_pd.register_and_keep_alive(websocket), timeout=1) + await asyncio.wait_for(api_http_pd.register_and_keep_alive(websocket), timeout=1) assert timeouts == [30] assert websocket.close.await_args.kwargs["code"] == 1011 manager.remove_pd.assert_awaited_once() diff --git a/unit_tests/server/test_pd_master_topology_api.py b/unit_tests/server/test_pd_master_topology_api.py index ada7487f3c..98300f7eb4 100644 --- a/unit_tests/server/test_pd_master_topology_api.py +++ b/unit_tests/server/test_pd_master_topology_api.py @@ -105,7 +105,8 @@ def test_health_rechecks_registration_after_downstream_io(monkeypatch, replace): async def check_old_peers(): pd.decode_nodes.clear() if replace: - pd.decode_nodes.append(SimpleNamespace(node_id=201)) + # Same advertised identity on a new registration. + pd.decode_nodes.append(SimpleNamespace(node_id=200)) pd.is_pd_nodes_ready.return_value = replace return True @@ -116,3 +117,13 @@ async def check_old_peers(): assert body["pd_nodes_ready"] is replace assert not body["pd_nodes_healthy"] assert body["registered_decode_nodes"] == int(replace) + + +def test_health_rechecks_inference_after_downstream_io(monkeypatch): + args, manager = _install(monkeypatch, ready=True, healthy=True) + args.pd_master_mode = "1p1d" + manager.is_healthy.side_effect = [True, False] + response = asyncio.run(api_http.healthcheck(None)) + body = json.loads(response.body) + assert response.status_code == 503 + assert body["pd_nodes_ready"] and not body["inference_healthy"] and not body["pd_nodes_healthy"]