"""AgentLongBench x Flash Next, banco v2 (BRIEF-BENCH-ALB-V2): UNA domanda con UNA politica di contesto. venv/bin/python scripts/run_alb_v2.py --file alb/data/benchmark/kf-c/64k/tool_response/find_duplicates_tool.jsonl \\ --qid 38_i13_j22_a_0031 --policy B --engine-url http://127.0.0.1:18797 --window 16384 --out runs/x Politiche (stesso modello, campionamento, budget di risposta M e di ragionamento): A finestra piena: i messaggi ufficiali (build_prompt) interi al motore. T troncamento: via gli scambi più vecchi (anche tutti) finché prompt + M + MARGIN <= W; nota fissa al loro posto. B compattazione: storia riletta scambio per scambio; quando lo scambio non entra, Flash Next riassume (system di sola sintesi, senza ragionamento, budget = summary_max sempre garantito) e il contesto diventa system + riassunto. D mnemonic-proxy installato (0.3.4), config proxy-cfg-D.json; la storia è rigiocata attraverso il proxy con una richiesta max_tokens=1 (senza reasoning_budget_tokens) prima di ogni messaggio assistant; poi la domanda. E D senza lo strumento recall offerto (inject_recall false). Garanzie v2: - A/T/B: ogni richiesta al motore è contata in modo esatto (template + tokenizer del pack) PRIMA dell'invio e parte solo se prompt + max_tokens + MARGIN <= W; altrimenti nessun invio, status WindowRefused (mai uno sforamento). - Tutte le chiamate al motore (anche quelle interne del proxy) passano dal contatore meter.py: costi completi in engine_calls.jsonl e result["engine"], con il controllo a posteriori del margine anche per D/E. - Esito della risposta finale classificato: vuota, chiamate residue, troncata (length), formato non valido. """ from __future__ import annotations import argparse import json import os import shutil import signal import subprocess import sys import threading import time import traceback from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import common as C # noqa: E402 import meter as MT # noqa: E402 from normfmt import fully_correct, normalize_format # noqa: E402 COMPACT_INSTRUCTION = """Your context window is full. The conversation so far will be replaced by the summary you write now. Write a summary for yourself to continue without the earlier messages. Be factual and complete: keep the exact values that may matter later (ids, numbers, lists, round numbers, tool results, feedback), in order. Do not call tools. Reply with the summary only.""" SUMMARY_PREFIX = "[Context compacted: earlier messages were replaced by this summary written by you.]\n\n" SUMMARY_SYSTEM = "You summarize conversations faithfully. Reply with the summary only." TRUNC_NOTE = "[{n} earlier messages were removed to fit the context window.]" CUT_MARK = "[... beginning of this message cut to fit the summarizer window ...] " BENCH = Path(__file__).resolve().parent.parent PROXY_BIN = {"D": BENCH / "venv/bin/mnemonic-proxy", "E": BENCH / "venv/bin/mnemonic-proxy"} PROXY_MARK = b"alb-bench-v2" # solo proxy di questo banco possono essere chiusi sulla porta MARGIN = 64 # = window_margin del proxy (INV-1) class WindowRefused(Exception): """Il banco non invia: la richiesta non rispetterebbe prompt + max_tokens + MARGIN <= W.""" # --------------------------------------------------------------------------------------------------------------- class Sampler(threading.Thread): """VRAM (nvidia-smi, se c'è), RSS motore/proxy, RAM disponibile e swap ogni `period` s.""" def __init__(self, path: Path, engine_port: int, proxy_port: int, period: float = 2.0): super().__init__(daemon=True) self.path, self.period, self.stop_ev = path, period, threading.Event() self.ep, self.pp = str(engine_port).encode(), str(proxy_port).encode() self.has_smi = shutil.which("nvidia-smi") is not None def run(self): with open(self.path, "a") as f: while not self.stop_ev.is_set(): rec = {"t": time.time()} if self.has_smi: try: out = subprocess.run(["nvidia-smi", "--query-gpu=memory.used,utilization.gpu,power.draw", "--format=csv,noheader,nounits"], capture_output=True, text=True, timeout=5).stdout.strip().split(",") rec.update(vram_mib=float(out[0]), gpu_util=float(out[1]), power_w=float(out[2])) except Exception: # noqa: BLE001 pass try: for pid in os.listdir("/proc"): if not pid.isdigit(): continue try: cmd = open("/proc/%s/cmdline" % pid, "rb").read().replace(b"\0", b" ") except OSError: continue role = ("strata" if b"build-cuda/strata" in cmd else "server" if b"serve/server.py" in cmd and self.ep in cmd else "proxy" if b"mnemonic-proxy" in cmd and self.pp in cmd else None) if role is None: continue for l in open("/proc/%s/status" % pid): if l.startswith("VmRSS"): rec["%s_rss_mib" % role] = rec.get("%s_rss_mib" % role, 0) + int(l.split()[1]) // 1024 mi = {l.split(":")[0]: int(l.split()[1]) for l in open("/proc/meminfo")} rec.update(mem_avail_mib=mi["MemAvailable"] // 1024, swap_used_mib=(mi["SwapTotal"] - mi["SwapFree"]) // 1024) except Exception: # noqa: BLE001 pass f.write(json.dumps(rec) + "\n") f.flush() self.stop_ev.wait(self.period) # --------------------------------------------------------------------------------------------------------------- def exchanges(history: list[dict]) -> list[list[dict]]: """Scambi completi: un messaggio assistant + tutto ciò che lo segue fino al prossimo assistant (le uscite degli strumenti restano con la loro chiamata). I messaggi prima del primo assistant formano un gruppo a sé.""" ex, cur = [], [] for m in history: if m.get("role") == "assistant" and cur: ex.append(cur) cur = [] cur.append(m) if cur: ex.append(cur) return ex def flat(ex): return [m for e in ex for m in e] class Runner: def __init__(self, a, sample, path, out: Path, engine_url: str): self.a, self.sample, self.path, self.out, self.engine_url = a, sample, path, out, engine_url self.msgs = C.official_messages(sample, path) # system + storia + domanda (ufficiale) self.system, self.history, self.question = self.msgs[0], self.msgs[1:-1], self.msgs[-1] self.idx = {id(m): i for i, m in enumerate(self.history, 1)} # numero del messaggio nella storia self.sampling = {"temperature": a.temperature, "top_p": a.top_p, "top_k": a.top_k, "seed": a.seed} if a.reasoning_budget: self.sampling["reasoning_budget_tokens"] = a.reasoning_budget self.calls = open(out / "calls.jsonl", "a") self.lock = threading.Lock() self.events: list[dict] = [] self.counter = C.Counter() if a.policy in ("A", "T", "B") else None self.proxy = None def sink(self, m): with self.lock: self.calls.write(json.dumps(m) + "\n") self.calls.flush() def limit(self, mt: int | None = None) -> int: """Prompt massimo per una richiesta con max_tokens = mt (default M): INV-1 prompt + mt + MARGIN <= W.""" return self.a.window - (self.a.max_tokens if mt is None else mt) - MARGIN def send(self, msgs, *, max_tokens, kind, sampling, extra_body=None): """Unico punto d'invio di A/T/B: controllo finale rigoroso ed esatto, poi la richiesta (via contatore).""" n = self.counter.prompt(msgs) slack = self.a.window - (n + int(max_tokens) + MARGIN) self.events.append({"event": "send_check", "kind": kind, "prompt_tokens": n, "max_tokens": int(max_tokens), "slack": slack}) if slack < 0 or max_tokens < 1: self.events.append({"event": "bench_refused", "kind": kind, "prompt_tokens": n, "max_tokens": int(max_tokens), "window": self.a.window}) raise WindowRefused("%s: prompt %d + max_tokens %d + %d > W %d" % (kind, n, max_tokens, MARGIN, self.a.window)) return C.chat(self.engine_url, msgs, max_tokens=max_tokens, sampling=sampling, stream=True, kind=kind, sink=self.sink, timeout=self.a.request_timeout, extra_body=extra_body, headers={"X-Bench-Kind": kind}) def answer_direct(self, msgs): return self.send(msgs, max_tokens=self.a.max_tokens, kind="answer", sampling=self.sampling) # ---- T ---------------------------------------------------------------------------------------------------- def run_T(self): ex = exchanges(self.history) removed = 0 while True: head = [self.system] + ([{"role": "user", "content": TRUNC_NOTE.format(n=removed)}] if removed else []) cand = head + flat(ex) + [self.question] n = self.counter.prompt(cand) if n <= self.limit(): break if not ex: # nemmeno system + nota + domanda: nessun invio (definito, registrato) self.events.append({"event": "truncate", "removed_messages": removed, "kept_messages": 0, "prompt_tokens": n, "impossible": True}) raise WindowRefused("T: system + question alone exceed the window") removed += len(ex.pop(0)) # anche l'ultimo scambio, se da solo non entra (scambio singolo enorme) self.events.append({"event": "truncate", "removed_messages": removed, "kept_messages": len(flat(ex)), "kept_exchanges": len(ex), "prompt_tokens": n}) return self.answer_direct(cand) # ---- B ---------------------------------------------------------------------------------------------------- def fits(self, msgs, mt=None) -> bool: return self.counter.prompt(msgs) <= self.limit(mt) def compact(self, body: list[dict], why: str): """Riassunto di `body` (messaggi della storia ed eventuale riassunto precedente). Il riassunto ha SEMPRE il suo budget pieno summary_max: se il testo da riassumere non ci sta, si tolgono le righe più vecchie e, se ne resta una sola troppo lunga, se ne taglia l'inizio (fine conservata). Tutto registrato.""" lines = [C.transcript_line(m, self.idx.get(id(m))) for m in body] budget = int(self.a.summary_max) dropped, cut_chars = 0, 0 def req_of(ls): text = "\n\n".join(ls) return [{"role": "system", "content": SUMMARY_SYSTEM}, {"role": "user", "content": "Conversation:\n\n" + text + "\n\n" + COMPACT_INSTRUCTION}] req = req_of(lines) n_before = self.counter.prompt(req) while not self.fits(req, budget): if len(lines) > 1: lines = lines[1:] dropped += 1 else: s = lines[0] if lines else "" lo, hi = 0, len(s) # quanti caratteri finali tenere: ricerca binaria del massimo che entra while lo < hi: mid = (lo + hi + 1) // 2 if self.fits(req_of([CUT_MARK + s[len(s) - mid:]]), budget): lo = mid else: hi = mid - 1 cut_chars = len(s) - lo lines = [CUT_MARK + s[len(s) - lo:]] if lo else [] req = req_of(lines) if not self.fits(req, budget): raise WindowRefused("B: the summarizer request cannot fit even empty") break req = req_of(lines) n = self.counter.prompt(req) t0 = time.time() sampling = {k: v for k, v in self.sampling.items() if k != "reasoning_budget_tokens"} res = self.send(req, max_tokens=budget, kind="compact", sampling=sampling, extra_body={"chat_template_kwargs": {"enable_thinking": False}}) summary = (res["message"].get("content") or "").strip() new = [self.system, {"role": "user", "content": SUMMARY_PREFIX + (summary or "(empty summary)")}] self.events.append({"event": "compact", "why": why, "messages_in": len(body), "lines_dropped": dropped, "chars_cut": cut_chars, "tokens_request_full": n_before, "tokens_request": n, "tokens_after": self.counter.prompt(new), "budget": budget, "finish_reason": res.get("finish_reason"), "completion_tokens": (res.get("usage") or {}).get("completion_tokens"), "dur_s": time.time() - t0, "summary_empty": not summary, "summary_chars": len(summary), "summary": summary}) return new def run_B(self): ctx = [self.system] q = [self.question] for e in exchanges(self.history): if self.fits(ctx + e + q): ctx = ctx + e continue if len(ctx) > 1: ctx = self.compact(ctx[1:], "before_exchange") if self.fits(ctx + e + q): ctx = ctx + e continue # scambio singolo enorme: non entra nemmeno accanto a system + riassunto + domanda -> si riassume # riassunto precedente + scambio (il testo da riassumere ha a sua volta la sua finestra garantita) self.events.append({"event": "huge_exchange", "messages": len(e), "tokens": self.counter.prompt([self.system] + e + q)}) ctx = self.compact(ctx[1:] + e, "huge_exchange") if not self.fits(ctx + q) and len(ctx) > 1: ctx = self.compact(ctx[1:], "final") self.events.append({"event": "final_context", "messages": len(ctx) + 1, "prompt_tokens": self.counter.prompt(ctx + q)}) return self.answer_direct(ctx + q) # send() rifiuta se non entra: mai uno sforamento # ---- D / E ------------------------------------------------------------------------------------------------ def run_proxy(self): pcfg = json.loads(self.a.proxy_cfg) self.proxy = start_proxy(self.a.policy, self.engine_url, self.a.proxy_port, self.out / "proxy", pcfg) url = "http://127.0.0.1:%d" % self.a.proxy_port full = [self.system] + self.history points = [i for i, m in enumerate(full) if m.get("role") == "assistant" and i > 0] # v2 (BRIEF §4): il rigioco con max_tokens=1 NON porta reasoning_budget_tokens (eventi budget_cap spuri) replay_sampling = {k: v for k, v in self.sampling.items() if k != "reasoning_budget_tokens"} t0 = time.time() for i in points: C.chat(url, full[:i], max_tokens=1, sampling=replay_sampling, stream=False, kind="replay", sink=self.sink, timeout=self.a.request_timeout) self.events.append({"event": "replay", "requests": len(points), "dur_s": time.time() - t0}) return C.chat(url, self.msgs, max_tokens=self.a.max_tokens, sampling=self.sampling, stream=True, kind="answer", sink=self.sink, timeout=self.a.request_timeout) def _port_holders(port: int) -> list[int]: import re out = subprocess.run(["ss", "-ltnpH", "sport = :%d" % port], capture_output=True, text=True).stdout return sorted({int(x) for x in re.findall(r"pid=(\d+)", out)}) def start_proxy(variant: str, upstream: str, port: int, data: Path, cfg: dict) -> subprocess.Popen: for pid in _port_holders(port): cmd = open("/proc/%d/cmdline" % pid, "rb").read().replace(b"\0", b" ") if PROXY_MARK in cmd and b"mnemonic-proxy" in cmd: os.kill(pid, signal.SIGKILL) else: raise RuntimeError("port %d held by foreign process %d" % (port, pid)) for _ in range(50): if not _port_holders(port): break time.sleep(0.2) else: raise RuntimeError("port %d still busy" % port) if data.exists(): shutil.rmtree(data) data.mkdir(parents=True) (data / "cfg.json").write_text(json.dumps(cfg, indent=1)) log = open(data / "proxy.log", "a") p = subprocess.Popen([str(PROXY_BIN[variant]), "--host", "127.0.0.1", "--port", str(port), "--upstream", upstream, "--data", str(data), "--config", str(data / "cfg.json"), "--tokenizer", C.PACK_TOK + "/tokenizer.json"], stdout=log, stderr=subprocess.STDOUT, start_new_session=True, env={**os.environ, "MNEMONIC_PROXY_ALLOW_SMALL_WINDOW": ""}) import urllib.request for _ in range(240): if p.poll() is not None: raise RuntimeError("proxy exited rc=%s (see %s)" % (p.returncode, data / "proxy.log")) try: with urllib.request.urlopen("http://127.0.0.1:%d/v1/engine" % port, timeout=2) as r: info = json.loads(r.read()) if p.poll() is not None or p.pid not in _port_holders(port): stop_proc(p) raise RuntimeError("port %d answered but not by our proxy pid %d" % (port, p.pid)) (data / "engine.json").write_text(json.dumps(info, indent=1)) return p except RuntimeError: raise except Exception: # noqa: BLE001 time.sleep(0.5) stop_proc(p) raise RuntimeError("proxy not ready") def stop_proc(p): if p is None or p.poll() is not None: return try: os.killpg(p.pid, signal.SIGTERM) p.wait(10) except Exception: # noqa: BLE001 try: os.killpg(p.pid, signal.SIGKILL) except Exception: # noqa: BLE001 pass def proxy_journal(data: Path) -> dict: """Eventi del giornale del proxy (solo diagnostica: i COSTI vengono dal contatore, non da qui).""" out = {"mask": 0, "switch": 0, "notes": [], "recall": [], "events": {}, "guard": {}, "budget_cap": [], "recall_texts": []} j = data / "journal.jsonl" if j.exists(): for l in open(j, errors="replace"): try: e = json.loads(l) except ValueError: continue ev = e.get("event") or "?" out["events"][ev] = out["events"].get(ev, 0) + 1 if ev == "mask": out["mask"] += 1 elif ev == "freeze": out["switch"] += 1 elif ev == "notes": out["notes"].append({k: e.get(k) for k in ("seg", "ms", "tokens", "usage", "finish", "timings")}) elif ev in ("recall", "recall_trimmed", "recall_dropped", "recall_use", "response_shrunk"): out["recall"].append(e) elif ev == "window_guard": a = str(e.get("action")) out["guard"][a] = out["guard"].get(a, 0) + 1 if a == "budget_cap": out["budget_cap"].append({k: e.get(k) for k in ("where", "max_tokens", "budget", "was")}) if a == "refused": out.setdefault("guard_refused", []).append(e) db = data / "archive.sqlite" if db.exists(): import sqlite3 try: con = sqlite3.connect("file:%s?mode=ro" % db, uri=True) for (msgs,) in con.execute("SELECT msgs FROM inserts"): for m in json.loads(msgs): if m.get("role") == "tool": out["recall_texts"].append(m.get("content")) elif m.get("tool_calls"): out["recall_texts"].append({"call": [c.get("function") for c in m["tool_calls"]]}) con.close() except Exception as e: # noqa: BLE001 out["recall_texts_error"] = repr(e)[:300] return out def answer_class(status, raw, msg, finish, parse_none) -> dict: calls = (msg or {}).get("tool_calls") or [] return {"answer_error": status != "ok", "answer_empty": status == "ok" and not raw.strip() and not calls, "answer_residual_calls": status == "ok" and bool(calls), "answer_truncated": finish == "length", "answer_invalid_format": status == "ok" and bool(raw.strip()) and parse_none} def main(): ap = argparse.ArgumentParser() ap.add_argument("--file", required=True) ap.add_argument("--qid", required=True) ap.add_argument("--policy", required=True, choices=["A", "T", "B", "D", "E"]) ap.add_argument("--engine-url", required=True) ap.add_argument("--window", type=int, required=True, help="finestra fisica del motore (token)") ap.add_argument("--out", required=True) ap.add_argument("--max-tokens", type=int, default=4096, help="M: budget di risposta (ragionamento incluso)") ap.add_argument("--reasoning-budget", type=int, default=3072, help="reasoning_budget_tokens di Strata (0=off)") ap.add_argument("--summary-max", type=int, default=2048, help="budget garantito dei riassunti di B") ap.add_argument("--temperature", type=float, default=0.6) ap.add_argument("--top-p", type=float, default=0.95) ap.add_argument("--top-k", type=int, default=20) ap.add_argument("--seed", type=int, default=1) ap.add_argument("--proxy-port", type=int, default=18896) ap.add_argument("--engine-port", type=int, default=18797) ap.add_argument("--proxy-cfg", default=None, help="JSON della config del proxy; default scripts/proxy-cfg-D.json") ap.add_argument("--request-timeout", type=float, default=3600.0) a = ap.parse_args() signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) path = Path(a.file).resolve() rel = path.relative_to(C.DATA.resolve()) setting, length = rel.parts[0], rel.parts[1] out = Path(a.out) / a.policy / setting / length / a.qid if (out / "result.json").exists(): print(json.dumps({"skip": str(out)})) return if out.exists(): ab = Path(a.out) / "_aborted" ab.mkdir(parents=True, exist_ok=True) shutil.move(str(out), str(ab / ("%s-%s-%s-%s-%d" % (a.policy, setting, length, a.qid, time.time())))) out.mkdir(parents=True) if a.policy in PROXY_BIN: if not PROXY_BIN[a.policy].exists(): sys.exit("proxy assente: %s" % PROXY_BIN[a.policy]) if a.proxy_cfg is None: a.proxy_cfg = (Path(__file__).resolve().parent / "proxy-cfg-D.json").read_text() if a.policy == "E": a.proxy_cfg = json.dumps({**json.loads(a.proxy_cfg), "inject_recall": False}) sample = C.load_sample(path, a.qid) meter = MT.Meter(a.engine_url, out / "engine_calls.jsonl", a.window, MARGIN) R = Runner(a, sample, path, out, meter.url) sampler = Sampler(out / "resources.jsonl", a.engine_port, a.proxy_port) sampler.start() t0 = time.time() status, raw, err, res = "ok", "", None, None try: if a.policy == "A": res = R.answer_direct(R.msgs) elif a.policy == "T": res = R.run_T() elif a.policy == "B": res = R.run_B() else: res = R.run_proxy() raw = C.answer_text(res["message"]) except WindowRefused as e: status, err = "WindowRefused", str(e) except C.EngineHTTPError as e: low = e.text.lower() status = "ProxyWindowRefused" if '"window_guard"' in e.text else "ContextOverflow" if e.status in (400, 413) and ("context" in low or "too long" in low or "exceeds" in low) else "EngineError" err = str(e)[:3000] except Exception as e: # noqa: BLE001 status, err = type(e).__name__, traceback.format_exc()[-4000:] finally: wall = time.time() - t0 sampler.stop_ev.set() stop_proc(R.proxy) time.sleep(0.2) meter.close() hl = C.infer_context_from_path(path)[3] qt = sample["question_type"] sc = C.official_score(sample, path, raw) # risposta vuota/errore = sbagliata (nel denominatore) norm = normalize_format(raw, qt, hl) sc_norm = C.official_score(sample, path, norm) if norm != raw else sc three = {"score_official": sc.get("score"), "score_format_norm": sc_norm.get("score"), "fully_correct": fully_correct(sc_norm.get("score"), norm, qt, hl), "format_normalized": norm != raw} msg = (res or {}).get("message") or {} cls = answer_class(status, raw, msg, (res or {}).get("finish_reason"), sc.get("pred_answer") is None) eng = MT.summarize(out / "engine_calls.jsonl") final = (res or {}).get("m") or {} result = {"bench": "alb-bench-v2", "qid": a.qid, "file": str(rel), "setting": setting, "length": length, "question_type": qt, "policy": a.policy, "window": a.window, "margin": MARGIN, "max_tokens": a.max_tokens, "reasoning_budget": a.reasoning_budget, "summary_max": a.summary_max, "sampling": R.sampling, "status": status, "error": err, "wall_s": wall, "gold": sample.get("answer"), "raw_response": raw, "normalized_response": norm if norm != raw else None, "reasoning": msg.get("reasoning_content"), "finish_reason": (res or {}).get("finish_reason"), **sc, **three, **cls, "final_call": {k: final.get(k) for k in ("ttft_client_s", "wall_s", "usage", "timings")}, "final_tool_calls": [c.get("function") for c in msg.get("tool_calls") or []], "engine": eng, "policy_events": R.events, "proxy": proxy_journal(out / "proxy") if a.policy in PROXY_BIN and (out / "proxy").exists() else None, "proxy_cfg": json.loads(a.proxy_cfg) if a.policy in PROXY_BIN else None} (out / "result.json").write_text(json.dumps(result, indent=1, ensure_ascii=False)) print(json.dumps({k: result[k] for k in ("qid", "policy", "status", "score_official", "score_format_norm", "fully_correct", "answer_empty", "answer_residual_calls", "answer_truncated", "answer_invalid_format", "wall_s")} | {"engine_calls": eng["n_calls"], "margin_violations": eng["margin_violations"], "min_slack": eng["min_window_slack"]}, ensure_ascii=False)) if __name__ == "__main__": main()