Files
tokenspeed/test/cli/test_proc.py
8912251d1e feat(engine): serve every role on SMG's direct lane and remove AsyncLLM (#2718)
## Summary

SMG's gateway now reaches TokenSpeed engines over the msgpack wire
directly
(its direct lane), for every role, so the in-process Python frontend
(`AsyncLLM`) and the gRPC servicer path have no serving caller left.
This PR
implements the wire revision the lane speaks in the engine host, moves
`ts
serve` onto the lane, and removes `AsyncLLM` with the code only it used.

Commits:

1. **feat(engine): the wire revision SMG's direct lane drives** (the
protocol
   #2668–#2671 and #2674 described on the Python loop, which #2603
   superseded):
- the ready response declares `request_types`, `positional_layouts`, the
disaggregation role, a prefill or encode server's bootstrap address, and
     the checkpoint facts a frontend computes MRoPE positions from;
- CONTROL takes control calls `[call_id, method, args]`, answered with
one
     `ControlReplySlim` each: `flush_cache`, `start_profile` and
     `stop_profile`, and the RL and weight operations, whose argument is
     the JSON body of the SGLang-compatible RL route of the same name;
- an EPD encode server's first rank dials the frontend and takes ENCODE
     (0x03) frames (the request channel #2682 had it bind is gone);
   - each rank's HELLO says how many engines dial as one group
     (`engine_count`).
2. **feat(cli): serve through SMG's direct ZMQ lane**: `ts serve` runs
SMG's
gateway in front of the headless engine; the in-engine RL control app
goes.
3. **feat(runtime): remove AsyncLLM and the Python frontend**:
`AsyncLLM`, the
Python `Engine` and `LLM` API, the frontend-only flags and metrics, and
   the SMG gRPC servicer dependencies. Tests and tools drive a headless
engine with `WireDriver`. A JSON schema on a reasoning model still waits
for the reasoning block, now in the host's ingress. Follower nodes keep
   #1921's guarantee: their ranks die with them.
4. **feat(cli): serve disaggregated and multi-node deployments on SMG's
lane**: `ts serve` fronts an attention-DP engine whose replica leaders
sit
on other nodes through a `tcp://` worker on `--dist-init-addr`'s host;
   PD and EPD run as headless engines behind `smg launch`
(`docs/serving/disaggregation.md`); the 7 CI jobs the removal had to
drop
   come back on that recipe.
5. **fix(engine): refuse control operations an engine never answers**:
review
   fixes and the stale-reference sweep.

## Dependency on SMG

The lane features this relies on (PD and EPD and MRoPE on the lane,
`tcp://` workers, control and RL calls, the declared engine group) are
in
SMG's pull request 4649 (its first part, the logprob columns, landed as
SMG's pull request 4630). Until it is released as `tokenspeed-smg` and
the
pin in `python/pyproject.toml` is bumped (a follow-up commit here), the
CI
jobs that need them cannot pass: the restored PD and EPD and multi-node
jobs, and `test_qwen35_vlm_e2e` (Qwen3.5 images through `ts serve`,
which
the pinned gateway refuses on the lane). Aggregated text serving works
with
the current pin.

## Validation (H20)

- Rust: workspace tests, clippy, fmt; Python: CLI and CI-system tests,
the
runtime-1gpu, runtime-2gpu and prefix-cache suites (failures match
`main`
  on this host, models it does not cache).
- With the SMG changes: aggregated greedy completions token-identical to
before; 1P1D token-identical to aggregated (also with a DP2 MoE
prefill);
1E1P1D image answers correct, embeddings byte-identical between the
encode
  server and prefill; gateway MRoPE positions equal
`compute_mrope_positions`; two-node `ts serve` with both ranks serving;
the
  CI PD and EPD launchers run end to end; flush, profile, pause and
continue, release and resume and a disk refit through the control calls.
- With the current pin: aggregated `ts serve` works.

Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>

---------

Signed-off-by: FC-Li <robert_lexis@163.com>
Signed-off-by: lightseek-bot <243258330+lightseek-bot@users.noreply.github.com>
Co-authored-by: longcat-ia-team <longcat_ia_team@meituan.com>
Co-authored-by: LightSeek Foundation <243258330+lightseek-bot@users.noreply.github.com>
2026-10-27 20:16:03 +08:00

147 lines
5.1 KiB
Python

# Copyright (c) 2026 LightSeek Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Tests for subprocess supervision helpers."""
from __future__ import annotations
import asyncio
import pytest
from tokenspeed.cli._proc import (
engine_argv,
spawn_gateway,
terminate_then_kill,
zmq_handshake_port,
)
class _RecordingProcess:
"""Stands in for an ``asyncio.subprocess.Process``: records the signals it
receives and drains ``wait`` on a test-controlled delay."""
def __init__(self, returncode, wait_delay=0.0):
self.returncode = returncode
self.wait_delay = wait_delay
self.signals = []
def terminate(self):
self.signals.append("terminate")
def kill(self):
self.signals.append("kill")
async def wait(self):
await asyncio.sleep(self.wait_delay)
return self.returncode
async def _gateway_command(monkeypatch, **kwargs) -> tuple:
captured = {}
async def fake_exec(*cmd, **exec_kwargs):
captured["cmd"] = cmd
class _P:
async def wait(self):
return 0
return _P()
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
await spawn_gateway(["--model", "/m"], **kwargs)
return captured["cmd"]
def _value(cmd, flag):
return cmd[cmd.index(flag) + 1] if flag in cmd else None
@pytest.mark.asyncio
async def test_spawn_gateway_fronts_one_tokenspeed_zmq_worker(monkeypatch):
"""Single-worker mode: one ipc:// TokenSpeed worker, with retries and the
circuit breaker off."""
cmd = await _gateway_command(
monkeypatch, worker_url="ipc:///tmp/smg-zmq/ts0.ipc", engine_count=1
)
assert cmd[1:4] == ("-m", "smg", "launch")
assert _value(cmd, "--worker-urls") == "ipc:///tmp/smg-zmq/ts0.ipc"
assert _value(cmd, "--backend") == "tokenspeed"
assert "--disable-retries" in cmd
assert "--disable-circuit-breaker" in cmd
# One engine is an ungrouped worker; the operator's args come last.
assert "--zmq-engine-count" not in cmd
assert cmd[-2:] == ("--model", "/m")
@pytest.mark.asyncio
async def test_spawn_gateway_awaits_every_attention_dp_rank(monkeypatch):
cmd = await _gateway_command(
monkeypatch, worker_url="ipc:///tmp/smg-zmq/ts0.ipc", engine_count=4
)
assert _value(cmd, "--zmq-engine-count") == "4"
def test_handshake_port_matches_the_gateways_derivation():
# SMG's own pinned vectors for its derive_handshake_port.
assert zmq_handshake_port("ipc:///tmp/smg-zmq/ts0.ipc") == 25152
assert zmq_handshake_port("ipc:///tmp/smg-zmq/engine-31000") == 22714
def test_engine_argv_dials_the_handshake_last(monkeypatch):
"""The handshake flags come last, so they win over the operator's; a
follower node none of whose ranks registers gets none."""
monkeypatch.delenv("TS_SERVE_ENGINE_MODULE", raising=False)
argv = engine_argv(
["--model", "/m", "--data-parallel-rpc-port", "30500"],
host="127.0.0.1",
port=31000,
handshake=("10.0.0.5", 23455),
)
assert argv[1:3] == ["-m", "tokenspeed.runtime.entrypoints.engine"]
assert argv[-6:] == [
"--data-parallel-address",
"10.0.0.5",
"--data-parallel-rpc-port",
"23455",
"--zmq-engine-index",
"0",
]
follower = engine_argv(["--model", "/m"], host="0.0.0.0", port=8000, handshake=None)
assert follower[3:] == ["--host", "0.0.0.0", "--port", "8000", "--model", "/m"]
@pytest.mark.asyncio
async def test_terminate_then_kill_escalates_only_when_the_drain_times_out():
"""The signals are the observable effect: noop on a dead child, SIGTERM
alone when it drains in time, SIGTERM then SIGKILL when it doesn't."""
dead = _RecordingProcess(returncode=0)
await terminate_then_kill(dead, drain_timeout=0.5)
assert dead.signals == []
draining = _RecordingProcess(returncode=None)
await terminate_then_kill(draining, drain_timeout=0.5)
assert draining.signals == ["terminate"]
stuck = _RecordingProcess(returncode=None, wait_delay=0.1)
await terminate_then_kill(stuck, drain_timeout=0.05)
assert stuck.signals == ["terminate", "kill"]