sandbox: fix supervisor (double probe, real spawn), retry+log in run_code, route tool requests to native :48005 (shim drops streamed tool_calls), e2e proof
This commit is contained in:
@@ -69,11 +69,49 @@ Telegram юзер -> бот (VPS) -> tool run_code -> 127.0.0.1:48979 (VPS)
|
||||
- Патч чужого кода — только по точным якорям с проверкой `count == 1`: regex-замена по
|
||||
префиксу файла вставила код в шапку `legacy.py` и уронила сервис (восстановлено из бэкапа).
|
||||
|
||||
## Главный питфол: шим на :48000 теряет tool_calls
|
||||
|
||||
Бот ходил в new-api через python-шим `127.0.0.1:48000`. В **стриме** (SSE) шим вырезает
|
||||
`delta.tool_calls`: модель получает инструмент, но вместо вызова печатает текст вида
|
||||
```` ```run_code: print(2**64)``` ````, `finish_reason` приходит `stop` вместо `tool_calls`.
|
||||
Нативный new-api на `:48005` отдаёт корректно: `tool_chunks: [(0,'run_code')]`, `finish: tool_calls`.
|
||||
|
||||
Проверка (`probe_stream.py`, один и тот же payload в оба порта):
|
||||
|
||||
```
|
||||
:48000 -> tool_chunks: [] finish: stop text: '''run_code: print('SANDBOX_OK', 2**64)'''
|
||||
:48005 -> tool_chunks: [(0,'run_code')] finish: tool_calls
|
||||
```
|
||||
|
||||
Лечение — `patch_sbx_v4.py`: `GW_BASE_TOOLS` и стрим-вызов идёт на `:48005`, когда в payload
|
||||
есть `tools`. Прочие запросы остаются на шиме.
|
||||
|
||||
## Полный e2e (прод-код бота, `sim_round2.py`)
|
||||
|
||||
```
|
||||
base: http://127.0.0.1:48005/v1
|
||||
round1 tool_calls: [('run_code', '{"code": "print(\'SANDBOX_OK\', 2**64)"}')]
|
||||
TOOL_RESULT: stdout: SANDBOX_OK 18446744073709551616 | exit_code: 0, elapsed: 0.94s
|
||||
round2 status: 200
|
||||
ROUND2_TEXT: SANDBOX_OK 18446744073709551616
|
||||
```
|
||||
|
||||
Ещё два питфола супервизора (были причиной «sandbox unreachable» у юзера):
|
||||
|
||||
- вызов несуществующей `spawn()` при мёртвом брокере → NameError и супервизор падал целиком;
|
||||
- туннель убивался с **одного** флейк-проба (крон каждые 2 минуты) → обрыв прямо во время
|
||||
вызова бота. Теперь двойная проба с паузой 5 с, брокер спавнится `Popen(..., DETACHED_PROCESS)`.
|
||||
- в `run_code` добавлен ретрай (+2 с) и лог неудач `/opt/grok-bot/sbx_calls.log` (`patch_sbx_v3.py`).
|
||||
|
||||
## Файлы
|
||||
|
||||
- `exec_broker.py` — E2B-брокер (порт 48971)
|
||||
- `sandbox_sup.py` — супервизор брокера + туннеля
|
||||
- `sandbox_sup.py` — супервизор брокера + туннеля (двойная проба, анти-флейк)
|
||||
- `prove_exec.py` — приёмка (12/12)
|
||||
- `patch_sbx_v2.py` — патч бота (инструмент `run_code`)
|
||||
- `patch_sbx_v2.py` — патч бота: инструмент `run_code` в `BOT_TOOLS` + `_bot_tool_exec`
|
||||
- `patch_sbx_v3.py` — ретрай и лог неудач в ветке `run_code`
|
||||
- `patch_sbx_v4.py` — tool-запросы на нативный new-api `:48005` (обход потери tool_calls)
|
||||
- `probe_stream.py` — проверка tool_calls в стриме (сравнение портов)
|
||||
- `sim_round2.py` — полный e2e прод-кода: tool_call → exec → второй раунд
|
||||
- `config.json` — лимиты и порт
|
||||
- `broker.py`, `prove.py` — offense.sh-вариант (reference, не исполняет код)
|
||||
@@ -0,0 +1,48 @@
|
||||
#!/usr/bin/env python3
|
||||
# patch_sbx_v3.py — добавляет в run_code: лог неудач (тип исключения) + 1 ретрай.
|
||||
import time, shutil
|
||||
|
||||
SRC = "/opt/grok-bot/iishko/legacy.py"
|
||||
|
||||
A_OLD = ''' except Exception as e:
|
||||
return "[run_code] sandbox unreachable: %s" % type(e).__name__'''
|
||||
A_NEW = ''' except Exception as e:
|
||||
try:
|
||||
with open("/opt/grok-bot/sbx_calls.log", "a") as _lf:
|
||||
_lf.write("%s UNREACH1 %s %r\\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), type(e).__name__, str(e)[:300]))
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
time.sleep(2)
|
||||
import urllib.request
|
||||
_req = urllib.request.Request(
|
||||
"http://127.0.0.1:48979/v1/exec",
|
||||
data=json.dumps({"code": code, "timeout_s": timeout_s}).encode(),
|
||||
headers={"Content-Type": "application/json", "X-Sandbox-Key": _tok},
|
||||
method="POST")
|
||||
with urllib.request.urlopen(_req, timeout=timeout_s + 40) as _resp:
|
||||
out = json.loads(_resp.read().decode("utf-8", "replace"))
|
||||
except Exception as e2:
|
||||
try:
|
||||
with open("/opt/grok-bot/sbx_calls.log", "a") as _lf:
|
||||
_lf.write("%s UNREACH2 %s %r\\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), type(e2).__name__, str(e2)[:300]))
|
||||
except Exception:
|
||||
pass
|
||||
return "[run_code] sandbox unreachable: %s" % type(e2).__name__
|
||||
if not out.get("ok"):
|
||||
return "[run_code] error: %s" % str(out.get("error"))[:200]'''
|
||||
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
if "UNREACH1" in src:
|
||||
print("ALREADY PATCHED v3")
|
||||
else:
|
||||
assert src.count(A_OLD) == 1, "anchor not unique: %d" % src.count(A_OLD)
|
||||
bak = SRC + ".bak-sbx3-" + time.strftime("%Y%m%dT%H%M%S")
|
||||
shutil.copy2(SRC, bak)
|
||||
src = src.replace(A_OLD, A_NEW)
|
||||
open(SRC, "w", encoding="utf-8").write(src)
|
||||
print("PATCHED OK, backup:", bak)
|
||||
|
||||
import py_compile
|
||||
py_compile.compile(SRC, doraise=True)
|
||||
print("compile OK")
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
# patch_sbx_v4.py — tool-запросы шлём на нативный new-api :48005
|
||||
# (шим :48000 в стриме вырезает delta.tool_calls: finish=stop вместо tool_calls).
|
||||
import time, shutil
|
||||
|
||||
SRC = "/opt/grok-bot/iishko/legacy.py"
|
||||
|
||||
A1_OLD = '''GW_BASE = CFG.get("newapi_url", "http://127.0.0.1:48000").rstrip("/") + "/v1"
|
||||
GW_KEY = CFG.get("main_key") or ""'''
|
||||
A1_NEW = '''GW_BASE = CFG.get("newapi_url", "http://127.0.0.1:48000").rstrip("/") + "/v1"
|
||||
GW_KEY = CFG.get("main_key") or ""
|
||||
# [SBX-TOOLS 1114] шим :48000 в стриме теряет delta.tool_calls (finish=stop),
|
||||
# нативный new-api :48005 отдаёт tool_calls. Запросы с tools идут напрямую.
|
||||
GW_BASE_TOOLS = (CFG.get("newapi_tools_url") or GW_BASE.replace(":48000", ":48005")).rstrip("/")'''
|
||||
|
||||
A2_OLD = ''' async with s.post(GW_BASE + "/chat/completions", json=payload,'''
|
||||
A2_NEW = ''' async with s.post((GW_BASE_TOOLS if payload.get("tools") else GW_BASE) + "/chat/completions", json=payload,'''
|
||||
|
||||
src = open(SRC, encoding="utf-8").read()
|
||||
if "SBX-TOOLS 1114" in src:
|
||||
print("ALREADY PATCHED v4")
|
||||
else:
|
||||
assert src.count(A1_OLD) == 1, "A1 count=%d" % src.count(A1_OLD)
|
||||
assert src.count(A2_OLD) == 1, "A2 count=%d" % src.count(A2_OLD)
|
||||
bak = SRC + ".bak-sbx4-" + time.strftime("%Y%m%dT%H%M%S")
|
||||
shutil.copy2(SRC, bak)
|
||||
src = src.replace(A1_OLD, A1_NEW).replace(A2_OLD, A2_NEW)
|
||||
open(SRC, "w", encoding="utf-8").write(src)
|
||||
print("PATCHED OK, backup:", bak)
|
||||
|
||||
import py_compile
|
||||
py_compile.compile(SRC, doraise=True)
|
||||
print("compile OK")
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
# probe_stream.py — стрим-путь: приходят ли tool_calls дельты от :48000 (grok-4.7).
|
||||
import json, sys, urllib.request
|
||||
sys.path.insert(0, "/opt/grok-bot")
|
||||
import iishko.legacy as L
|
||||
|
||||
body = {"model": "grok-4.7",
|
||||
"messages": [{"role": "user", "content": "ОБЯЗАТЕЛЬНО вызови run_code: print('SANDBOX_OK', 2**64). Не отвечай по памяти."}],
|
||||
"tools": L.BOT_TOOLS, "tool_choice": "auto", "max_tokens": 300, "stream": True}
|
||||
|
||||
for base in ("http://127.0.0.1:48000/v1", "http://127.0.0.1:48005/v1"):
|
||||
req = urllib.request.Request(base + "/chat/completions", data=json.dumps(body).encode(),
|
||||
headers={"Authorization": "Bearer " + L.GW_KEY,
|
||||
"Content-Type": "application/json"}, method="POST")
|
||||
names, txt, fr = [], [], None
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=90) as r:
|
||||
for raw in r:
|
||||
line = raw.decode("utf-8", "replace").strip()
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
data = line[5:].strip()
|
||||
if data == "[DONE]":
|
||||
break
|
||||
try:
|
||||
ch = json.loads(data)
|
||||
except ValueError:
|
||||
continue
|
||||
c0 = (ch.get("choices") or [{}])[0]
|
||||
if c0.get("finish_reason"):
|
||||
fr = c0["finish_reason"]
|
||||
d = c0.get("delta") or {}
|
||||
if d.get("content"):
|
||||
txt.append(d["content"])
|
||||
for tc in (d.get("tool_calls") or []):
|
||||
fn = tc.get("function") or {}
|
||||
names.append((tc.get("index"), fn.get("name")))
|
||||
print(base, "| tool_chunks:", names[:6], "| finish:", fr, "| text:", "".join(txt)[:100].replace("\n", " "))
|
||||
except Exception as e:
|
||||
print(base, "ERR", type(e).__name__, str(e)[:150])
|
||||
+9
-1
@@ -73,7 +73,10 @@ def main():
|
||||
else:
|
||||
kill_matching("exec_broker.py")
|
||||
time.sleep(1)
|
||||
spawn([PY311, os.path.join(HOME_DIR, "exec_broker.py")], out="broker.log")
|
||||
with open(os.path.join(HOME_DIR, "broker.log"), "ab") as fh:
|
||||
subprocess.Popen([PY311, os.path.join(HOME_DIR, "exec_broker.py")], cwd=HOME_DIR,
|
||||
stdout=fh, stderr=subprocess.STDOUT, creationflags=DETACHED,
|
||||
stdin=subprocess.DEVNULL, close_fds=True)
|
||||
time.sleep(6)
|
||||
log("broker " + ("started" if http_ok(LOCAL_HEALTH) else "START FAILED"))
|
||||
|
||||
@@ -82,6 +85,11 @@ def main():
|
||||
if ok:
|
||||
log("tunnel ok")
|
||||
return
|
||||
time.sleep(5)
|
||||
ok, _ = vps_probe()
|
||||
if ok:
|
||||
log("tunnel ok (2nd probe)")
|
||||
return
|
||||
kill_matching(VPS_FWD)
|
||||
time.sleep(1)
|
||||
spawn_detached_cmd("ssh %s -N -R %s %s" % (SSH_OPTS, VPS_FWD, VPS))
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
# sim_round2.py — полная симуляция двух раундов как у бота: stream(tools) -> run_code -> stream(result).
|
||||
import asyncio, json, sys
|
||||
sys.path.insert(0, "/opt/grok-bot")
|
||||
|
||||
async def main():
|
||||
import iishko.legacy as L
|
||||
model = "deepseek-v4.1-flash-1017"
|
||||
messages = [{"role": "user", "content": "ОБЯЗАТЕЛЬНО вызови run_code: print('SANDBOX_OK', 2**64). Не отвечай по памяти."}]
|
||||
|
||||
# раунд 1: получаем tool_calls через тот же _gw путь, что и бот
|
||||
acc = {}
|
||||
async def send(txt):
|
||||
return None
|
||||
# прямой вызов стрима бота с перехватом
|
||||
payload = {"model": model, "messages": messages, "max_tokens": 400, "stream": True,
|
||||
**L._thinking_off(model), "tools": L.BOT_TOOLS}
|
||||
if model not in L.TOOL_CHOICE_REJECTED_MODELS:
|
||||
payload["tool_choice"] = "auto"
|
||||
import aiohttp
|
||||
base = L.GW_BASE_TOOLS if payload.get("tools") else L.GW_BASE
|
||||
print("base:", base)
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(base + "/chat/completions", json=payload,
|
||||
headers={"Authorization": "Bearer " + L.GW_KEY},
|
||||
timeout=aiohttp.ClientTimeout(total=90)) as r:
|
||||
print("status:", r.status)
|
||||
async for raw in r.content:
|
||||
line = raw.decode("utf-8", "replace").strip()
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
d0 = line[5:].strip()
|
||||
if d0 == "[DONE]":
|
||||
break
|
||||
try:
|
||||
ch = json.loads(d0)
|
||||
except ValueError:
|
||||
continue
|
||||
c0 = (ch.get("choices") or [{}])[0]
|
||||
for tc in ((c0.get("delta") or {}).get("tool_calls") or []):
|
||||
i = tc.get("index", 0)
|
||||
a = acc.setdefault(i, {"id": "", "type": "function", "function": {"name": "", "arguments": ""}})
|
||||
if tc.get("id"):
|
||||
a["id"] = tc["id"]
|
||||
fn = tc.get("function") or {}
|
||||
if fn.get("name"):
|
||||
a["function"]["name"] = fn["name"]
|
||||
if fn.get("arguments"):
|
||||
a["function"]["arguments"] += fn["arguments"]
|
||||
tcs = list(acc.values())
|
||||
print("round1 tool_calls:", [(t["function"]["name"], t["function"]["arguments"][:60]) for t in tcs])
|
||||
if not tcs:
|
||||
print("NO_TOOL_CALLS"); return
|
||||
|
||||
# исполняем
|
||||
res = await L._bot_tool_exec(tcs[0]["function"]["name"], json.loads(tcs[0]["function"]["arguments"] or "{}"))
|
||||
print("TOOL_RESULT:", res[:300].replace("\n", " | "))
|
||||
|
||||
# раунд 2: отдаём результат модели
|
||||
messages2 = messages + [{"role": "assistant", "content": None, "tool_calls": tcs},
|
||||
{"role": "tool", "tool_call_id": tcs[0].get("id", ""), "content": res}]
|
||||
payload2 = {"model": model, "messages": messages2, "max_tokens": 400, "stream": True,
|
||||
**L._thinking_off(model)}
|
||||
txt = []
|
||||
async with aiohttp.ClientSession() as s:
|
||||
async with s.post(base + "/chat/completions", json=payload2,
|
||||
headers={"Authorization": "Bearer " + L.GW_KEY},
|
||||
timeout=aiohttp.ClientTimeout(total=90)) as r:
|
||||
print("round2 status:", r.status)
|
||||
async for raw in r.content:
|
||||
line = raw.decode("utf-8", "replace").strip()
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
d0 = line[5:].strip()
|
||||
if d0 == "[DONE]":
|
||||
break
|
||||
try:
|
||||
ch = json.loads(d0)
|
||||
except ValueError:
|
||||
continue
|
||||
c0 = (ch.get("choices") or [{}])[0]
|
||||
t = (c0.get("delta") or {}).get("content")
|
||||
if t:
|
||||
txt.append(t)
|
||||
print("ROUND2_TEXT:", "".join(txt)[:400].replace("\n", " | "))
|
||||
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user