Keep a dead login out of free-best until a real request through it answers

OmniRoute's credential test marks a logged-out kilo-gateway active and clears
its last error every few minutes; the sync took it back each time and the
board's free turns answered 401 (2026-11-29 12:56). A login seen dead is now
remembered in dead_logins.json and stays out until one real completion through
one of its models answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-29 14:04:19 +01:00
parent da2bf4f78e
commit dfb29d3444
4 changed files with 122 additions and 32 deletions

View File

@ -1,25 +0,0 @@
#!/bin/bash
# Claude Code with your full ~/.claude setup, but every model (main, subagents,
# background) is the free-best chain on the local OmniRoute gateway. Free providers log
# prompts, so it refuses to start outside public repos unless --force.
set -euo pipefail
readonly GW="http://127.0.0.1:20128"
readonly MODEL="${CLAUDE_FREE_MODEL:-free-best}"
KEY="$(cat "${HOME}/.config/omniroute/api_key")"
readonly KEY
if [[ "${1:-}" == --force ]]; then
shift
else
free-llm-check-dir . || { echo "claude-free: only public repos, /tmp, /var/log (or --force)" >&2; exit 2; }
fi
curl -fsS -m 3 -o /dev/null "${GW}/v1/models" -H "Authorization: Bearer ${KEY}" ||
{ echo "claude-free: gateway down; run ~/src/omniroute-tetris-test/start.sh" >&2; exit 3; }
export ANTHROPIC_BASE_URL="${GW}" ANTHROPIC_AUTH_TOKEN="${KEY}" ANTHROPIC_MODEL="${MODEL}" \
ANTHROPIC_SMALL_FAST_MODEL="${MODEL}" ANTHROPIC_DEFAULT_OPUS_MODEL="${MODEL}" \
ANTHROPIC_DEFAULT_SONNET_MODEL="${MODEL}" ANTHROPIC_DEFAULT_HAIKU_MODEL="${MODEL}" \
CLAUDE_CODE_SUBAGENT_MODEL="${MODEL}"
exec claude --model "${MODEL}" "$@"

View File

@ -69,13 +69,13 @@ def alive(cfg: Config) -> bool:
return True return True
def chat(cfg: Config, key: str) -> str: def chat(cfg: Config, key: str, model: str = COMBO, max_tokens: int = 300) -> str:
"""One real completion through the combo; returns its text or raises ApiError.""" """One real completion through the combo (or one model); its text, or ApiError."""
reply = call( reply = call(
f"{cfg.base_url}/v1/chat/completions", f"{cfg.base_url}/v1/chat/completions",
{ {
"model": COMBO, "model": model,
"max_tokens": 300, "max_tokens": max_tokens,
"messages": [{"role": "user", "content": "Reply with exactly: OK"}], "messages": [{"role": "user", "content": "Reply with exactly: OK"}],
}, },
headers={"authorization": f"Bearer {key}"}, headers={"authorization": f"Bearer {key}"},

View File

@ -5,15 +5,19 @@ 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 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 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 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 turns). OmniRoute's own test revives such a login now and then, so one seen dead
set changes, so a reconnected provider comes back by itself. is remembered (DEAD_FILE) until a real completion through it answers. `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 from __future__ import annotations
import csv import csv
import json
import math import math
import sys import sys
from datetime import UTC, datetime
from typing import TYPE_CHECKING, Any from typing import TYPE_CHECKING, Any
from omniroute_offload import _gw_api as api from omniroute_offload import _gw_api as api
@ -35,6 +39,9 @@ MIN_TETRIS = 0.85
MIN_CONTEXT = 32_000 MIN_CONTEXT = 32_000
# testStatus (or lastErrorType) of a login that is gone: kuhy reconnects it # testStatus (or lastErrorType) of a login that is gone: kuhy reconnects it
DEAD = frozenset({"expired", "unauthorized"}) DEAD = frozenset({"expired", "unauthorized"})
# state_dir file of logins seen dead; one stays out until a real request answers
DEAD_FILE = "dead_logins.json"
PROBE_TOKENS = 20
def _logged_out(conn: dict[str, Any]) -> bool: def _logged_out(conn: dict[str, Any]) -> bool:
@ -72,15 +79,64 @@ def dead_providers(conns: Iterable[dict[str, Any]]) -> set[str]:
return {name for name, live in usable.items() if not live} return {name for name, live in usable.items() if not live}
def _remembered(cfg: Config) -> dict[str, str]:
"""Return the logins seen dead (provider -> first seen), kept across ticks."""
try:
data = json.loads((cfg.state_dir / DEAD_FILE).read_text())
except OSError, json.JSONDecodeError:
return {}
return {str(k): str(v) for k, v in data.items()} if isinstance(data, dict) else {}
def _remember(cfg: Config, dead: dict[str, str]) -> None:
cfg.state_dir.mkdir(parents=True, exist_ok=True)
(cfg.state_dir / DEAD_FILE).write_text(json.dumps(dead, sort_keys=True))
def _answers(cfg: Config, model: str) -> bool:
"""Say whether one real completion through `model` (not the combo) answers."""
try:
api.chat(cfg, health.secret(cfg, "api_key"), model, PROBE_TOKENS)
except (api.ApiError, OSError) as err:
print(f"still out: {model}: {err}", file=sys.stderr)
return False
return True
def still_dead(cfg: Config, seen: set[str], order: Path) -> set[str]:
"""Return providers to leave out: dead now, or seen dead and not yet answering.
OmniRoute's own credential test passes a logged-out kilo-gateway every few
minutes (it marks it "active" and clears its last error), so a sync took it
back and the board's next free turn answered 401 (2026-11-29 12:56). A login
seen dead stays out until a real completion through one of its models answers.
"""
dead = _remembered(cfg)
now = datetime.now(UTC).isoformat()
for name in seen:
dead.setdefault(name, now)
for name in sorted(set(dead) - seen):
probe = next(iter(ranked_models(order, only=name)), None)
if probe is None: # no ranked model left: nothing of it can join the combo
del dead[name]
elif _answers(cfg, probe):
del dead[name]
print(f"back in: {name} answered a real request", file=sys.stderr)
_remember(cfg, dead)
return set(dead)
def ranked_models( def ranked_models(
order: Path, order: Path,
dead: Iterable[str] = (), dead: Iterable[str] = (),
contexts: Mapping[str, int] | None = None, contexts: Mapping[str, int] | None = None,
floor: int = MIN_PROMPT, floor: int = MIN_PROMPT,
only: str | None = None,
) -> list[str]: ) -> list[str]:
"""Return agent-capable models from order.tsv that pass the filters, best first. """Return agent-capable models from order.tsv that pass the filters, best first.
A model's input limit: the smaller of order.tsv's measured one and OmniRoute's. A model's input limit: the smaller of order.tsv's measured one and OmniRoute's.
`only` keeps one provider's models.
""" """
gone, known = set(dead), contexts or {} gone, known = set(dead), contexts or {}
with order.open(newline="") as handle: with order.open(newline="") as handle:
@ -94,6 +150,7 @@ def ranked_models(
and min(float(row.get("max_prompt") or 0), known.get(row["model"], math.inf)) and min(float(row.get("max_prompt") or 0), known.get(row["model"], math.inf))
>= floor >= floor
and row["model"].split("/", 1)[0] not in gone and row["model"].split("/", 1)[0] not in gone
and only in (None, row["model"].split("/", 1)[0])
] ]
@ -111,7 +168,8 @@ def _ranked(cfg: Config) -> bool:
def _wanted(cfg: Config, admin: api.Admin) -> tuple[list[str], set[str]] | None: 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.""" """Return the combo and the dead providers left out; None (logged) if all dead."""
dead = dead_providers(admin.providers()) order = cfg.conf_dir / "order.tsv"
dead = still_dead(cfg, dead_providers(admin.providers()), order)
models = ranked_models( models = ranked_models(
cfg.conf_dir / "order.tsv", dead, admin.contexts(), MIN_CONTEXT cfg.conf_dir / "order.tsv", dead, admin.contexts(), MIN_CONTEXT
) )

View File

@ -241,6 +241,63 @@ def test_keep_live_brings_a_reconnected_provider_back(
assert notices == ["free-best re-synced: every provider is back"] assert notices == ["free-best re-synced: every provider is back"]
@pytest.fixture
def probes(cfg: gwc.Config, monkeypatch: pytest.MonkeyPatch) -> dict[str, bool]:
"""Model -> whether a real completion through it answers; records each probe."""
(cfg.conf_dir / "api_key").write_text("k\n")
answers: dict[str, bool] = {}
def chat(_cfg: gwc.Config, key: str, model: str = api.COMBO, _n: int = 0) -> str:
assert key == "k"
answers.setdefault(f"asked:{model}", True)
if not answers.get(model):
msg = "HTTP Error 401: Unauthorized"
raise api.ApiError(msg)
return "OK"
monkeypatch.setattr(api, "chat", chat)
return answers
def test_keep_live_keeps_a_dead_login_out_when_omniroute_marks_it_active(
cfg: gwc.Config,
admins: list[FakeAdmin],
notices: list[str],
probes: dict[str, bool],
) -> None:
"""OmniRoute's test revived a logged-out kilo-gateway; its next request was 401."""
_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
CURRENT[:] = ["nv/a"]
CONNS[1] = _conn("kilo") # OmniRoute's credential test reset it to "active"
assert combo.keep_live(cfg) is False
assert probes == {"asked:kilo/auto": True}
assert admins[-1].upserts == []
assert len(notices) == 1
def test_keep_live_takes_a_dead_login_back_once_a_real_request_answers(
cfg: gwc.Config,
admins: list[FakeAdmin],
notices: list[str],
probes: dict[str, bool],
capsys: pytest.CaptureFixture[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
CURRENT[:] = ["nv/a"]
CONNS[1] = _conn("kilo") # kuhy reconnected it
probes["kilo/auto"] = True
assert combo.keep_live(cfg) is True
assert admins[-1].upserts == [(api.COMBO, ["nv/a", "kilo/auto"])]
assert "back in: kilo answered a real request" in capsys.readouterr().err
assert combo._remembered(cfg) == {}
def test_keep_live_does_nothing_while_an_update_holds_the_lock( def test_keep_live_does_nothing_while_an_update_holds_the_lock(
cfg: gwc.Config, admins: list[FakeAdmin] cfg: gwc.Config, admins: list[FakeAdmin]
) -> None: ) -> None: