#!/usr/bin/env python3 """Dashboard eval-progress patch (Young's request 2026-11-20 15:01): add a self-discovering "Tien do eval" section to the sera-v4 dashboard (~/sera_v4_dashboard/server.py). - eval_progress() scans every *.jsonl eval result in the result dirs the dashboard knows (fewshot/results, frontend_probe/results, round2_probe/results, measurement/results) on each collect() call, so future eval tasks appear automatically with no code change. - Per file: episodes = parsed JSONL rows, success = rows with truthy "success", expected total inferred from the companion .log first, then from protocol name patterns (cond/e3 -> 180, z -> 60, o2ctrl -> 30, probe dirs/horizon/oracle -> 70), else null ("chua ro tong" -- never fabricate a denominator). - Status: RUNNING when a live eval process writes that exact file (--out in cmdline, or an open fd in /proc, or mtime < 180s), DONE when rows >= expected, PARTIAL when short with no writer, UNKNOWN when the total cannot be inferred. - Smoke/trace files are skipped, same convention as probe_files(). Every replacement is exact-match asserted. Backup: server.py.bak-eval-20261120. """ import shutil from pathlib import Path P = Path.home() / "sera_v4_dashboard" / "server.py" src = P.read_text() orig = src EVAL_FUNCS = ''' def _eval_expected_total(fn, dirkey, path): """Suy tong episode ky vong cua mot file eval: log di kem truoc, mau ten file theo giao thuc sau. Khong suy ra duoc -> None (hien 'chua ro tong').""" logp = path[:-len(".jsonl")] + ".log" try: text = _read_tail(logp, 131072) for pat in (r"episodes?\\s*[:=]\\s*(\\d{2,4})", r"total[ _]?episodes?\\s*[:=]\\s*(\\d{2,4})", r"\\b(\\d{2,4})\\s+episodes?\\b"): v = _last_float(pat, text) if v: return int(v) except Exception: pass low = fn.lower() if "o2ctrl" in low: return 30 if "cond" in low or "-e3-" in low: return 180 if "comp-z" in low or re.search(r"(^|[-_])z([-_.]|$)", low): return 60 if dirkey in ("frontend_probe", "round2_probe") or "probe" in low \\ or "horizon" in low or "oracle" in low: return 70 return None def _eval_active_files(): """Tap path .jsonl dang duoc tien trinh eval ghi: --out trong cmdline hoac fd dang mo cua tien trinh eval (loai tru chinh dashboard).""" active = set() try: r = subprocess.run(["pgrep", "-af", "python"], capture_output=True, text=True, timeout=6) for line in r.stdout.splitlines(): if "eval" not in line: continue m = re.search(r"--out[= ](\\S+\\.jsonl)", line) if m: active.add(os.path.abspath(m.group(1))) except Exception: pass me = str(os.getpid()) try: for pid in os.listdir("/proc"): if not pid.isdigit() or pid == me: continue try: with open(os.path.join("/proc", pid, "cmdline"), "rb") as f: cmd = f.read().decode("utf-8", errors="ignore") except Exception: continue if "eval" not in cmd: continue fdd = os.path.join("/proc", pid, "fd") try: fds = os.listdir(fdd) except Exception: continue for fd in fds: try: t = os.readlink(os.path.join(fdd, fd)) except Exception: continue if t.endswith(".jsonl"): active.add(t) except Exception: pass return active def _age_text(age): if age is None: return None if age < 90: return "vua xong" if age < 3600: return "%d phut truoc" % int(age // 60) if age < 86400: return "%d gio truoc" % int(age // 3600) return "%d ngay truoc" % int(age // 86400) def eval_progress(): """Tu phat hien moi file .jsonl ket qua eval trong cac thu muc ket qua da biet; doc tuoi moi lan collect() nen eval moi tu hien.""" active = _eval_active_files() now = time.time() rows = [] for dirkey, folder in EVAL_DIRS: try: files = sorted(os.listdir(folder)) except Exception: continue for fn in files: if not fn.endswith(".jsonl") or ".trace" in fn or "smoke" in fn: continue path = os.path.join(folder, fn) n = succ = 0 try: with open(path, errors="ignore") as f: for line in f: line = line.strip() if not line: continue try: r = json.loads(line) except Exception: continue n += 1 if r.get("success"): succ += 1 except Exception: continue try: age = now - os.path.getmtime(path) except Exception: age = None expected = _eval_expected_total(fn, dirkey, path) running = os.path.abspath(path) in active or \\ (age is not None and age < 180) if running: status = "RUNNING" elif expected is not None and n >= expected: status = "DONE" elif expected is not None: status = "PARTIAL" else: status = "UNKNOWN" rows.append({ "name": fn[:-len(".jsonl")], "file": fn, "dir": dirkey, "episodes": n, "expected": expected, "pct": round(100.0 * n / expected, 1) if expected else None, "success": succ, "success_rate": round(100.0 * succ / n, 1) if n else None, "status": status, "age_s": round(age) if age is not None else None, "age_text": _age_text(age), }) rank = {"RUNNING": 0, "PARTIAL": 1, "UNKNOWN": 2, "DONE": 3} rows.sort(key=lambda r: (rank.get(r["status"], 9), r["age_s"] if r["age_s"] is not None else 10 ** 12)) return rows ''' EVAL_RENDER = ''' if(d.eval_progress&&d.eval_progress.length){ let s=""; for(const e of d.eval_progress){ const tot=e.expected?e.episodes+"/"+e.expected:e.episodes+" / chưa rõ tổng"; s+=``; } $("evals").innerHTML=s+"
EvalThư mụcEpisode% xongThành côngTrạng tháiCập nhật
${e.name}${e.dir}${tot}${e.pct===null?"—":e.pct+"%"}${e.success} (${e.success_rate===null?"—":e.success_rate+"%"})${ebadge(e.status)}${e.age_text||"—"}
"; } else $("evals").innerHTML="—"; ''' REPLACEMENTS = [] # 1. FS_RES + EVAL_DIRS constants after FE_RES REPLACEMENTS.append(( 'FE_RES = os.path.join(EXP, "frontend_probe", "results")\n', 'FE_RES = os.path.join(EXP, "frontend_probe", "results")\n' 'FS_RES = os.path.join(EXP, "fewshot", "results")\n' 'EVAL_DIRS = [("fewshot", FS_RES), ("frontend_probe", FE_RES),\n' ' ("round2_probe", R2_RES), ("measurement", MEAS_DIR)]\n', )) # 2. eval functions before collect() REPLACEMENTS.append(( "def collect():\n", EVAL_FUNCS + "def collect():\n", )) # 3. collect(): add eval_progress payload REPLACEMENTS.append(( ' "ledger": VERDICT_LEDGER,\n', ' "ledger": VERDICT_LEDGER,\n' ' "eval_progress": eval_progress(),\n', )) # 4. CSS: partial / unknown badges REPLACEMENTS.append(( ".badge.fail{background:var(--red)} .badge.pass{background:var(--green)} .badge.stopped{background:#5a6b7a} .badge.cancel{background:#8a97a5}", ".badge.fail{background:var(--red)} .badge.pass{background:var(--green)} .badge.stopped{background:#5a6b7a} .badge.cancel{background:#8a97a5}\n" " .badge.part{background:var(--orange)} .badge.unk{background:#8a97a5}", )) # 5. HTML: eval section before the verdict ledger section REPLACEMENTS.append(( '

Tổng kết verdict toàn chương trình

\n', '

Tiến độ eval

\n' '

Tự động quét mọi file .jsonl kết quả eval trong fewshot/results, frontend_probe/results, round2_probe/results, measurement/results — task eval mới tự hiện ở lần tải kế tiếp, không cần sửa dashboard. RUNNING = có tiến trình eval đang ghi vào đúng file đó; DONE = đủ số episode kỳ vọng; PARTIAL = thiếu episode và không còn tiến trình ghi; tổng kỳ vọng suy từ log đi kèm hoặc giao thức theo tên file, không suy ra được thì ghi "chưa rõ tổng".

\n' '

Tổng kết verdict toàn chương trình

\n', )) # 6. JS: ebadge helper after vbadge REPLACEMENTS.append(( 'function vbadge(s){return s?`${s}`:"—"}\n', 'function vbadge(s){return s?`${s}`:"—"}\n' 'function ebadge(s){const c=s==="RUNNING"?"run":s==="DONE"?"done":s==="PARTIAL"?"part":"unk";return `${s==="UNKNOWN"?"CHƯA RÕ":s}`}\n', )) # 7. JS: eval render before ledger render REPLACEMENTS.append(( " if(d.ledger&&d.ledger.length){", EVAL_RENDER + " if(d.ledger&&d.ledger.length){", )) for i, (old, new) in enumerate(REPLACEMENTS): n = src.count(old) assert n == 1, f"replacement {i}: anchor found {n} times (expected 1)" src = src.replace(old, new) assert src != orig shutil.copy(P, P.with_name("server.py.bak-eval-20261120")) P.write_text(src) print(f"dashboard server.py patched OK ({len(REPLACEMENTS)} replacements), backup at server.py.bak-eval-20261120")