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" API = "https://api.minara.ai"
INVITE = os.environ.get("MINARA_INVITE", "UM9Y8P") INVITE = os.environ.get("MINARA_INVITE", "UM9Y8P")
PROXIES = [p.strip() for p in os.environ.get("MINARA_PROXY_POOL", "").split(",") if p.strip()] 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 {} IMAPMAP = json.load(open(IMAPMAP_PATH)) if os.path.exists(IMAPMAP_PATH) else {}
POP_HOSTS = {"rediffmail.com": ("pop.rediffmail.com", 995)} POP_HOSTS = {"rediffmail.com": ("pop.rediffmail.com", 995)}
BANK = os.environ.get("MINARA_BANK", HERE + "/bank.jsonl") BANK = os.environ.get("MINARA_BANK", HERE + "/bank.jsonl")
+95 -90
View File
@@ -15,103 +15,108 @@ def bump(d, k):
d[k] = d.get(k, 0) + 1 d[k] = d.get(k, 0) + 1
for path in glob.glob(HERE + "/farm*.log"): def main():
for line in io.open(path, encoding="utf8", errors="ignore"): for path in glob.glob(HERE + "/farm*.log"):
line = line.rstrip() for line in io.open(path, encoding="utf8", errors="ignore"):
if not line or "@" not in line: line = line.rstrip()
if not line or "@" not in line:
continue
m = re.search(r"@([A-Za-z0-9._-]+)", line)
if not m:
continue
dom = m.group(1).lower()
if line.startswith("OK "):
bump(ok, dom)
elif "FAIL" in line:
bump(bad, dom)
stats = {}
for dom in set(list(ok) + list(bad)):
o, b = ok.get(dom, 0), bad.get(dom, 0)
stats[dom] = {"ok": o, "bad": b, "rate": round(o / (o + b), 3) if o + b else 0}
json.dump(stats, io.open(HERE + "/domain_stats.json", "w", encoding="utf8"), ensure_ascii=False, indent=1)
min_rate = float(sys.argv[1]) if len(sys.argv) > 1 else 0.4
min_ok = int(sys.argv[2]) if len(sys.argv) > 2 else 1
good = {d for d, s in stats.items() if s["ok"] >= min_ok and s["rate"] >= min_rate}
dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2}
rows, seen = [], set()
# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank)
for name in ("farm_done.txt", "bank.jsonl"):
p = os.path.join(HERE, name)
if not os.path.exists(p):
continue continue
m = re.search(r"@([A-Za-z0-9._-]+)", line) for line in io.open(p, encoding="utf8", errors="ignore"):
if not m: line = line.strip()
if not line:
continue
em = line.split("\t")[0].strip().lower()
if name == "bank.jsonl":
try:
em = (json.loads(line).get("email") or "").strip().lower()
except Exception:
pass
if em:
seen.add(em)
for f in ("pool_mix.jsonl", "pool.jsonl"):
p = os.path.join(HERE, f)
if not os.path.exists(p):
continue continue
dom = m.group(1).lower() for line in io.open(p, encoding="utf8", errors="ignore"):
if line.startswith("OK "): line = line.strip()
bump(ok, dom) if not line:
elif "FAIL" in line: continue
bump(bad, dom)
stats = {}
for dom in set(list(ok) + list(bad)):
o, b = ok.get(dom, 0), bad.get(dom, 0)
stats[dom] = {"ok": o, "bad": b, "rate": round(o / (o + b), 3) if o + b else 0}
json.dump(stats, io.open(HERE + "/domain_stats.json", "w", encoding="utf8"), ensure_ascii=False, indent=1)
min_rate = float(sys.argv[1]) if len(sys.argv) > 1 else 0.4
min_ok = int(sys.argv[2]) if len(sys.argv) > 2 else 1
good = {d for d, s in stats.items() if s["ok"] >= min_ok and s["rate"] >= min_rate}
dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2}
rows, seen = [], set()
# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank)
for name in ("farm_done.txt", "bank.jsonl"):
p = os.path.join(HERE, name)
if not os.path.exists(p):
continue
for line in io.open(p, encoding="utf8", errors="ignore"):
line = line.strip()
if not line:
continue
em = line.split("\t")[0].strip().lower()
if name == "bank.jsonl":
try: try:
em = (json.loads(line).get("email") or "").strip().lower() r = json.loads(line)
except Exception: except Exception:
pass continue
if em: dom = (r.get("dom") or "").lower()
em = (r.get("email") or "").lower()
if em in seen or dom in dead or dom not in good:
continue
seen.add(em) seen.add(em)
rows.append(r)
for f in ("pool_mix.jsonl", "pool.jsonl"): with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh:
p = os.path.join(HERE, f) for r in rows:
if not os.path.exists(p): fh.write(json.dumps(r, ensure_ascii=False) + "\n")
continue
for line in io.open(p, encoding="utf8", errors="ignore"):
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except Exception:
continue
dom = (r.get("dom") or "").lower()
em = (r.get("email") or "").lower()
if em in seen or dom in dead or dom not in good:
continue
seen.add(em)
rows.append(r)
with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh: # exploration lane: домены без статистики (новые), чтобы расширять whitelist
for r in rows: explore = []
fh.write(json.dumps(r, ensure_ascii=False) + "\n") seen2 = set()
for f in ("pool_mix.jsonl", "pool.jsonl"):
# exploration lane: домены без статистики (новые), чтобы расширять whitelist p = os.path.join(HERE, f)
explore = [] if not os.path.exists(p):
seen2 = set()
for f in ("pool_mix.jsonl", "pool.jsonl"):
p = os.path.join(HERE, f)
if not os.path.exists(p):
continue
for line in io.open(p, encoding="utf8", errors="ignore"):
line = line.strip()
if not line:
continue continue
try: for line in io.open(p, encoding="utf8", errors="ignore"):
r = json.loads(line) line = line.strip()
except Exception: if not line:
continue continue
dom = (r.get("dom") or "").lower() try:
em = (r.get("email") or "").lower() r = json.loads(line)
if dom in stats or em in seen or em in seen2: except Exception:
continue continue
seen2.add(em) dom = (r.get("dom") or "").lower()
explore.append(r) em = (r.get("email") or "").lower()
with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh: if dom in stats or em in seen or em in seen2:
for r in explore: continue
fh.write(json.dumps(r, ensure_ascii=False) + "\n") seen2.add(em)
explore.append(r)
with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh:
for r in explore:
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
print("explore pool (unseen domains):", len(explore), "| domains:", len({r["dom"] for r in explore})) print("explore pool (unseen domains):", len(explore), "| domains:", len({r["dom"] for r in explore}))
print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead)) print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead))
print("whitelist pool:", len(rows), "| domains:", len({r["dom"] for r in rows})) 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] 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]) print("top:", [(d, s["ok"], s["bad"]) for d, s in top])
if __name__ == "__main__":
main()
+61 -46
View File
@@ -2,58 +2,73 @@
"""Patch iishko gates for minara-pool models (line-based, no escape games).""" """Patch iishko gates for minara-pool models (line-based, no escape games)."""
import json, py_compile, shutil, time import json, py_compile, shutil, time
MODELS = json.load(open("/root/minara_models.json", encoding="utf-8")) import os
ts = time.strftime("%Y%m%d-%H%M%S") import sys
TAG = " # [MINARA 1106]"
line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG MODELS_PATH = os.environ.get("MINARA_MODELS_JSON", "minara_models.json")
line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG GATE_SSO = os.environ.get("MINARA_GATE_SSO", "/root/sso_limits.py")
line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG 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 insert_after(path, anchor, newline): def main():
lines = open(path, encoding="utf-8").read().split("\n")
if any("MINARA 1106" in l for l in lines): MODELS = json.load(open(MODELS_PATH, encoding="utf-8"))
return "already" ts = time.strftime("%Y%m%d-%H%M%S")
idx = [i for i, l in enumerate(lines) if anchor in l] TAG = " # [MINARA 1106]"
if not idx:
return "anchor-missing" line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG
shutil.copy2(path, path + ".bak-minara-" + ts) line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG
out = lines[:idx[0] + 1] + [newline] + lines[idx[0] + 1:] line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG
open(path, "w", encoding="utf-8").write("\n".join(out))
py_compile.compile(path, doraise=True)
return "patched"
def insert_before(path, anchor, newline): def insert_after(path, anchor, newline):
lines = open(path, encoding="utf-8").read().split("\n") lines = open(path, encoding="utf-8").read().split("\n")
if any("MINARA 1106" in l for l in lines): if any("MINARA 1106" in l for l in lines):
return "already" return "already"
idx = [i for i, l in enumerate(lines) if anchor in l] idx = [i for i, l in enumerate(lines) if anchor in l]
if not idx: if not idx:
return "anchor-missing" return "anchor-missing"
shutil.copy2(path, path + ".bak-minara-" + ts) shutil.copy2(path, path + ".bak-minara-" + ts)
out = lines[:idx[0]] + [newline] + lines[idx[0]:] out = lines[:idx[0] + 1] + [newline] + lines[idx[0] + 1:]
open(path, "w", encoding="utf-8").write("\n".join(out)) open(path, "w", encoding="utf-8").write("\n".join(out))
py_compile.compile(path, doraise=True) py_compile.compile(path, doraise=True)
return "patched" return "patched"
def append_line(path, newline): def insert_before(path, anchor, newline):
lines = open(path, encoding="utf-8").read().split("\n") lines = open(path, encoding="utf-8").read().split("\n")
if any("MINARA 1106" in l for l in lines): if any("MINARA 1106" in l for l in lines):
return "already" return "already"
shutil.copy2(path, path + ".bak-minara-" + ts) idx = [i for i, l in enumerate(lines) if anchor in l]
out = lines + [newline, ""] if not idx:
open(path, "w", encoding="utf-8").write("\n".join(out)) return "anchor-missing"
py_compile.compile(path, doraise=True) shutil.copy2(path, path + ".bak-minara-" + ts)
return "patched" out = lines[:idx[0]] + [newline] + lines[idx[0]:]
open(path, "w", encoding="utf-8").write("\n".join(out))
py_compile.compile(path, doraise=True)
return "patched"
print("sso_limits:", insert_before("/root/sso_limits.py", "parts = [x.strip()", line_sso)) def append_line(path, newline):
print("legacy:", insert_after("/opt/grok-bot/iishko/legacy.py", lines = open(path, encoding="utf-8").read().split("\n")
"models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank)) if any("MINARA 1106" in l for l in lines):
print("toolgate:", append_line("/root/toolgate.py", line_tool)) return "already"
for p in ("/root/sso_limits.py", "/opt/grok-bot/iishko/legacy.py", "/root/toolgate.py"): shutil.copy2(path, path + ".bak-minara-" + ts)
n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l) out = lines + [newline, ""]
print(p, "markers:", n) open(path, "w", encoding="utf-8").write("\n".join(out))
py_compile.compile(path, doraise=True)
return "patched"
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(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_TOKENS (default /opt/minara-shim/tokens.jsonl)
MINARA_STATE (default /opt/minara-shim/state.json) 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 from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import requests import requests
@@ -96,10 +96,17 @@ def pick(n=8):
start = RR[0] % len(live) start = RR[0] % len(live)
RR[0] += 1 RR[0] += 1
live = live[start:] + live[:start] live = live[start:] + live[:start]
return live[:n] head = live[:n]
random.shuffle(head) # иначе первые живые токены получают весь трафик
return head
def mark_dead(t, code, body=""): def mark_dead(t, code, body=""):
"""Помечаем токен мёртвым только на реальных отказах доступа.
400/404/422 — это ошибка тела запроса или имени модели, токен тут не виноват:
раньше любой 400 от невалидного запроса выключал живой аккаунт на 30 минут.
"""
with LOCK: with LOCK:
t["fail"] = t.get("fail", 0) + 1 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(): 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)