fix: no import-time side effects, env-driven paths, shim dead-logic, smoke test

This commit is contained in:
ENI
2026-11-07 14:01:53 +03:00
parent 7cf876a87a
commit 0e68513e1b
6 changed files with 270 additions and 139 deletions
+1 -1
View File
@@ -24,7 +24,7 @@ from flow import solve_captcha
API = "https://api.minara.ai"
INVITE = os.environ.get("MINARA_INVITE", "UM9Y8P")
PROXIES = [p.strip() for p in os.environ.get("MINARA_PROXY_POOL", "").split(",") if p.strip()]
IMAPMAP_PATH = os.environ.get("MINARA_IMAPMAP", "discovered_imap.json")
IMAPMAP_PATH = os.environ.get("MINARA_IMAPMAP") or os.path.join(HERE, "discovered_imap.json")
IMAPMAP = json.load(open(IMAPMAP_PATH)) if os.path.exists(IMAPMAP_PATH) else {}
POP_HOSTS = {"rediffmail.com": ("pop.rediffmail.com", 995)}
BANK = os.environ.get("MINARA_BANK", HERE + "/bank.jsonl")
+5
View File
@@ -15,6 +15,7 @@ def bump(d, k):
d[k] = d.get(k, 0) + 1
def main():
for path in glob.glob(HERE + "/farm*.log"):
for line in io.open(path, encoding="utf8", errors="ignore"):
line = line.rstrip()
@@ -115,3 +116,7 @@ print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead))
print("whitelist pool:", len(rows), "| domains:", len({r["dom"] for r in rows}))
top = sorted(stats.items(), key=lambda kv: (-kv[1]["rate"], -kv[1]["ok"]))[:10]
print("top:", [(d, s["ok"], s["bad"]) for d, s in top])
if __name__ == "__main__":
main()
+20 -5
View File
@@ -2,7 +2,18 @@
"""Patch iishko gates for minara-pool models (line-based, no escape games)."""
import json, py_compile, shutil, time
MODELS = json.load(open("/root/minara_models.json", encoding="utf-8"))
import os
import sys
MODELS_PATH = os.environ.get("MINARA_MODELS_JSON", "minara_models.json")
GATE_SSO = os.environ.get("MINARA_GATE_SSO", "/root/sso_limits.py")
GATE_LEGACY = os.environ.get("MINARA_GATE_LEGACY", "/opt/grok-bot/iishko/legacy.py")
GATE_TOOL = os.environ.get("MINARA_GATE_TOOL", "/root/toolgate.py")
def main():
MODELS = json.load(open(MODELS_PATH, encoding="utf-8"))
ts = time.strftime("%Y%m%d-%H%M%S")
TAG = " # [MINARA 1106]"
@@ -50,10 +61,14 @@ def append_line(path, newline):
return "patched"
print("sso_limits:", insert_before("/root/sso_limits.py", "parts = [x.strip()", line_sso))
print("legacy:", insert_after("/opt/grok-bot/iishko/legacy.py",
print("sso_limits:", insert_before(GATE_SSO, "parts = [x.strip()", line_sso))
print("legacy:", insert_after(GATE_LEGACY,
"models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank))
print("toolgate:", append_line("/root/toolgate.py", line_tool))
for p in ("/root/sso_limits.py", "/opt/grok-bot/iishko/legacy.py", "/root/toolgate.py"):
print("toolgate:", append_line(GATE_TOOL, line_tool))
for p in (GATE_SSO, GATE_LEGACY, GATE_TOOL):
n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l)
print(p, "markers:", n)
if __name__ == "__main__":
main()
+4
View File
@@ -0,0 +1,4 @@
requests>=2.31
curl-cffi>=0.7 # MINARA_IMPERSONATE=chrome
playwright>=1.40 # browser_farm.py
psutil>=5.9
+9 -2
View File
@@ -16,7 +16,7 @@ Env:
MINARA_TOKENS (default /opt/minara-shim/tokens.jsonl)
MINARA_STATE (default /opt/minara-shim/state.json)
"""
import json, os, re, sys, threading, time
import json, os, random, re, sys, threading, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import requests
@@ -96,10 +96,17 @@ def pick(n=8):
start = RR[0] % len(live)
RR[0] += 1
live = live[start:] + live[:start]
return live[:n]
head = live[:n]
random.shuffle(head) # иначе первые живые токены получают весь трафик
return head
def mark_dead(t, code, body=""):
"""Помечаем токен мёртвым только на реальных отказах доступа.
400/404/422 — это ошибка тела запроса или имени модели, токен тут не виноват:
раньше любой 400 от невалидного запроса выключал живой аккаунт на 30 минут.
"""
with LOCK:
t["fail"] = t.get("fail", 0) + 1
if code in (401, 402, 403) or "insufficient" in (body or "").lower() or "quota" in (body or "").lower():
+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Smoke-тест: импорты без побочек + шим поднимается и отдаёт /health на пустом пуле.
Запуск: python smoke_test.py
Код возврата 0 = всё зелёное.
"""
import json
import os
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
FAILS = []
def check(name, cond, extra=""):
print(("PASS " if cond else "FAIL ") + name + (" " + extra if extra else ""))
if not cond:
FAILS.append(name)
# 1. импорты не должны тянуть сеть/файлы/печатать
for mod in ("core", "farm_parallel", "domain_score", "flow", "shim", "sync_tokens", "patch_gates2", "browser_farm"):
try:
__import__(mod)
check("import " + mod, True)
except Exception as e:
check("import " + mod, False, type(e).__name__ + " " + str(e)[:60])
# 2. шим на пустом пуле
port = 48199
tmp = tempfile.mkdtemp()
tokens = os.path.join(tmp, "tokens.jsonl")
open(tokens, "w").close()
env = dict(os.environ)
env.update({"MINARA_PORT": str(port), "MINARA_TOKENS": tokens,
"MINARA_STATE": os.path.join(tmp, "state.json")})
env.pop("PYTHONPATH", None)
proc = subprocess.Popen([sys.executable, os.path.join(HERE, "shim.py")], env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
ok = False
for _ in range(30):
time.sleep(0.5)
try:
with urllib.request.urlopen("http://127.0.0.1:%d/health" % port, timeout=2) as r:
body = json.loads(r.read().decode())
ok = r.status == 200 and body.get("tokens") == 0
break
except Exception:
continue
check("shim /health on empty pool", ok)
# 503 когда токенов нет
try:
body = json.dumps({"model": "claude-haiku-5.5", "messages": [{"role": "user", "content": "hi"}]}).encode()
req = urllib.request.Request("http://127.0.0.1:%d/v1/chat/completions" % port, data=body,
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=5)
check("shim 503 without tokens", False, "unexpected 200")
except urllib.error.HTTPError as e:
check("shim 503 without tokens", e.code == 503, "code=%d" % e.code)
except Exception as e:
check("shim 503 without tokens", False, str(e)[:60])
finally:
proc.terminate()
try:
proc.wait(timeout=5)
except Exception:
proc.kill()
# 3. map_model нормализует короткие имена
import shim # noqa: E402
shim.MODELS_CACHE["data"] = {"data": [{"id": "anthropic/claude-haiku-5.5"}, {"id": "openai/gpt-6.1-sol"}]}
check("map_model short name", shim.map_model("claude-haiku-5.5") == "anthropic/claude-haiku-5.5")
check("map_model passthrough", shim.map_model("openai/gpt-6.1-sol") == "openai/gpt-6.1-sol")
# 4. domain_score считает статистику на синтетическом логе
os.chdir(tmp)
open(os.path.join(tmp, "farm_test.log"), "w").write(
"OK a@good.com \r\nOK b@good.com \r\nFAIL c@dead.com mail \r\nFAIL d@dead.com mail \r\n")
import io
os.environ["MINARA_HOME"] = tmp
import importlib
import domain_score
importlib.reload(domain_score)
io.open(os.path.join(tmp, "pool_mix.jsonl"), "w").write(
json.dumps({"email": "e@good.com", "pw": "x", "dom": "good.com"}) + "\n" +
json.dumps({"email": "f@dead.com", "pw": "x", "dom": "dead.com"}) + "\n")
domain_score.main()
wl = io.open(os.path.join(tmp, "pool_whitelist.jsonl")).read().strip()
check("domain_score keeps only good domains", "e@good.com" in wl and "f@dead.com" not in wl, wl[:60])
print("\nRESULT:", "OK" if not FAILS else "FAILED %d: %s" % (len(FAILS), ",".join(FAILS)))
sys.exit(0 if not FAILS else 1)