fix: no import-time side effects, env-driven paths, shim dead-logic, smoke test
This commit is contained in:
@@ -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")
|
||||||
|
|||||||
+28
-23
@@ -15,7 +15,8 @@ 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 path in glob.glob(HERE + "/farm*.log"):
|
||||||
for line in io.open(path, encoding="utf8", errors="ignore"):
|
for line in io.open(path, encoding="utf8", errors="ignore"):
|
||||||
line = line.rstrip()
|
line = line.rstrip()
|
||||||
if not line or "@" not in line:
|
if not line or "@" not in line:
|
||||||
@@ -29,22 +30,22 @@ for path in glob.glob(HERE + "/farm*.log"):
|
|||||||
elif "FAIL" in line:
|
elif "FAIL" in line:
|
||||||
bump(bad, dom)
|
bump(bad, dom)
|
||||||
|
|
||||||
stats = {}
|
stats = {}
|
||||||
for dom in set(list(ok) + list(bad)):
|
for dom in set(list(ok) + list(bad)):
|
||||||
o, b = ok.get(dom, 0), bad.get(dom, 0)
|
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}
|
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)
|
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_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
|
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}
|
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}
|
dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2}
|
||||||
|
|
||||||
rows, seen = [], set()
|
rows, seen = [], set()
|
||||||
|
|
||||||
# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank)
|
# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank)
|
||||||
for name in ("farm_done.txt", "bank.jsonl"):
|
for name in ("farm_done.txt", "bank.jsonl"):
|
||||||
p = os.path.join(HERE, name)
|
p = os.path.join(HERE, name)
|
||||||
if not os.path.exists(p):
|
if not os.path.exists(p):
|
||||||
continue
|
continue
|
||||||
@@ -61,7 +62,7 @@ for name in ("farm_done.txt", "bank.jsonl"):
|
|||||||
if em:
|
if em:
|
||||||
seen.add(em)
|
seen.add(em)
|
||||||
|
|
||||||
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
||||||
p = os.path.join(HERE, f)
|
p = os.path.join(HERE, f)
|
||||||
if not os.path.exists(p):
|
if not os.path.exists(p):
|
||||||
continue
|
continue
|
||||||
@@ -80,14 +81,14 @@ for f in ("pool_mix.jsonl", "pool.jsonl"):
|
|||||||
seen.add(em)
|
seen.add(em)
|
||||||
rows.append(r)
|
rows.append(r)
|
||||||
|
|
||||||
with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh:
|
with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh:
|
||||||
for r in rows:
|
for r in rows:
|
||||||
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
||||||
|
|
||||||
# exploration lane: домены без статистики (новые), чтобы расширять whitelist
|
# exploration lane: домены без статистики (новые), чтобы расширять whitelist
|
||||||
explore = []
|
explore = []
|
||||||
seen2 = set()
|
seen2 = set()
|
||||||
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
for f in ("pool_mix.jsonl", "pool.jsonl"):
|
||||||
p = os.path.join(HERE, f)
|
p = os.path.join(HERE, f)
|
||||||
if not os.path.exists(p):
|
if not os.path.exists(p):
|
||||||
continue
|
continue
|
||||||
@@ -105,13 +106,17 @@ for f in ("pool_mix.jsonl", "pool.jsonl"):
|
|||||||
continue
|
continue
|
||||||
seen2.add(em)
|
seen2.add(em)
|
||||||
explore.append(r)
|
explore.append(r)
|
||||||
with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh:
|
with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh:
|
||||||
for r in explore:
|
for r in explore:
|
||||||
fh.write(json.dumps(r, ensure_ascii=False) + "\n")
|
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()
|
||||||
|
|||||||
+28
-13
@@ -2,16 +2,27 @@
|
|||||||
"""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():
|
||||||
|
|
||||||
|
MODELS = json.load(open(MODELS_PATH, encoding="utf-8"))
|
||||||
|
ts = time.strftime("%Y%m%d-%H%M%S")
|
||||||
|
TAG = " # [MINARA 1106]"
|
||||||
|
|
||||||
|
line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG
|
||||||
|
line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG
|
||||||
|
line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG
|
||||||
|
|
||||||
|
|
||||||
|
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"
|
||||||
@@ -25,7 +36,7 @@ def insert_after(path, anchor, newline):
|
|||||||
return "patched"
|
return "patched"
|
||||||
|
|
||||||
|
|
||||||
def insert_before(path, anchor, 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"
|
||||||
@@ -39,7 +50,7 @@ def insert_before(path, anchor, newline):
|
|||||||
return "patched"
|
return "patched"
|
||||||
|
|
||||||
|
|
||||||
def append_line(path, newline):
|
def append_line(path, 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"
|
||||||
@@ -50,10 +61,14 @@ def append_line(path, newline):
|
|||||||
return "patched"
|
return "patched"
|
||||||
|
|
||||||
|
|
||||||
print("sso_limits:", insert_before("/root/sso_limits.py", "parts = [x.strip()", line_sso))
|
print("sso_limits:", insert_before(GATE_SSO, "parts = [x.strip()", line_sso))
|
||||||
print("legacy:", insert_after("/opt/grok-bot/iishko/legacy.py",
|
print("legacy:", insert_after(GATE_LEGACY,
|
||||||
"models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank))
|
"models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank))
|
||||||
print("toolgate:", append_line("/root/toolgate.py", line_tool))
|
print("toolgate:", append_line(GATE_TOOL, line_tool))
|
||||||
for p in ("/root/sso_limits.py", "/opt/grok-bot/iishko/legacy.py", "/root/toolgate.py"):
|
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)
|
n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l)
|
||||||
print(p, "markers:", n)
|
print(p, "markers:", n)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
requests>=2.31
|
||||||
|
curl-cffi>=0.7 # MINARA_IMPERSONATE=chrome
|
||||||
|
playwright>=1.40 # browser_farm.py
|
||||||
|
psutil>=5.9
|
||||||
@@ -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
@@ -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)
|
||||||
Reference in New Issue
Block a user