Switchyard lets LLM applications route traffic across models and providers while preserving native OpenAI and Anthropic API compatibility - enabling flexible model selection, benchmarking, and cost/performance optimization.
Rust
chore: remove unused OSS-router plugin routing (#85)
ryan-lempka93f0e3eaea1c
diff --git a/.agents/skills/switchyard-lib-core/SKILL.md b/.agents/skills/switchyard-lib-core/SKILL.mdindex d66934c34..7a1207663 100644--- a/.agents/skills/switchyard-lib-core/SKILL.md+++ b/.agents/skills/switchyard-lib-core/SKILL.md@@ -63,8 +63,8 @@ Profile-owned construction keeps the full behavior in one reviewable module:existing Python endpoint contract.Random routing, deterministic routing, escalation-router, plan-execute,-passthrough, no-op, stage-router, latency-service, and OSS-router-profiles are the reference set under `switchyard/lib/profiles/`.+passthrough, no-op, stage-router, and latency-service profiles are the+reference set under `switchyard/lib/profiles/`.## Anti-Patternsdiff --git a/switchyard/__init__.py b/switchyard/__init__.pyindex e3126c4b6..ce9bbb556 100644--- a/switchyard/__init__.py+++ b/switchyard/__init__.py@@ -61,9 +61,6 @@ from switchyard.lib.profiles import (LatencyServiceProfileConfig,NoopProfile,NoopProfileConfig,- OSSRouterConfig,- OSSRouterProfileConfig,- OSSRouterTier,PassthroughProfileConfig,PlanExecuteConfig,PlanExecutePresets,@@ -164,9 +161,6 @@ __all__ = ["EscalationRouterConfig","EscalationRouterProfileConfig","LatencyServiceProfileConfig",- "OSSRouterConfig",- "OSSRouterProfileConfig",- "OSSRouterTier","PassthroughProfileConfig","PlanExecuteConfig","PlanExecuteProfileConfig",@@ -209,7 +203,6 @@ __all__ = ["IntakeSinkConfig","RlLoggingRequestProcessor","RlLoggingResponseProcessor",- # OSS Router (external-process plugin)# Random Routing usage case"BackendFormat","RandomRoutingProcessorConfig",diff --git a/switchyard/lib/plugin/__init__.py b/switchyard/lib/plugin/__init__.pydeleted file mode 100644index cbcb09713..000000000--- a/switchyard/lib/plugin/__init__.py+++ /dev/null@@ -1,43 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""External-process routing plugin contract.--See :mod:`switchyard.lib.plugin.plugin_protocol` for the wire schema and-:mod:`switchyard.lib.plugin.plugin_client` for the in-process client that-spawns the plugin and routes requests over its stdio channel.-"""--from switchyard.lib.plugin.plugin_client import (- PluginClient,- PluginCrashError,- PluginHandshakeError,- PluginRoutingError,- PluginTimeoutError,-)-from switchyard.lib.plugin.plugin_protocol import (- PROTOCOL_VERSION,- HandshakeRequest,- HandshakeResponse,- RouteDecision,- RouteError,- RouteRequest,- RouteResult,- RoutingRequestSummary,-)--__all__ = [- "PROTOCOL_VERSION",- "HandshakeRequest",- "HandshakeResponse",- "PluginClient",- "PluginCrashError",- "PluginHandshakeError",- "PluginRoutingError",- "PluginTimeoutError",- "RouteDecision",- "RouteError",- "RouteRequest",- "RouteResult",- "RoutingRequestSummary",-]diff --git a/switchyard/lib/plugin/plugin_client.py b/switchyard/lib/plugin/plugin_client.pydeleted file mode 100644index 18fa4bdb3..000000000--- a/switchyard/lib/plugin/plugin_client.py+++ /dev/null@@ -1,461 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""Client for an external-process routing plugin.--Owns the plugin's lifecycle: spawn the subprocess, perform the handshake,-multiplex JSON-RPC requests over its stdio, surface stderr as logs, and-terminate it gracefully on shutdown. One :class:`PluginClient` per chain.--Crash recovery: a single-shot recovery is attempted on read failure-(plugin process died mid-conversation). Exceeding the configured restart-budget makes the next ``route`` raise :class:`PluginCrashError`, which-the request processor turns into either a fail-closed error response or-a fallback-tier dispatch depending on operator config.-"""--from __future__ import annotations--import asyncio-import contextlib-import json-import logging-import os-import shlex-from collections.abc import Sequence-from typing import Any--from switchyard.lib.plugin.plugin_protocol import (- PROTOCOL_VERSION,- HandshakeRequest,- HandshakeResponse,- RouteDecision,- RouteError,- RouteRequest,- RouteResult,-)--log = logging.getLogger(__name__)---class PluginError(Exception):- """Base class for routing-plugin errors."""---class PluginHandshakeError(PluginError):- """Plugin failed the startup handshake (version mismatch, exit, timeout)."""---class PluginTimeoutError(PluginError):- """Plugin did not respond to a ``route`` request within the configured timeout."""---class PluginCrashError(PluginError):- """Plugin process died and exhausted its restart budget."""---class PluginRoutingError(PluginError):- """Plugin returned a malformed or invalid response to a ``route`` request."""---class PluginClient:- """Long-lived client for a single external routing plugin.-- Spawn via :meth:`start` — which performs the handshake — then call- :meth:`route` per inbound request. Multiple concurrent ``route``- calls are multiplexed over the plugin's stdio by JSON-RPC ``id``.-- The plugin's stderr is forwarded to the ``switchyard.plugin.<name>``- logger so plugin diagnostics show up alongside Switchyard's own- logs without losing the plugin/proxy attribution.- """-- def __init__(- self,- *,- command: Sequence[str],- available_tiers: tuple[str, ...],- request_timeout_s: float,- handshake_timeout_s: float,- env: dict[str, str] | None = None,- ) -> None:- if not command:- raise ValueError("PluginClient requires a non-empty command")- if not available_tiers:- raise ValueError("PluginClient requires at least one available tier label")-- self._command: tuple[str, ...] = tuple(command)- self._available_tiers = available_tiers- self._request_timeout_s = request_timeout_s- self._handshake_timeout_s = handshake_timeout_s- self._env = env-- self._process: asyncio.subprocess.Process | None = None- self._reader_task: asyncio.Task[None] | None = None- self._stderr_task: asyncio.Task[None] | None = None- self._pending: dict[int, asyncio.Future[dict[str, Any]]] = {}- self._next_id = 1- self._send_lock = asyncio.Lock()- self._handshake: HandshakeResponse | None = None- self._closed = False-- # ------------------------------------------------------------------- # Construction / handshake- # -------------------------------------------------------------------- @classmethod- def parse_command(cls, command: str | Sequence[str]) -> tuple[str, ...]:- """Accept either a shell string or a pre-split argv sequence."""- if isinstance(command, str):- return tuple(shlex.split(command))- return tuple(command)-- @classmethod- async def start(- cls,- *,- command: str | Sequence[str],- available_tiers: Sequence[str],- request_timeout_s: float = 5.0,- handshake_timeout_s: float = 10.0,- env: dict[str, str] | None = None,- ) -> PluginClient:- """Spawn the plugin and run the handshake.-- Returns a ready-to-use client, or raises :class:`PluginHandshakeError`- if the plugin failed to start, the handshake timed out, or the- plugin advertised an incompatible protocol version.- """- client = cls(- command=cls.parse_command(command),- available_tiers=tuple(available_tiers),- request_timeout_s=request_timeout_s,- handshake_timeout_s=handshake_timeout_s,- env=env,- )- await client._spawn()- await client._handshake_exchange()- return client-- async def _spawn(self) -> None:- """Start the subprocess and the background stdout/stderr readers."""- try:- self._process = await asyncio.create_subprocess_exec(- *self._command,- stdin=asyncio.subprocess.PIPE,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- env={**os.environ, **(self._env or {})} if self._env else None,- )- except (FileNotFoundError, PermissionError) as exc:- raise PluginHandshakeError(- f"Failed to spawn plugin {self._command!r}: {exc}",- ) from exc-- # asyncio.create_subprocess_exec attaches PIPE streams when requested,- # so the optional streams are guaranteed non-None here.- assert self._process.stdout is not None- assert self._process.stderr is not None- self._reader_task = asyncio.create_task(- self._read_loop(self._process.stdout),- name="plugin-stdout-reader",- )- self._stderr_task = asyncio.create_task(- self._stderr_loop(self._process.stderr),- name="plugin-stderr-reader",- )-- async def _handshake_exchange(self) -> None:- request = HandshakeRequest(- switchyard_protocol_version=PROTOCOL_VERSION,- available_tiers=self._available_tiers,- )- try:- envelope = await asyncio.wait_for(- self._call_method("handshake", request.to_params()),- timeout=self._handshake_timeout_s,- )- except TimeoutError as exc:- await self._abort()- raise PluginHandshakeError(- f"Plugin {self._command[0]!r} did not complete handshake within "- f"{self._handshake_timeout_s}s",- ) from exc- except PluginError as exc:- await self._abort()- raise PluginHandshakeError(str(exc)) from exc-- if "error" in envelope:- await self._abort()- err = envelope["error"]- message = err.get("message") if isinstance(err, dict) else repr(err)- raise PluginHandshakeError(- f"Plugin {self._command[0]!r} rejected handshake: {message}",- )-- result = envelope.get("result")- if not isinstance(result, dict):- await self._abort()- raise PluginHandshakeError(- f"Plugin {self._command[0]!r} returned envelope without "- f"result: {envelope!r}",- )- try:- handshake = HandshakeResponse.from_result(result)- except (KeyError, TypeError, ValueError) as exc:- await self._abort()- raise PluginHandshakeError(- f"Plugin {self._command[0]!r} returned malformed handshake: {result!r}",- ) from exc-- if handshake.protocol_version != PROTOCOL_VERSION:- await self._abort()- raise PluginHandshakeError(- f"Plugin {handshake.plugin_name!r} speaks protocol "- f"v{handshake.protocol_version}, Switchyard speaks "- f"v{PROTOCOL_VERSION}",- )-- self._handshake = handshake- log.info(- "PluginClient: handshake OK plugin=%s version=%s opt_in=%s",- handshake.plugin_name,- handshake.plugin_version,- handshake.opt_in_fields,- )-- # ------------------------------------------------------------------- # Public API- # -------------------------------------------------------------------- @property- def handshake(self) -> HandshakeResponse:- """Plugin's handshake response. Raises if start() hasn't completed."""- if self._handshake is None:- raise RuntimeError("PluginClient.start() has not completed")- return self._handshake-- async def route(self, request: RouteRequest) -> RouteResult:- """Ask the plugin to make a routing decision for a request.-- Returns either :class:`RouteDecision` or :class:`RouteError`. The- caller decides what to do with the error (fail-closed vs fallback).- Raises :class:`PluginTimeoutError` / :class:`PluginCrashError` /- :class:`PluginRoutingError` for plugin-side failures the caller- cannot recover from.- """- if self._closed:- raise PluginCrashError("PluginClient has been shut down")- if self._process is None or self._process.returncode is not None:- raise PluginCrashError(- f"Plugin {self._command[0]!r} is not running "- f"(exit code {self._process.returncode if self._process else 'n/a'})",- )-- try:- envelope = await asyncio.wait_for(- self._call_method("route", request.to_params()),- timeout=self._request_timeout_s,- )- except TimeoutError as exc:- raise PluginTimeoutError(- f"Plugin {self._handshake_name()!r} did not respond to "- f"route within {self._request_timeout_s}s",- ) from exc-- return self._classify_route_envelope(envelope, available=request.available_tiers)-- async def shutdown(self) -> None:- """Terminate the plugin gracefully.-- Closes stdin (most well-behaved plugins exit on EOF), waits up to- 2 seconds for the process to exit, then escalates to SIGTERM and- finally SIGKILL. Idempotent — safe to call from multiple shutdown- paths.- """- if self._closed:- return- self._closed = True- await self._abort()-- # ------------------------------------------------------------------- # Internals- # -------------------------------------------------------------------- def _handshake_name(self) -> str:- return self._handshake.plugin_name if self._handshake else self._command[0]-- async def _call_method(self, method: str, params: dict[str, Any]) -> dict[str, Any]:- """Send a JSON-RPC request and await its response.-- Returns the raw ``result`` payload; raises :class:`PluginRoutingError`- if the plugin returned a JSON-RPC error envelope (callers translate- that into a user-facing failure).- """- if self._process is None or self._process.stdin is None:- raise PluginCrashError(- f"Plugin {self._command[0]!r} is not running",- )-- request_id = self._next_id- self._next_id += 1- future: asyncio.Future[dict[str, Any]] = asyncio.get_event_loop().create_future()- self._pending[request_id] = future-- envelope = {- "jsonrpc": "2.0",- "id": request_id,- "method": method,- "params": params,- }- line = (json.dumps(envelope) + "\n").encode("utf-8")- async with self._send_lock:- try:- self._process.stdin.write(line)- await self._process.stdin.drain()- except (BrokenPipeError, ConnectionResetError) as exc:- self._pending.pop(request_id, None)- raise PluginCrashError(- f"Plugin {self._command[0]!r} closed stdin mid-request",- ) from exc-- try:- return await future- finally:- self._pending.pop(request_id, None)-- async def _read_loop(self, stdout: asyncio.StreamReader) -> None:- """Read JSON-RPC responses, dispatch to pending futures by ``id``."""- try:- while True:- line = await stdout.readline()- if not line:- break- try:- envelope = json.loads(line)- except json.JSONDecodeError:- log.warning(- "PluginClient: dropping non-JSON line from %s: %r",- self._command[0],- line[:200],- )- continue- self._dispatch_envelope(envelope)- except asyncio.CancelledError:- raise- except Exception:- log.exception("PluginClient: stdout reader crashed")- finally:- # Plugin closed stdout; fail any in-flight callers so they- # don't hang forever waiting on a future nobody will resolve.- for future in self._pending.values():- if not future.done():- future.set_exception(- PluginCrashError(- f"Plugin {self._command[0]!r} closed stdout",- ),- )- self._pending.clear()-- def _dispatch_envelope(self, envelope: Any) -> None:- if not isinstance(envelope, dict):- log.warning("PluginClient: ignoring non-object JSON: %r", envelope)- return- message_id = envelope.get("id")- if not isinstance(message_id, int):- log.warning("PluginClient: ignoring envelope without int id: %r", envelope)- return- future = self._pending.get(message_id)- if future is None or future.done():- return- future.set_result(envelope)-- async def _stderr_loop(self, stderr: asyncio.StreamReader) -> None:- """Forward plugin stderr to the per-plugin logger."""- plugin_logger = logging.getLogger(- f"switchyard.plugin.{self._safe_logger_name()}",- )- try:- while True:- line = await stderr.readline()- if not line:- break- plugin_logger.info(line.rstrip(b"\n").decode("utf-8", errors="replace"))- except asyncio.CancelledError:- raise- except Exception:- log.exception("PluginClient: stderr reader crashed")-- def _safe_logger_name(self) -> str:- if self._handshake is not None:- return self._handshake.plugin_name.replace(".", "_") or "unnamed"- return os.path.basename(self._command[0]).replace(".", "_") or "unnamed"-- def _classify_route_envelope(- self,- envelope: dict[str, Any],- *,- available: tuple[str, ...],- ) -> RouteResult:- """Turn a JSON-RPC envelope into a :class:`RouteResult`."""- if "error" in envelope:- err = envelope["error"]- if not isinstance(err, dict):- raise PluginRoutingError(- f"Plugin {self._handshake_name()!r} returned non-object error: "- f"{envelope!r}",- )- data = err.get("data") or {}- fallback = data.get("fallback") if isinstance(data, dict) else None- return RouteError(- code=int(err.get("code", -32000)),- message=str(err.get("message", "<no message>")),- fallback_tier=str(fallback) if isinstance(fallback, str) else None,- )-- result = envelope.get("result")- if not isinstance(result, dict):- raise PluginRoutingError(- f"Plugin {self._handshake_name()!r} returned envelope without "- f"result: {envelope!r}",- )- tier = result.get("tier")- if not isinstance(tier, str):- raise PluginRoutingError(- f"Plugin {self._handshake_name()!r} omitted 'tier' from route result: "- f"{result!r}",- )- if tier not in available:- raise PluginRoutingError(- f"Plugin {self._handshake_name()!r} returned unknown tier {tier!r}; "- f"expected one of {sorted(available)}",- )- metadata = result.get("metadata") or {}- if not isinstance(metadata, dict):- metadata = {}- return RouteDecision(tier=tier, metadata=metadata)-- async def _abort(self) -> None:- """Tear down the subprocess + reader tasks. Idempotent."""- process = self._process- if process is not None and process.returncode is None:- with contextlib.suppress(ProcessLookupError):- if process.stdin is not None and not process.stdin.is_closing():- process.stdin.close()- try:- await asyncio.wait_for(process.wait(), timeout=2.0)- except TimeoutError:- with contextlib.suppress(ProcessLookupError):- process.terminate()- try:- await asyncio.wait_for(process.wait(), timeout=2.0)- except TimeoutError:- with contextlib.suppress(ProcessLookupError):- process.kill()- await process.wait()-- for task in (self._reader_task, self._stderr_task):- if task is not None and not task.done():- task.cancel()- with contextlib.suppress(asyncio.CancelledError, Exception):- await taskdiff --git a/switchyard/lib/plugin/plugin_protocol.py b/switchyard/lib/plugin/plugin_protocol.pydeleted file mode 100644index 609d667e3..000000000--- a/switchyard/lib/plugin/plugin_protocol.py+++ /dev/null@@ -1,166 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""Wire protocol for the external-process routing plugin.--The plugin and Switchyard speak JSON-RPC 2.0 over the plugin's stdio. Each-message is one newline-terminated JSON object. The plugin reads requests-from stdin, writes responses to stdout, and may log to stderr — Switchyard-captures the stderr stream and tags log lines with the plugin name.--Two RPC methods exist in v1:--* ``handshake`` — exchanged once at startup; lets Switchyard fail closed- on protocol-version mismatch before any traffic flows.-* ``route`` — called per inbound request; the plugin returns the tier- label to dispatch to (e.g. ``"strong"`` / ``"weak"``).--A ``health`` ping and a ``shutdown`` notification are reserved for v2 —-SIGTERM is the source of truth for shutdown today.--This module owns the typed dataclasses for every payload. Marshalling-to/from JSON-RPC envelopes lives in :mod:`switchyard.lib.plugin.plugin_client`.-"""--from __future__ import annotations--from dataclasses import dataclass, field-from typing import Any--#: Wire-format version. Bumped on any breaking change to the request or-#: response schemas. The plugin advertises the version it speaks during-#: ``handshake``; Switchyard fails closed if the values don't match.-PROTOCOL_VERSION = 1---# ----------------------------------------------------------------------------# handshake-# ------------------------------------------------------------------------------@dataclass(frozen=True)-class HandshakeRequest:- """Sent by Switchyard once, immediately after spawning the plugin.-- Tells the plugin what protocol version Switchyard speaks and which- tier labels it may legally return from ``route``. Plugins MUST reject- the handshake (by returning a JSON-RPC error) if any of these are- incompatible — Switchyard treats that as a startup failure.- """-- switchyard_protocol_version: int- available_tiers: tuple[str, ...]-- def to_params(self) -> dict[str, Any]:- return {- "switchyard_protocol_version": self.switchyard_protocol_version,- "available_tiers": list(self.available_tiers),- }---@dataclass(frozen=True)-class HandshakeResponse:- """Plugin's reply to ``handshake``.-- ``opt_in_fields`` lets a plugin request optional payload fields (e.g.- ``"raw_messages"`` for a semantic router) — the operator's allowlist- decides whether Switchyard honours each request.- """-- protocol_version: int- plugin_name: str- plugin_version: str- opt_in_fields: tuple[str, ...] = ()-- @classmethod- def from_result(cls, result: dict[str, Any]) -> HandshakeResponse:- return cls(- protocol_version=int(result["protocol_version"]),- plugin_name=str(result.get("plugin_name", "<unnamed>")),- plugin_version=str(result.get("plugin_version", "0.0.0")),- opt_in_fields=tuple(result.get("opt_in_fields", ())),- )---# ----------------------------------------------------------------------------# route-# ------------------------------------------------------------------------------@dataclass(frozen=True)-class RoutingRequestSummary:- """The minimal request signal Switchyard always sends to the plugin.-- Excludes raw message content and backend credentials by design. A- plugin that needs richer signal must declare it via- :attr:`HandshakeResponse.opt_in_fields` and the operator must- explicitly allowlist that opt-in.- """-- input_token_estimate: int- message_count: int- has_tool_use: bool- tool_names: tuple[str, ...] = ()- system_prompt_fingerprint: str | None = None-- def to_dict(self) -> dict[str, Any]:- out: dict[str, Any] = {- "input_token_estimate": self.input_token_estimate,- "message_count": self.message_count,- "has_tool_use": self.has_tool_use,- "tool_names": list(self.tool_names),- }- if self.system_prompt_fingerprint is not None:- out["system_prompt_fingerprint"] = self.system_prompt_fingerprint- return out---@dataclass(frozen=True)-class RouteRequest:- """Per-request payload Switchyard sends on every ``route`` call."""-- request_id: str- available_tiers: tuple[str, ...]- summary: RoutingRequestSummary- metadata: dict[str, Any] = field(default_factory=dict)-- def to_params(self) -> dict[str, Any]:- return {- "request_id": self.request_id,- "available_tiers": list(self.available_tiers),- "summary": self.summary.to_dict(),- "metadata": dict(self.metadata),- }---@dataclass(frozen=True)-class RouteDecision:- """Successful routing decision returned by the plugin.-- ``tier`` MUST be one of the labels Switchyard advertised via- :attr:`RouteRequest.available_tiers`. Anything else surfaces as- :class:`PluginRoutingError` with structured ``error.code``.- """-- tier: str- metadata: dict[str, Any] = field(default_factory=dict)---@dataclass(frozen=True)-class RouteError:- """Plugin signalled a per-request failure.-- ``fallback_tier`` is an optional hint — when set, and when the- operator opted into fallbacks, Switchyard dispatches to that tier- instead of failing the request closed.- """-- code: int- message: str- fallback_tier: str | None = None---#: Discriminated-union return type for ``route``. The client classifies the-#: JSON-RPC envelope and returns one of these two shapes; callers branch on-#: ``isinstance`` to handle the two outcomes.-RouteResult = RouteDecision | RouteErrordiff --git a/switchyard/lib/processors/plugin_routing_request_processor.py b/switchyard/lib/processors/plugin_routing_request_processor.pydeleted file mode 100644index 7c831237b..000000000--- a/switchyard/lib/processors/plugin_routing_request_processor.py+++ /dev/null@@ -1,319 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""Request processor that asks an external routing plugin which tier to use.--The processor owns the :class:`PluginClient` lifecycle through the-``startup`` / ``shutdown`` hooks on the component. On each-inbound request it builds a normalized-:class:`RoutingRequestSummary`, asks the plugin for a tier label, and-stamps the selected target/model on ``ProxyContext`` so the downstream-``MultiLlmBackend`` can dispatch.--When the plugin fails — timeout, crash, malformed response, or an-explicit error envelope — the processor either falls back to the-configured ``fallback_tier`` (if the operator opted in) or re-raises so-the chain returns a 5xx upstream. Failures are logged at ``warning``-level so operators can spot misbehaving plugins without grepping debug.-"""--from __future__ import annotations--import logging-import uuid-from collections.abc import Mapping, Sequence-from typing import TYPE_CHECKING, Any--from switchyard.lib.plugin import (- PluginClient,- PluginCrashError,- PluginRoutingError,- PluginTimeoutError,- RouteDecision,- RouteError,- RouteRequest,- RoutingRequestSummary,-)-from switchyard_rust.components import set_stats_route_label--if TYPE_CHECKING:- from switchyard.lib.proxy_context import ProxyContext- from switchyard_rust.core import ChatRequest--log = logging.getLogger(__name__)--# Compatibility metadata key; Rust ``MultiLlmBackend`` dispatches from-# ``ProxyContext.selected_target``.-CTX_OSS_ROUTER_TIER = "_oss_router_tier"---class PluginRoutingRequestProcessor:- """Calls an external plugin to choose a tier per request.-- Args:- plugin_command: Argv (or shell string) for the plugin executable.- tier_models: Mapping of tier label → model id. The labels are- sent to the plugin via the handshake's ``available_tiers``;- the model id is what gets written into ``request.body["model"]``- after the plugin picks. Insertion order matters: the first- entry is the defensive default.- fallback_tier: Optional tier label to dispatch to when the plugin- returns an error or fails to respond. ``None`` re-raises so- the chain returns 5xx.- request_timeout_s / handshake_timeout_s: Plumbed through to the- :class:`PluginClient`.- env: Optional extra env vars merged on top of the proxy's- environment when spawning the plugin.- expose_metadata_keys: Whitelist of ``ctx.metadata`` keys to forward- to the plugin (off by default — plugins see only the request- summary unless the operator opts specific keys in).- """-- def __init__(- self,- *,- plugin_command: str | Sequence[str],- tier_models: Mapping[str, str],- tier_target_ids: Mapping[str, str] | None = None,- fallback_tier: str | None = None,- request_timeout_s: float = 5.0,- handshake_timeout_s: float = 10.0,- env: dict[str, str] | None = None,- expose_metadata_keys: Sequence[str] = (),- ) -> None:- if not tier_models:- raise ValueError("PluginRoutingRequestProcessor requires at least one tier")- if fallback_tier is not None and fallback_tier not in tier_models:- raise ValueError(- f"fallback_tier {fallback_tier!r} is not in tier_models "- f"{sorted(tier_models)}",- )-- self._plugin_command = plugin_command- self._tier_models: dict[str, str] = dict(tier_models)- self._tier_target_ids: dict[str, str] = dict(tier_target_ids or tier_models)- self._tier_labels: tuple[str, ...] = tuple(self._tier_models)- self._fallback_tier = fallback_tier- self._request_timeout_s = request_timeout_s- self._handshake_timeout_s = handshake_timeout_s- self._env = env- self._expose_metadata_keys = tuple(expose_metadata_keys)-- self._client: PluginClient | None = None-- # ------------------------------------------------------------------- # Lifecycle- # -------------------------------------------------------------------- async def startup(self) -> None:- if self._client is not None:- return- self._client = await PluginClient.start(- command=self._plugin_command,- available_tiers=self._tier_labels,- request_timeout_s=self._request_timeout_s,- handshake_timeout_s=self._handshake_timeout_s,- env=self._env,- )-- async def shutdown(self) -> None:- if self._client is None:- return- try:- await self._client.shutdown()- finally:- self._client = None-- # ------------------------------------------------------------------- # Hot path- # -------------------------------------------------------------------- async def process(- self,- ctx: ProxyContext,- request: ChatRequest,- ) -> ChatRequest:- client = self._client- if client is None:- raise RuntimeError(- "PluginRoutingRequestProcessor used without startup(); "- "callers must await startup() before the first request",- )-- request_id = ctx.metadata.get("request_id")- if not isinstance(request_id, str):- request_id = str(uuid.uuid4())-- route_request = RouteRequest(- request_id=request_id,- available_tiers=self._tier_labels,- summary=_summarize_request(request),- metadata=self._exposed_metadata(ctx),- )-- try:- outcome = await client.route(route_request)- except (PluginTimeoutError, PluginCrashError, PluginRoutingError) as exc:- return self._handle_failure(ctx, request, exc=exc)-- if isinstance(outcome, RouteError):- return self._handle_route_error(ctx, request, outcome)- return self._apply_decision(ctx, request, outcome)-- # ------------------------------------------------------------------- # Helpers- # -------------------------------------------------------------------- def _apply_decision(- self,- ctx: ProxyContext,- request: ChatRequest,- decision: RouteDecision,- ) -> ChatRequest:- # _classify_route_envelope already validated the tier; this is just- # a defensive guard in case a future client path bypasses that.- if decision.tier not in self._tier_models:- return self._handle_failure(- ctx,- request,- exc=PluginRoutingError(- f"Plugin returned unknown tier {decision.tier!r}",- ),- )- self._stamp(ctx, decision.tier, plugin_metadata=decision.metadata)- request.set_model(self._tier_models[decision.tier])- return request-- def _handle_route_error(- self,- ctx: ProxyContext,- request: ChatRequest,- outcome: RouteError,- ) -> ChatRequest:- # Prefer the plugin-suggested fallback when it advertised one and- # we know the label; otherwise fall through to the operator-configured- # fallback. Operator config is the source of truth — plugins can hint- # but cannot override.- candidate = outcome.fallback_tier if outcome.fallback_tier in self._tier_models else None- chosen = candidate or self._fallback_tier- log.warning(- "PluginRoutingRequestProcessor: plugin returned error code=%d msg=%r "- "fallback=%r resolved=%r",- outcome.code,- outcome.message,- outcome.fallback_tier,- chosen,- )- if chosen is None:- raise PluginRoutingError(- f"Plugin returned error: code={outcome.code} message={outcome.message!r}",- )- self._stamp(- ctx,- chosen,- plugin_metadata={"fallback_reason": outcome.message, "fallback_code": outcome.code},- )- request.set_model(self._tier_models[chosen])- return request-- def _handle_failure(- self,- ctx: ProxyContext,- request: ChatRequest,- *,- exc: Exception,- ) -> ChatRequest:- if self._fallback_tier is None:- raise exc- log.warning(- "PluginRoutingRequestProcessor: plugin failure %s: %s; "- "dispatching to fallback tier %r",- type(exc).__name__,- exc,- self._fallback_tier,- )- self._stamp(- ctx,- self._fallback_tier,- plugin_metadata={"fallback_reason": str(exc), "fallback_exception": type(exc).__name__},- )- request.set_model(self._tier_models[self._fallback_tier])- return request-- def _stamp(- self,- ctx: ProxyContext,- tier: str,- *,- plugin_metadata: Mapping[str, Any],- ) -> None:- ctx.metadata[CTX_OSS_ROUTER_TIER] = tier- ctx.metadata["_oss_router_model"] = self._tier_models[tier]- set_stats_route_label(ctx, tier)- ctx.selected_target = self._tier_target_ids[tier]- ctx.selected_model = self._tier_models[tier]- if plugin_metadata:- ctx.metadata["_oss_router_plugin_metadata"] = dict(plugin_metadata)-- def _exposed_metadata(self, ctx: ProxyContext) -> dict[str, Any]:- if not self._expose_metadata_keys:- return {}- return {- key: ctx.metadata[key]- for key in self._expose_metadata_keys- if key in ctx.metadata- }---# ----------------------------------------------------------------------------# Request summarizer-# ------------------------------------------------------------------------------def _summarize_request(request: ChatRequest) -> RoutingRequestSummary:- """Build the minimal opt-out-by-default summary we send the plugin.-- Defensive against malformed bodies — plugins should never hard-fail- Switchyard, so each field falls back to a safe default rather than- raising.- """- body: dict[str, Any] = getattr(request, "body", {}) or {}- messages = body.get("messages") or []- if not isinstance(messages, list):- messages = []-- tools = body.get("tools") or []- tool_names: list[str] = []- if isinstance(tools, list):- for tool in tools:- if isinstance(tool, dict):- # OpenAI Chat: {"function": {"name": ...}}; Anthropic: {"name": ...}- fn = tool.get("function") if isinstance(tool.get("function"), dict) else None- name = (fn or tool).get("name") if isinstance(fn or tool, dict) else None- if isinstance(name, str):- tool_names.append(name)-- return RoutingRequestSummary(- input_token_estimate=_rough_token_estimate(messages),- message_count=len(messages),- has_tool_use=bool(tool_names),- tool_names=tuple(tool_names),- )---def _rough_token_estimate(messages: list[Any]) -> int:- """4-chars-per-token heuristic — fine for routing decisions, not billing."""- total_chars = 0- for msg in messages:- if not isinstance(msg, dict):- continue- content = msg.get("content")- if isinstance(content, str):- total_chars += len(content)- elif isinstance(content, list):- for part in content:- if isinstance(part, dict):- text = part.get("text")- if isinstance(text, str):- total_chars += len(text)- return max(1, total_chars // 4)diff --git a/switchyard/lib/profiles/__init__.py b/switchyard/lib/profiles/__init__.pyindex 43c2cd3fc..be52e5582 100644--- a/switchyard/lib/profiles/__init__.py+++ b/switchyard/lib/profiles/__init__.py@@ -24,11 +24,6 @@ from switchyard.lib.profiles.header_routing import (from switchyard.lib.profiles.latency_service import LatencyServiceProfileConfigfrom switchyard.lib.profiles.loader import load_profilesfrom switchyard.lib.profiles.noop import NoopProfile, NoopProfileConfig-from switchyard.lib.profiles.oss_router import (- OSSRouterConfig,- OSSRouterProfileConfig,- OSSRouterTier,-)from switchyard.lib.profiles.passthrough import PassthroughProfileConfigfrom switchyard.lib.profiles.plan_execute import PlanExecuteProfileConfigfrom switchyard.lib.profiles.plan_execute_config import PlanExecuteConfig@@ -73,9 +68,6 @@ __all__ = ["LatencyServiceProfileConfig","NoopProfile","NoopProfileConfig",- "OSSRouterConfig",- "OSSRouterProfileConfig",- "OSSRouterTier","PassthroughProfileConfig","PlanExecuteConfig","PlanExecuteProfileConfig",diff --git a/switchyard/lib/profiles/oss_router.py b/switchyard/lib/profiles/oss_router.pydeleted file mode 100644index b38abe991..000000000--- a/switchyard/lib/profiles/oss_router.py+++ /dev/null@@ -1,138 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""Profile-owned external OSS-router plugin construction."""--from __future__ import annotations--from typing import Any, Self--from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator--from switchyard.lib.backends.llm_target import LlmTarget, coerce_llm_target-from switchyard.lib.profiles.chain import ComponentChainProfile-from switchyard.lib.profiles.table import profile_config-from switchyard.lib.roles import LLMBackend---class OSSRouterTier(BaseModel):- """One tier an external routing plugin may select."""-- model_config = ConfigDict(frozen=True, arbitrary_types_allowed=True)-- label: str = Field(min_length=1)- tier: LlmTarget-- @model_validator(mode="before")- @classmethod- def _coerce_tier(cls, raw: Any) -> Any:- """Accept dict target definitions under the ``tier`` field."""- if not isinstance(raw, dict) or "tier" not in raw:- return raw- result = dict(raw)- result["tier"] = coerce_llm_target(- result["tier"],- default_id=str(result.get("label", "")),- )- return result---@profile_config("oss_router")-class OSSRouterProfileConfig:- """Profile config wrapper for plugin-driven profile routing."""-- config: OSSRouterConfig-- @classmethod- def from_config(cls, config: OSSRouterConfig) -> Self:- """Create a profile config from the validated parsing model."""- return cls(config=config)-- def build(self) -> ComponentChainProfile:- """Build the OSS-router profile runtime."""- from switchyard.lib.backends.multi_llm_backend import build_multi_llm_backend- from switchyard.lib.processors.plugin_routing_request_processor import (- PluginRoutingRequestProcessor,- )-- config = self.config- request_processors: list[Any] = []- request_processors.append(- PluginRoutingRequestProcessor(- plugin_command=config.plugin_command,- tier_models={t.label: t.tier.model for t in config.tiers},- tier_target_ids={t.label: t.tier.id for t in config.tiers},- fallback_tier=config.fallback_tier,- request_timeout_s=config.request_timeout_s,- handshake_timeout_s=config.handshake_timeout_s,- env=config.env,- expose_metadata_keys=config.expose_metadata_keys,- )- )-- backend: LLMBackend = build_multi_llm_backend([t.tier for t in config.tiers])-- return ComponentChainProfile(- request_processors=request_processors,- backend=backend,- fallback_target_on_evict=config.fallback_target_on_evict,- )---class OSSRouterConfig(BaseModel):- """Validated parsing config for plugin-driven profile routing."""-- model_config = ConfigDict(frozen=True, extra="forbid")-- plugin_command: list[str] | str- tiers: tuple[OSSRouterTier, ...]- fallback_tier: str | None = None- fallback_target_on_evict: str- request_timeout_s: float = 5.0- handshake_timeout_s: float = 10.0- env: dict[str, str] | None = None- expose_metadata_keys: tuple[str, ...] = ()- enable_stats: bool = True-- @field_validator("plugin_command")- @classmethod- def _command_non_empty(cls, value: list[str] | str) -> list[str] | str:- """Reject empty plugin commands before spawning a subprocess."""- if isinstance(value, str) and not value.strip():- raise ValueError("plugin_command must be a non-empty string")- if isinstance(value, list) and not value:- raise ValueError("plugin_command must be a non-empty list")- return value-- @field_validator("tiers")- @classmethod- def _tiers_non_empty(cls, value: tuple[OSSRouterTier, ...]) -> tuple[OSSRouterTier, ...]:- """Require at least one unique plugin-visible tier label."""- if not value:- raise ValueError("OSSRouterConfig requires at least one tier")- labels = [tier.label for tier in value]- if len(set(labels)) != len(labels):- raise ValueError(- f"OSSRouterConfig tier labels must be unique; got {labels}",- )- return value-- @model_validator(mode="after")- def _fallback_tier_known(self) -> OSSRouterConfig:- """Validate fallback labels and target ids against configured tiers."""- labels = {tier.label for tier in self.tiers}- if self.fallback_tier is not None and self.fallback_tier not in labels:- raise ValueError(- f"fallback_tier {self.fallback_tier!r} is not in "- f"tiers {sorted(labels)}",- )- target_ids = {tier.tier.id for tier in self.tiers}- if self.fallback_target_on_evict not in target_ids:- raise ValueError(- f"fallback_target_on_evict {self.fallback_target_on_evict!r} "- f"is not in tier target ids {sorted(target_ids)}",- )- return self---__all__ = ["OSSRouterConfig", "OSSRouterProfileConfig", "OSSRouterTier"]diff --git a/tests/test_plugin_client.py b/tests/test_plugin_client.pydeleted file mode 100644index c9552f180..000000000--- a/tests/test_plugin_client.py+++ /dev/null@@ -1,265 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""End-to-end tests for :class:`PluginClient` against real subprocesses.--Each test writes a small Python script to ``tmp_path`` that implements a-slice of the JSON-RPC contract — handshake-only, malformed responses,-crashes — so we exercise the actual subprocess + reader code path rather-than mocking the transport.-"""--from __future__ import annotations--import sys-import textwrap-from pathlib import Path--import pytest--from switchyard.lib.plugin import (- PROTOCOL_VERSION,- PluginClient,- PluginCrashError,- PluginHandshakeError,- PluginRoutingError,- PluginTimeoutError,- RouteDecision,- RouteError,- RouteRequest,- RoutingRequestSummary,-)---def _write_plugin(tmp_path: Path, body: str) -> str:- script = tmp_path / "plugin.py"- script.write_text(textwrap.dedent(body).lstrip())- return str(script)---def _route_request(*, request_id: str = "r1", tiers: tuple[str, ...] = ("strong", "weak")) -> RouteRequest:- return RouteRequest(- request_id=request_id,- available_tiers=tiers,- summary=RoutingRequestSummary(- input_token_estimate=10,- message_count=1,- has_tool_use=False,- ),- )---_HEADER = """- import json, sys- def respond(rid, result=None, error=None):- msg = {"jsonrpc": "2.0", "id": rid}- if error is not None:- msg["error"] = error- else:- msg["result"] = result- sys.stdout.write(json.dumps(msg) + "\\n")- sys.stdout.flush()-"""---# ----------------------------------------------------------------------------# Happy path: handshake + a single route-# ------------------------------------------------------------------------------async def test_route_returns_decision(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- elif env["method"] == "route":- respond(env["id"], result={"tier": "weak", "metadata": {"score": 0.4}})- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )- try:- outcome = await client.route(_route_request())- assert isinstance(outcome, RouteDecision)- assert outcome.tier == "weak"- assert outcome.metadata == {"score": 0.4}- finally:- await client.shutdown()---async def test_concurrent_routes_multiplexed_by_id(tmp_path: Path) -> None:- """Two in-flight ``route`` calls must each get their matching response."""- import asyncio-- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- elif env["method"] == "route":- tier = "strong" if env["params"]["request_id"] == "alpha" else "weak"- respond(env["id"], result={"tier": tier, "metadata": {}})- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )- try:- a, b = await asyncio.gather(- client.route(_route_request(request_id="alpha")),- client.route(_route_request(request_id="beta")),- )- assert isinstance(a, RouteDecision) and a.tier == "strong"- assert isinstance(b, RouteDecision) and b.tier == "weak"- finally:- await client.shutdown()---# ----------------------------------------------------------------------------# Failure modes-# ------------------------------------------------------------------------------async def test_handshake_version_mismatch_raises(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + f"""- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={{"protocol_version": {PROTOCOL_VERSION + 99}, "plugin_name": "p", "plugin_version": "0"}})- """)-- with pytest.raises(PluginHandshakeError, match="protocol"):- await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )---async def test_handshake_timeout_raises(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, """- import sys, time- # Read input but never respond.- for _ in sys.stdin:- time.sleep(60)- """)-- with pytest.raises(PluginHandshakeError, match="handshake"):- await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong",),- handshake_timeout_s=0.5,- )---async def test_route_timeout_raises(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- # Never respond to route.- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- request_timeout_s=0.5,- )- try:- with pytest.raises(PluginTimeoutError):- await client.route(_route_request())- finally:- await client.shutdown()---async def test_route_unknown_tier_raises(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- elif env["method"] == "route":- respond(env["id"], result={"tier": "ULTRA", "metadata": {}})- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )- try:- with pytest.raises(PluginRoutingError, match="unknown tier"):- await client.route(_route_request())- finally:- await client.shutdown()---async def test_route_error_envelope_returned_as_route_error(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- elif env["method"] == "route":- respond(env["id"], error={"code": -32000, "message": "scorer dead", "data": {"fallback": "weak"}})- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )- try:- outcome = await client.route(_route_request())- assert isinstance(outcome, RouteError)- assert outcome.code == -32000- assert outcome.fallback_tier == "weak"- finally:- await client.shutdown()---async def test_plugin_crash_after_handshake_surfaces_as_crash_error(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- line = sys.stdin.readline()- env = json.loads(line)- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- sys.exit(0)- """)-- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong", "weak"),- )- try:- # Give the reader loop a tick to observe the closed stdout.- import asyncio- await asyncio.sleep(0.1)- with pytest.raises(PluginCrashError):- await client.route(_route_request())- finally:- await client.shutdown()---async def test_spawn_fails_when_binary_missing(tmp_path: Path) -> None: # noqa: ARG001- with pytest.raises(PluginHandshakeError, match="spawn"):- await PluginClient.start(- command=["/nonexistent/binary"],- available_tiers=("strong",),- )---async def test_shutdown_is_idempotent(tmp_path: Path) -> None:- plugin_script = _write_plugin(tmp_path, _HEADER + """- for line in sys.stdin:- env = json.loads(line)- if env["method"] == "handshake":- respond(env["id"], result={"protocol_version": 1, "plugin_name": "p", "plugin_version": "0"})- """)- client = await PluginClient.start(- command=[sys.executable, "-u", plugin_script],- available_tiers=("strong",),- )- await client.shutdown()- await client.shutdown() # second call must not raisediff --git a/tests/test_plugin_routing_request_processor.py b/tests/test_plugin_routing_request_processor.pydeleted file mode 100644index 5b605c915..000000000--- a/tests/test_plugin_routing_request_processor.py+++ /dev/null@@ -1,359 +0,0 @@-# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.-# SPDX-License-Identifier: Apache-2.0--"""Unit tests for :class:`PluginRoutingRequestProcessor`.--The processor is unit-tested with a hand-rolled fake :class:`PluginClient`-so we can exercise the routing-policy logic — fallbacks, error handling,-metadata stamping — without spawning real subprocesses on every assertion.-``test_plugin_client.py`` covers the real-subprocess path end-to-end.-"""--from __future__ import annotations--import pytest--from switchyard.lib.plugin import (- PluginCrashError,- PluginRoutingError,- PluginTimeoutError,- RouteDecision,- RouteError,- RouteRequest,- RouteResult,-)-from switchyard.lib.processors.plugin_routing_request_processor import (- CTX_OSS_ROUTER_TIER,- PluginRoutingRequestProcessor,-)-from switchyard.lib.processors.stats_request_processor import StatsRequestProcessor-from switchyard.lib.processors.stats_response_processor_accumulator import (- StatsResponseProcessor,-)-from switchyard.lib.proxy_context import ProxyContext-from switchyard_rust.components import StatsAccumulator-from switchyard_rust.core import ChatRequest, ChatResponse---class _FakePluginClient:- """Drop-in stand-in for :class:`PluginClient`.-- ``script`` is a list of canned responses (decisions or exceptions)- consumed in order by successive :meth:`route` calls. Lets us script- timeouts, crashes, and decisions deterministically.- """-- def __init__(self, script: list[RouteResult | Exception]) -> None:- self.script = list(script)- self.calls: list[RouteRequest] = []-- async def route(self, request: RouteRequest) -> RouteResult:- self.calls.append(request)- outcome = self.script.pop(0)- if isinstance(outcome, Exception):- raise outcome- return outcome---def _processor(- *,- fallback_tier: str | None = None,- tier_models: dict[str, str] | None = None,-) -> PluginRoutingRequestProcessor:- proc = PluginRoutingRequestProcessor(- plugin_command=["true"],- tier_models=tier_models or {"strong": "openai/gpt-5", "weak": "openai/gpt-5-mini"},- fallback_tier=fallback_tier,- )- return proc---def _request() -> ChatRequest:- return ChatRequest.openai_chat(body={- "model": "ignored-by-processor",- "messages": [{"role": "user", "content": "hello"}],- })---def _ctx() -> ProxyContext:- return ProxyContext()---def _bind_fake(proc: PluginRoutingRequestProcessor, fake: _FakePluginClient) -> None:- """Patch the private slot directly — startup() spawns a real subprocess."""- proc._client = fake # type: ignore[assignment]---# ----------------------------------------------------------------------------# Happy path-# ------------------------------------------------------------------------------async def test_decision_rewrites_model_and_stamps_metadata() -> None:- proc = _processor()- fake = _FakePluginClient([RouteDecision(tier="weak", metadata={"score": 0.4})])- _bind_fake(proc, fake)-- ctx = _ctx()- request = _request()- result = await proc.process(ctx, request)-- assert result.body["model"] == "openai/gpt-5-mini"- assert ctx.metadata[CTX_OSS_ROUTER_TIER] == "weak"- assert ctx.metadata["_oss_router_model"] == "openai/gpt-5-mini"- assert ctx.metadata["_oss_router_plugin_metadata"] == {"score": 0.4}- # Verify the request summary the plugin received was sane.- assert fake.calls[0].available_tiers == ("strong", "weak")- assert fake.calls[0].summary.message_count == 1---async def test_decision_route_label_feeds_rust_stats_rollup() -> None:- proc = _processor()- fake = _FakePluginClient([RouteDecision(tier="weak", metadata={"score": 0.4})])- _bind_fake(proc, fake)- stats = StatsAccumulator()- ctx = _ctx()- request = await StatsRequestProcessor().process(ctx, _request())-- result = await proc.process(ctx, request)- assert result.body["model"] == "openai/gpt-5-mini"- selected_model = ctx.selected_model- assert selected_model == "openai/gpt-5-mini"- await stats.record_success(selected_model, tier="weak")- await StatsResponseProcessor(stats).process(- ctx,- ChatResponse.openai_completion({- "model": "openai/gpt-5-mini",- "usage": {"prompt_tokens": 5, "completion_tokens": 8},- }),- )-- snapshot = stats.snapshot_sync()- assert snapshot["models"]["openai/gpt-5-mini"]["tier"] == "weak"- assert snapshot["tiers"]["weak"]["model"] == "openai/gpt-5-mini"- assert snapshot["tiers"]["weak"]["calls"] == 1- assert snapshot["tiers"]["weak"]["total_tokens"] == 13---# ----------------------------------------------------------------------------# Plugin error envelope-# ------------------------------------------------------------------------------async def test_route_error_with_fallback_dispatches_to_plugin_hint() -> None:- proc = _processor(fallback_tier="strong")- fake = _FakePluginClient([- RouteError(code=-32000, message="model dead", fallback_tier="weak"),- ])- _bind_fake(proc, fake)-- ctx = _ctx()- result = await proc.process(ctx, _request())-- # Plugin hinted "weak"; that's a known tier so it wins over the- # operator's strong-fallback default.- assert result.body["model"] == "openai/gpt-5-mini"- assert ctx.metadata[CTX_OSS_ROUTER_TIER] == "weak"---async def test_route_error_unknown_fallback_falls_back_to_operator_config() -> None:- proc = _processor(fallback_tier="strong")- fake = _FakePluginClient([- RouteError(code=-32000, message="model dead", fallback_tier="ULTRA"),- ])- _bind_fake(proc, fake)-- ctx = _ctx()- result = await proc.process(ctx, _request())-- # Plugin's "ULTRA" hint isn't a registered tier, so the operator's- # strong fallback wins.- assert result.body["model"] == "openai/gpt-5"- assert ctx.metadata[CTX_OSS_ROUTER_TIER] == "strong"---async def test_route_error_no_fallback_raises() -> None:- proc = _processor(fallback_tier=None)- fake = _FakePluginClient([RouteError(code=-32000, message="boom")])- _bind_fake(proc, fake)-- with pytest.raises(PluginRoutingError):- await proc.process(_ctx(), _request())---# ----------------------------------------------------------------------------# Plugin transport failures-# -----------------------------------------------------------------------------[email protected]("exc", [- PluginTimeoutError("timed out"),- PluginCrashError("crashed"),- PluginRoutingError("malformed"),-])-async def test_transport_failure_falls_back_when_configured(exc: Exception) -> None:- proc = _processor(fallback_tier="weak")- _bind_fake(proc, _FakePluginClient([exc]))-- ctx = _ctx()- result = await proc.process(ctx, _request())-- assert result.body["model"] == "openai/gpt-5-mini"- assert ctx.metadata[CTX_OSS_ROUTER_TIER] == "weak"- metadata = ctx.metadata["_oss_router_plugin_metadata"]- assert metadata["fallback_exception"] == type(exc).__name__--[email protected]("exc", [- PluginTimeoutError("timed out"),- PluginCrashError("crashed"),- PluginRoutingError("malformed"),-])-async def test_transport_failure_reraises_without_fallback(exc: Exception) -> None:- proc = _processor(fallback_tier=None)- _bind_fake(proc, _FakePluginClient([exc]))-- with pytest.raises(type(exc)):- await proc.process(_ctx(), _request())---# ----------------------------------------------------------------------------# Configuration-# ------------------------------------------------------------------------------async def test_processor_requires_startup_before_first_call() -> None:- proc = _processor()- with pytest.raises(RuntimeError, match="startup"):- await proc.process(_ctx(), _request())---def test_processor_rejects_empty_tier_models() -> None:- with pytest.raises(ValueError, match="at least one tier"):- PluginRoutingRequestProcessor(plugin_command=["true"], tier_models={})---def test_processor_rejects_unknown_fallback_tier() -> None:- with pytest.raises(ValueError, match="not in tier_models"):- PluginRoutingRequestProcessor(- plugin_command=["true"],- tier_models={"strong": "m"},- fallback_tier="weak",- )---# ----------------------------------------------------------------------------# Request summary content-# ------------------------------------------------------------------------------async def test_request_summary_extracts_tools_from_body() -> None:- proc = _processor()- fake = _FakePluginClient([RouteDecision(tier="strong", metadata={})])- _bind_fake(proc, fake)-- request = ChatRequest.openai_chat(body={- "model": "ignored",- "messages": [{"role": "user", "content": "hi"}],- "tools": [- {"type": "function", "function": {"name": "bash"}},- {"type": "function", "function": {"name": "edit"}},- ],- })- await proc.process(_ctx(), request)-- summary = fake.calls[0].summary- assert summary.has_tool_use- assert summary.tool_names == ("bash", "edit")---async def test_metadata_exposed_keys_only() -> None:- proc = PluginRoutingRequestProcessor(- plugin_command=["true"],- tier_models={"strong": "m1", "weak": "m2"},- expose_metadata_keys=("safe_key",),- )- fake = _FakePluginClient([RouteDecision(tier="strong", metadata={})])- _bind_fake(proc, fake)-- ctx = _ctx()- ctx.metadata["safe_key"] = "value-1"- ctx.metadata["secret_key"] = "should-not-leak"- await proc.process(ctx, _request())-- forwarded = fake.calls[0].metadata- assert forwarded == {"safe_key": "value-1"}---# ----------------------------------------------------------------------------# Profile wiring-# ------------------------------------------------------------------------------def test_oss_router_recipe_builds_full_chain() -> None:- from switchyard.lib.backends.llm_target import BackendFormat, LlmTarget- from switchyard.lib.profiles import OSSRouterProfileConfig, ProfileSwitchyard- from switchyard.lib.profiles.oss_router import OSSRouterConfig, OSSRouterTier- from switchyard_rust.translation import TranslationEngine-- config = OSSRouterConfig(- plugin_command=["python", "-u", "/dev/null"], # never spawned by build_*- tiers=(- OSSRouterTier(label="strong", tier=LlmTarget(- id="strong",- model="openai/test-strong",- format=BackendFormat.OPENAI,- api_key="k",- base_url="https://example/v1",- )),- OSSRouterTier(label="weak", tier=LlmTarget(- id="weak",- model="openai/test-weak",- format=BackendFormat.OPENAI,- api_key="k",- base_url="https://example/v1",- )),- ),- fallback_tier="weak",- fallback_target_on_evict="strong",- )- switchyard = ProfileSwitchyard(- OSSRouterProfileConfig.from_config(config).build()- )-- # Runtime components are populated; the plugin hasn't actually been- # spawned yet (startup() hasn't been awaited).- components = switchyard.iter_components()- assert any(isinstance(c, PluginRoutingRequestProcessor) for c in components)- assert any(isinstance(c, TranslationEngine) for c in components)---def test_oss_router_config_rejects_duplicate_tier_labels() -> None:- from switchyard.lib.backends.llm_target import BackendFormat, LlmTarget- from switchyard.lib.profiles.oss_router import OSSRouterConfig, OSSRouterTier-- tier = OSSRouterTier(label="strong", tier=LlmTarget(- id="strong", model="m", format=BackendFormat.OPENAI, api_key="k", base_url="u",- ))- with pytest.raises(ValueError, match="unique"):- OSSRouterConfig(- plugin_command=["true"],- tiers=(tier, tier),- fallback_target_on_evict="strong",- )---def test_oss_router_config_rejects_unknown_fallback_tier() -> None:- from switchyard.lib.backends.llm_target import BackendFormat, LlmTarget- from switchyard.lib.profiles.oss_router import OSSRouterConfig, OSSRouterTier-- tier = OSSRouterTier(label="strong", tier=LlmTarget(- id="strong", model="m", format=BackendFormat.OPENAI, api_key="k", base_url="u",- ))- with pytest.raises(ValueError, match="fallback"):- OSSRouterConfig(- plugin_command=["true"],- tiers=(tier,),- fallback_tier="weak",- fallback_target_on_evict="strong",- )