diff --git a/docker/Dockerfile b/docker/Dockerfile index e597a7de1f..0d4745f91a 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 lightllm/utils/verify_hypercorn.py diff --git a/docker/Dockerfile.glm53_flashkda_megamoe b/docker/Dockerfile.glm53_flashkda_megamoe index 8e686d0c22..460730cea2 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 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 b1728117ff..4858a47e3a 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 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 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 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_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 8c8ed804ab..39fb98bd53 100755 --- a/lightllm/server/api_http.py +++ b/lightllm/server/api_http.py @@ -21,10 +21,12 @@ import time import uvloop +from anyio import create_task_group import requests import base64 import os from io import BytesIO +from itertools import zip_longest import setproctitle asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) @@ -43,6 +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 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 @@ -56,6 +59,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 @@ -69,6 +73,7 @@ ModelListResponse, ) from .build_prompt import build_prompt, init_tokenizer +from .api_http_pd import PDHeartbeatMonitor, router as pd_router logger = init_logger(__name__) @@ -76,6 +81,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 @@ -87,6 +94,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 @@ -155,6 +165,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) @@ -192,7 +282,7 @@ async def generation_exception_handler(request: Request, exc: GenerationError) - @app.get("/liveness") @app.post("/liveness") -def liveness(): +async def liveness(): return {"status": "ok"} @@ -247,35 +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 = ( - 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": + 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 @@ -520,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": 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: @@ -551,7 +633,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 +658,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 +680,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..9d9afbd9ef 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,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 @@ -36,12 +92,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,17 +109,10 @@ 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 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 1ee9994643..cc2edb1913 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.server.tokenizer import get_tokenizer from lightllm.utils.log_utils import init_logger from functools import lru_cache @@ -151,6 +152,10 @@ def _redact_message_image_data_in_place(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 3dab0526fd..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 @@ -47,12 +48,32 @@ ) 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 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: + # 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, @@ -87,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() @@ -240,7 +257,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 get_pd_prompt_pool().run( self._prepare_prefill_prompt, prompt, multimodal_params, sampling_params ) from lightllm.server.httpserver.manager import HttpServerManager @@ -465,7 +482,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 ) # 原始输入长度已在准入时计算;长度差作为重新编码后的历史输出长度。 @@ -1157,7 +1174,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..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 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)) 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 e3b8c322f4..77b6c7dafd 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 @@ -51,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() @@ -66,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() @@ -84,3 +83,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_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 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 diff --git a/unit_tests/server/test_pd_master_topology_api.py b/unit_tests/server/test_pd_master_topology_api.py index de92995ddc..98300f7eb4 100644 --- a/unit_tests/server/test_pd_master_topology_api.py +++ b/unit_tests/server/test_pd_master_topology_api.py @@ -94,3 +94,36 @@ 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: + # 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 + + 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) + + +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"]