diff --git a/docker/Dockerfile b/docker/Dockerfile index 4750e851b2..829b4c8e06 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -53,6 +53,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 \ @@ -148,4 +149,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 lightllm/utils/verify_hypercorn.py diff --git a/docker/requirements.hypercorn.txt b/docker/requirements.hypercorn.txt new file mode 100644 index 0000000000..0dc4443ba7 --- /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://github.com/mayuriphad/hypercorn/archive/52f4134ec2c1366b36246f5a01b219136d1ec454.tar.gz?download=1#sha256=ed82db9986a45b422a0d11d497f38a6a282840df3648ec080dc208cf3e1d7534 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 77ca18a01e..c7232b51c0 100644 --- a/docs/CN/source/tutorial/pd_master_multiprocess.rst +++ b/docs/CN/source/tutorial/pd_master_multiprocess.rst @@ -132,6 +132,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 ff9e8b44bd..c061de67ba 100644 --- a/docs/EN/source/tutorial/pd_master_multiprocess.rst +++ b/docs/EN/source/tutorial/pd_master_multiprocess.rst @@ -140,6 +140,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_anthropic.py b/lightllm/server/api_anthropic.py index 299fd524de..d8d48e611f 100644 --- a/lightllm/server/api_anthropic.py +++ b/lightllm/server/api_anthropic.py @@ -1325,6 +1325,7 @@ async def anthropic_count_tokens_impl(raw_request: Request) -> Response: from .api_openai import _build_multimodal_params, _select_chat_template_tools 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,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_prompt_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 3dee676df1..1aabce29ac 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 @@ -45,6 +46,7 @@ from .multimodal_params import MultimodalParams from .httpserver.manager import HttpServerManager from .httpserver_for_pd_master.manager import HttpServerManagerForPDMaster +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 @@ -58,6 +60,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 @@ -71,6 +74,7 @@ ModelListResponse, ) from .build_prompt import build_prompt, init_tokenizer +from .api_http_pd import PDHeartbeatMonitor, router as pd_router logger = init_logger(__name__) @@ -78,6 +82,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 @@ -89,6 +95,9 @@ class G_Objs: model_created: int = None 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 @@ -158,6 +167,86 @@ 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 + + +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. + routes = frozenset( + { + ("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"), + } + ) + + def __init__(self, app): + self.app = app + self.in_flight = 0 + + async def __call__(self, scope, receive, send): + if ( + scope["type"] != "http" + 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 = 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()) + ): + return await _reject_pd_request(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) @@ -204,7 +293,7 @@ async def generation_exception_handler(request: Request, exc: GenerationError) - @app.get("/liveness") @app.post("/liveness") -def liveness(): +async def liveness(): return {"status": "ok"} @@ -259,35 +348,29 @@ 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 = ( - inference_is_healthy and pd_nodes_are_ready and await pd_manager.check_pd_nodes_health() - ) - 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": + probed_version = pd_manager.registration_version + reachable = await pd_manager.check_pd_nodes_health() + # A reconnect can replace a socket on the same PD_Client_Obj. + same_registrations = pd_manager.registration_version == probed_version + inference_healthy = httpserver_manager.is_healthy() + nodes_ready = pd_manager.is_pd_nodes_ready() + is_healthy = reachable and same_registrations 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 @@ -538,14 +621,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": 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: @@ -569,7 +648,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) @@ -595,6 +673,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) # 杀掉所有子进程 @@ -614,6 +695,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 91d0672ebb..81ffe5a6d2 100644 --- a/lightllm/server/api_http_pd.py +++ b/lightllm/server/api_http_pd.py @@ -10,8 +10,10 @@ import asyncio import pickle +import time import ujson as json +from anyio import fail_after from fastapi import APIRouter, WebSocket, WebSocketDisconnect from lightllm.server.pd_io_struct import ObjType @@ -24,6 +26,60 @@ router = APIRouter() +_PD_HEARTBEAT_TIMEOUT = 30 +_PD_HEARTBEAT_INTERVAL = 15 +_SAMPLE_INTERVAL = 1 +_SLOW_SAMPLE_INTERVAL = 1.5 +_RECENT_DELAY_WINDOW = 5 + + +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") + self.last_slow_sample = float("-inf") + + async def run(self): + while True: + await asyncio.sleep(_SAMPLE_INTERVAL) + now = time.monotonic() + 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 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 < _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. + 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 @@ -38,25 +94,25 @@ 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: - data = await asyncio.wait_for(websocket.receive_bytes(), timeout=heartbeat_timeout_seconds) + 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: continue await g_objs.httpserver_manager.put_to_handle_queue(obj) - except asyncio.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 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=pd_client, websocket=websocket) diff --git a/lightllm/server/build_prompt.py b/lightllm/server/build_prompt.py index ede0159456..4d603418d0 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_prompt_work from lightllm.utils.log_utils import init_logger from functools import lru_cache from lightllm.utils.config_utils import get_model_type_v1 @@ -143,6 +144,10 @@ def _normalize_multimodal_content_types(messages: list) -> None: async def build_prompt(request, tools) -> str: + return await run_prompt_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 217dd96faf..7ca394ec8b 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 @@ -38,12 +39,32 @@ from lightllm.utils.websocket_utils import websocket_message_exceeds_limit from .pd_normal_master import HttpPdNormalManagerHelper from .pd_pf_master import HttpPdPrefillFirstManagerHelper +from .prompt_processing import get_pd_prompt_pool from .pd_selector import PDSelectionExtraInfo, create_selector 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(HttpPdNormalManagerHelper, HttpPdPrefillFirstManagerHelper, object): + # 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, @@ -76,7 +97,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() @@ -201,7 +222,7 @@ async def _generate_choices( await multimodal_params.verify_and_preload(request) # 计算输入的 input_token_num, 进行校验,如果输入+输出参数设置太长,则将 # sampling_params 的参数进行修正。 - input_token_num = await asyncio.to_thread(self.tokens, prompt, multimodal_params, sampling_params) + input_token_num = await get_pd_prompt_pool().run(self.tokens, prompt, multimodal_params, sampling_params) # Length validation only checks emptiness and len(); no token list is needed. fake_prompt_ids = range(input_token_num) from lightllm.server.httpserver.manager import HttpServerManager @@ -400,7 +421,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 get_pd_prompt_pool().run( self.tokens, block_prompt, multimodal_params, sampling_params ) # 原始输入长度已在准入时计算;长度差作为重新编码后的历史输出长度。 @@ -884,6 +905,7 @@ def __init__(self, args: StartArgs): self.args: StartArgs = args self.prefill_nodes: List[PD_Client_Obj] = [] self.decode_nodes: List[PD_Client_Obj] = [] + self.registration_version = 0 self.url_to_pd_nodes: Dict[str, PD_Client_Obj] = {} self.selector = create_selector(args.select_p_d_node_strategy, self) return @@ -920,7 +942,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 @@ -980,6 +1003,7 @@ def register_pd(self, pd_info_json, websocket): self.selector.update_nodes(self.prefill_nodes, self.decode_nodes) node.sub_connections[connection_id] = websocket + self.registration_version += 1 logger.info( f"mode: {node.mode} url: {node.client_ip_port} dp_index: {node.dp_index} " f"connection_id: {connection_id} registed" @@ -993,6 +1017,8 @@ def remove_pd(self, pd_client, websocket=None): for connection_id, current in list(pd_client.sub_connections.items()): if current is websocket: pd_client.sub_connections.pop(connection_id, None) + if pd_client.sub_connections: + self.registration_version += 1 removed_connection_id = connection_id break if pd_client.sub_connections: @@ -1007,6 +1033,7 @@ def remove_pd(self, pd_client, websocket=None): if self.url_to_pd_nodes.get(pd_client.connection_key) is not pd_client: return + self.registration_version += 1 self.url_to_pd_nodes.pop(pd_client.connection_key, None) self.prefill_nodes = [e for e in self.prefill_nodes if e.connection_key != pd_client.connection_key] self.decode_nodes = [e for e in self.decode_nodes if e.connection_key != pd_client.connection_key] 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..aae26a8fcb --- /dev/null +++ b/lightllm/server/httpserver_for_pd_master/prompt_processing.py @@ -0,0 +1,105 @@ +"""Bound CPU-heavy prompt work separately from the HTTP worker's default executor.""" + +import asyncio +import os +import time +from concurrent.futures import ThreadPoolExecutor +from contextvars import copy_context +from functools import lru_cache +from itertools import islice +from pathlib import Path +from threading import Lock + + +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 quota / period if quota > 0 and period > 0 else None + + +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() + 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 + return available + + +class PDPromptPool: + 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 = {} + 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. + 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): + # 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/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/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_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 new file mode 100644 index 0000000000..736b49d8b4 --- /dev/null +++ b/unit_tests/server/httpserver/test_pd_request_admission.py @@ -0,0 +1,190 @@ +import asyncio +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock, Mock + +import pytest + +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(worker, 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) + 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()) + + +@pytest.mark.parametrize("method", ["GET", "POST"]) +def test_http1_rejected_tokens_upload_finishes_before_429(worker, method): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + 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(worker, last): + async def run(): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + 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(worker, method): + gate = api_http._PDRequestAdmission(AsyncMock()) + gate.in_flight = 1 + send = AsyncMock() + receive = AsyncMock(return_value={"type": "http.disconnect"}) + 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 + + +@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 + send = AsyncMock() + receive = AsyncMock(return_value={"type": "http.request"}) + 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" + worker.metric_client.counter_inc.assert_called_once_with("lightllm_request_failure") + + +def test_backed_up_prompt_pool_rejects_before_dispatch(worker, monkeypatch): + gate = api_http._PDRequestAdmission(AsyncMock()) + monkeypatch.setattr( + prompt_processing, "get_pd_prompt_pool", lambda: SimpleNamespace(backed_up=lambda: True, subcore=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() + + +@pytest.mark.parametrize("delayed", [False, True]) +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( + prompt_processing, "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/httpserver/test_pd_split_connections.py b/unit_tests/server/httpserver/test_pd_split_connections.py index 3691088a81..ec4fc72893 100644 --- a/unit_tests/server/httpserver/test_pd_split_connections.py +++ b/unit_tests/server/httpserver/test_pd_split_connections.py @@ -78,6 +78,39 @@ def test_unsplit_reconnection_ignores_old_connection_id_cleanup(mode): assert key not in manager.url_to_pd_nodes +@pytest.mark.parametrize("change", ["disconnect", "reregister", "replace_socket", "drop_subconnection"]) +def test_fixed_health_rechecks_registrations_after_probe(monkeypatch, change): + from lightllm.server import api_http + + args = StartArgs(run_mode="pd_master", pd_master_mode="1p1d") + pd = PDManager(args) + pd.register_pd(_registration(args), object()) + info = _registration(args, mode="decode") + old_socket = object() + node = pd.register_pd(info, old_socket) + if change == "drop_subconnection": + pd.register_pd(dict(info, connection_id="second"), object()) + + async def probe(): + if change != "replace_socket": + pd.remove_pd(node, old_socket) + if change in ("reregister", "replace_socket"): + replacement = pd.register_pd(info, object()) + if change == "replace_socket": + assert replacement is node + return True + + monkeypatch.setattr(pd, "check_pd_nodes_health", probe) + manager = SimpleNamespace(pd_manager=pd, is_healthy=lambda: True) + monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(args=args, httpserver_manager=manager)) + response = asyncio.run(api_http.healthcheck(None)) + data = json.loads(response.body) + assert response.status_code == 503 + assert data["pd_nodes_ready"] is (change != "disconnect") + assert not data["pd_nodes_healthy"] + assert data["registered_decode_nodes"] == int(change != "disconnect") + + def test_master_picks_one_live_websocket(monkeypatch): import lightllm.server.pd_io_struct as pd_io_struct @@ -170,6 +203,7 @@ async def run(): manager = SimpleNamespace( args=args, host_ip="p", + abort=AsyncMock(), pd_mode=pd_loop.NodeRole.P, ) monkeypatch.setattr( @@ -293,11 +327,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)) 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..5c00fe054e --- /dev/null +++ b/unit_tests/server/httpserver/test_pd_tokenizer_concurrency.py @@ -0,0 +1,67 @@ +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 +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 import prompt_processing + + +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 = 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. + 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/httpserver/test_pd_websocket_lifecycle.py b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py index 5f2cbdf717..96402f04fd 100644 --- a/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py +++ b/unit_tests/server/httpserver/test_pd_websocket_lifecycle.py @@ -5,7 +5,7 @@ import pickle from contextlib import asynccontextmanager from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock, MagicMock, Mock import pytest @@ -36,7 +36,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 @@ -50,20 +51,20 @@ 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 = [] async def wait_forever(): await asyncio.Event().wait() - async def short_heartbeat_wait(awaitable, timeout): + def short_heartbeat_wait(timeout): timeouts.append(timeout) - return await original_wait_for(awaitable, timeout=0.01) + return original_fail_after(0.01) manager = _manager(monkeypatch) - monkeypatch.setattr(api_http_pd.asyncio, "wait_for", short_heartbeat_wait) + 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() @@ -138,3 +139,60 @@ async def connect(uri, **kwargs): asyncio.run(register_loop.register_loop(manager)) assert pickle.loads(websocket.send.await_args_list[0].args[0]) == PD_Master_Obj(100, "master:8000") assert websocket.send.await_args_list[1].args[0] == "heartbeat" + + +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_hypercorn_config.py b/unit_tests/server/test_hypercorn_config.py index 7dfaed758e..a96afc792d 100644 --- a/unit_tests/server/test_hypercorn_config.py +++ b/unit_tests/server/test_hypercorn_config.py @@ -46,3 +46,20 @@ def test_pd_nodes_reject_custom_hypercorn_config(run_mode): with pytest.raises(ValueError, match="not supported in PD mode"): _validate_pd_features(args) + + +def test_pd_worker_rejects_unpatched_handler_before_initializing(monkeypatch, tmp_path): + import asyncio + + from hypercorn.protocol import h2 + from lightllm.server import api_http + + 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 diff --git a/unit_tests/server/test_pd_master_mode.py b/unit_tests/server/test_pd_master_mode.py index 066eec8f16..1a6c2b97c1 100644 --- a/unit_tests/server/test_pd_master_mode.py +++ b/unit_tests/server/test_pd_master_mode.py @@ -243,10 +243,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 diff --git a/unit_tests/server/test_pd_master_topology_api.py b/unit_tests/server/test_pd_master_topology_api.py index e96df98ce7..95def612ad 100644 --- a/unit_tests/server/test_pd_master_topology_api.py +++ b/unit_tests/server/test_pd_master_topology_api.py @@ -27,6 +27,7 @@ def _install(monkeypatch, *, ready=False, healthy=False): manager.__dict__.update( args=args, pd_manager=SimpleNamespace( + registration_version=0, prefill_nodes=[SimpleNamespace(node_id=199)], decode_nodes=[SimpleNamespace(node_id=200)], is_pd_nodes_ready=Mock(return_value=ready), @@ -35,7 +36,8 @@ def _install(monkeypatch, *, ready=False, healthy=False): is_healthy=Mock(return_value=healthy), update_req_status=AsyncMock(), ) - monkeypatch.setattr(api_http, "g_objs", SimpleNamespace(args=args, httpserver_manager=manager)) + state = SimpleNamespace(args=args, httpserver_manager=manager, pd_heartbeat_monitor=api_http.PDHeartbeatMonitor()) + monkeypatch.setattr(api_http, "g_objs", state) return args, manager @@ -91,6 +93,7 @@ def test_fixed_topology_health_failure_has_consistent_payload(monkeypatch): def test_kv_status_is_accepted_on_the_register_connection(monkeypatch): _, manager = _install(monkeypatch) manager.register_pd = AsyncMock() + manager.remove_pd = AsyncMock() manager.put_to_handle_queue = AsyncMock() status = PDUpKVStatus(8, 100, b"metadata") with TestClient(api_http.app) as client: @@ -99,3 +102,13 @@ def test_kv_status_is_accepted_on_the_register_connection(monkeypatch): websocket.send_bytes(pickle.dumps((ObjType.PD_UPLOAD_KV_STATUS, status))) client.portal.call(_wait_until, lambda: manager.put_to_handle_queue.await_count == 1) manager.put_to_handle_queue.assert_awaited_once_with((ObjType.PD_UPLOAD_KV_STATUS, status)) + + +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"]