diff --git a/proxy/app.py b/proxy/app.py index 1a94ae84..31691fba 100644 --- a/proxy/app.py +++ b/proxy/app.py @@ -138,11 +138,45 @@ def version() -> str: def _live_engine() -> dict: """The live stream's engine block for a server with no engine: the proxy's in-flight - count.""" + count, plus the engine block of the TandemLLM backend behind it (proxy/liverelay.py) + when one is fresh: the model, its KV window, its memory — what only the engine knows.""" svc: Service = STATE["svc"] - return {"model": None, "version": STATE.get("version", ""), - "draining": bool(STATE.get("draining")), "kv": {"length": 0, "max_len": 0}, - "memory": {"mem_available_gib": None, "rss_gib": None}, "store": None} + out = {"model": None, "version": STATE.get("version", ""), + "draining": bool(STATE.get("draining")), "kv": {"length": 0, "max_len": 0}, + "memory": {"mem_available_gib": None, "rss_gib": None}, "store": None} + relay = STATE.get("liverelay") + eng = relay.engine_block() if relay is not None else None + if eng: + out.update(eng) + return out + + +def _live_enrich(rec) -> dict | None: + """An in-flight row's engine-side figures (proxy/liverelay.py): the live rates of a + relayed request, joined by its answer's id — the `X-Tandem-Request-Id` header of a new + engine names it at stream open (proxy/relay.py), the first frame of an old one carries + it. While an old engine's request is still prefilling it has no id to join with: if the + backend has exactly one prefill row open it can only be this request's, and its prefill + figures join the row (`sole_prefill`); two is ambiguous and the row stays exactly what + the controller measured. None without a relay or a fresh engine figure.""" + relay = STATE.get("liverelay") + if relay is None: + return None + fields = relay.row_fields(rec) + if fields: + return fields + if (getattr(rec, "upstream_request", None) is None and rec.t_first is None + and getattr(rec, "backend_kind", None) == "tandemllm" + and getattr(rec, "backend", None)): + return relay.sole_prefill(rec.backend) + return None + + +def _live_rates() -> dict | None: + """The rates the controller cannot measure, from the TandemLLM backend behind it + (proxy/liverelay.py); None when none is fresh.""" + relay = STATE.get("liverelay") + return relay.rates() if relay is not None else None def _live_status() -> dict: @@ -1239,7 +1273,8 @@ def build(args, env=None) -> Service: registry = metrics_mod.Registry() live = live_mod.LiveRegistry(blocks=lambda: None, last_prefill=lambda: None, engine=_live_engine, hz=live_mod.DEFAULT_HZ, activity=False, - queue_timeout=lambda: 0.0) + queue_timeout=lambda: 0.0, + enrich=_live_enrich, live_rates=_live_rates) STATE.update(version=version(), ledger=led, auth=a, accounts=accounts, registry=registry, live=live, dashboard_dir=args.dashboard_dir, verbose=args.verbose, args={k: v for k, v in vars(args).items()}) @@ -1287,6 +1322,14 @@ def build(args, env=None) -> Service: # the sampler: it sleeps while nothing is in flight (the live stream and the parallel view's # once-a-second sample; before 0.3.32 the standalone proxy never started it) live.start() + # the engines' live figures for the Performance page (proxy/liverelay.py): the + # controller has no decode loop of its own, so its live view carries its TandemLLM + # backends' rates; TANDEM_LIVE_RELAY=off leaves the live view exactly as it was + if env.get("TANDEM_LIVE_RELAY", "on") != "off": + from proxy import liverelay + STATE["liverelay"] = svc.liverelay = liverelay.LiveRelay( + svc, log=lambda m: print(m, flush=True)) + svc.liverelay.start() STATE.pop("dashboard_api", None) return svc diff --git a/proxy/liverelay.py b/proxy/liverelay.py new file mode 100644 index 00000000..2477b07c --- /dev/null +++ b/proxy/liverelay.py @@ -0,0 +1,333 @@ +"""The engines' live figures, relayed into the controller's own live view. + +The controller measures what a client could measure (proxy/measure.py): the request's +arrival, its first frame, its frames. The live rates of the Performance page — a request's +`decode_live_now_tps` and `decode_live_avg_tps`, the history sample's and `now`'s +`decode_live_tps` and `prefill_live_tps` — come off the engine's decode loop, and the +controller has none: its `LiveRegistry` is built with `blocks=None, activity=False` +(proxy/app.py), so behind a TandemLLM backend the charts were empty and every in-flight +row read null. + +THE JOIN. The engine keys its live rows by its request id, which is the id its answer +carries — `Stamps.response_id` (SRV-733: "our engine's is its ledger row's request_id"). +A new engine names it in the response header at stream open (`X-Tandem-Request-Id`, the +sibling TandemEngine PR), and proxy/relay.py stamps it before the pump starts, so the row +joins through the whole prefill; an old engine's id arrives only with the first frame, and +the relay stamps it then. The rule for a relayed row's engine figures: **exact when the +header is there, heuristic only when unambiguous, null otherwise.** The heuristic covers an +old engine's prefill phase, where the request has no id to join with yet: when the backend +has exactly one prefill row open (`sole_prefill`), it can only be this request's, and its +prefill figures merge into the row; two prefill rows is ambiguous and the row stays exactly +what the controller measured (proxy/app.py `_live_enrich`). The engine's own `phase` is not +carried: the controller's row keeps the phase its own stamps say, which is what its timings +are consistent with. + +One subscriber thread per enabled `tandemllm` backend reads the engine's live stream +(`/v1/dashboard/live`, the same SSE the dashboard reads, with the backend's key when it +has one) and keeps, fresh for `ttl_s`: the in-flight rows by engine request id, the +engine's `now` block, its newest sample and its engine block. A supervisor thread syncs +the subscribers with the backend table and lets what went stale drop out. Every getter +answers None when there is nothing fresh, and the live view is then exactly what it was +before this module existed. + +The figures of the whole engine (the rates, the engine block) come from one backend: the +default one when it is a fresh TandemLLM backend, else the freshest — a controller in +front of several engines shows one engine's rates, named by its model. Per-request rows +join exactly, each to the engine that answered it. +""" + +from __future__ import annotations + +import http.client +import json +import threading +import time +import urllib.parse + +from proxy import canary as canary_mod + +#: how long the engine's figures may stand in for ones the controller cannot measure +TTL_S = 5.0 +#: how often the supervisor syncs the subscribers with the backend table +SYNC_S = 2.0 +#: the live connection's socket timeout: the engine pings its streams every 15 s +READ_TIMEOUT_S = 60.0 +#: the reconnect backoff: seconds until the next try after the stream died n times in a row +BACKOFF_S = (1.0, 2.0, 5.0, 10.0, 30.0) +#: the per-request fields carried into the controller's in-flight rows (its own nulls filled) +ROW_FIELDS = ("decode_live_now_tps", "decode_live_avg_tps", "decode_warmup") +#: the prefill figures of an engine row in the prefill phase, named as the proxy's row +#: carries them: the live rate over the engine's chunk marks (`activity.prefill.tps_live`, +#: its average once the live window has moved past the marks) and the prefill's elapsed +#: and ETA fields. The controller has no prefill to measure; these are the engine's. +PREFILL_DST_FIELDS = ("prefill_live_tps", "prefill_elapsed_ms", "prefill_eta_ms") +#: the rate fields carried into the controller's history sample and `now` +RATE_FIELDS = ("decode_tps", "prefill_tps", "decode_live_tps", "prefill_live_tps") +#: the engine block's fields the controller cannot measure itself +ENGINE_FIELDS = ("model", "kv", "memory", "store") +#: the phases worth keeping: a finished engine row is the controller's own `recent` already +IN_FLIGHT = ("queued", "prefill", "decode") + + +class _Sub: + """One backend: its subscriber thread and the last event it saw.""" + + def __init__(self, bid: str, url: str): + self.id, self.url = bid, url + self.stop = threading.Event() + self.thread: threading.Thread | None = None + self.at = 0.0 # perf time of the last event kept (0: none yet) + self.rows: dict[str, dict] = {} # engine request id -> the fields we carry + self.prefill: dict[str, dict] = {} # the prefill-phase rows, for the heuristic join + self.now: dict = {} + self.sample: dict = {} + self.engine: dict = {} + + +class LiveRelay: + """`row_fields(rec)` / `rates()` / `engine_block()`: the engine-side live figures, or + None when nothing fresh backs them. `svc` is read as the fleet changes: its backend + table picks the subscribers, its key store answers for the ones that need a key.""" + + def __init__(self, svc, *, ttl_s: float = TTL_S, sync_s: float = SYNC_S, log=None): + self.svc = svc + self.ttl_s = float(ttl_s) + self.sync_s = float(sync_s) + self.log = log or (lambda m: None) + self._lock = threading.Lock() + self._subs: dict[str, _Sub] = {} + self._stop = threading.Event() + self._thread: threading.Thread | None = None + + # ----------------------------------------------------------------- lifecycle + def start(self) -> None: + if self._thread is not None: + return + self._thread = threading.Thread(target=self._supervise, name="qse-liverelay", + daemon=True) + self._thread.start() + + def stop(self) -> None: + self._stop.set() + with self._lock: + subs = list(self._subs.values()) + self._subs.clear() + for s in subs: + s.stop.set() + for s in subs: + if s.thread is not None: + s.thread.join(timeout=1.0) + if self._thread is not None: + self._thread.join(timeout=1.0) + self._thread = None + + # ----------------------------------------------------------------- the subscribers + def _supervise(self) -> None: + while not self._stop.wait(self.sync_s): + try: + self._sync() + except Exception as exc: # noqa: BLE001 (never the box) + self.log(f"[live-relay] the sync failed: {type(exc).__name__}: {exc}") + + def _sync(self) -> None: + """One subscriber per enabled tandemllm backend, none for the others; a backend + whose URL moved gets a fresh one (the old thread sees its stop and dies).""" + want = {b["id"]: b["url"] for b in self.svc.cfg.backends() + if b.get("kind") == "tandemllm" and b.get("enabled", True)} + with self._lock: + for bid in list(self._subs): + if bid not in want or self._subs[bid].url != want[bid]: + self._subs.pop(bid).stop.set() + for bid, url in want.items(): + if bid in self._subs: + continue + s = _Sub(bid, url) + s.thread = threading.Thread(target=self._watch, args=(s,), + name=f"qse-liverelay-{bid}", daemon=True) + self._subs[bid] = s + s.thread.start() + + def _watch(self, s: _Sub) -> None: + fails = 0 + while not s.stop.is_set(): + try: + self._read_once(s) + fails = 0 + except Exception: # noqa: BLE001 (reconnect) + pass + if s.stop.is_set(): + return + s.stop.wait(BACKOFF_S[min(fails, len(BACKOFF_S) - 1)]) + fails += 1 + + def _read_once(self, s: _Sub) -> None: + """One live connection: keep the subscriber's figures at the newest event. The + engine ticks once a second while a stream is open, so one read per event is the + whole cost; a stream that dies (restart, idle cut) returns and reconnects.""" + conn, target = _conn(canary_mod.engine_url(s.url, "/v1/dashboard/live")) + try: + conn.request("GET", target, headers=self._headers(s.id)) + resp = conn.getresponse() + if resp.status != 200: + resp.read(64 * 1024) + return + if conn.sock is not None: + conn.sock.settimeout(READ_TIMEOUT_S) # the engine pings every 15 s + data: list[str] = [] + while not s.stop.is_set(): + line = resp.readline() + if not line: + return + line = line.decode("utf-8", "replace").rstrip("\r\n") + if line.startswith("data:"): + data.append(line[5:].lstrip()) + elif not line and data: + self._keep(s, "\n".join(data)) + data = [] + finally: + conn.close() + + def _headers(self, bid: str) -> dict: + h = {"User-Agent": "tandem-app/live-relay", "Accept": "text/event-stream"} + try: + key = self.svc.cfg.key_for(bid) + except Exception: # noqa: BLE001 + key = None + if key: + h["Authorization"] = f"Bearer {key}" + return h + + def _keep(self, s: _Sub, payload: str) -> None: + try: + doc = json.loads(payload) + except ValueError: + return + if not isinstance(doc, dict): + return + rows, prefill = {}, {} + for r in doc.get("requests") or []: + if not isinstance(r, dict) or r.get("phase") not in IN_FLIGHT: + continue + rid = r.get("request_id") + if not isinstance(rid, str): + continue + row = {k: r[k] for k in ROW_FIELDS if r.get(k) is not None} + if r.get("phase") == "prefill": + row.update(_prefill_fields(r)) + prefill[rid] = row + rows[rid] = row + now, sample, engine = (doc.get("now"), doc.get("sample"), doc.get("engine")) + with self._lock: + if s.stop.is_set(): + return + s.rows = rows + s.prefill = prefill + s.now = now if isinstance(now, dict) else {} + s.sample = sample if isinstance(sample, dict) else {} + s.engine = engine if isinstance(engine, dict) else {} + s.at = time.monotonic() + + # ----------------------------------------------------------------- the getters + def _fresh(self) -> dict[str, _Sub]: + with self._lock: + subs = dict(self._subs) + return {bid: s for bid, s in subs.items() + if s.at and time.monotonic() - s.at <= self.ttl_s} + + def _preferred(self) -> _Sub | None: + """The engine whose whole-engine figures the controller shows: the default backend + when it is a fresh tandemllm one, else the freshest.""" + fresh = self._fresh() + if not fresh: + return None + try: + default = self.svc.cfg.default_backend + except Exception: # noqa: BLE001 + default = None + sub = fresh.get(default) if default else None + return sub or max(fresh.values(), key=lambda s: s.at) + + def row_fields(self, rec) -> dict | None: + """The engine-side fields of a relayed request's live row, None when the engine + has no fresh row for it. The join: `rec.backend` picks the engine, and + `rec.upstream_request` — the answer's id, the engine's request id (SRV-733) — + picks its row.""" + bid = getattr(rec, "backend", None) + rid = getattr(rec, "upstream_request", None) + if not bid or not rid: + return None + with self._lock: + s = self._subs.get(bid) + row = None + if s is not None and s.at and time.monotonic() - s.at <= self.ttl_s: + row = s.rows.get(rid) + return dict(row) if row else None + + def sole_prefill(self, bid: str | None) -> dict | None: + """The prefill figures of the one prefill-phase row open on `bid` — the heuristic + join for an engine that sends no `X-Tandem-Request-Id` (proxy/app.py `_live_enrich`): + a controller request still waiting for its first token can only be that row when the + backend has exactly one. None when the backend has none, has more than one (never + guess), or its stream went quiet for longer than the TTL. The figures are the + engine's for its one running prefill: if the controller's own request is still + queued behind it, the rate shown is the prefill the engine is running now.""" + if not bid: + return None + with self._lock: + s = self._subs.get(bid) + if s is None or not s.at or time.monotonic() - s.at > self.ttl_s: + return None + rows = list(s.prefill.values()) + return dict(rows[0]) if len(rows) == 1 else None + + def rates(self) -> dict | None: + """The rate fields the controller cannot measure, from the engine it serves by + default: the newest sample's, falling back to its `now`. None when no engine is + fresh — the live view then reads exactly as it did without this module.""" + s = self._preferred() + if s is None: + return None + out = {} + for k in RATE_FIELDS: + v = s.sample.get(k) + if v is None: + v = s.now.get(k) + if v is not None: + out[k] = v + return out or None + + def engine_block(self) -> dict | None: + """The engine block's facts the controller cannot measure (model, kv, memory, + store) from the engine it serves by default; None when none is fresh.""" + s = self._preferred() + if s is None: + return None + out = {k: s.engine[k] for k in ENGINE_FIELDS if s.engine.get(k) is not None} + return out or None + + +def _prefill_fields(r: dict) -> dict: + """The prefill figures of an engine row in the prefill phase (its `activity.prefill`, + tandemapp/activity.py `prefill_of`), named as the controller's row carries them: the + live rate over the engine's chunk marks (`tps_live`, its average once the live window + has moved past them), the prefill's elapsed time at the newest mark and its ETA. The + controller has no prefill to measure; these are the engine's, and they join the row + only through the exact join or `sole_prefill` — never a guess.""" + p = r.get("activity") + p = (p.get("prefill") if isinstance(p, dict) else None) or {} + out = {"prefill_live_tps": (p.get("tps_live") if p.get("tps_live") is not None + else p.get("tps_live_avg"))} + for src, dst in (("at_ms", "prefill_elapsed_ms"), ("eta_ms", "prefill_eta_ms")): + if p.get(src) is not None: + out[dst] = p[src] + return {k: out[k] for k in PREFILL_DST_FIELDS if out.get(k) is not None} + + +def _conn(url: str, connect_s: float = 5.0) -> tuple[http.client.HTTPConnection, str]: + """A connection to an engine route (the idiom of proxy/chatengine.py's live pass- + through): (conn, path+query to request).""" + u = urllib.parse.urlsplit(url) + cls = http.client.HTTPSConnection if u.scheme == "https" else http.client.HTTPConnection + target = u.path + (f"?{u.query}" if u.query else "") + return cls(u.hostname, u.port or (443 if u.scheme == "https" else 80), + timeout=connect_s), target or "/" \ No newline at end of file diff --git a/proxy/relay.py b/proxy/relay.py index 7f624ce0..b2801fbf 100644 --- a/proxy/relay.py +++ b/proxy/relay.py @@ -517,6 +517,15 @@ def _start(self, handler, status: int, uh, backend: dict, adapter, stream: bool, def _stream(self, handler, path, conn, pool, uh, adapter, injected, backend, rec, poll, headers=None): st = Stamps() + # SRV-733 (additive): a new engine names its live request id in the response header + # at stream open (`X-Tandem-Request-Id`, the sibling TandemEngine PR), so the row + # joins to the engine's live row through the whole prefill — before the first frame + # (proxy/liverelay.py). The first-frame stamp in `_pump` stays the fallback for an + # engine that sends no header; `_finish` still writes the answer's own id at the end. + hdr_id = next((v for k, v in uh + if k.lower() == "x-tandem-request-id" and v), None) + if hdr_id and rec.upstream_request is None: + rec.upstream_request = hdr_id to = backend["timeouts"] hx = getattr(rec, "hx", None) self._start(handler, 200, uh, backend, adapter, True, rec=rec) @@ -605,6 +614,11 @@ def _pump(self, conn, path, adapter, st, injected, rec, w, to, poll, hx) -> bool event = bytes(buf[:end + sep]) del buf[:end + sep] token, drop = adapter.read_frame(path, event[:end], st, injected) + if st.response_id is not None and rec.upstream_request is None: + # liverelay: the engine's answer id is its live request id (SRV-733); + # stamped while the stream runs so the live view can join this row to + # the engine's (proxy/liverelay.py). `_finish` still writes the final. + rec.upstream_request = st.response_id if token: rec.stamp_token(t_arr, st.kind, st.tool_name, st.tool_chars) if hk is not None and not drop: @@ -852,7 +866,10 @@ def _finish(self, st: Stamps, adapter, path, backend, rec) -> None: rec.cost_micros = adapter.price(u, self.svc.price_of(backend["id"], rec.backend_model or rec.public_model), rec.ts) rec.system_fingerprint = st.fingerprint - rec.upstream_request = st.response_id + if st.response_id is not None: + # an id the header or the first frame stamped stays when the answer never + # carried one (a stream that died before its first frame) + rec.upstream_request = st.response_id def _cost_line(self, st: Stamps, adapter, path, backend, rec) -> bytes: """The cost comment: the usage so far (the harness's requests summed, else the stream's diff --git a/proxy/service.py b/proxy/service.py index 7822db11..e7304b2f 100644 --- a/proxy/service.py +++ b/proxy/service.py @@ -203,6 +203,8 @@ def __init__(self, cfg: "config_mod.ConfigDB", *, ledger=None, live=None, auth=N self.notifier = None # notify.send; a test puts its own here # SRV-873: an API token's limits (proxy/tokenlimits.py) self.limits = None + # the engines' live figures for the live view (proxy/liverelay.py); app.build starts it + self.liverelay = None # SRV-849: the remote hooks around the relay (proxy/hooks.py); idle while none is enabled self.hooks = hooks_mod.Runner(cfg, log=lambda m: self.log(m)) if registry is not None: @@ -239,6 +241,9 @@ def stop(self) -> None: self.hooks.stop() if getattr(self, "providers", None) is not None: self.providers.stop() + relay = getattr(self, "liverelay", None) + if relay is not None: + relay.stop() self.health.stop() self.engines.stop() self.collect.stop() diff --git a/tandemapp/live.py b/tandemapp/live.py index 477e0eb0..8db8fa68 100644 --- a/tandemapp/live.py +++ b/tandemapp/live.py @@ -219,17 +219,26 @@ class LiveRegistry: `STATE["last_prefill"]`; `engine` returns the engine block's plain facts (model, version, draining, kv, memory, store). `clock` is wall time for the payload, `perf` the counter the records are stamped with; tests inject both. + + `enrich` (additive) is called with each in-flight record once a tick; a dict it returns is + merged into that request's row. `live_rates` (additive) is called with nothing; a dict of + `decode_tps` / `prefill_tps` / `decode_live_tps` / `prefill_live_tps` fills the nulls of + the history sample and of `now`. The controller has no decode loop to sample: it uses both + to carry its TandemLLM backends' own live figures (proxy/liverelay.py). Both default None: + the payload is exactly what this registry measured. """ def __init__(self, *, blocks=None, last_prefill=None, engine=None, clock=time.time, perf=time.perf_counter, keep_s: float = KEEP_S, history: int = HISTORY, interval: float = INTERVAL_S, hz: int = DEFAULT_HZ, activity: bool = True, queue_timeout=None, sock_closed=None, windows: dict | None = None, - slot_blocks=None): + slot_blocks=None, enrich=None, live_rates=None): self.blocks_fn = blocks or (lambda: None) self.slot_blocks_fn = slot_blocks or (lambda i: None) self.last_prefill_fn = last_prefill or (lambda: None) self.engine_fn = engine or (lambda: {}) + self.enrich_fn = enrich + self.live_rates_fn = live_rates self.queue_timeout_fn = queue_timeout or (lambda: None) self.sock_closed = sock_closed or act.socket_closed self.clock, self.perf = clock, perf @@ -601,12 +610,14 @@ def _sample(self, live, now_p: float, now_c: float) -> None: if tps is not None and not self._mostly_cached(r): prefill_live += tps pl_n += 1 - self._samples.append({"t": _r(now_c, 3), "decode_tps": decode_tps, - "prefill_tps": prefill_tps, - "running": sum(1 for r in live if r.t_first is not None), - "waiting": sum(1 for r in live if r.t_lock is None), - "tokens": total, "decode_live_tps": _r(decode_live) if dl_n else None, - "prefill_live_tps": _r(prefill_live) if pl_n else None}) + sample = {"t": _r(now_c, 3), "decode_tps": decode_tps, + "prefill_tps": prefill_tps, + "running": sum(1 for r in live if r.t_first is not None), + "waiting": sum(1 for r in live if r.t_lock is None), + "tokens": total, "decode_live_tps": _r(decode_live) if dl_n else None, + "prefill_live_tps": _r(prefill_live) if pl_n else None} + self._fill_rates(sample) + self._samples.append(sample) self._prev = (now_p, total, decoding) self._last_sample_p = now_p self.samples_taken += 1 @@ -632,7 +643,7 @@ def _snapshot_locked(self, now_p: float, now_c: float, *, history: bool, live = list(self._live.values()) bs = self.blocks_fn() lp = self.last_prefill_fn() - rows = [self._row(r, now_p, None, bs) for r in live] + rows = [self._row_enriched(r, now_p, bs) for r in live] rows.sort(key=lambda x: {"decode": 0, "prefill": 1, "queued": 2}[x["phase"]]) in_flight = list(rows) acts: dict[str, dict] = {} @@ -708,6 +719,7 @@ def _snapshot_locked(self, now_p: float, now_c: float, *, history: bool, "tick_cpu_us_mean": _r(self.tick_us["cpu_sum"] / self.tick_us["n"], 1) if self.tick_us["n"] else None, "tick_cpu_us_max": _r(self.tick_us["cpu_max"], 1)}} + self._fill_rates(out["now"]) if history: out["history"] = samples return (out, raw_parts) if raw else out @@ -983,6 +995,35 @@ def _prefill_tps(self, rec, *, done: bool) -> float | None: fwd = int(lp.get("forwarded") or 0) return fwd / (ms / 1e3) if fwd and ms else None + def _row_enriched(self, rec, now_p: float, bs) -> dict: + """The in-flight row, plus whatever `enrich` carries for the record (additive; + `enrich=None`: exactly `_row`). A hook that raises never costs the tick its row.""" + row = self._row(rec, now_p, None, bs) + if self.enrich_fn is not None: + try: + extra = self.enrich_fn(rec) + except Exception: # noqa: BLE001 (never the tick) + extra = None + if extra: + row.update(extra) + return row + + def _fill_rates(self, into: dict) -> None: + """The nulls of a history sample or of `now` from `live_rates` (additive; None: no-op). + The controller has no decode loop: its engine's figures stand in for the rates it + cannot measure itself, and only where its own answer is null.""" + if self.live_rates_fn is None: + return + try: + rates = self.live_rates_fn() + except Exception: # noqa: BLE001 (never the tick) + return + if not rates: + return + for k in ("decode_tps", "prefill_tps", "decode_live_tps", "prefill_live_tps"): + if into.get(k) is None and rates.get(k) is not None: + into[k] = rates[k] + def _row(self, rec, now_p: float, ended: float | None, bs) -> dict: bs = _own_blocks(rec, bs, self.slot_blocks_fn if ended is None else None) live = ended is None diff --git a/tests/test_proxy_liverelay.py b/tests/test_proxy_liverelay.py new file mode 100644 index 00000000..43e9ade0 --- /dev/null +++ b/tests/test_proxy_liverelay.py @@ -0,0 +1,471 @@ +"""The live relay: the engine's live figures into the controller's live view. + +A fake engine (stdlib http.server) streams `/v1/dashboard/live` and answers chat requests; +the relay (proxy/liverelay.py) keeps its rows, its `now`, its sample and its engine block +fresh; a `LiveRegistry` built the way the controller builds one (`blocks=None, +activity=False`) carries them into its in-flight rows, its history sample and its `now` — +joined by the answer's id, the engine's request id (SRV-733) — and drops them once the +engine goes quiet for longer than the TTL. The hooks default off: a registry without them +reads exactly as it did before, and a hook that raises never costs the tick its row. + +The prefill phase: a new engine names its live request id in the response header at stream +open (`X-Tandem-Request-Id`), which proxy/relay.py stamps before the pump starts, so the +row joins through the whole prefill; an old engine's id arrives only with the first frame, +and there the sole-prefill heuristic joins the request when the backend has exactly one +prefill row open — never when two could be it. + +Run: python tests/test_proxy_liverelay.py +""" + +from __future__ import annotations + +import http.client +import json +import os +import sys +import threading +import time +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from proxy_util import Proxy, run # noqa: E402 + +from proxy import app as proxy_app # noqa: E402 +from proxy import liverelay # noqa: E402 +from proxy.measure import RelayRecord # noqa: E402 +from tandemapp import live as live_mod # noqa: E402 + +ENGINE_ID = "chatcmpl-fake0123456789abcdef01" +ENGINE_ID2 = "chatcmpl-fake1123456789abcdef01" +HDR_ID = "chatcmpl-hdr0123456789abcdef01" +HDR_ID2 = "chatcmpl-hdr1123456789abcdef01" +UNKNOWN_ID = "chatcmpl-000000000000000000000000" + +#: one live event of the fake engine: one request decoding, its rates, its engine block +EVENT = { + "contract_version": "1.2", "seq": 1, + "engine": {"model": "fake-model", "version": "0.0.0", "draining": False, + "kv": {"length": 100, "max_len": 4096}, + "memory": {"mem_available_gib": 9.0, "rss_gib": 8.0}, "store": None}, + "counts": {"in_flight": 1, "queued": 0, "prefilling": 0, "waiting_memory": 0, + "decoding": 1, "completed_1m": 0, "served": 1, "errors": 0, "refused": 0}, + "now": {"decode_tps": 41.0, "prefill_tps": None, "prefilling": False, + "tokens_per_block": None, "last_prefill_ms_ago": None, + "prefill_live_tps": 600.0, "prefill_live_count": 1, + "decode_live_tps": 42.5, "decode_warming": 0}, + "requests": [{"request_id": ENGINE_ID, "phase": "decode", "status": 200, + "decode_live_now_tps": 42.5, "decode_live_avg_tps": 40.0, + "decode_warmup": {"tokens": 30, "reached": True}}], + "sample": {"t": 0.0, "decode_tps": 41.0, "prefill_tps": 500.0, "running": 1, + "waiting": 0, "tokens": 100, "decode_live_tps": 42.5, + "prefill_live_tps": 600.0}, + "recent": None, "sample_last": None, +} + + +class _Engine(ThreadingHTTPServer): + """The fake engine: it streams live events until told to go quiet (the connection + stays open, like a link that stopped ticking) or to drop it (a restart). `rows` are + the in-flight rows its live stream carries; a chat answer is streamed with + `first_delay_s` of silence before its first frame (the prefill) and, when `chat_id` + is set, names it in `X-Tandem-Request-Id` at stream open (a new engine, SRV-733).""" + + daemon_threads = True + + def __init__(self, handler): + super().__init__(("127.0.0.1", 0), handler) + self.quiet = threading.Event() + self.drop = threading.Event() + self.rows = list(EVENT["requests"]) + self.chat_id = None + self.first_delay_s = 0.0 + + +def _chunk(cid, delta, finish): + doc = {"id": cid, "object": "chat.completion.chunk", "created": 0, + "model": "fake-model", + "choices": [{"index": 0, "delta": delta, "finish_reason": finish}]} + if finish == "stop": + doc["usage"] = {"prompt_tokens": 10, "completion_tokens": 2, "total_tokens": 12} + return b"data: " + json.dumps(doc).encode() + b"\n\n" + + +class _Handler(BaseHTTPRequestHandler): + def do_GET(self): # noqa: N802 + if self.path.startswith("/v1/models"): + body = json.dumps({"object": "list", + "data": [{"id": "fake-model", "object": "model"}]}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + return + if not self.path.startswith("/v1/dashboard/live"): + self.send_response(404) + self.end_headers() + return + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + seq = 0 + try: + while True: + if self.server.drop.is_set(): + return # the stream dies: the connection closes + if not self.server.quiet.is_set(): + seq += 1 + doc = dict(EVENT, seq=seq, requests=list(self.server.rows)) + self.wfile.write(b"event: live\nid: %d\ndata: %s\n\n" + % (seq, json.dumps(doc).encode())) + self.wfile.flush() + time.sleep(0.2) + except (BrokenPipeError, ConnectionResetError, OSError): + pass + + def do_POST(self): # noqa: N802 + if not self.path.startswith("/v1/chat/completions"): + self.send_response(404) + self.end_headers() + return + self.rfile.read(int(self.headers.get("Content-Length") or 0)) + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + if self.server.chat_id: + # a new engine: its live request id, named at stream open (SRV-733 sibling) + self.send_header("X-Tandem-Request-Id", self.server.chat_id) + self.end_headers() + cid = self.server.chat_id or "chatcmpl-fake-chat" + try: + time.sleep(self.server.first_delay_s) # the prefill: no frame yet + for frame in (_chunk(cid, {"content": "ok"}, None), + _chunk(cid, {}, "stop"), b"data: [DONE]\n\n"): + self.wfile.write(frame) + self.wfile.flush() + except (BrokenPipeError, ConnectionResetError, OSError): + pass + + def log_message(self, *args): + pass + + +class _Cfg: + def __init__(self, url): + self._url = url + self.default_backend = "e1" + + def backends(self): + return [{"id": "e1", "kind": "tandemllm", "enabled": True, "url": self._url}] + + def key_for(self, bid): + return None + + +class _Svc: + def __init__(self, cfg): + self.cfg = cfg + + +def _app_enrich(relay): + """The controller's own enrich hook (proxy/app.py `_live_enrich`) aimed at this relay: + the tests drive the same code the live view runs, heuristic join included.""" + def enrich(rec): + had = "liverelay" in proxy_app.STATE + saved = proxy_app.STATE.get("liverelay") + proxy_app.STATE["liverelay"] = relay + try: + return proxy_app._live_enrich(rec) + finally: + if had: + proxy_app.STATE["liverelay"] = saved + else: + proxy_app.STATE.pop("liverelay", None) + return enrich + + +def _start(rows=None): + """(engine, relay, registry): the fake engine on its port, the relay watching it, + and a registry built the way proxy/app.py builds its own — its engine block the + controller's nulls plus the relay's `engine_block()`, exactly as `_live_engine`, and + its enrich hook the controller's own `_live_enrich`. `rows` replaces the in-flight + rows the engine's live stream carries.""" + eng = _Engine(_Handler) + if rows is not None: + eng.rows = rows + threading.Thread(target=eng.serve_forever, kwargs={"poll_interval": 0.05}, + daemon=True).start() + url = f"http://127.0.0.1:{eng.server_address[1]}/v1" + relay = liverelay.LiveRelay(_Svc(_Cfg(url)), ttl_s=1.0, sync_s=0.2) + relay.start() + + def engine_block(): + out = {"model": None, "version": "test", "draining": False, + "kv": {"length": 0, "max_len": 0}, + "memory": {"mem_available_gib": None, "rss_gib": None}, "store": None} + out.update(relay.engine_block() or {}) + return out + + reg = live_mod.LiveRegistry(blocks=lambda: None, last_prefill=lambda: None, + engine=engine_block, hz=live_mod.DEFAULT_HZ, + activity=False, queue_timeout=lambda: 0.0, + enrich=_app_enrich(relay), live_rates=relay.rates) + return eng, relay, reg + + +def _decoding_rec(request_id="px-1", upstream=ENGINE_ID): + """A relayed request mid-decode, as the relay stamps it (proxy/measure.py).""" + rec = RelayRecord(request_id, "chat", True) + rec.backend = "e1" + rec.upstream_request = upstream + rec.stamp_sent() + rec.stamp_token(time.perf_counter(), "content") + return rec + + +def _row(snap, request_id): + return next(r for r in snap["requests"] if r["request_id"] == request_id) + + +def _wait(fn, timeout=5.0): + end = time.time() + timeout + while time.time() < end: + got = fn() + if got: + return got + time.sleep(0.05) + return None + + +def test_relayed_row_carries_the_engine_rates_and_goes_stale(): + eng, relay, reg = _start() + try: + rec = _decoding_rec() + reg.register(rec) + assert _wait(lambda: relay.row_fields(rec)), "the relay never went fresh" + snap = reg.snapshot() + row = _row(snap, "px-1") + assert row["decode_live_now_tps"] == 42.5, row + assert row["decode_live_avg_tps"] == 40.0, row + assert row["decode_warmup"] == {"tokens": 30, "reached": True}, row + # the controller's own `now` cannot measure the prefill rate: the engine's stands in + assert snap["now"]["prefill_live_tps"] == 600.0, snap["now"] + # the engine block: the model and the KV window only the engine knows + assert snap["engine"]["model"] == "fake-model", snap["engine"] + assert snap["engine"]["kv"]["max_len"] == 4096, snap["engine"] + # the history sample: the chart series the controller cannot sample itself + reg.tick() + snap = reg.snapshot() + assert snap["sample"]["decode_live_tps"] == 42.5, snap["sample"] + assert snap["sample"]["prefill_live_tps"] == 600.0, snap["sample"] + assert snap["sample"]["decode_tps"] == 41.0, snap["sample"] + assert snap["sample"]["prefill_tps"] == 500.0, snap["sample"] + # quiet longer than the TTL: every figure drops back to what the controller measured + eng.quiet.set() + assert _wait(lambda: relay.row_fields(rec) is None and relay.rates() is None + and relay.engine_block() is None, timeout=4.0), "the figures went stale" + snap = reg.snapshot() + row = _row(snap, "px-1") + assert row["decode_live_now_tps"] is None, row + assert snap["now"]["prefill_live_tps"] is None, snap["now"] + assert snap["engine"]["model"] is None, snap["engine"] + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_no_join_no_enrichment(): + """A request the engine has no row for — no answer id yet (still prefilling), or one + the engine does not know — keeps the row exactly as the controller measured it.""" + eng, relay, reg = _start() + try: + fresh = _decoding_rec() + reg.register(fresh) + assert _wait(lambda: relay.row_fields(fresh)), "the relay never went fresh" + unknown = _decoding_rec("px-2", "chatcmpl-000000000000000000000000") + reg.register(unknown) + reg.register(_decoding_rec("px-3", upstream=None)) + snap = reg.snapshot() + assert _row(snap, "px-1")["decode_live_now_tps"] == 42.5 + rows = [r for r in snap["requests"] if r["request_id"] != "px-1"] + assert len(rows) == 2 and all(r["decode_live_now_tps"] is None for r in rows), rows + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_reconnect_after_the_engine_drops_the_stream(): + eng, relay, reg = _start() + try: + rec = _decoding_rec() + reg.register(rec) + assert _wait(lambda: relay.row_fields(rec)), "the relay never went fresh" + eng.drop.set() + assert _wait(lambda: relay.row_fields(rec) is None, timeout=4.0), \ + "the dropped stream kept its figures" + eng.drop.clear() + assert _wait(lambda: relay.row_fields(rec), timeout=8.0), "the relay did not reconnect" + assert reg.snapshot()["requests"][0]["decode_live_now_tps"] == 42.5 + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_hooks_default_off_and_a_raising_hook_costs_nothing(): + """A registry built without the hooks — the engine's own build, and the controller's + before this module — reads exactly as it did: nulls, no enrichment, no fill.""" + reg = live_mod.LiveRegistry(blocks=lambda: None, last_prefill=lambda: None, + engine=lambda: {}, activity=False, + queue_timeout=lambda: 0.0) + rec = _decoding_rec() + reg.register(rec) + snap = reg.snapshot() + assert _row(snap, "px-1")["decode_live_now_tps"] is None + assert snap["now"]["prefill_live_tps"] is None + # a hook that raises never costs the tick its row + def boom(_rec): + raise RuntimeError("the relay is on fire") + reg.enrich_fn = boom + reg.live_rates_fn = boom + snap = reg.snapshot() + assert _row(snap, "px-1")["decode_live_now_tps"] is None + assert snap["now"]["prefill_live_tps"] is None + + +def _prefill_row(rid, tps_live, at_ms=2000.0, eta_ms=1500.0): + """One engine live row in the prefill phase, with the activity figures the engine's + chunk marks give it (tandemapp/activity.py `prefill_of`).""" + return {"request_id": rid, "phase": "prefill", "status": 200, + "decode_live_now_tps": None, "decode_live_avg_tps": None, + "decode_warmup": None, + "activity": {"prefill": {"tps_live": tps_live, "tps_live_avg": tps_live, + "at_ms": at_ms, "eta_ms": eta_ms}}} + + +def _prefilling_rec(request_id="px-1", upstream=None): + """A relayed request mid-prefill: sent upstream, no answer id yet, no first token.""" + rec = RelayRecord(request_id, "chat", True) + rec.backend = "e1" + rec.backend_kind = "tandemllm" + rec.upstream_request = upstream + rec.stamp_sent() + return rec + + +def test_the_sole_prefill_row_joins_a_request_still_prefilling(): + """An old engine (no header): the answer id arrives only with the first frame, so a + request mid-prefill has nothing to join with. Exactly one prefill row open on the + backend means it can only be this request's: its prefill figures join the row.""" + eng, relay, reg = _start(rows=[_prefill_row(ENGINE_ID, 777.0)]) + try: + rec = _prefilling_rec() + reg.register(rec) + assert _wait(lambda: relay.sole_prefill("e1")), "the relay never went fresh" + row = _row(reg.snapshot(), "px-1") + assert row["phase"] == "prefill", row + assert row["prefill_live_tps"] == 777.0, row + assert row["prefill_elapsed_ms"] == 2000.0, row + assert row["prefill_eta_ms"] == 1500.0, row + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_two_prefill_rows_are_ambiguous_and_stay_null(): + """Two prefill rows open: either could be the request's, so neither is — the row + stays exactly what the controller measured.""" + eng, relay, reg = _start(rows=[_prefill_row(ENGINE_ID, 777.0), + _prefill_row(ENGINE_ID2, 888.0)]) + try: + rec = _prefilling_rec() + reg.register(rec) + assert _wait(lambda: relay.rates()), "the relay never went fresh" + assert relay.sole_prefill("e1") is None, "two prefill rows were not ambiguous" + row = _row(reg.snapshot(), "px-1") + assert row.get("prefill_live_tps") is None, row + assert row.get("prefill_elapsed_ms") is None, row + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_the_header_join_wins_over_the_heuristic(): + """With an id stamped from the response header the join is exact and the heuristic is + never consulted: a header id the engine has no row for stays null (never guess, even + with one prefill row open), and the header id the engine does have joins exactly.""" + eng, relay, reg = _start(rows=[_prefill_row(ENGINE_ID, 777.0)]) + try: + missed = _prefilling_rec("px-1", UNKNOWN_ID) + joined = _prefilling_rec("px-2", ENGINE_ID) + reg.register(missed) + reg.register(joined) + assert _wait(lambda: relay.sole_prefill("e1")), "the relay never went fresh" + snap = reg.snapshot() + assert _row(snap, "px-1").get("prefill_live_tps") is None, snap + assert _row(snap, "px-2")["prefill_live_tps"] == 777.0, snap + finally: + relay.stop() + eng.shutdown() + eng.server_close() + + +def test_the_header_stamps_the_join_before_the_first_frame(): + """A new engine names its live request id in the response header at stream open + (`X-Tandem-Request-Id`): proxy/relay.py stamps it before the pump starts, so the row + joins to the engine's prefill row through the whole prefill. The engine keeps two + prefill rows open, where the sole-prefill heuristic could not guess — so the figure + the row shows before the first frame can only come from the header.""" + eng = _Engine(_Handler) + eng.rows = [_prefill_row(HDR_ID, 777.0), _prefill_row(HDR_ID2, 888.0)] + eng.chat_id = HDR_ID + eng.first_delay_s = 2.0 + threading.Thread(target=eng.serve_forever, kwargs={"poll_interval": 0.05}, + daemon=True).start() + port = eng.server_address[1] + try: + env = {"TANDEM_BACKENDS": "e1", "TANDEM_BACKEND_E1_KIND": "tandemllm", + "TANDEM_BACKEND_E1_URL": f"http://127.0.0.1:{port}/v1", + "TANDEM_DEFAULT_BACKEND": "e1"} + with Proxy(env=env) as px: + px.sync() + assert _wait(lambda: px.svc.liverelay.rates()), "the relay never went fresh" + first: list[float] = [] + + def fire(): + c = http.client.HTTPConnection("127.0.0.1", px.port, timeout=30) + body = {"model": "fake-model", "stream": True, + "messages": [{"role": "user", "content": "hello"}]} + c.request("POST", "/v1/chat/completions", json.dumps(body), + {"Content-Type": "application/json"}) + r = c.getresponse() + while True: + line = r.readline() + if not line: + break + if line.startswith(b"data: "): + first.append(time.time()) + break + while r.read(4096): + pass + c.close() + + t = threading.Thread(target=fire, daemon=True) + t.start() + got = _wait(lambda: next((x for x in px.svc.live.snapshot()["requests"] + if x.get("prefill_live_tps") == 777.0), None), + timeout=6.0) + assert got, "the header-stamped row never joined the engine's prefill row" + assert got["phase"] == "prefill", got + assert not first, "the join waited for the first frame" + t.join(15.0) + finally: + eng.shutdown() + eng.server_close() + + +if __name__ == "__main__": + run(globals()) \ No newline at end of file