Source code for mstar.api_server.rust_frontend

"""The Rust axum frontend in front of ``APIServer``.

``mstar-server`` (``rust/server/``) owns the HTTP surface — routes, OpenAI
translation, SSE/NDJSON streaming, uploads, CORS — and speaks a flattened
msgpack protocol over the Rust ZMQ transport to this bridge, which
drives the existing Python data plane (``APIServer.submit_request`` /
``iter_result_chunks`` / ``abort_submission``; preprocessing and the conductor
protocol are untouched):

    frontend -> bridge:  {t:"submit", rid, sub, text, file_paths,
                          input_modalities, output_modalities, model_kwargs,
                          prompt_parts, streaming, accepts_chunks, report_usage}
                       | {t:"abort", rid, sub}
                       | {t:"ping", rid, sub}
                       | {t:"metrics", rid, sub, refusals:{route, status, count}}
                       | {t:"check_ref_audio", rid, sub, path, decoder, bare}
                       | {t:"voices", rid, sub}
                       | {t:"windows", rid, sub, op, plan, ...}
                       | {t:"live", rid, sub, op, call, ..., stream?, audio?(bin)}
                       | {t:"end_of_turn", rid, sub, audio(bin)}
                       | {t:"lora", rid, sub, op, lora_name, lora_path?}
    bridge -> frontend:  {t:"chunk", rid, sub, modality, data(bin), metadata}
                       | {t:"chunks", subs, modalities, payloads(bin), metadatas}
                       | {t:"err", rid, sub, msg} | {t:"done", rid, sub}
                       | {t:"pong", rid, sub}
                       | {t:"metrics", rid, sub, data(bin), metadata}
                       | {t:"checked", rid, sub, error?, status?}
                       | {t:"voices", rid, sub, metadata:{voices?}}
                       | {t:"windows", rid, sub, metadata:{duration, single, windows} | {error}}
                       | {t:"live", rid, sub, metadata:{taking | accepted | rejected | error, status, error_id?}}
                       | {t:"end_of_turn", rid, sub, metadata:{p} | {error}}
                       | {t:"lora", rid, sub, metadata:{text} | {error:{status, message}}}
                       | {t:"served", adapters}   (unsolicited, on every change)

A ``live`` request is one operation on a ``/generate/ws`` live call, the
submission ``call`` names: ``taking`` (``taking_input``), ``append``
(``stream_input``) or ``reject`` (``reject_input``). An append the model finds
late is sent later as a ``chunk`` (modality ``late``) on the socket's
``notice`` route, its ``tag`` echoed in the metadata.

A ``windows`` request is one operation on a transcription upload's
``WindowPlanner`` (``serving_transcriptions``), kept here under the frontend's
``plan`` id: ``plan`` makes it (and decodes an upload that will be windowed),
``fixed``, ``at`` and ``cut`` cut windows, and ``close`` deletes the upload
and its windows, with no reply. The model's own loader decodes the upload,
which no Rust decoder matches.

A ``metrics`` request carries the frontend's cumulative refusal counts as
three parallel lists (route template, status, count), which the API server
exports as ``mstar_http_refusals_total``. The reply is what ``GET /metrics``
serves on the Python frontend: the text rendered from ``APIServer.metrics``
with its ``content_type`` in ``metadata``, or empty ``metadata`` when metrics
are off (a 404; the counts are then ignored).

``chunks`` carries many submissions' chunks as parallel lists, in order:
the API server's message thread hands the bridge every chunk it drained in
one pass (``APIServer.relay_chunks_to``), so a decode step costs one message
rather than one per request. Only a submit that sets ``accepts_chunks`` gets
them, so a frontend binary older than this bridge still gets ``chunk``s. A
submission's error chunk, and anything its handler finds unrelayed at the
end, always goes out as ``chunk``.

A submit that sets ``report_usage`` (a chat) gets a last ``chunk`` of
modality ``usage`` before ``done``: its token counts and finish reason in
``metadata`` (``APIServer.submit_request``'s ``report_usage``).

``sub`` names one submission and is never reused. A client may resubmit its
``rid`` as soon as it drops a stream, and that stream's ``done`` or late
chunks can cross the retry, so everything about a submission is addressed by
``sub``. The frontend refuses a ``rid`` still in flight with a 409 itself and
sends a dropped stream's abort before it frees the ``rid``, so the abort
arrives here before the retry's submit.

The submit shape is ``APIServer.submit_request``'s signature verbatim — the
protocol was designed by flattening it. ``prompt_parts`` travels for a chat
only, one map of ``PromptPart``'s fields per part. The bridge mesh lives in
its own socket dir (private to the frontend/bridge pair), so entity names
never collide with the conductor/worker mesh.

``mstar-serve`` runs the ``mstar-server`` binary + this loop in place of
``uvicorn.run`` (unless ``--python-frontend``). Everything else in the process
(preprocess worker, conductor spawn, tensor transport) is identical. The
frontend enforces the API key (``--api-key`` / ``MSTAR_API_KEY``) itself; the
bridge socket is private to the pair.
"""

from __future__ import annotations

import asyncio
import json
import logging
import os
import re
import shutil
import signal
import subprocess
import sysconfig
import threading
from enum import StrEnum
from pathlib import Path

from mstar.api_server.auth import API_KEY_ENV
from mstar.communication.communicator import CommProtocol
from mstar.communication.rust_communicator import (
    MsgpackCodec,
    RustZMQCommunicator,
)
from mstar.graph.runtime.utils import CHECKOUT_RUST, is_mstar_rust_crate, require_rust_extension
from mstar.model.multimodal import PromptPart
from mstar.utils.client_errors import client_error_text, exception_status_text, scrub_paths
from mstar.utils.threads import ThreadPool

logger = logging.getLogger(__name__)

#: Upper bound on one blocking receive, so ``stop()`` is noticed promptly and
#: the loop stays responsive to shutdown. Not a latency knob: an arriving
#: message ends the wait immediately.
BRIDGE_RECV_WAIT_S = 0.05

#: The model's adapter class in ``ADAPTER_REGISTRY``; ``mstar-server`` picks
#: its OpenAI translation by it (``Adapter::from_python``).
OPENAI_ADAPTER_ENV = "MSTAR_OPENAI_ADAPTER"


[docs] def openai_adapter_class(model_name: str) -> str: """The class name of ``model_name``'s OpenAI adapter, "" when it has none.""" from mstar.api_server.openai.adapters import get_adapter adapter = get_adapter(model_name) return "" if adapter is None else type(adapter).__name__
[docs] def find_server_binary(explicit: str | None = None, rust_dir: Path = CHECKOUT_RUST) -> str: """Resolve the ``mstar-server`` binary: explicit arg, ``MSTAR_SERVER_BIN``, the running environment's scripts directory (where a Linux wheel installs it, also when the venv is not activated), ``$PATH``, then the in-repo release build. The scripts directory goes before ``$PATH`` so another environment's older binary never serves this one's bridge. In a checkout, a binary built from other sources than ``rust_dir`` is skipped, or used with a warning when named by the arg or the variable. Raises FileNotFoundError when there is none, RuntimeError when all are stale.""" checkout = is_mstar_rust_crate(rust_dir) if checkout: require_rust_extension() # its source_hash is what binaries are compared with stale = [] for candidate, named in ( (explicit, True), (os.getenv("MSTAR_SERVER_BIN"), True), (str(Path(sysconfig.get_path("scripts")) / "mstar-server"), False), (shutil.which("mstar-server"), False), (str(rust_dir / "server" / "target" / "release" / "mstar-server"), False), ): if not (candidate and Path(candidate).is_file()): continue problem = _stale_server(candidate, rust_dir) if checkout else None if problem is None: return candidate if named: logger.warning("Using mstar-server %s, which %s", candidate, problem) return candidate stale.append(f"{candidate} {problem}") if stale: # Both touches, for the reason in require_rust_extension. server = rust_dir / "server" raise RuntimeError( f"No mstar-server built from {rust_dir}: {'; '.join(stale)}. Rebuild it with " f"`touch {rust_dir / 'build.rs'} {server / 'build.rs'} && " f"cargo build --release --manifest-path {server / 'Cargo.toml'}`.") raise FileNotFoundError( "mstar-server binary not found: build it with " "`cargo build --release` in rust/server/, put it on $PATH, or set " "MSTAR_SERVER_BIN")
def _stale_server(binary: str, rust_dir: Path) -> str | None: """Why ``binary`` was not built from the sources in ``rust_dir``, or None.""" import mstar_rust # No arguments, which every mstar-server exits on (an older one would # serve `--source-hash` as a model name); a newer one prints its sources. try: ran = subprocess.run([binary], capture_output=True, text=True, errors="replace", timeout=30, check=False) except (OSError, subprocess.TimeoutExpired) as e: return f"could not be run ({e})" built = re.search(r"built from sources ([0-9a-f]{16}) ([0-9a-f]{16})", ran.stdout + ran.stderr) if built is None: return "predates the source check" current = (mstar_rust.source_hash(str(rust_dir)), mstar_rust.source_hash(str(rust_dir / "server"))) if built.groups() == current: return None return (f"was built from sources hashing to {' '.join(built.groups())}, " f"but {rust_dir} and its server/ hash to {' '.join(current)}") #: The serve settings ``mstar-server`` reads from its environment. The #: launcher's resolved values win over inherited ones, as the API key's does. REQUEST_TIMEOUT_ENV = "MSTAR_REQUEST_TIMEOUT_S" SAMPLE_RATE_ENV = "MSTAR_SAMPLE_RATE" #: The libsndfile ``soundfile`` loaded, which mstar-server opens for mp3/flac/opus. LIBSNDFILE_ENV = "MSTAR_LIBSNDFILE" #: ``ServedModels`` as JSON: the names that select the base model, and the LoRA adapters. SERVED_MODELS_ENV = "MSTAR_SERVED_MODELS" #: What ``/v1/audio/transcriptions`` needs from the model, as JSON (``transcription_facts``). TRANSCRIPTION_ENV = "MSTAR_TRANSCRIPTION" #: The deployment's openpi policy, as JSON (``openpi_facts``); unset serves no openpi socket. OPENPI_ENV = "MSTAR_OPENPI" #: The largest WebSocket message, in bytes (the config's ``ws_max_message_mb``). WS_MAX_BYTES_ENV = "MSTAR_WS_MAX_BYTES" #: The model's client streams, as JSON: a request to a model with any is a live call. CLIENT_STREAMS_ENV = "MSTAR_CLIENT_STREAMS" #: What ``/v1/realtime`` runs with, as JSON (``realtime_facts``). REALTIME_ENV = "MSTAR_REALTIME"
[docs] class WindowOp(StrEnum): """A ``windows`` request's operation on a transcription upload's ``WindowPlanner``.""" PLAN = "plan" # read the upload, and check it against the route's caps FIXED = "fixed" # fixed-length windows over the whole upload AT = "at" # the window that starts at ``offset`` CUT = "cut" # ``duration`` seconds from ``offset`` CLOSE = "close" # the request ended: delete the upload and its windows
[docs] class LiveOp(StrEnum): """A ``live`` request's operation on a live call.""" TAKING = "taking" # taking_input: whether the call still takes input APPEND = "append" # stream_input: text, files, model_kwargs or samples, maybe ending streams REJECT = "reject" # reject_input: end the call with the client's error
[docs] def soundfile_library() -> str | None: """The libsndfile that ``soundfile`` loaded (the copy its wheel bundles, else the system one it found), for ``mstar-server`` to encode the compressed speech formats with the same library; ``None`` without soundfile, which leaves only wav and pcm on both frontends (``media_io.audio_formats``). These are soundfile's own module attributes, which it sets as it loads the library.""" try: import soundfile except (ImportError, OSError): return None # `_libname` is set only when the packaged library failed to load and soundfile # fell back to the system one; `_full_path` is set before that attempt return getattr(soundfile, "_libname", None) or getattr(soundfile, "_full_path", None)
[docs] def served_models_json(served_models) -> str: """``SERVED_MODELS_ENV``'s value for a ``ServedModels``.""" return json.dumps({ "base": sorted(served_models.base), "adapters": list(served_models.adapters), "lora": served_models.lora, })
[docs] def transcription_facts(server, adapter) -> dict | None: """``TRANSCRIPTION_ENV``'s value: what mstar-server's transcription route needs that only this side knows. The model's declared kwargs (``request_kwargs``, which decide what the long-form drivers add), the deployment's ``max_concurrent_requests`` (which parallel uploads share), the language tables the adapter checks against, and the URL pydantic's error text cites. ``None`` for a model with no transcription surface.""" if adapter is None or not adapter.supports_transcriptions: return None from pydantic.version import version_short from mstar.api_server.openai import adapters model = getattr(server, "model", None) declared = model.request_kwargs() if model is not None else None facts = { "request_kwargs": sorted(declared) if declared is not None else None, "max_concurrent_requests": getattr(server, "max_concurrent_requests", None), "errors_url": f"https://errors.pydantic.dev/{version_short()}/v/", } if isinstance(adapter, adapters.CanaryAdapter): from mstar.model.canary.config import LANGUAGES facts["languages"] = list(LANGUAGES) if isinstance(adapter, adapters.TransducerAdapter) and adapter.detects_language: from mstar.model.utils import GRANARY_LANGUAGES facts["languages"] = list(GRANARY_LANGUAGES) facts["detects_language"] = True if isinstance(adapter, adapters.Qwen3ASRAdapter): from mstar.model.qwen3_asr.config import LANGUAGE_CODES facts["language_codes"] = [[code, name] for code, name in LANGUAGE_CODES.items()] return facts
[docs] def openpi_facts(policy) -> dict | None: """``OPENPI_ENV``'s value for an ``OpenpiPolicy``: the block as the API server checked it against its model, its metadata frame packed as this side packs it. ``None`` (no ``openpi:`` block) serves no socket at ``/``.""" if policy is None: return None import base64 from mstar.api_server.openpi import pack return { "image_keys": list(policy.image_keys), "state_keys": list(policy.state_keys), "state_kwarg": policy.state_kwarg, "action_horizon": policy.action_horizon, "action_dim": policy.action_dim, "action_dims": policy.action_dims, "metadata": base64.b64encode(pack(policy.metadata)).decode("ascii"), }
[docs] def onnxruntime_library() -> str | None: """The ONNX Runtime library the ``onnxruntime`` package loads, for mstar-server to score turn detection with the same runtime; ``None`` without it.""" try: import onnxruntime except ImportError: return None # the versioned name (libonnxruntime.so.1.31.1) is the file itself libs = sorted(Path(onnxruntime.__file__).parent.joinpath("capi").glob("libonnxruntime.so*"), key=lambda p: len(p.name)) return str(libs[-1]) if libs else None
[docs] def conversation_facts(server) -> dict | None: """What a ``/v1/realtime`` conversation needs from a model with a ``ClientAudio`` client stream, as the Python route reads it off the model: how many such streams, whether it has turn tokens and its output channels (which decide whether it converses), and, for one that does, its stream and the reply settings. ``None`` for a model with no such stream.""" audio = list(getattr(server, "client_audio", None) or []) if not audio: return None model = server.model facts = {"streams": len(audio), "turn_tokens": getattr(model, "turn_tokens", None) is not None, "channels": model.get_output_audio_channels("audio")} if facts["turn_tokens"] and len(audio) == 1 and facts["channels"] == 1: stream = audio[0] facts.update( stream=stream.edge_name, rate=stream.audio.sample_rate, frame_samples=stream.audio.frame_samples, output_rate=model.get_output_sample_rate("audio"), voice=model.get_default_voice(), idle_steps=model.turn_idle_steps, silence_rms=float(model.turn_silence_rms), ) return facts
[docs] def realtime_facts(server, adapter, directory: str) -> dict | None: """``REALTIME_ENV``'s value for a model with a ``/v1/realtime`` surface. ``conversation`` is ``conversation_facts``'. For a realtime transcription surface: ONNX Runtime's library and Silero's weights (``None`` where this server has none, which leaves server_vad off as it is here), why Smart Turn did not load (``None`` when it did), and the model's tokenizer, saved under ``directory`` for the stable prefix. ``None`` for any other model.""" conversation = conversation_facts(server) transcribes = adapter is not None and getattr(adapter, "supports_realtime_transcription", False) if not transcribes and conversation is None: return None facts = {"conversation": conversation} if not transcribes: return facts from mstar.api_server.openai import realtime_vad def file(path): return str(path) if path is not None and Path(path).is_file() else None # semantic_vad's end-of-turn model runs here, over the bridge (``_end_of_turn``) facts.update({ "onnxruntime": onnxruntime_library(), "silero": file(realtime_vad.silero_weights()), "smart_turn_problem": None if realtime_vad.smart_turn() is not None else realtime_vad.smart_turn_problem(), "tokenizer": None, }) tokenizer = getattr(getattr(server, "model", None), "tokenizer", None) if tokenizer is not None and getattr(tokenizer, "is_fast", False): path = Path(directory) / "tokenizer.json" tokenizer.backend_tokenizer.save(str(path)) facts["tokenizer"] = str(path) return facts
[docs] def launch_rust_server(binary: str, model_name: str, port: int, bridge_dir: str, upload_dir: str, api_key: str | None = None, timeout_s: float | None = None, sample_rate: int | None = None, served_models=None, transcription: dict | None = None, openpi: dict | None = None, ws_max_bytes: int | None = None, client_streams=(), realtime: dict | None = None) -> subprocess.Popen: """``timeout_s`` is ``--timeout`` and ``sample_rate`` the model's audio output rate (``get_output_sample_rate``); ``None`` leaves the frontend's own default. ``served_models`` is the API server's ``ServedModels``, whose LoRA adapters a request's ``model`` selects; ``None`` serves the base model alone. ``transcription`` is ``transcription_facts``' for the served model, ``openpi`` ``openpi_facts``' for its policy, ``ws_max_bytes`` the config's WebSocket message limit, ``client_streams`` the model's (``APIServer.client_streams``), and ``realtime`` ``realtime_facts``' for its realtime surface.""" # The key goes through the environment, not argv, which any local user # can read from the process list. ``api_key`` is the resolved setting, so # an inherited MSTAR_API_KEY must not override it. env = {k: v for k, v in os.environ.items() if k != API_KEY_ENV} if api_key: env[API_KEY_ENV] = api_key if timeout_s is not None: # inf and nan never time out on the Python frontend, so they get a deadline past # any request (~31 years); a negative one times every request out there, as 0 does timeout_s = float(timeout_s) env[REQUEST_TIMEOUT_ENV] = repr(max(timeout_s, 0.0) if timeout_s < 1e9 else 1e9) if sample_rate is not None: env[SAMPLE_RATE_ENV] = str(int(sample_rate)) env.pop(SERVED_MODELS_ENV, None) if served_models is not None: env[SERVED_MODELS_ENV] = served_models_json(served_models) env.pop(TRANSCRIPTION_ENV, None) if transcription is not None: env[TRANSCRIPTION_ENV] = json.dumps(transcription) env.pop(OPENPI_ENV, None) if openpi is not None: env[OPENPI_ENV] = json.dumps(openpi) env.pop(WS_MAX_BYTES_ENV, None) if ws_max_bytes is not None: env[WS_MAX_BYTES_ENV] = str(int(ws_max_bytes)) env[CLIENT_STREAMS_ENV] = json.dumps(sorted(client_streams)) env.pop(REALTIME_ENV, None) if realtime is not None: env[REALTIME_ENV] = json.dumps(realtime) env.pop(LIBSNDFILE_ENV, None) if (libsndfile := soundfile_library()) is not None: env[LIBSNDFILE_ENV] = libsndfile env[OPENAI_ADAPTER_ENV] = openai_adapter_class(model_name) proc = subprocess.Popen([binary, model_name, str(port), bridge_dir, upload_dir], env=env) logger.info("Rust frontend started (pid=%d, port=%d)", proc.pid, port) return proc
def _stream_and_raw_inputs(msg: dict) -> dict: """A submit's ``end_input``, ``file_streams`` and ``raw_inputs``, those it carries: the frontend sends each only when set, so the others keep ``submit_request``'s defaults. ``raw_inputs`` arrive as numpy's ``(dtype.str, shape, bytes)`` and go on as the tensors the model loads.""" extra = {k: msg[k] for k in ("end_input", "file_streams") if msg.get(k) is not None} if raw := msg.get("raw_inputs"): import numpy as np import torch extra["raw_inputs"] = { modality: [ torch.from_numpy(np.frombuffer(a["data"], dtype=np.dtype(a["dtype"])).reshape(a["shape"]).copy()) for a in arrays ] for modality, arrays in raw.items() } return extra
[docs] class RustFrontendBridge: """The serve loop between the Rust frontend and ``APIServer``.""" def __init__(self, server, bridge_dir: str): # Fail fast: the frontend tokenizes when MSTAR_TOKENIZER is set and # ships token ids, which this backend cannot ingest (it owns # tokenization). Reject at launch rather than 500 every request. if os.getenv("MSTAR_TOKENIZER"): raise RuntimeError( "MSTAR_TOKENIZER is set, but the Rust-frontend bridge does " "not support frontend-tokenized (pre-tokenized) ingest — the " "model side owns tokenization. Unset MSTAR_TOKENIZER.") self.server = server # Rust transport with the msgpack codec: we bind as "bridge" in the # PRIVATE bridge dir (that is who the frontend sends to). Named # "bridge", not "conductor", to avoid confusion with M*'s Conductor. self.comm = RustZMQCommunicator( "bridge", push_ids=["frontend"], protocol=CommProtocol.IPC, ipc_socket_path_prefix=bridge_dir, codec=MsgpackCodec) self.running = True # sub -> its submission's key, until its relay ends. self._keys: dict[int, str] = {} # set by _serve; the API server's message thread schedules relay() on it self.loop: asyncio.AbstractEventLoop | None = None # a transcription upload's WindowPlanner, by the frontend's plan id, until it closes self._planners: dict = {} # mstar-server selects LoRA adapters itself, with no round trip per request: # every change to the served set (a runtime load or unload, a conductor's # answer that came after its request timed out) is pushed to it served = getattr(server, "served_models", None) if served is not None: served.subscribe(self._push_served) # -- outbound ---------------------------------------------------------- def _send(self, msg: dict) -> None: self.comm.send("frontend", msg) def _push_served(self, adapters: tuple[str, ...]) -> None: """``ServedModels``' listener: the served adapters, from whichever thread changed them (the conductor's answers arrive on the message thread).""" msg = {"t": "served", "rid": "", "sub": None, "adapters": list(adapters)} loop = self.loop if loop is None: self._send(msg) # not serving yet: nothing else sends return try: loop.call_soon_threadsafe(self._send, msg) except RuntimeError: pass # the loop has closed, and the frontend with it def _err(self, rid: str, sub: int | None, detail: str) -> None: self._send({"t": "err", "rid": rid, "sub": sub, "msg": detail}) def _refuse(self, rid: str, sub: int | None, text: str, status: int) -> None: """``submit_request`` refused the submission: an in-band error chunk, the only reply that carries a status, marked ``refused`` since the request never had its id (``/generate/ws`` answers an unnamed one with null).""" self._send({"t": "chunk", "rid": rid, "sub": sub, "modality": "error", "data": text.encode("utf-8"), "metadata": {"status": status, "refused": True}})
[docs] def relay(self, tags: list[int], chunks: list) -> None: """``ChunkSink.relay``: one ``chunks`` message for a message pass.""" self._send({ "t": "chunks", "subs": tags, "modalities": [c.modality for c in chunks], "payloads": [bytes(c.data) for c in chunks], "metadatas": [c.metadata for c in chunks], })
# -- request lifecycle --------------------------------------------------- def _submit(self, msg: dict) -> None: rid, sub = msg["rid"], msg.get("sub") if msg.get("tokens") is not None: # The Python preprocess worker owns tokenization; run the # frontend without MSTAR_TOKENIZER so it sends text. self._refuse(rid, sub, "pre-tokenized ingest is not supported by this " "backend (unset MSTAR_TOKENIZER)", 500) return try: parts = msg.get("prompt_parts") self.server.submit_request( text=msg.get("text"), file_paths=msg.get("file_paths") or None, input_modalities=list(msg.get("input_modalities") or []), output_modalities=list(msg.get("output_modalities") or ["text"]), model_kwargs=dict(msg.get("model_kwargs") or {}), prompt_parts=[PromptPart(**p) for p in parts] if parts else None, streaming=bool(msg.get("streaming", True)), request_id=rid, report_usage=bool(msg.get("report_usage")), **_stream_and_raw_inputs(msg), ) except (ValueError, TypeError) as e: # a refused input: an in-band error chunk carries its 400 to the client. # A TypeError may be a bug here instead (the two sides' PromptPart # drifting), so it keeps its traceback, as on the router. if isinstance(e, ValueError): logger.info("submit %s refused: %s", rid, e) text = scrub_paths(str(e)) else: text, _ = client_error_text(e, f"submit {rid} failed", log=logger, type_name=False) self._refuse(rid, sub, text, 400) return except Exception as e: # noqa: BLE001 — one bad request must not kill the loop status = getattr(e, "status_code", None) if isinstance(status, int): # An HTTPException (not imported: this bridge runs without # fastapi), e.g. the 409 for a rid still in flight. detail = getattr(e, "detail", e) logger.warning("submit %s refused (%d): %s", rid, status, detail) self._refuse(rid, sub, str(detail), status) return text, _ = client_error_text( e, f"submit {rid} failed", log=logger, type_name=False, ) self._refuse(rid, sub, text, 500) return # Bound to this submission now, not when the task first runs: a later # submit in the same receive batch may reuse the rid. key = self._keys[sub] = self.server.submission_key(rid) if msg.get("accepts_chunks"): self.server.relay_chunks_to(key, self, sub) chunks = self.server.iter_result_chunks(rid) asyncio.get_running_loop().create_task(self._relay(rid, sub, chunks)) async def _relay(self, rid: str, sub: int | None, chunks) -> None: """Forward this request's ResultChunks; terminal err on failure.""" try: async for chunk in chunks: self._send({ "t": "chunk", "rid": rid, "sub": sub, "modality": chunk.modality, "data": bytes(chunk.data), "metadata": chunk.metadata, }) self._send({"t": "done", "rid": rid, "sub": sub}) except Exception as e: # noqa: BLE001 — includes the per-request timeout detail = getattr(e, "detail", None) if detail: detail = str(detail) logger.warning("request %s failed: %s", rid, detail) else: detail, _ = client_error_text( e, f"request {rid} failed", log=logger, type_name=False, ) self._err(rid, sub, detail) finally: self._keys.pop(sub, None) def _abort(self, msg: dict) -> None: """The frontend dropped submission ``sub``; a newer one under its rid (the client's retry) may already be running and is left alone.""" sub = msg.get("sub") if sub is None: self.server.abort_request(msg["rid"]) else: self.server.abort_submission(self._keys.pop(sub, None)) def _metrics(self, msg: dict) -> None: metrics = self.server.metrics reply = {"t": "metrics", "rid": msg["rid"], "sub": msg.get("sub"), "data": b"", "metadata": {}} if metrics is not None: refusals = msg.get("refusals") if refusals is not None: metrics.refusals.update_rust( refusals["route"], refusals["status"], refusals["count"]) reply["data"] = metrics.render() reply["metadata"] = {"content_type": metrics.content_type} self._send(reply) def _check_ref_audio(self, msg: dict) -> None: """``mstar-server`` saved a request's reference clip; the model's own loader judges it (``media_io.check_saved_ref_audio``), off this loop since it decodes. The reply carries the refusal and its status, or no ``error``.""" reply = {"t": "checked", "rid": msg.get("rid"), "sub": msg.get("sub")} async def check() -> None: # every outcome replies: the frontend waits on it before submitting try: from mstar.api_server import media_io path = Path(msg["path"]) # it deletes what it refuses, so only a clip the frontend saved under upload_dir if not path.resolve().is_relative_to(Path(self.server.upload_dir).resolve()): raise RuntimeError(f"ref_audio {path} is outside the upload directory") await asyncio.to_thread( media_io.check_saved_ref_audio, str(path), msg["decoder"], bool(msg.get("bare"))) self._send(reply) except ValueError as exc: self._send({**reply, "error": str(exc), "status": 400}) except Exception: # noqa: BLE001 — the request fails, the bridge goes on logger.exception("bridge: checking a ref_audio clip raised") self._send({**reply, "error": "the server could not check ref_audio", "status": 500}) self.loop.create_task(check()) def _voices(self, msg: dict) -> None: """``GET /v1/audio/voices``' body, asked per request since a model's list can change while it serves (CosyVoice3 lists its voices directory); no ``voices`` in ``metadata`` when the model publishes none (a 404).""" reply = {"t": "voices", "rid": msg.get("rid"), "sub": msg.get("sub"), "data": b"", "metadata": {}} async def answer() -> None: try: from mstar.api_server.openai.serving_speech import list_voices voices = await asyncio.to_thread(list_voices, self.server) if voices is not None: reply["metadata"] = {"voices": voices.model_dump()} self._send(reply) except Exception: # noqa: BLE001 — the request fails, the bridge goes on logger.exception("bridge: listing the voices raised") self._send({"t": "chunk", "rid": msg.get("rid"), "sub": msg.get("sub"), "modality": "error", "data": b"the server could not list the voices", "metadata": {"status": 500}}) self.loop.create_task(answer()) def _live(self, msg: dict) -> None: """One operation on a live call (``/generate/ws``, or a ``/v1/realtime`` conversation, whose appends carry ``audio``: float32 samples for the ``ClientAudio`` stream ``stream``), answered as the Python route would act on it. The call is the submission its ``call`` names; one that has ended has no key and takes nothing.""" key = self._keys.get(msg.get("call")) reply = {"t": "live", "rid": msg.get("rid"), "sub": msg.get("sub"), "data": b"", "metadata": {}} try: op = LiveOp(msg.get("op")) if op is LiveOp.TAKING: meta = {"taking": key is not None and self.server.taking_input(key)} elif op is LiveOp.REJECT: meta = {"rejected": key is not None and self.server.reject_input(key, msg["error"], int(msg["status"]))} elif key is None: meta = {"accepted": False} else: notice, tag, loop = msg.get("notice"), msg.get("tag") or {}, self.loop def on_late(error: str) -> None: # from the preprocess thread: sent from this loop late = {"t": "chunk", "rid": "", "sub": notice, "modality": "late", "data": error.encode("utf-8"), "metadata": tag} try: loop.call_soon_threadsafe(self._send, late) except RuntimeError: pass # the loop has closed, and the frontend with it audio, samples = msg.get("audio"), {} if audio: import numpy as np # copied: torch.from_numpy warns on a read-only buffer samples = {"samples": {msg["stream"]: np.frombuffer(audio, dtype="<f4").copy()}} try: accepted = self.server.stream_input( key, msg.get("file_paths") or None, end_input=msg.get("end_input", False), text=msg.get("text"), file_streams=msg.get("file_streams"), model_kwargs=msg.get("model_kwargs"), on_late=on_late if notice is not None else None, **samples, ) meta = {"accepted": accepted} except ValueError as exc: # the client's fault meta = {"error": scrub_paths(str(exc)), "status": 400} except Exception as exc: # noqa: BLE001 — the append fails, the bridge goes on route = "realtime" if audio else "generate/ws" text, error_id = client_error_text(exc, f"{route} append failed", log=logger, type_name=False) meta = {"error": text, "status": 500, "error_id": error_id} except Exception as exc: # noqa: BLE001 — an unknown op included text, _ = client_error_text(exc, f"live {msg.get('op')!r} failed", log=logger, type_name=False) meta = {"error": text, "status": 500} reply["metadata"] = meta self._send(reply) def _lora(self, msg: dict) -> None: """``/v1/load_lora_adapter`` or ``/v1/unload_lora_adapter``: the API server's ``LoraAdmin`` call, answered with its text or with the error the Python route answers (``exception_status_text``). The served set it changes reaches mstar-server by ``_push_served``.""" reply = {"t": "lora", "rid": msg.get("rid"), "sub": msg.get("sub"), "data": b"", "metadata": {}} route = "/v1/load_lora_adapter" if msg.get("op") == "load" else "/v1/unload_lora_adapter" async def run() -> None: try: admin = getattr(self.server, "lora_admin", None) if admin is None: raise RuntimeError("this API server has no LoRA admin") if msg.get("op") == "load": text = await admin.load(msg.get("lora_name"), msg.get("lora_path")) elif msg.get("op") == "unload": text = await admin.unload(msg.get("lora_name")) else: raise RuntimeError(f"unknown lora operation {msg.get('op')!r}") reply["metadata"] = {"text": text} except Exception as exc: # noqa: BLE001 — the call fails, the bridge goes on status, text = exception_status_text(exc, route, log=logger) reply["metadata"] = {"error": {"status": status, "message": text}} self._send(reply) self.loop.create_task(run()) def _end_of_turn(self, msg: dict) -> None: """``semantic_vad``'s end-of-turn probability of a turn's last audio (float32), by this side's Smart Turn: its int8 model moves by tenths when its features move by 1e-5, so the frontend asks rather than computing the features itself. Off this loop: a call is about 45 ms.""" reply = {"t": "end_of_turn", "rid": msg.get("rid"), "sub": msg.get("sub"), "data": b"", "metadata": {}} async def run() -> None: try: import numpy as np from mstar.api_server.openai import realtime_vad model = realtime_vad.smart_turn() if model is None: raise RuntimeError(realtime_vad.smart_turn_problem()) audio = np.frombuffer(msg["audio"], dtype="<f4") reply["metadata"] = {"p": float(await asyncio.to_thread(model, audio))} except Exception as exc: # noqa: BLE001 — the session goes on without the model logger.exception("bridge: the end-of-turn model failed") reply["metadata"] = {"error": f"{type(exc).__name__}: {exc}"} self._send(reply) self.loop.create_task(run()) def _in_uploads(self, path: Path) -> bool: return path.resolve().is_relative_to(Path(self.server.upload_dir).resolve()) def _windows(self, msg: dict) -> None: """One operation on a transcription upload's ``WindowPlanner``, off this loop since it decodes and writes. A failure is answered as the Python route answers it: its status and message (an ``HTTPException``'s, or ``client_error_text``'s), and the exception's type for a stream's ``transcription failed (<type>)``.""" try: op = WindowOp(msg.get("op")) except ValueError: op = None # answered with an error below plan = msg.get("plan") reply = {"t": "windows", "rid": msg.get("rid"), "sub": msg.get("sub"), "data": b"", "metadata": {}} async def run() -> None: from fastapi import HTTPException from mstar.api_server import media_io from mstar.api_server.openai import serving_transcriptions as st if op is WindowOp.CLOSE: planner = self._planners.pop(plan, None) if planner is not None: await asyncio.to_thread(planner.cleanup) elif msg.get("path") and self._in_uploads(Path(msg["path"])): Path(msg["path"]).unlink(missing_ok=True) return try: if op is None: raise RuntimeError(f"unknown windows operation {msg.get('op')!r}") if op is WindowOp.PLAN: path = Path(msg["path"]) # the planner deletes the upload, so only one the frontend saved under upload_dir if not self._in_uploads(path): raise RuntimeError(f"upload {path} is outside the upload directory") planner = await asyncio.to_thread( st.WindowPlanner, str(path), msg["max_seconds"], Path(self.server.upload_dir), balanced=bool(msg["balanced"]), search_seconds=msg["search_seconds"], frame_seconds=msg["frame_seconds"], whole_seconds=msg["whole_seconds"], ) self._planners[plan] = planner windows = await self._prepare(planner, plan, st, media_io) else: planner = self._planners[plan] if op is WindowOp.FIXED: windows = await asyncio.to_thread(planner.fixed) elif op is WindowOp.AT: windows = [await asyncio.to_thread(planner.window_at, msg["offset"])] else: windows = [await asyncio.to_thread(planner.cut, msg["offset"], msg["duration"])] reply["metadata"] = { "duration": planner.duration, "single": planner.single, "windows": [{"path": w.path, "offset": w.offset, "duration": w.duration} for w in windows], } except Exception as exc: # noqa: BLE001 — the request fails, the bridge goes on status, detail = getattr(exc, "status_code", None), getattr(exc, "detail", None) if isinstance(status, int) and detail is not None: message = str(detail) else: message, _ = client_error_text( exc, "/v1/audio/transcriptions request failed", log=logger, type_name=False) if not isinstance(status, int): status = 400 if isinstance(exc, (ValueError, TypeError)) else 500 reply["metadata"] = {"error": { "status": status, "message": message, "http": isinstance(exc, HTTPException), "type": type(exc).__name__, }} self._send(reply) self.loop.create_task(run()) async def _prepare(self, planner, plan, st, media_io) -> list: """``create_transcription``'s checks on a new upload: past the cap by its header, then decoded when it will be windowed; a refusal deletes it.""" from fastapi import HTTPException def refuse(status: int, detail: str): self._planners.pop(plan, None) planner.cleanup() return HTTPException(status_code=status, detail=detail) if planner.duration is not None and planner.duration > st.MAX_DURATION_SECONDS: raise refuse(413, f"audio is {planner.duration:.0f} s; the limit is {st.MAX_DURATION_SECONDS} s") try: if planner.decodes: await asyncio.to_thread(planner.prepare) except media_io.AudioTooLongError: raise refuse(413, f"audio is longer than the {st.MAX_DURATION_SECONDS} s limit") from None except ValueError as exc: raise refuse(400, str(exc)) from None except BaseException: self._planners.pop(plan, None) planner.cleanup() raise return [] def _handle(self, msg: dict) -> None: t = msg.get("t") if t == "submit": self._submit(msg) elif t == "abort": self._abort(msg) elif t == "ping": # Deep-health liveness: the frontend's /health goes red # unless this loop answers. self._send({"t": "pong", "rid": msg["rid"], "sub": msg.get("sub")}) elif t == "metrics": self._metrics(msg) elif t == "check_ref_audio": self._check_ref_audio(msg) elif t == "voices": self._voices(msg) elif t == "windows": self._windows(msg) elif t == "live": self._live(msg) elif t == "lora": self._lora(msg) elif t == "end_of_turn": self._end_of_turn(msg) else: logger.warning("bridge: unknown message type %r", t) # -- loop ---------------------------------------------------------------- async def _serve(self) -> None: logger.info("Rust-frontend bridge serving") loop = self.loop = asyncio.get_running_loop() # asyncio would start its default pool from this thread, and so on # the result CPU when the bridge is pinned; handlers' to_thread work # (audio planning, request decoding) belongs on the process mask loop.set_default_executor(ThreadPool(thread_name_prefix="mstar-bridge")) # Blocking receive on an executor thread: the wait happens inside the # transport (GIL released), so an arriving submit is picked up # immediately instead of on the next tick of a sleep/poll loop — and # an idle bridge costs no wakeups. The event loop itself stays free # to run the per-request relay tasks; `send` is safe from those # concurrently (the transport serializes its push sockets internally). recv = lambda: self.comm.get_all_new_messages( # noqa: E731 blocking=True, timeout_s=BRIDGE_RECV_WAIT_S) while self.running: for msg in await loop.run_in_executor(None, recv): # Per-message isolation: FastAPI turns a handler exception into # one 500 and keeps serving. The bridge must restore that — a # failure in any branch (a bad `rid` lookup in abort, a codec # decode error surfacing as a malformed msg, a send failure) # would otherwise propagate out of `_serve` → `run()` → # `entrypoint.py`'s `finally`, which terminates the Rust process # and takes the whole server down. `_submit` is already wrapped; # this guards every other branch. try: self._handle(msg) except Exception: # noqa: BLE001 — one bad message must not kill the loop logger.exception("bridge: dropping a message that raised (%r)", msg.get("t"))
[docs] def run(self, frontend: subprocess.Popen | None = None) -> None: """Blocking serve loop (the ``uvicorn.run`` replacement). The first SIGINT or SIGTERM goes on to ``frontend`` (mstar-server), and the loop keeps relaying tokens while it drains its in-flight requests, as uvicorn does on a graceful shutdown; its exit then stops the loop (``_stop_with`` in ``entrypoint.py``). A second signal, or one with no frontend running, stops the loop at once.""" # with the message thread: tokens pass from it to this loop. The Rust # process is already running, so it keeps the process mask. Test doubles # stand in for the server without the pin. pin = getattr(self.server, "pin_result_thread", None) if pin is not None: pin() # The bridge installs its own handlers: asyncio.run installs a SIGINT # handler only over Python's default one, and a server started as a # background job inherits SIGINT ignored (tokio's handlers in # mstar-server replace an inherited SIG_IGN) signals = 0 def stop(signum, frame): nonlocal signals signals += 1 if signals == 1 and frontend is not None and frontend.poll() is None: frontend.send_signal(signum) else: self.running = False handled = (signal.SIGINT, signal.SIGTERM) on_main = threading.current_thread() is threading.main_thread() previous = {sig: signal.signal(sig, stop) for sig in handled} if on_main else {} try: asyncio.run(self._serve()) except KeyboardInterrupt: pass finally: for sig, handler in previous.items(): signal.signal(sig, handler)
[docs] def stop(self) -> None: self.running = False # the uploads of transcriptions still running go with the frontend for planner in list(self._planners.values()): planner.cleanup() self._planners.clear()