File size: 12,832 Bytes
510314e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"""Contatore delle chiamate al motore (banco ALB v2, BRIEF §5): un passante HTTP fra chi chiama (banco per A/T/B,
mnemonic-proxy per D/E) e il motore (Strata o motore finto). Ogni POST /v1/chat/completions che arriva al motore
passa di qui UNA volta e viene registrato una volta: giri interni del proxy, note di passaggio, retry K, rigioco,
compattazioni di B, risposta finale. Nessuna modifica al corpo o alla risposta (passaggio byte per byte; lo stream
SSE viene inoltrato riga per riga mentre lo si legge).

Per chiamata: kind, max_tokens, reasoning_budget_tokens, enable_thinking, strumenti offerti, messaggi, prompt /
generazione / cache (usage), timings del motore, TTFT e durata visti dal contatore, finish_reason, caratteri di
content e ragionamento, chiamate a strumenti, stato HTTP, e il controllo a posteriori
prompt_tokens + max_tokens + margine <= W (margin_violation).

kind: header X-Bench-Kind se presente (chiamate dirette del banco); altrimenti (chiamate del proxy):
  replay   max_tokens == 1                     (rigioco della storia)
  notes    un messaggio contiene il marcatore delle note di passaggio
  round    l'ultimo messaggio è un risultato di strumento (giro interno: dopo recall/answerfix)
  final    il resto (richiesta finale inoltrata, eventuale retry K senza strumenti)
"""
from __future__ import annotations

import http.client
import json
import threading
import time
import urllib.parse
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

NOTES_MARKS = ("[strata-context: handoff notes request]", "[strata-context: richiesta note di passaggio]")
HOP = {"connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-connection", "content-length"}


def _kind(body: dict, hdr: str | None) -> str:
    if hdr:
        return hdr
    if int(body.get("max_tokens") or body.get("max_completion_tokens") or 0) == 1:
        return "replay"
    msgs = body.get("messages") or []
    for m in msgs:
        c = m.get("content")
        c = c if isinstance(c, str) else json.dumps(c, ensure_ascii=False) if c else ""
        if any(k in c for k in NOTES_MARKS):
            return "notes"
    if msgs and msgs[-1].get("role") == "tool":
        return "round"
    return "final"


class Meter:
    def __init__(self, upstream: str, log_path, window: int, margin: int = 64, port: int = 0):
        u = urllib.parse.urlparse(upstream)
        self.host, self.uport = u.hostname, u.port or 80
        self.window, self.margin = int(window), int(margin)
        self.logf = open(log_path, "a")
        self.lock = threading.Lock()
        self.n = 0
        meter = self

        class H(BaseHTTPRequestHandler):
            protocol_version = "HTTP/1.1"

            def log_message(self, *a):
                pass

            def _fwd_simple(self, method, data=None):
                conn = http.client.HTTPConnection(meter.host, meter.uport, timeout=3600)
                hdrs = {k: v for k, v in self.headers.items() if k.lower() not in HOP and k.lower() != "host"}
                conn.request(method, self.path, body=data, headers=hdrs)
                r = conn.getresponse()
                return conn, r

            def do_GET(self):
                conn, r = self._fwd_simple("GET")
                d = r.read()
                self.send_response(r.status)
                for k, v in r.getheaders():
                    if k.lower() not in HOP:
                        self.send_header(k, v)
                self.send_header("Content-Length", str(len(d)))
                self.end_headers()
                self.wfile.write(d)
                conn.close()

            def do_POST(self):
                n = int(self.headers.get("Content-Length") or 0)
                data = self.rfile.read(n)
                if not self.path.startswith("/v1/chat/completions"):
                    conn, r = self._fwd_simple("POST", data)
                    d = r.read()
                    self.send_response(r.status)
                    for k, v in r.getheaders():
                        if k.lower() not in HOP:
                            self.send_header(k, v)
                    self.send_header("Content-Length", str(len(d)))
                    self.end_headers()
                    self.wfile.write(d)
                    conn.close()
                    return
                try:
                    body = json.loads(data or b"{}")
                except ValueError:
                    body = {}
                ctk = body.get("chat_template_kwargs") or {}
                rec = {"t_start": time.time(), "kind": _kind(body, self.headers.get("X-Bench-Kind")),
                       "max_tokens": int(body.get("max_tokens") or body.get("max_completion_tokens") or 0),
                       "reasoning_budget_tokens": body.get("reasoning_budget_tokens"),
                       "enable_thinking": ctk.get("enable_thinking"), "stream": bool(body.get("stream")),
                       "n_messages": len(body.get("messages") or []),
                       "tools": [(t.get("function") or {}).get("name") for t in body.get("tools") or []]}
                t0 = time.time()
                conn, r = self._fwd_simple("POST", data)
                rec["http_status"] = r.status
                ttft, usage, timings, finish = None, None, None, None
                content, reasoning, calls = 0, 0, {}
                ctype = r.getheader("Content-Type") or ""
                if r.status >= 400 or "event-stream" not in ctype:
                    d = r.read()
                    self.send_response(r.status)
                    for k, v in r.getheaders():
                        if k.lower() not in HOP:
                            self.send_header(k, v)
                    self.send_header("Content-Length", str(len(d)))
                    self.end_headers()
                    self.wfile.write(d)
                    ttft = time.time() - t0
                    try:
                        j = json.loads(d)
                        if r.status >= 400:
                            rec["error"] = json.dumps(j.get("error") or j)[:500]
                        else:
                            ch = (j.get("choices") or [{}])[0]
                            msg = ch.get("message") or {}
                            usage, timings, finish = j.get("usage"), j.get("timings"), ch.get("finish_reason")
                            content = len(msg.get("content") or "")
                            reasoning = len(msg.get("reasoning_content") or "")
                            for i, c in enumerate(msg.get("tool_calls") or []):
                                calls[i] = (c.get("function") or {}).get("name")
                    except ValueError:
                        rec["error"] = d[:500].decode("utf-8", "replace")
                else:
                    self.send_response(r.status)
                    for k, v in r.getheaders():
                        if k.lower() not in HOP:
                            self.send_header(k, v)
                    self.send_header("Connection", "close")
                    self.end_headers()
                    while True:
                        line = r.readline()
                        if not line:
                            break
                        self.wfile.write(line)
                        s = line.strip()
                        if s.startswith(b"data:"):
                            p = s[5:].strip()
                            if p == b"[DONE]":
                                self.wfile.flush()
                                continue
                            try:
                                c = json.loads(p)
                            except ValueError:
                                continue
                            usage = c.get("usage") or usage
                            timings = c.get("timings") or timings
                            for ch in c.get("choices") or []:
                                dl = ch.get("delta") or {}
                                if ttft is None and (dl.get("content") or dl.get("reasoning_content")
                                                     or dl.get("tool_calls")):
                                    ttft = time.time() - t0
                                content += len(dl.get("content") or "")
                                reasoning += len(dl.get("reasoning_content") or "")
                                for tc in dl.get("tool_calls") or []:
                                    nm = (tc.get("function") or {}).get("name")
                                    k = tc.get("index", len(calls))
                                    calls[k] = (calls.get(k) or "") + (nm or "")
                                finish = ch.get("finish_reason") or finish
                        elif not s:
                            self.wfile.flush()
                    self.wfile.flush()
                    self.close_connection = True
                conn.close()
                u = usage or {}
                pt = u.get("prompt_tokens")
                rec.update(wall_s=time.time() - t0, ttft_s=ttft, finish_reason=finish, usage=usage, timings=timings,
                           prompt_tokens=pt, completion_tokens=u.get("completion_tokens"),
                           cached_tokens=((u.get("prompt_tokens_details") or {}).get("cached_tokens")
                                          if isinstance(u.get("prompt_tokens_details"), dict) else None),
                           content_chars=content, reasoning_chars=reasoning,
                           tool_calls=[calls[k] for k in sorted(calls)])
                if pt is not None:
                    rec["window_slack"] = meter.window - (int(pt) + rec["max_tokens"] + meter.margin)
                    rec["margin_violation"] = rec["window_slack"] < 0
                with meter.lock:
                    meter.n += 1
                    rec["seq"] = meter.n
                    meter.logf.write(json.dumps(rec, ensure_ascii=False) + "\n")
                    meter.logf.flush()

        self.srv = ThreadingHTTPServer(("127.0.0.1", port), H)
        self.srv.daemon_threads = True
        self.port = self.srv.server_address[1]
        self.url = "http://127.0.0.1:%d" % self.port
        self.th = threading.Thread(target=self.srv.serve_forever, daemon=True)
        self.th.start()

    def close(self):
        self.srv.shutdown()
        self.srv.server_close()
        self.logf.close()


def summarize(path) -> dict:
    """Costi completi da engine_calls.jsonl: totali e per kind (ogni chiamata al motore contata una volta)."""
    tot = {"n_calls": 0, "prompt_tokens": 0, "completion_tokens": 0, "cached_tokens": 0, "prompt_n": 0, "cache_n": 0,
           "prompt_ms": 0.0, "predicted_ms": 0.0, "wall_s": 0.0, "max_prompt_tokens": 0, "finish_length": 0,
           "empty_output": 0, "http_errors": 0, "margin_violations": 0, "min_window_slack": None,
           "max_tokens_sum": 0, "reasoning_budget_given": 0}
    by = {}
    try:
        lines = open(path).read().splitlines()
    except OSError:
        lines = []
    for l in lines:
        c = json.loads(l)
        for t in (tot, by.setdefault(c["kind"], {k: (0 if not isinstance(v, float) else 0.0) if v is not None else None
                                                 for k, v in tot.items()})):
            t["n_calls"] += 1
            t["prompt_tokens"] += int(c.get("prompt_tokens") or 0)
            t["completion_tokens"] += int(c.get("completion_tokens") or 0)
            t["cached_tokens"] += int(c.get("cached_tokens") or 0)
            tm = c.get("timings") or {}
            t["prompt_n"] += int(tm.get("prompt_n") or 0)
            t["cache_n"] += int(tm.get("cache_n") or 0)
            t["prompt_ms"] += float(tm.get("prompt_ms") or 0.0)
            t["predicted_ms"] += float(tm.get("predicted_ms") or 0.0)
            t["wall_s"] += float(c.get("wall_s") or 0.0)
            t["max_prompt_tokens"] = max(t["max_prompt_tokens"], int(c.get("prompt_tokens") or 0))
            t["finish_length"] += c.get("finish_reason") == "length"
            t["empty_output"] += (c.get("http_status") == 200 and not c.get("content_chars")
                                  and not c.get("tool_calls") and c.get("max_tokens", 0) > 1)
            t["http_errors"] += int(c.get("http_status") or 0) >= 400
            t["margin_violations"] += bool(c.get("margin_violation"))
            if c.get("window_slack") is not None:
                t["min_window_slack"] = c["window_slack"] if t["min_window_slack"] is None else \
                    min(t["min_window_slack"], c["window_slack"])
            t["max_tokens_sum"] += int(c.get("max_tokens") or 0)
            t["reasoning_budget_given"] += c.get("reasoning_budget_tokens") is not None
    tot["by_kind"] = by
    return tot