stability: shim fallback map + health_loop (base<->fallback), 429 retry, watcher probes the shim; guide 7.5

This commit is contained in:
2026-11-14 01:08:35 +02:00
parent 3180cc7bff
commit e8486ad186
3 changed files with 143 additions and 25 deletions
+26
View File
@@ -237,6 +237,32 @@ curl -s https://api.numes.ai/api/v1/chat/completions \
| все ключи «мёртвые» в `dead.json` | все получили 401/403 подряд | шим сам сбрасывает паузы при пустом пуле; проверить `/status` | | все ключи «мёртвые» в `dead.json` | все получили 401/403 подряд | шим сам сбрасывает паузы при пустом пуле; проверить `/status` |
| ключ создан, но `http=None` | тест-запрос упал на флапе апстрима | ключ валиден, проверить позже | | ключ создан, но `http=None` | тест-запрос упал на флапе апстрима | ключ валиден, проверить позже |
## 7.5 Стабильность: почему модели пропадают и как это закрыто
Три механизма держат выдачу полной:
1. **Fallback-маппинг в шиме.** Провайдер одного слага уходит на часы → alias переключается на
ближайший живой слаг (`FALLBACK` в `shim.py`), клиент продолжает получать `200`:
`kimi-k3-abliterated → moonshotai/kimi-k3.1-pro`, `glm-5.3-uncensored → z-ai/glm-5.3`,
`deepseek-v4.1-flash-uncensored → deepseek/deepseek-v4.1-flash`.
2. **`health_loop` в шиме** (поток, каждые 2 мин): параллельно пробует базовые слаги, переключает
alias на резерв и **возвращает обратно**, когда база оживает. Переключения пишутся в журнал
(`journalctl -u numes-shim | grep health`).
3. **Сторож проверяет шим, а не numes напрямую.** Иначе он видит `503` базового слага, выключает
`abilities`, и юзер теряет модель, которую шим уже отдаёт через резерв. Проба идёт на
`http://127.0.0.1:48961/v1/chat/completions` по alias.
Плюс шим больше не отдаёт клиенту `429` без ретрая (раньше `429` возвращался сразу, минуя перебор
ключей) — теперь `429/5xx` = пауза ключа и следующий ключ, до 6 попыток.
Диагностика стабильности:
```bash
journalctl -u numes-shim | grep health # переключения base/fallback
tail -20 /var/log/numes_watch.log # live-сет и abilities on=N/N
curl -s localhost:48961/status # keys_alive + текущий маппинг
```
## 8. Экономика и риски ## 8. Экономика и риски
- OpenRouter для сравнения: `kimi-k3.1-pro` $2/$10, `glm-5.3` $0.08/$3.60, `deepseek-v4.1-flash` $0.30/$1.20 за 1M. Здесь — $0. - OpenRouter для сравнения: `kimi-k3.1-pro` $2/$10, `glm-5.3` $0.08/$3.60, `deepseek-v4.1-flash` $0.30/$1.20 за 1M. Здесь — $0.
+59 -21
View File
@@ -3,7 +3,7 @@
Live = HTTP 200 on a tiny chat completion through api.numes.ai. Live = HTTP 200 on a tiny chat completion through api.numes.ai.
Unpark channel numes-pool + enable abilities for live aliases; park when none live. Unpark channel numes-pool + enable abilities for live aliases; park when none live.
Runs on the gateway host (cron every 10 min). Runs on 2.27.98.196 (cron every 10 min).
""" """
import json import json
import os import os
@@ -13,9 +13,10 @@ import time
from concurrent.futures import ThreadPoolExecutor from concurrent.futures import ThreadPoolExecutor
KEYS = "/opt/numes-shim/keys.json" KEYS = "/opt/numes-shim/keys.json"
BASE = "https://api.numes.ai/api/v1" BASE = "http://127.0.0.1:48961/v1" # проверяем шим: он держит fallback-маппинг
CHANNEL = "numes-pool" CHANNEL = "numes-pool"
STATE = "/opt/numes-shim/watch_state.json" STATE = "/opt/numes-shim/watch_state.json"
REVOKED = "/opt/numes-shim/revoked.json"
MAP = { MAP = {
"glm-5.3": "z-ai/glm-5.3", "glm-5.3": "z-ai/glm-5.3",
@@ -33,33 +34,52 @@ def log(msg):
sys.stdout.flush() sys.stdout.flush()
def first_key(): def all_keys():
"""Rotate across the key bank so one account never eats the whole probe load."""
try: try:
d = json.load(open(KEYS)) d = json.load(open(KEYS))
if isinstance(d, dict): if isinstance(d, dict):
d = d.get("keys", []) d = d.get("keys", [])
if not d: return list(d or [])
return None
return d[int(time.time() // 600) % len(d)]
except Exception: except Exception:
return []
def revoked():
try:
return set(json.load(open(REVOKED)))
except Exception:
return set()
def mark_revoked(k):
rv = revoked()
rv.add(k)
try:
json.dump(sorted(rv), open(REVOKED, "w"))
except Exception:
pass
def first_key():
"""Rotate across the key bank so one account never eats the whole probe load."""
ks = [k for k in all_keys() if k not in revoked()]
if not ks:
return None return None
return ks[int(time.time() // 600) % len(ks)]
def probe(item): def probe(item):
alias, slug = item """Один алиас через шим: 200 = жив (шим сам держит fallback), 503 = реально мёртв."""
k = first_key() alias, _slug = item
if not k: body = json.dumps({"model": alias,
return alias, 0, 0.0
body = json.dumps({"model": slug,
"messages": [{"role": "user", "content": "ping"}], "messages": [{"role": "user", "content": "ping"}],
"max_tokens": 16}) "max_tokens": 32})
t0 = time.time() t0 = time.time()
r = subprocess.run( r = subprocess.run(
["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-m", "90", ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "-m", "200",
BASE + "/chat/completions", "-H", "Authorization: Bearer " + k, BASE + "/chat/completions", "-H", "Authorization: Bearer numes-shim-local",
"-H", "Content-Type: application/json", "-d", body], "-H", "Content-Type: application/json", "-d", body],
capture_output=True, text=True, timeout=120) capture_output=True, text=True, timeout=240)
try: try:
code = int((r.stdout or "0").strip() or 0) code = int((r.stdout or "0").strip() or 0)
except Exception: except Exception:
@@ -90,14 +110,31 @@ def main():
log("probe: " + " ".join("%s=%s/%.0fs" % (a, c, s) for a, c, s in res)) log("probe: " + " ".join("%s=%s/%.0fs" % (a, c, s) for a, c, s in res))
try: try:
prev = json.load(open(STATE)).get("live", []) st = json.load(open(STATE))
prev = st.get("live", [])
fails = st.get("fails", {})
except Exception: except Exception:
prev = [] prev, fails = [], {}
# a single flapped probe must not pull a model out of the catalog: need 2 misses in a row
for a, code, _s in res:
if code == 200:
fails.pop(a, None)
else:
fails[a] = int(fails.get(a, 0)) + 1
unstable = {a for a, n in fails.items() if n >= 2}
live = {a for a in live if a not in unstable}
if live: if live:
psql("update channels set status=1 where name='%s';" % CHANNEL) psql("update channels set status=1 where name='%s';" % CHANNEL)
psql("update abilities set enabled=true where channel_id=(select id from channels where name='%s') and model in (%s);" if len(live) == len(MAP):
% (CHANNEL, ",".join("'%s'" % m for m in sorted(live)))) on = psql("update abilities set enabled=true where channel_id=(select id from channels where name='%s');"
% CHANNEL)
else:
on = psql("update abilities set enabled=true where channel_id=(select id from channels where name='%s') and model in (%s);"
% (CHANNEL, ",".join("'%s'" % m for m in sorted(live))))
cnt = psql("select count(*) filter (where enabled)||'/'||count(*) from abilities where channel_id=(select id from channels where name='%s');" % CHANNEL)
log("abilities on=%s" % cnt)
dead = sorted(set(MAP) - live) dead = sorted(set(MAP) - live)
if dead: if dead:
psql("update abilities set enabled=false where channel_id=(select id from channels where name='%s') and model in (%s);" psql("update abilities set enabled=false where channel_id=(select id from channels where name='%s') and model in (%s);"
@@ -106,7 +143,8 @@ def main():
psql("update channels set status=2 where name='%s';" % CHANNEL) psql("update channels set status=2 where name='%s';" % CHANNEL)
changed = sorted(live) != sorted(prev) changed = sorted(live) != sorted(prev)
json.dump({"live": sorted(live), "ts": int(time.time())}, open(STATE, "w")) json.dump({"live": sorted(live), "fails": fails, "ts": int(time.time())},
open(STATE, "w"))
log("live=%s%s" % (sorted(live), " CHANGED" if changed else "")) log("live=%s%s" % (sorted(live), " CHANGED" if changed else ""))
if changed: if changed:
log("ALERT numes live set: %s" % sorted(live)) log("ALERT numes live set: %s" % sorted(live))
+58 -4
View File
@@ -27,6 +27,19 @@ MAP = {
"deepseek-v4.1-flash-uncensored": "dealignai/deepseek-v4.1-flash-uncensored-fp8", "deepseek-v4.1-flash-uncensored": "dealignai/deepseek-v4.1-flash-uncensored-fp8",
} }
# Семантически ближайший слаг, если провайдер базового ушёл (503 держится часами).
# health_loop переключает alias на резерв автоматически и возвращает обратно, когда база оживает.
FALLBACK = {
"glm-5.3": "z-ai/glm-5.3",
"glm-5.3-uncensored": "z-ai/glm-5.3",
"glm-5.3-flash": "dealignai/glm-5.3-uncensored-fp8",
"kimi-k3.1-pro": "moonshotai/kimi-k3.1-pro",
"kimi-k3-abliterated": "moonshotai/kimi-k3.1-pro",
"deepseek-v4.1-flash": "deepseek/deepseek-v4.1-flash",
"deepseek-v4.1-flash-uncensored": "deepseek/deepseek-v4.1-flash",
}
BASE_SLUG = dict(MAP)
lock = threading.Lock() lock = threading.Lock()
_rr = [0] _rr = [0]
_dead = {} _dead = {}
@@ -90,6 +103,44 @@ def alive():
return live return live
def _slug_ok(slug, k, timeout=120):
body = json.dumps({"model": slug,
"messages": [{"role": "user", "content": "ping"}],
"max_tokens": 8}).encode()
req = urllib.request.Request(BASE + "/chat/completions", data=body,
headers={"Authorization": "Bearer " + k,
"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status == 200
except Exception:
return False
def health_loop(interval=120):
"""Держит каждый alias на живом слаге: база умерла -> резерв, база ожила -> обратно."""
time.sleep(20)
while True:
try:
ks = alive()
k = ks[int(time.time() // 600) % len(ks)] if ks else None
if k:
from concurrent.futures import ThreadPoolExecutor
pairs = [(a, b) for a, b in BASE_SLUG.items() if FALLBACK.get(a)]
with ThreadPoolExecutor(max_workers=4) as ex:
oks = list(ex.map(lambda ab: _slug_ok(ab[1], k, timeout=70), pairs))
for (alias, base), ok in zip(pairs, oks):
want = base if ok else FALLBACK[alias]
if MAP.get(alias) != want:
MAP[alias] = want
print("health: %s -> %s (%s)" % (alias, want, "base" if ok else "fallback"),
flush=True)
except Exception as e:
print("health err: %s" % str(e)[:120], flush=True)
time.sleep(interval)
class H(BaseHTTPRequestHandler): class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1" protocol_version = "HTTP/1.1"
@@ -145,7 +196,7 @@ class H(BaseHTTPRequestHandler):
payload = json.dumps(body).encode() payload = json.dumps(body).encode()
last = None last = None
for _ in range(4): for _ in range(6):
cand = alive() cand = alive()
if not cand: if not cand:
break break
@@ -158,7 +209,7 @@ class H(BaseHTTPRequestHandler):
headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"}, headers={"Authorization": "Bearer " + k, "Content-Type": "application/json"},
) )
try: try:
resp = urllib.request.urlopen(req, timeout=300) resp = urllib.request.urlopen(req, timeout=200)
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
code = e.code code = e.code
try: try:
@@ -174,8 +225,10 @@ class H(BaseHTTPRequestHandler):
last = (code, err) last = (code, err)
continue continue
if code == 429: if code == 429:
mark_dead(k, 30) # rate limit: короткая пауза mark_dead(k, 30) # rate limit: короткая пауза и другой ключ
elif code in (500, 502, 503, 504): last = (code, err)
continue
if code in (500, 502, 503, 504):
mark_dead(k, 15) # upstream flap: не вина ключа, пауза минимальная mark_dead(k, 15) # upstream flap: не вина ключа, пауза минимальная
last = (code, err) last = (code, err)
continue continue
@@ -226,4 +279,5 @@ class H(BaseHTTPRequestHandler):
if __name__ == "__main__": if __name__ == "__main__":
print("numes-shim on 127.0.0.1:%d models=%d keys=%d" % (PORT, len(MAP), len(keys())), flush=True) print("numes-shim on 127.0.0.1:%d models=%d keys=%d" % (PORT, len(MAP), len(keys())), flush=True)
threading.Thread(target=health_loop, daemon=True).start()
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever() ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()