Leave providers with no live login out of free-best
Some checks are pending
kuhy_credit drift / drift (push) Waiting to run
md-naming / markdown naming convention (push) Waiting to run
omniroute_offload pre-commit / pre-commit (push) Waiting to run
palette drift / palette (push) Waiting to run
repo-contract / repo contract (push) Waiting to run
shared gate tests / gate unit tests (push) Waiting to run

The health tick re-syncs the combo when a login dies or comes back, so a
dead kilo-gateway (401) no longer reaches free turns as a hard error.

Bug-class-check: combo built from order.tsv alone trusted every ranked provider; now gated on live connections (T2624)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-29 12:04:38 +01:00
parent 5ed2129215
commit 7942f7ec57
5 changed files with 245 additions and 12 deletions

View File

@ -124,6 +124,18 @@ class Admin:
if isinstance(m, dict)
}
def combo_models(self, name: str = COMBO) -> list[str]:
"""Return the combo's models in priority order (empty when it is missing)."""
got = self._call("/api/combos")
combos = got.get("combos", got) if isinstance(got, dict) else got
return [
str(m.get("model", ""))
for c in combos
if c.get("name") == name
for m in c.get("models", [])
if isinstance(m, dict)
]
def reactivate(self, conn_id: str) -> None:
"""Mark a connection active again (the PUT merges; keys are kept)."""
self._call(f"/api/providers/{conn_id}", {"testStatus": "active"}, "PUT")

View File

@ -1,29 +1,50 @@
"""Rebuild the free-best combo from the benchmark's order.tsv in conf_dir.
Keeps tool-capable models with a big enough prompt window and Tetris score, in
the file's rank order (the combo is a priority chain).
the file's rank order (the combo is a priority chain), and drops every model of
a provider whose connections are all inactive or logged out: OmniRoute hands
such a member's 401 to the caller instead of the next model's answer (a
kilo-gateway login expired on 2026-11-29 and failed a third of the board's free
turns). `keep_live` runs after each health tick and re-syncs the combo when that
set changes, so a reconnected provider comes back by itself.
"""
from __future__ import annotations
import csv
import sys
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, Any
from omniroute_offload import _gw_api as api
from omniroute_offload import _gw_config as gwc
from omniroute_offload import _gw_health as health
from omniroute_offload import _gw_notify as note
if TYPE_CHECKING:
from collections.abc import Iterable
from pathlib import Path
from omniroute_offload._gw_config import Config
MIN_PROMPT = 16_000
MIN_TETRIS = 0.85
# testStatus of a login that is gone: kuhy reconnects it
DEAD = frozenset({"expired", "unauthorized"})
def ranked_models(order: Path) -> list[str]:
def dead_providers(conns: Iterable[dict[str, Any]]) -> set[str]:
"""Return providers with connections but none usable (inactive or logged out)."""
usable: dict[str, bool] = {}
for conn in conns:
live = bool(conn.get("isActive")) and conn.get("testStatus") not in DEAD
name = str(conn.get("provider"))
usable[name] = usable.get(name, False) or live
return {name for name, live in usable.items() if not live}
def ranked_models(order: Path, dead: Iterable[str] = ()) -> list[str]:
"""Return agent-capable models from order.tsv that pass the filters, best first."""
gone = set(dead)
with order.open(newline="") as handle:
rows = list(csv.DictReader(handle, delimiter="\t"))
return [
@ -33,20 +54,78 @@ def ranked_models(order: Path) -> list[str]:
and row.get("tetris", "-") != "-"
and float(row["tetris"]) >= MIN_TETRIS
and float(row.get("max_prompt") or 0) >= MIN_PROMPT
and row["model"].split("/", 1)[0] not in gone
]
def refresh(cfg: Config) -> bool:
"""Upsert the combo; log and return False when order.tsv is missing or empty."""
def _ranked(cfg: Config) -> bool:
"""Say whether order.tsv exists and ranks a model; log why not (needs no login)."""
order = cfg.conf_dir / "order.tsv"
if not order.exists():
print(f"combo kept: no {order}", file=sys.stderr)
return False
models = ranked_models(order)
if not models:
if not ranked_models(order):
print(f"combo kept: no model in {order} passes the filter", file=sys.stderr)
return False
admin = api.Admin(cfg, health.secret(cfg, "admin_password"))
admin.upsert_combo(api.COMBO, models)
print(f"{api.COMBO}: {' > '.join(models)}", file=sys.stderr)
return True
def _wanted(cfg: Config, admin: api.Admin) -> tuple[list[str], set[str]] | None:
"""Return the combo and the dead providers left out; None (logged) if all dead."""
dead = dead_providers(admin.providers())
models = ranked_models(cfg.conf_dir / "order.tsv", dead)
if not models:
print(
"combo kept: no ranked provider has a live login"
f" ({', '.join(sorted(dead))})",
file=sys.stderr,
)
return None
return models, dead
def refresh(cfg: Config) -> bool:
"""Upsert the combo; log and return False when order.tsv is missing or empty."""
if not _ranked(cfg):
return False
admin = api.Admin(cfg, health.secret(cfg, "admin_password"))
wanted = _wanted(cfg, admin)
if wanted is None:
return False
models, dead = wanted
admin.upsert_combo(api.COMBO, models)
left_out = f" (left out, no live login: {', '.join(sorted(dead))})" if dead else ""
print(f"{api.COMBO}: {' > '.join(models)}{left_out}", file=sys.stderr)
return True
def keep_live(cfg: Config) -> bool:
"""Re-sync the combo when a provider login died or came back; True if it changed.
Skips while an update holds the instance lock; an unreachable API changes nothing.
"""
with gwc.locked(cfg, blocking=False) as got:
if not got or not _ranked(cfg):
return False
try:
admin = api.Admin(cfg, health.secret(cfg, "admin_password"))
wanted = _wanted(cfg, admin)
if wanted is None or wanted[0] == admin.combo_models():
return False
models, dead = wanted
admin.upsert_combo(api.COMBO, models)
except (api.ApiError, OSError) as err:
print(f"combo sync skipped: {err}", file=sys.stderr)
return False
left_out = (
f"; no live login: {', '.join(sorted(dead))} (reconnect in the dashboard)"
if dead
else ""
)
print(f"combo synced: {' > '.join(models)}{left_out}", file=sys.stderr)
note.notify(
cfg,
f"free-best re-synced{left_out or ': every provider is back'}",
urgency="low",
)
return True

View File

@ -1,7 +1,8 @@
"""omniroute-gateway: keep the local OmniRoute gateway up, checked and current.
start (re)create the container on the pinned image and wait for its API
health real chat probe + fix ladder (systemd timer, every 10 min)
health real chat probe + fix ladder, then free-best re-synced to the live logins
(systemd timer, every 10 min)
update backup + newest stable tag with rollback (systemd timer, weekly)
backup stop, tar the data volume, start
combo rebuild free-best from ~/.config/omniroute/order.tsv
@ -39,6 +40,14 @@ def _backup(cfg: Config) -> int:
return 0
def _health(cfg: Config) -> int:
code = health.run(cfg)
combo.keep_live(
cfg
) # a provider whose login died leaves free-best, a reconnected one comes back
return code
def _combo(cfg: Config) -> int:
return 0 if combo.refresh(cfg) else 1
@ -57,7 +66,7 @@ def main(argv: list[str] | None = None) -> int:
cfg = Config.from_env()
actions: dict[str, Callable[[Config], int]] = {
"start": _start,
"health": health.run,
"health": _health,
"update": update.run,
"backup": _backup,
"combo": _combo,

View File

@ -93,6 +93,22 @@ def test_combo_members_filters_by_name_and_falls_back_to_model_prefix(
assert adm.combo_members("free-best") == set()
def test_combo_models_lists_the_combo_in_priority_order(
admin: tuple[api.Admin, Net],
) -> None:
adm, net = admin
combos = [
{"name": "other", "models": [{"model": "zzz/x"}]},
{
"name": "free-best",
"models": [{"model": "nv/a"}, "not-a-dict", {"model": "or/b"}],
},
]
net.replies = [{"combos": combos}, []]
assert adm.combo_models() == ["nv/a", "or/b"]
assert adm.combo_models() == []
def test_reactivate_puts_active(admin: tuple[api.Admin, Net]) -> None:
adm, net = admin
net.replies = [{}]

View File

@ -9,6 +9,7 @@ import pytest
from omniroute_offload import _gw_api as api
from omniroute_offload import _gw_combo as combo
from omniroute_offload import _gw_config as gwc
from omniroute_offload import _gw_notify as note
if TYPE_CHECKING:
from pathlib import Path
@ -38,11 +39,21 @@ def cfg(tmp_path: Path) -> gwc.Config:
return made
CONNS: list[dict[str, Any]] = []
CURRENT: list[str] = []
class FakeAdmin:
def __init__(self, cfg: gwc.Config, password: str) -> None:
self.pw = password
self.upserts: list[tuple[str, list[str]]] = []
def providers(self) -> list[dict[str, Any]]:
return CONNS
def combo_models(self, name: str = api.COMBO) -> list[str]:
return CURRENT
def upsert_combo(self, name: str, models: list[str]) -> None:
self.upserts.append((name, models))
@ -50,6 +61,8 @@ class FakeAdmin:
@pytest.fixture
def admins(monkeypatch: pytest.MonkeyPatch) -> list[FakeAdmin]:
made: list[FakeAdmin] = []
CONNS.clear()
CURRENT.clear()
def factory(cfg: gwc.Config, password: str) -> FakeAdmin:
made.append(FakeAdmin(cfg, password))
@ -118,3 +131,107 @@ def test_refresh_keeps_combo_when_nothing_passes(
assert combo.refresh(cfg) is False
assert admins == []
assert "passes the filter" in capsys.readouterr().err
def _conn(
provider: str, status: str = "active", *, active: bool = True
) -> dict[str, Any]:
return {"provider": provider, "testStatus": status, "isActive": active}
def test_dead_providers_are_those_with_no_usable_connection() -> None:
conns = [
_conn("kilo", "expired"),
_conn("two", "expired"),
_conn("two"),
_conn("off", active=False),
_conn("nope", "unauthorized"),
_conn(
"cool", "unavailable"
), # cooling down: the ladder reactivates it, it stays
]
assert combo.dead_providers(conns) == {"kilo", "off", "nope"}
def test_refresh_leaves_out_a_provider_whose_login_expired(
cfg: gwc.Config, admins: list[FakeAdmin], capsys: pytest.CaptureFixture[str]
) -> None:
_write(
cfg,
HEADER
+ "nv/a\tyes\t1.0\t128000\n"
+ "kilo/auto\tyes\t1.0\t128000\n"
+ "or/b\tyes\t0.9\t64000\n",
)
CONNS.extend([_conn("nv"), _conn("kilo", "expired"), _conn("or")])
assert combo.refresh(cfg) is True
assert admins[0].upserts == [(api.COMBO, ["nv/a", "or/b"])]
assert "left out, no live login: kilo" in capsys.readouterr().err
def test_refresh_keeps_the_combo_when_every_ranked_provider_is_dead(
cfg: gwc.Config, admins: list[FakeAdmin]
) -> None:
_write(cfg, HEADER + "kilo/auto\tyes\t1.0\t128000\n")
CONNS.append(_conn("kilo", "expired"))
assert combo.refresh(cfg) is False
assert admins[0].upserts == []
@pytest.fixture
def notices(monkeypatch: pytest.MonkeyPatch) -> list[str]:
sent: list[str] = []
monkeypatch.setattr(
note, "notify", lambda _cfg, text, urgency="normal": sent.append(text) or True
)
return sent
def test_keep_live_drops_a_dead_member_and_says_so_once(
cfg: gwc.Config, admins: list[FakeAdmin], notices: list[str]
) -> None:
_write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\nkilo/auto\tyes\t1.0\t128000\n")
CONNS.extend([_conn("nv"), _conn("kilo", "expired")])
CURRENT.extend(["nv/a", "kilo/auto"])
assert combo.keep_live(cfg) is True
assert admins[-1].upserts == [(api.COMBO, ["nv/a"])]
assert notices == [
"free-best re-synced; no live login: kilo (reconnect in the dashboard)"
]
CURRENT[:] = ["nv/a"]
assert combo.keep_live(cfg) is False # in sync: nothing sent again
assert len(notices) == 1
def test_keep_live_brings_a_reconnected_provider_back(
cfg: gwc.Config, admins: list[FakeAdmin], notices: list[str]
) -> None:
_write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\nkilo/auto\tyes\t1.0\t128000\n")
CONNS.extend([_conn("nv"), _conn("kilo")])
CURRENT.append("nv/a")
assert combo.keep_live(cfg) is True
assert admins[-1].upserts == [(api.COMBO, ["nv/a", "kilo/auto"])]
assert notices == ["free-best re-synced: every provider is back"]
def test_keep_live_does_nothing_while_an_update_holds_the_lock(
cfg: gwc.Config, admins: list[FakeAdmin]
) -> None:
_write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\n")
with gwc.locked(cfg, blocking=True):
assert combo.keep_live(cfg) is False
assert admins == []
def test_keep_live_survives_an_unreachable_api(
cfg: gwc.Config, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]
) -> None:
_write(cfg, HEADER + "nv/a\tyes\t1.0\t128000\n")
def refused(_cfg: gwc.Config, _pw: str) -> FakeAdmin:
msg = "refused"
raise api.ApiError(msg)
monkeypatch.setattr(api, "Admin", refused)
assert combo.keep_live(cfg) is False
assert "combo sync skipped: refused" in capsys.readouterr().err