diff --git a/docs/SWARM-DELEGATION.md b/docs/SWARM-DELEGATION.md index 6abc19602..033cce66d 100644 --- a/docs/SWARM-DELEGATION.md +++ b/docs/SWARM-DELEGATION.md @@ -27,12 +27,29 @@ carrying a name; nothing resolves, routes, or activates a route at runtime. bytes exactly, so peers on the older vocabulary are unaffected. The wire carries the name; nothing on the wire resolves it. +## Runtime prerequisite (router helpers, D02 not yet active) + +The router side now has the primitives the later activation slice will build on, but nothing calls +them outside the router's own tests: + +- **`Router.stream(..., _exact="provider:model")`** (private, optional): pins the call to the one + configured route the ref names. The chain is that route alone — no fallback to any other route, + in this role or another — while the ordinary credential rotation, cooldowns, circuit breaker and + spend guard of this Router all still apply. A bad ref raises `ValueError` before anything is + streamed. +- **`Router.provider_for(ref, role="delegate")`**: a `RoleProvider` for one route on this same + Router (one shared cooldown, breaker and spend state; default `provider()` is unchanged). It + validates the ref up front — shape, known provider, and the provider's `roles` table permitting + `role` — and raises `ValueError` before any credential is read. +- Helpers (`_exhausted`, `_chain_cooldowns`, `_refused`) now scope their wait hints and refusals to + the chain the call actually walked, so a pinned failure speaks only for its route. + ## What is deliberately NOT built (later slices) -- No runtime activation: no code path reads `route_config.py` yet; `Delegator`, the router, and - the child loop ignore the `route` field. -- No provider/catalog validation of a ref, no credential handling, no `profile_routes`. -- No resolution or fallback behavior for a failed route. +- No runtime activation: no code path reads `route_config.py` yet, and delegation itself does not + use the router helpers above; `Delegator` and the child loop ignore the `route` field. +- No resolution, fallback, or profile_routes behavior for a failed route; `provider_for` is not + called by any delegation path. D02 is incomplete until that runtime slice lands. Until then, setting `delegation.routes` in a config file parses (see `tests/agents/test_route_config.py`) and does nothing else. diff --git a/src/exo/core/models/router.py b/src/exo/core/models/router.py index 9d5b59e14..c8f4993eb 100644 --- a/src/exo/core/models/router.py +++ b/src/exo/core/models/router.py @@ -238,6 +238,22 @@ def _allows(self, provider: str, role: str) -> bool: allowed = (self.providers.get(provider) or {}).get("roles") return not allowed or role in allowed + def pinned(self, ref: str, role: str = "delegate") -> Route: + """The one route ``ref`` names, checked against the configured providers and the role's limits. + Raises ``ValueError`` for a bad shape, an unknown provider, or a provider that may not serve ``role``.""" + if not ref or ref.startswith("-") or any(c.isspace() for c in ref): + raise ValueError(f"bad model ref {ref!r}") + route = Route.parse(ref) + if route.provider not in self.providers and route.provider not in self.instances: + raise ValueError(f"unknown provider {route.provider!r} in {ref!r}") + if not self._allows(route.provider, role): + raise ValueError(f"provider {route.provider!r} cannot serve role {role!r}") + return route + + def _chain_for(self, role: str, ref: str | None = None) -> list[Route]: + """The chain for ``role``, or only the route ``ref`` names: an exact-route call never falls back.""" + return self.chain(role) if ref is None else [self.pinned(ref, role)] + def tier_route(self, tier: str) -> Route | None: """First route of ``tier`` (then its fallbacks) whose provider has credentials, else None.""" return next((r for r in self.chain(tier) if self.credentials(r.provider)), None) @@ -413,16 +429,23 @@ def price(self, route: Route, usage: Usage | None) -> Usage | None: # --- streaming ----------------------------------------------------------- async def stream(self, role: str, messages: list[Message], tools: list[ToolSpec], - **opts: Any) -> AsyncIterator[ProviderEvent]: + *, _exact: str | None = None, **opts: Any) -> AsyncIterator[ProviderEvent]: """Stream from the first available route of ``role``, rotating sibling credentials then falling back to later routes until output has started. Ends with exactly one - ``done`` or ``error``.""" + ``done`` or ``error``. + + ``_exact`` (private, D02 prerequisite): pin this call to the one route named + ``"provider:model"``. No other configured route is tried, in this role or another. The + route keeps the ordinary credential rotation, cooldowns, circuit breaker and spend guard. + An invalid ref raises ``ValueError`` before anything is streamed.""" + if _exact is not None: + self.pinned(_exact, role) # raises before anything is streamed; also limits the chain below tried: list[str] = [] attempts: list[dict[str, Any]] = [] # every try, for the model.call record (D-025) last: ProviderEvent | None = None failed_credentials: set[str] = set() attempted_credentials: set[tuple[str, str]] = set() - chain = self.chain(role) + chain = self._chain_for(role, _exact) # Breaker state is cheap; resolve credentials only when reaching a route, off the event loop. skip = {r.ref for r in chain if self.route_open(r.ref, self.clock())} pending_routes, i = chain, 0 @@ -519,7 +542,7 @@ async def stream(self, role: str, messages: list[Message], tools: list[ToolSpec] yield ProviderEvent(kind="notice", text=f"{route.ref} failed repeatedly; skipping it for {cs / 60:.0f} min") if attempts and attempts[-1]["outcome"] == "fallback": attempts[-1]["outcome"] = "error" # normal routes and the optional last resort are exhausted - end = self._exhausted(role, tried, last) + end = self._exhausted(role, tried, last, _chain=chain) end.attempts = attempts yield end @@ -591,29 +614,34 @@ def note(outcome: str, err: str = "") -> None: ev.message.meta.setdefault("model", route.ref) yield ev - def _exhausted(self, role: str, tried: list[str], last: ProviderEvent | None) -> ProviderEvent: + def _exhausted(self, role: str, tried: list[str], last: ProviderEvent | None, + *, _chain: list[Route] | None = None) -> ProviderEvent: + """The closing event. ``_chain`` is the chain this call actually walked (exact route: one route), so the + wait hint and the refusal speak only for that route.""" + chain = self.chain(role) if _chain is None else _chain now = self.clock() - waits = [until - now for until, _, _ in self._chain_cooldowns(role, now)] + waits = [until - now for until, _, _ in self._chain_cooldowns(role, now, _chain=chain)] wait = min(waits) if waits else None - if not self.chain(role): + if not chain: return error_event(f"no model configured for role {role!r}; use /providers and choose a default model", None, retryable=False) if not tried and not waits: return error_event(f"no credentials for role {role!r}: set the provider key_env variables, " "or use /providers to add a provider and choose its model", None, retryable=False) - if refused := self._refused(role, tried, last, now): # no retry now, say what to fix; retry_after: it reopens + if refused := self._refused(role, tried, last, now, _chain=chain): # no retry now, say what to fix return error_event(refused[1], refused[0], retryable=False, retry_after=wait) why = f"; last error: {last.error}" if last is not None else "" hint = f"; next route reopens in {wait:.0f}s" if wait else "" return error_event(f"all routes for {role!r} failed or are cooling down{why}{hint}", last.status if last is not None else 429, retryable=True, retry_after=wait) - def _chain_cooldowns(self, role: str, now: float) -> list[tuple[float, str, Cooldown]]: + def _chain_cooldowns(self, role: str, now: float, *, + _chain: list[Route] | None = None) -> list[tuple[float, str, Cooldown]]: """Live cooldowns that bear on ``role``: a credential of a chain provider, or a credential|model cooldown on a model of the chain. A gate side call (D-081) cools a model this role never asks, and another provider's cooldown says nothing about this role's routes, so neither moves the wait hint or the refusal.""" - routes = {(r.provider, r.model) for r in self.chain(role)} + routes = {(r.provider, r.model) for r in (self.chain(role) if _chain is None else _chain)} out: list[tuple[float, str, Cooldown]] = [] for key, cd in self.cooldowns.items(): cred, scoped, model = key.partition("|") @@ -623,12 +651,12 @@ def _chain_cooldowns(self, role: str, now: float) -> list[tuple[float, str, Cool return out def _refused(self, role: str, tried: list[str], last: ProviderEvent | None, - now: float) -> tuple[int | None, str] | None: + now: float, *, _chain: list[Route] | None = None) -> tuple[int | None, str] | None: """Status and message when waiting cannot help: the provider refused the key or login (401, 403), or the key is over its spend limit (402) which a new key does not fix; on a later call too, while that credential, or a model of the chain on it, reopens first; or a local server is not running.""" if last is None: # nothing ran: the first of this chain's cooldowns to reopen holds the cause - cooling = self._chain_cooldowns(role, now) + cooling = self._chain_cooldowns(role, now, _chain=_chain) _, name, cd = min(cooling, key=lambda c: c[0], default=(0.0, "", Cooldown())) status, err = cd.status, cd.error or f"HTTP {cd.status}" else: @@ -650,6 +678,14 @@ def _refused(self, role: str, tried: list[str], last: ProviderEvent | None, def provider(self, role: str = "main") -> RoleProvider: return RoleProvider(self, role) + def provider_for(self, ref: str, role: str = "delegate") -> RoleProvider: + """A Provider for the one route ``ref`` names (D02 prerequisite). Raises ``ValueError`` before any + credential is read, for a bad shape, a provider that is not configured, or a provider whose ``roles`` + table may not serve ``role``. Uses this same Router (one cooldown, breaker and spend state) with + ``role`` as the stream role, so it never falls back to another route.""" + self.pinned(ref, role) + return RoleProvider(self, role, exact=ref) + def status(self) -> list[dict[str, Any]]: """Routes per role with availability, for ``models.list``.""" now, out = self.clock(), [] @@ -684,13 +720,14 @@ def resolved_roles(self) -> dict[str, list[str]]: class RoleProvider: """A Router bound to one role; satisfies the ``Provider`` protocol for the loop.""" - def __init__(self, router: Router, role: str) -> None: + def __init__(self, router: Router, role: str, *, exact: str | None = None) -> None: self.router = router self.role = role - self.name = f"router:{role}" + self.exact = exact + self.name = f"router:{role}" if exact is None else f"router:{role}:{exact}" def stream(self, messages: list[Message], tools: list[ToolSpec], **opts: Any) -> AsyncIterator[ProviderEvent]: - return self.router.stream(self.role, messages, tools, **opts) + return self.router.stream(self.role, messages, tools, _exact=self.exact, **opts) class ModelError(RuntimeError): diff --git a/tests/test_router_exact_route.py b/tests/test_router_exact_route.py new file mode 100644 index 000000000..db5e0cfd4 --- /dev/null +++ b/tests/test_router_exact_route.py @@ -0,0 +1,187 @@ +"""Exact-route provider prerequisite (D02): one configured route, no fallback, shared router state. + +The route is pinned before anything is streamed; an invalid ref fails at construction of the +provider (or at the first ``stream``) with ``ValueError``. A pinned call keeps the ordinary +credential rotation, cooldowns, circuit breaker and spend guard of the Router it came from. +""" + +import json +import sqlite3 + +import httpx +import pytest + +from exo.core.models import FakeProvider, Router +from exo.core.models.fake import rate_limited +from exo.core.models.router import SOLE_TTL +from exo.core.types import Message, ProviderEvent + +from tests.core.models.conftest import collect + + +class Clock: + def __init__(self, t=1_000_000.0): + self.t = t + + def __call__(self): + return self.t + + +CATALOG = { + "providers": {"limited": {"base_url": "http://127.0.0.1:1", "roles": ["decision"]}}, + "models": {}, + "roles": {}, +} + + +def make(roles, clock=None, providers=None, **fakes): + return Router(roles=roles, catalog=CATALOG, providers=providers or {}, instances=fakes, + env={}, clock=clock or Clock()) + + +def run(provider): + return collect(provider.stream([Message.user("hi")], [])) + + +def test_unknown_provider_fails_before_stream(): + r = make({"main": ["p:m"]}, p=FakeProvider(["ok"], name="p")) + with pytest.raises(ValueError, match="unknown provider"): + r.provider_for("nope:m") + with pytest.raises(ValueError, match="unknown provider"): + collect(r.stream("delegate", [Message.user("hi")], [], _exact="nope:m")) + + +def test_non_delegate_role_provider_fails_before_stream(): + # The catalog table limits this provider to the decision role; it may not serve a delegate. + r = make({"main": ["p:m"]}, providers={"limited": {"base_url": "http://127.0.0.1:1"}}) + with pytest.raises(ValueError, match="cannot serve role"): + r.provider_for("limited:m") + with pytest.raises(ValueError, match="cannot serve role"): + collect(r.stream("delegate", [Message.user("hi")], [], _exact="limited:m")) + + +@pytest.mark.parametrize("ref", ["", "p", "p:", ":m", "p:m extra"]) +def test_bad_ref_shape_fails_before_stream(ref): + r = make({"main": ["p:m"]}, p=FakeProvider(["ok"], name="p")) + with pytest.raises(ValueError): + r.provider_for(ref) + + +def test_exact_route_used_even_when_main_is_another(): + exact, main = FakeProvider(["from exact"], name="p"), FakeProvider(["from main"], name="b") + r = make({"main": ["b:m"]}, p=exact, b=main) + events = run(r.provider_for("p:m")) + assert events[-1].kind == "done" and events[-1].message.text() == "from exact" + assert events[-1].message.meta["model"] == "p:m" + assert len(exact.calls) == 1 and not main.calls # the main role's route was never asked + + +def test_retryable_error_does_not_reach_another_provider(): + exact = FakeProvider([ProviderEvent(kind="error", error="down", status=503, retryable=True)], name="p") + other = FakeProvider(["must not be used"], name="b") + clock = Clock() + r = make({"main": ["b:m"], "delegate": ["p:m", "b:m"]}, clock, p=exact, b=other) + events = run(r.provider_for("p:m")) + assert events[-1].kind == "error" and events[-1].retryable + assert len(exact.calls) == 1 and not other.calls # no fallback, in this role or another + # Only the pinned route was tried: 'b:m' is a delegate route but was not part of this call. + assert [a["route"] for a in events[-1].attempts] == ["p:m"] + + +def test_exact_route_keeps_cooldown_and_breaker_state_on_the_shared_router(): + clock = Clock() + p = FakeProvider([rate_limited(retry_after=30), "recovered"], name="p") + r = make({"main": ["p:m"]}, clock, p=p) + prov = r.provider_for("p:m") + assert prov.router is r + assert run(prov)[-1].kind == "error" # sole credential rate limited: the call fails, no second route + assert r.cooldowns["p"].until == clock.t + 30 # the shared Router recorded the provider cooldown + assert run(prov)[-1].kind == "error" and len(p.calls) == 1 # benched: the same provider is not asked again + clock.t = r.cooldowns["p"].until + 1 + assert run(prov)[-1].message.text() == "recovered" + assert "p" not in r.cooldowns + + +def test_exact_route_and_default_role_share_one_cooldown(): + clock = Clock() + p = FakeProvider([rate_limited(), "after cooldown"], name="p") + r = make({"main": ["p:m"]}, clock, p=p) + assert run(r.provider("main"))[-1].kind == "error" + assert r.cooldowns["p"].until > clock.t + assert run(r.provider_for("p:m"))[-1].kind == "error" # the default role's cooldown applies here too + assert len(p.calls) == 1 + + +def test_default_provider_and_role_stream_unchanged(): + p, b = FakeProvider([rate_limited()], name="p"), FakeProvider(["from backup"], name="b") + r = make({"main": ["p:m", "b:m"]}, p=p, b=b) + events = collect(r.stream("main", [Message.user("hi")], [])) + assert events[-1].message.text() == "from backup" # ordinary fallback still happens + assert r.provider("main").exact is None and r.provider("main").name == "router:main" + assert r.provider_for("p:m").name == "router:delegate:p:m" + + +def test_exact_route_records_model_call_attempts(): + p = FakeProvider(["ok"], name="p") + r = make({"main": ["p:m"]}, p=p) + events = run(r.provider_for("p:m")) + assert events[-1].attempts == [{"route": "p:m", "outcome": "ok", "error": "", "ms": events[-1].attempts[0]["ms"]}] + + +# --- injected SpendJournal: a pinned call still reserves and settles -------------------------- + + +@pytest.fixture(autouse=True) +def synthetic_native_contract(monkeypatch): + # This fake-price model exists only in test code. Production config cannot add native bounds. + from exo.model_spend import billing + monkeypatch.setattr(billing, 'NATIVE_BOUNDS', { + **billing.NATIVE_BOUNDS, + ('openai', 'https://api.openai.com/v1', 'm'): (1000, 1000), + }) + + +def spend_router(tmp_path, handler, clock): + from exo.model_spend import SpendJournal + routes = {"test:m": dict(contract="text-tokens-v1", base_url="https://api.openai.com/v1", model="m", + transport="openai", input_bound=1000, max_output=100, + input=1, output=10, cache_read=1, cache_write=1)} + cfg = dict(journal=str(tmp_path / "spend.sqlite"), journal_id=SpendJournal.provision(tmp_path / "spend.sqlite", "alice"), + principal="alice", daily_usd="1", monthly_usd="1", routes=routes) + return Router(roles={"main": ["test:m"], "delegate": ["other:m"]}, catalog={}, + providers={"test": {"transport": "openai", "base_url": "https://api.openai.com/v1"}}, + env={}, clock=clock, spend=SpendJournal(cfg), + client=httpx.AsyncClient(transport=httpx.MockTransport(handler))) + + +def ok_response(input=100, output=10, cost=99): + data = {'choices': [{'delta': {'content': 'hi'}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': input, 'completion_tokens': output, 'cost': cost}} + return httpx.Response(200, text='data: ' + json.dumps(data) + '\n\ndata: [DONE]\n\n') + + +def test_exact_route_with_injected_journal_reserves_and_settles(tmp_path): + r = spend_router(tmp_path, lambda req: ok_response(), Clock()) + r.roles["delegate"] = ["test:m"] # route 'test:m' may serve the pinned call's role + prov = r.provider_for("test:m") + events = run(prov) + assert events[-1].kind == "done" and events[-1].message.meta["model"] == "test:m" + reserved, actual = sqlite3.connect(tmp_path / "spend.sqlite").execute( + "SELECT reserved, actual FROM calls").fetchall()[0] + assert actual == 200_000 and reserved == 2_000_000 # $0.0002 settled under the 100-token reservation + + +def test_exact_route_keeps_breaker_state_on_the_shared_router(): + clock = Clock() + outages = [ProviderEvent(kind="error", error="HTTP 503: unavailable", status=503, retryable=True)] * 2 + p = FakeProvider(outages + ["recovered"], name="p") + r = make({"main": ["p:m"]}, clock, p=p) + prov = r.provider_for("p:m") + run(prov) # first 503: error, the sole credential cools for SOLE_TTL + clock.t += SOLE_TTL + 1 + events = run(prov) # second failure opens the route's breaker + assert events[-1].kind == "error" and r.breakers["p:m"].level == 1 + assert run(prov)[-1].kind == "error" and len(p.calls) == 2 # benched, not asked again + clock.t += 600 + assert run(prov)[-1].message.text() == "recovered" # sole pinned ref: it is the one trial call + assert not r.breakers and not r._forced_probes # recovered; no fallback probe was ever spawned