okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-1402-w' into f-140253623e56f

main
6.1 KiB125 linesraw
1#!/usr/bin/env python3
2"""#1012 на живом сервере: запрос ждёт движок, движок умирает во время чтения промпта.
3
4Что проверяем (из релиза v0.1.40.1): раньше запрос, дожидавшийся перезапуска мёртвого движка,
5висел навсегда или падал с `list.remove(x)`, а длинный промпт, который читался в момент смерти
6движка, завершался через ~300 с. Теперь тот же запрос либо продолжается с новым движком, либо
7заканчивается сразу с 503 («не отправлен» -> клиент может повторить).
8
9Ход: отправить длинный запрос -> через N секунд убить процесс движка -> смотреть, чем и когда
10закончится запрос. Сервер поднимает движок сам.
11
12usage: probe_restart_waiters.py [--kill-after 15] [--out results_restart.json]
13"""
14import json
15import pathlib
16import subprocess
17import threading
18import time
19import urllib.error
20import urllib.request
21
22REPO = "/home/dgbox/Strata"
23CFG = REPO + "/strata-200k.json"
24BASE = "http://127.0.0.1:8080"
25cfg = json.load(open(CFG, encoding="utf-8"))
26KEY, MODEL = cfg["api_key"], cfg.get("model_name", "strata")
27
28FILLER = ("Разбирается модуль разбора конфигурации: он читает список секций, проверяет обязательные поля и "
29          "собирает структуру настроек, которую дальше использует планировщик. Сбой на одной секции не должен "
30          "останавливать остальные, поэтому парсер собирает список замечаний. ")
31
32
33def big_prompt(tokens: int) -> str:
34    # ~0.28 токена на символ для русского текста
35    return (FILLER * (int(tokens / 0.28 / len(FILLER)) + 1))[:int(tokens / 0.28)]
36
37
38def send(rec, label, tokens):
39    payload = json.dumps({"model": MODEL, "messages": [{"role": "user",
40                        "content": big_prompt(tokens) + "\n\nОтветь одним словом."}],
41                        "max_tokens": 32, "stream": True, "reasoning_effort": "none"}).encode()
42    req = urllib.request.Request(BASE + "/v1/chat/completions", data=payload,
43                                headers={"Content-Type": "application/json",
44                                         "Authorization": f"Bearer {KEY}"})
45    t0 = time.time()
46    out = {"label": label, "prompt_tokens_asked": tokens, "started_at": round(t0, 3),
47           "first_delta_s": None, "end_s": None, "http_status": None, "outcome": None,
48           "deltas": 0}
49    try:
50        with urllib.request.urlopen(req, timeout=600) as r:
51            out["http_status"] = r.status
52            for line in r:
53                s = line.decode(errors="replace").strip()
54                if not s.startswith("data:"):
55                    continue
56                data = s[5:].strip()
57                if data == "[DONE]":
58                    break
59                try:
60                    obj = json.loads(data)
61                except json.JSONDecodeError:
62                    continue
63                for ch in obj.get("choices", []):
64                    if (ch.get("delta") or {}).get("content"):
65                        out["deltas"] += 1
66                        if out["first_delta_s"] is None:
67                            out["first_delta_s"] = round(time.time() - t0, 2)
68        out["outcome"] = "done"
69    except urllib.error.HTTPError as e:
70        out["outcome"] = f"HTTPError {e.code}"
71        out["http_status"] = e.code
72        try:
73            out["error_body"] = e.read().decode()[:300]
74        except Exception:  # noqa: BLE001
75            pass
76    except Exception as e:  # noqa: BLE001
77        out["outcome"] = repr(e)[:200]
78    out["end_s"] = round(time.time() - t0, 2)
79    print(f"[{label}] status={out['http_status']} outcome={out['outcome']} "
80          f"first_delta={out['first_delta_s']} end={out['end_s']} deltas={out['deltas']}")
81    rec.append(out)
82
83
84def main():
85    import argparse
86    ap = argparse.ArgumentParser()
87    ap.add_argument("--kill-after", type=float, default=15.0)
88    ap.add_argument("--out", default=str(pathlib.Path(__file__).parent / "results_restart.json"))
89    a = ap.parse_args()
90
91    before = subprocess.run(["pgrep", "-f", REPO + "/engine/strata"], capture_output=True, text=True).stdout.split()
92    recs = []
93    threads = [threading.Thread(target=send, args=(recs, f"waiter-{i}", 60000)) for i in range(1, 4)]
94    for t in threads:
95        t.start()
96    time.sleep(a.kill_after)
97    killed = subprocess.run(["pkill", "-f", REPO + "/engine/strata"], capture_output=True, text=True)
98    kill_at = round(time.time(), 3)
99    print(f"движок убит через {a.kill_after} с: pkill rc={killed.returncode} (pid до: {before})")
100    for t in threads:
101        t.join(timeout=420)
102
103    health = None
104    for _ in range(80):
105        try:
106            with urllib.request.urlopen(urllib.request.Request(BASE + "/health"), timeout=5) as r:
107                h = json.loads(r.read().decode())
108            if h.get("loaded"):
109                health = {"recovered_after_kill_s": round(time.time() - kill_at, 1), "health": h}
110                break
111        except Exception:  # noqa: BLE001
112            pass
113        time.sleep(3)
114
115    out = {"kill_after_s": a.kill_after, "engine_pids_before": before, "killed_at": kill_at,
116           "requests": recs, "server_recovered": health,
117           "log_tail": subprocess.run(["bash", "-c",
118                                      f"tail -n 200 {REPO}/strata-200k.log | grep -iE 'engine|restart|503|died|wait' | tail -15"],
119                                     capture_output=True, text=True).stdout}
120    pathlib.Path(a.out).write_text(json.dumps(out, ensure_ascii=False, indent=1), encoding="utf-8")
121    print("записано:", a.out)
122
123
124if __name__ == "__main__":
125    main()