mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 21:04:21 +01:00
- P3: an Anthropic body goes to the engine's own /v1/messages/count_tokens
(its conversion, tools included), each image priced from its header and
replaced by an empty text block (an empty list is a 500 there). Measured on
the box: five screenshots in tool_result blocks were counted 2,044,251 and
refused, the engine serves 28,463 (28,458 counted now); 8 tools, 422 counted
before, 2,709 now and served
- P4: a raw control or non-ASCII byte in the query is a 400, not a dropped
socket and a "client vanished" line
- P5: the logged-once memories keep 16-byte digests, 512 at most; the moved
effort is printed 40 characters long (five 20 MB values: 22 -> 346 MiB and
a 20,000,137-character journal line each, before)
- P7: a client named by the identity wall is named on the request's first
line too, as one word; the cockpit's feed accepts the label after the peer
- P6: the cockpit greps the banner in its current shape ("on 0.0.0.0:30001");
it showed v6.20 while v6.24 ran. U7: the too-old-to-abort warning compares
versions part by part, server-side (as floats, v6.2 to v6.9 passed)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
617 lines
30 KiB
Python
617 lines
30 KiB
Python
"""Engine lifecycle: pure logic, no I/O.
|
|
|
|
Turns raw facts (systemd state, container presence, boot-log lines, health)
|
|
into ONE explicit state plus progress, ETA and blocked-action reasons.
|
|
Every function here is pure so the whole module is unit-testable offline.
|
|
|
|
States (a strict superset of what the UI shows):
|
|
stopped, failed, starting, loading-weights, loading-draft, allocating-kv,
|
|
capturing-graphs, warming-up, ready, degraded, stopping
|
|
Flags: rebuild (PLE table rebuild in progress), overdue (stage took > 2x ETA).
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
from datetime import datetime
|
|
import statistics
|
|
|
|
# ── Boot-log stage markers (real lines, see tests/test_lifecycle.py) ─────────
|
|
_TS = r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] "
|
|
MARKERS = [
|
|
("init", re.compile(_TS + r"server_args=ServerArgs\(")),
|
|
("weights", re.compile(_TS + r"Load weight begin\.")),
|
|
("ple", re.compile(_TS + r"PLE table -> ")),
|
|
("weights_end", re.compile(_TS + r"Load weight end\. elapsed=([\d.]+) s, type=(\w+)")),
|
|
("kv", re.compile(_TS + r"KV Cache is allocated\.")),
|
|
("graphs", re.compile(_TS + r"Capture .* CUDA graph begin\.")),
|
|
("graphs_end", re.compile(_TS + r"Capture .* CUDA graph end\.")),
|
|
("ready", re.compile(_TS + r"The server is fired up and ready to roll!")),
|
|
]
|
|
REBUILD_RE = re.compile(r"rebuilding the PLE table")
|
|
|
|
# Boot stages in order; parse_boot_log maps marker hits onto these.
|
|
STAGES = ("init", "loading-weights", "loading-draft", "allocating-kv",
|
|
"capturing-graphs", "warming-up")
|
|
|
|
# ── The image lane speaks another dialect ───────────────────────────────────
|
|
# SGLang Diffusion has no draft, no KV pool and no CUDA graphs, and it writes its
|
|
# own timestamps in two formats (the engine "[09-22 17:20:37]", uvicorn "[2026-09-22
|
|
# 17:21:34]"), so its lines are matched on what they say, never on when. Measured on
|
|
# the reference box, one boot from process start to fired up, 64 s:
|
|
# 0 s Starting server 7 s Loading pipeline modules 18 s Loaded text_encoder
|
|
# 51 s Loaded transformer 57 s Loaded vae, Pipeline instantiated 64 s fired up
|
|
# The transformer is half a minute with nothing printed in between, which is why the
|
|
# component being loaded travels as `detail`: a stage called "weights" for 33 s says
|
|
# less than "the 13.3 GB DiT".
|
|
IMAGE_STAGES = ("init", "loading-weights", "warming-up")
|
|
IMAGE_MARKERS = [
|
|
# (substring, stage it opens, what is being loaded while that line is the latest)
|
|
("Starting server...", "init", "starting the server"),
|
|
("Loading pipeline modules...", "loading-weights", "reading the checkpoint layout"),
|
|
("Loading text_encoder from", "loading-weights", "the 16.5 GB Qwen3-VL encoder"),
|
|
("Loading transformer from", "loading-weights", "the 13.3 GB DiT"),
|
|
("Loading vae from", "loading-weights", "the VAE"),
|
|
("Pipeline instantiated", "loading-weights", "building the pipeline"),
|
|
("Starting FastAPI server", "warming-up", "one throwaway image"),
|
|
("fired up and ready to roll", "warming-up", "ready"),
|
|
]
|
|
|
|
|
|
def parse_image_boot_log(lines: list[str]) -> dict:
|
|
"""The image lane's journal, reduced to the same shape parse_boot_log returns.
|
|
|
|
Only the latest boot counts: journald keeps every previous life of the unit,
|
|
and a "fired up" from yesterday must not make today's boot read as ready."""
|
|
start = 0
|
|
for i, ln in enumerate(lines):
|
|
if "Starting server..." in ln:
|
|
start = i
|
|
stage, detail, fired = None, "", False
|
|
for ln in lines[start:]:
|
|
for needle, st, what in IMAGE_MARKERS:
|
|
if needle in ln:
|
|
stage, detail = st, what
|
|
if needle == "fired up and ready to roll":
|
|
fired = True
|
|
done = list(IMAGE_STAGES[:IMAGE_STAGES.index(stage)]) if stage in IMAGE_STAGES else []
|
|
if fired:
|
|
done = list(IMAGE_STAGES)
|
|
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
|
|
|
|
|
|
def parse_boot_log(lines: list[str]) -> dict:
|
|
"""Reduce a container log tail to {stage, done[], fired_up, weight_loads}.
|
|
|
|
weight_loads counts completed 'Load weight end' lines: the first is the
|
|
target model, the second the draft/MTP head. That distinction is what
|
|
separates loading-weights from loading-draft.
|
|
"""
|
|
fired = False
|
|
saw_init = False
|
|
weight_begins = 0
|
|
weight_ends = 0
|
|
kv = False
|
|
graphs_begun = False
|
|
graphs_done = False
|
|
ple = False
|
|
for ln in lines:
|
|
for name, rx in MARKERS:
|
|
m = rx.match(ln)
|
|
if not m:
|
|
continue
|
|
if name == "init":
|
|
# A fresh ServerArgs line means a fresh boot: reset everything
|
|
# (docker log tails can span a previous life of the container).
|
|
fired = saw_init = kv = graphs_begun = graphs_done = ple = False
|
|
weight_begins = weight_ends = 0
|
|
saw_init = True
|
|
elif name == "weights":
|
|
weight_begins += 1
|
|
elif name == "weights_end":
|
|
weight_ends += 1
|
|
elif name == "ple":
|
|
ple = True
|
|
elif name == "kv":
|
|
kv = True
|
|
elif name == "graphs":
|
|
graphs_begun = True
|
|
elif name == "graphs_end":
|
|
graphs_done = True
|
|
elif name == "ready": # pragma: no branch
|
|
fired = True
|
|
# The chain above handles every name in MARKERS, so this break is
|
|
# never reached by falling off the end of it. That is a property, not
|
|
# a hope: test_every_marker_is_handled_by_the_chain fails the day a
|
|
# marker is declared without an arm, which is the only way this line
|
|
# could start swallowing one.
|
|
break
|
|
if fired:
|
|
stage = "warming-up" # fired up; health flips it to ready
|
|
elif graphs_begun:
|
|
stage = "capturing-graphs"
|
|
elif kv:
|
|
stage = "allocating-kv"
|
|
elif weight_ends >= 2 or (weight_ends >= 1 and weight_begins >= 2):
|
|
stage = "loading-draft"
|
|
elif weight_begins >= 1:
|
|
stage = "loading-weights"
|
|
elif saw_init:
|
|
stage = "init"
|
|
else:
|
|
stage = None # no boot evidence in this tail
|
|
done = []
|
|
if stage in STAGES: # no marker evidence => nothing is "done"
|
|
for s in STAGES: # pragma: no branch (the guard above
|
|
if s == stage: # guarantees a match, so the loop always breaks)
|
|
break
|
|
done.append(s)
|
|
return {"stage": stage, "done": done, "fired_up": fired,
|
|
"ple_mmap": ple, "weight_ends": weight_ends,
|
|
"graphs_done": graphs_done}
|
|
|
|
|
|
def journal_flags(lines: list[str]) -> dict:
|
|
"""Flags derivable only from the unit journal (launcher speaks there)."""
|
|
return {"rebuild": any(REBUILD_RE.search(ln) for ln in lines)}
|
|
|
|
|
|
def derive_state(*, unit_active: str, unit_sub: str, container_running: bool,
|
|
healthy: bool, boot: dict, rebuild: bool = False) -> dict:
|
|
"""The single source of truth the UI renders. Pure function of facts."""
|
|
flags = {"rebuild": bool(rebuild)}
|
|
if container_running and unit_active in ("failed", "inactive", "dead", "?", ""):
|
|
# The unit is down and its container is not: a stop past its timeout (systemd
|
|
# kills the docker client and marks the unit failed, while the container belongs
|
|
# to the docker daemon and keeps its pool), or one started by hand. It read
|
|
# "failed" or "stopped", and neither was busy for the one-engine gate.
|
|
return {"state": "orphan", **flags}
|
|
if unit_active == "failed":
|
|
return {"state": "failed", **flags}
|
|
if unit_active == "activating" and unit_sub == "auto-restart":
|
|
# Between two attempts of Restart=always after a crash: RestartSec=15 never reaches
|
|
# systemd's start limit, so a unit dying at load never reads "failed" and was drawn
|
|
# as a boot in its first stage forever (found in review, 2026-09-24).
|
|
return {"state": "failed", "restarting": True, **flags}
|
|
if unit_active == "deactivating":
|
|
return {"state": "stopping", **flags}
|
|
if unit_active in ("inactive", "dead", "?", ""):
|
|
return {"state": "stopped", **flags}
|
|
# unit is active/activating from here on
|
|
if not container_running:
|
|
return {"state": "starting", **flags}
|
|
if healthy:
|
|
return {"state": "ready", **flags}
|
|
stage = boot.get("stage")
|
|
if boot.get("fired_up"):
|
|
# fired up but health probe failing right now
|
|
return {"state": "degraded", **flags}
|
|
if stage in (None, "init"):
|
|
return {"state": "starting", **flags}
|
|
mapping = {"loading-weights": "loading-weights",
|
|
"loading-draft": "loading-draft",
|
|
"allocating-kv": "allocating-kv",
|
|
"capturing-graphs": "capturing-graphs",
|
|
"warming-up": "warming-up"}
|
|
return {"state": mapping.get(stage, "starting"), **flags}
|
|
|
|
|
|
# States during which an engine occupies (or is about to occupy) the GPU pool.
|
|
BUSY_STATES = {"starting", "loading-weights", "loading-draft", "allocating-kv",
|
|
"capturing-graphs", "warming-up", "ready", "degraded",
|
|
"stopping", "wedged", "orphan"}
|
|
# An orphan or a wedge does not settle by waiting (autoheal is off by default), so neither
|
|
# holds a switch back, which only rewrites files; both stay busy for a second engine.
|
|
TRANSITIONAL = BUSY_STATES - {"ready", "degraded", "orphan", "wedged"}
|
|
# Every unit that holds the GPU pool while it runs. The image lane is one of them:
|
|
# 31 GB of weights, and two engines at once on 121.6 GB of unified memory is the
|
|
# livelock this whole module exists to prevent.
|
|
ENGINE_UNITS = ("qwen38-sglang.service", "qwen38-flash.service", "qwen38-image.service")
|
|
IMAGE_UNIT = "qwen38-image.service"
|
|
# The engines that serve text on ENGINE_BASE. Every probe, guard and belt that talks to
|
|
# that port (the generation canary, the pool guard, the wedge autoheal) is about these
|
|
# and only these: with the image lane serving, :30000 is closed, and asking "is an
|
|
# engine ready" instead sent the canary a chat completion to a dead port every 90 s.
|
|
TEXT_UNITS = tuple(u for u in ENGINE_UNITS if u != IMAGE_UNIT)
|
|
|
|
|
|
def blocked_reasons(action: str, params: dict, states: dict) -> list[str]:
|
|
"""Why an action must NOT run now. Empty list = allowed.
|
|
|
|
states: {unit_name: state_string} for the two engine units.
|
|
The cardinal rule on 128 GB unified memory: never two engines at once.
|
|
"""
|
|
reasons = []
|
|
def st(u):
|
|
return states.get(u, "stopped")
|
|
if action == "unit":
|
|
unit, verb = params.get("unit", ""), params.get("verb", "")
|
|
if unit in ENGINE_UNITS and verb in ("start", "restart"):
|
|
# Every other engine, not "the other one": with three lanes, picking [0]
|
|
# checked one of two neighbours and let the third through.
|
|
for other in ENGINE_UNITS:
|
|
if other != unit and st(other) == "orphan":
|
|
reasons.append(
|
|
f"{other}'s container still runs outside systemd: two engines never "
|
|
f"run at once on unified memory (remove it first, see the banner)")
|
|
elif other != unit and st(other) in BUSY_STATES:
|
|
reasons.append(
|
|
f"{other} is {st(other)}: two engines never run at once "
|
|
f"on unified memory (stop it first)")
|
|
elif action in ("switch", "update_stack"):
|
|
for u in ENGINE_UNITS:
|
|
if st(u) in TRANSITIONAL:
|
|
reasons.append(f"{u} is {st(u)}: wait for it to settle")
|
|
return reasons
|
|
|
|
|
|
def warn_reasons(action: str, params: dict, states: dict,
|
|
lane_of_unit: dict | None = None) -> list[str]:
|
|
"""Truthful warnings for allowed-but-consequential actions."""
|
|
warns = []
|
|
if action == "unit" and params.get("verb") in ("stop", "restart"):
|
|
unit = params.get("unit", "")
|
|
state = states.get(unit, "stopped")
|
|
if unit == "qwen38-flash.service" and state in TRANSITIONAL:
|
|
# Since v1.8 the launcher deletes the table before every boot and each boot
|
|
# writes it whole, so a stop marks nothing dirty; what it costs is this boot.
|
|
warns.append("this boot is thrown away: every flash boot writes its 47.7 GiB PLE "
|
|
"table from scratch, so the next start takes the full 12 to 15 min again")
|
|
elif unit == IMAGE_UNIT and state == "ready":
|
|
# the proxy on :30001 is a text door; nothing reaches this lane through it
|
|
warns.append("an image being generated right now is lost, and the Image "
|
|
"tab has nothing to talk to until this lane is back (about 70 s)")
|
|
elif state == "ready":
|
|
warns.append("clients on :30001 will get errors until an engine "
|
|
"is back")
|
|
return warns
|
|
|
|
|
|
# ── Stage timing: history + ETA (median of real observed durations) ─────────
|
|
def eta_for(history: dict, unit: str, rebuild: bool) -> float | None:
|
|
"""Median full-boot duration for this unit (seconds), rebuild-aware."""
|
|
key = f"{unit}:rebuild" if rebuild else unit
|
|
vals = [v for v in history.get(key, []) if isinstance(v, (int, float))]
|
|
if not vals:
|
|
vals = [v for v in history.get(unit, [])
|
|
if isinstance(v, (int, float))]
|
|
return statistics.median(vals) if vals else None
|
|
|
|
|
|
def record_boot(history: dict, unit: str, seconds: float,
|
|
rebuild: bool, keep: int = 12) -> dict:
|
|
key = f"{unit}:rebuild" if rebuild else unit
|
|
lst = list(history.get(key, []))
|
|
lst.append(round(float(seconds), 1))
|
|
history[key] = lst[-keep:]
|
|
return history
|
|
|
|
|
|
def pool_key(unit: str, target: str | None) -> str:
|
|
"""History key for one unit's KV pool, per served target.
|
|
|
|
The pool is a boot lottery AND it depends on the checkpoint: mixing an NVFP4
|
|
boot with an FP8 one produces a spread that means nothing. Keyed by target,
|
|
each series answers a question you can act on, which is what this repo's two
|
|
disagreeing 1m pool campaigns needed and did not have.
|
|
"""
|
|
return f"{unit}:pool:{target or 'unknown'}"
|
|
|
|
|
|
def record_pool(history: dict, unit: str, target: str | None, pool: int,
|
|
keep: int = 12) -> dict:
|
|
"""Append one boot's KV pool, ignoring the zero an engine reports before ready."""
|
|
if not pool or pool <= 0:
|
|
return history
|
|
key = pool_key(unit, target)
|
|
lst = list(history.get(key, []))
|
|
lst.append(int(pool))
|
|
history[key] = lst[-keep:]
|
|
return history
|
|
|
|
|
|
def pool_shortfall(pinned: int | None, served: int | None) -> str | None:
|
|
"""One sentence when a boot's KV pool came up short of the pin in its launcher.
|
|
|
|
SGLang treats --max-total-tokens as a ceiling: a boot that profiles less (something
|
|
else held memory at that instant) silently serves the smaller pool for its whole
|
|
life. That is the one thing a pin cannot fix on its own, so it is said out loud."""
|
|
# SGLang aligns the pin down to its page (64 tokens, or 128 with the c128 layout):
|
|
# 190,000 serves as 189,952, and that is the pin honoured, not a shortfall.
|
|
if not pinned or not served or served >= pinned - 128:
|
|
return None
|
|
return (f"KV pool {served:,} is short of the {pinned:,} pinned in the launcher: something "
|
|
f"held memory when the engine profiled. A restart on a quiet box restores it.")
|
|
|
|
|
|
def pool_spread(history: dict, unit: str, target: str | None) -> dict | None:
|
|
"""min/max/last/n for a target's recorded pools, or None below two boots."""
|
|
lst = [int(x) for x in history.get(pool_key(unit, target), []) if x]
|
|
if len(lst) < 2:
|
|
return {"n": len(lst), "last": lst[-1]} if lst else None
|
|
lo, hi = min(lst), max(lst)
|
|
return {"n": len(lst), "last": lst[-1], "min": lo, "max": hi,
|
|
"spread_pct": round((hi - lo) * 100.0 / hi, 1)}
|
|
|
|
|
|
# ── Wedge detection: health says yes, generation says no ────────────────────
|
|
def decide_wedge(*, health_ok: bool, canary_fails: int, num_reqs: int,
|
|
progress_age: float | None, threshold: int = 3,
|
|
stall_after: float = 300.0) -> bool:
|
|
"""True when the frontend answers but nothing is being generated.
|
|
|
|
Two routes, never mixed:
|
|
- idle route: no request running, yet threshold consecutive generation
|
|
probes failed (field case 29/08: scheduler spinning, /get_load 0 requests);
|
|
- busy route: requests running but no prefill/decode progress line for
|
|
stall_after seconds. Probes are never sent while requests run (they
|
|
would just queue behind a legitimate long generation), so a slow user
|
|
request can never be mistaken for a wedge.
|
|
"""
|
|
if not health_ok:
|
|
return False
|
|
if num_reqs == 0:
|
|
return canary_fails >= threshold
|
|
return progress_age is not None and progress_age > stall_after
|
|
|
|
|
|
def wedge_plan(*, decided: bool, prev_state: str | None, wedged_since: float | None,
|
|
now: float, grace: float, autoheal: bool, cooldown_ok: bool,
|
|
job_running: bool) -> dict:
|
|
"""What to do this tick about a wedge decision. Pure, so it is testable:
|
|
the 29/08 regression had the forensics and the restart in the wrong branch.
|
|
|
|
Returns {"state": "wedged"|None, "first": bool, "since": float|None, "restart": bool}
|
|
"""
|
|
if not decided:
|
|
return {"state": None, "first": False, "since": None, "restart": False}
|
|
since = wedged_since if wedged_since is not None else now
|
|
first = prev_state != "wedged"
|
|
restart = bool(autoheal and cooldown_ok and (now - since) >= grace and not job_running)
|
|
return {"state": "wedged", "first": first, "since": since, "restart": restart}
|
|
|
|
|
|
def decide_mem_floor(*, avail_gib: float | None, floor_gib: float, num_reqs: int,
|
|
last_abort_ts: float | None, now: float,
|
|
cooldown_s: float = 60.0) -> tuple[bool, str]:
|
|
"""Memory-floor belt: abort every in-flight generation when host MemAvailable
|
|
drops under the floor while requests run (unified memory: a prefill's
|
|
activations can take the box to the livelock edge, measured 29/08 at 0.8 GiB
|
|
after a 177k prompt). Pure decision: (abort?, reason). Never aborts twice
|
|
within the cooldown, never when nothing runs, never on a missing reading."""
|
|
if avail_gib is None:
|
|
return False, "no reading"
|
|
if avail_gib >= floor_gib:
|
|
return False, "above floor"
|
|
if num_reqs <= 0:
|
|
return False, f"below floor ({avail_gib:.1f} GiB) but nothing running"
|
|
if last_abort_ts is not None and now - last_abort_ts < cooldown_s:
|
|
return False, "cooldown"
|
|
return True, f"MemAvailable {avail_gib:.1f} GiB under the {floor_gib:.1f} GiB floor with {num_reqs} running"
|
|
|
|
|
|
# ── keepalive proxy journal -> request feed (pure) ──────────────────────────
|
|
# With the identity wall on, the proxy names a listed client after the peer on every line
|
|
# of its request ("127.0.0.1:5555 key=alice"): the key part is optional, so a request is
|
|
# still matched by its ip:port (found in review, 2026-09-24: every such request stayed
|
|
# "in flight").
|
|
_KEY = r"(?: key=\S+)?"
|
|
FEED_START = re.compile(r"\[proxy\] (\S+)" + _KEY + r" -> (POST|GET) (\S+) body=(\d+)b")
|
|
FEED_END = re.compile(r"\[proxy\] (\S+)" + _KEY + r" (POST|GET) (\S+) (.+?) in ([\d.]+)s")
|
|
FEED_REFUSED = re.compile(r"\[proxy\] (\S+)" + _KEY + r" REFUSED oversize \(\d+b, (.+?), limit (\d+)\)")
|
|
FEED_FIT = re.compile(r"\[proxy\] (\S+)" + _KEY + r" oversize check: (\d+) tokens fit \((\d+) usable")
|
|
|
|
|
|
# How an outcome reads, so the UI never has to match strings itself (it did, and it
|
|
# painted a client that walked away the same red as a lane that failed):
|
|
# ok the answer was delivered
|
|
# gone the CLIENT left; the proxy aborted or drained the generation. Not a fault
|
|
# of this box, and the whole point of v6.14 is that it costs nothing further
|
|
# fail the request did not get an answer: the engine, the guard or the stream
|
|
# live still in flight
|
|
# unknown no end line was ever written (a proxy restart mid-request)
|
|
def outcome_kind(outcome: str) -> str:
|
|
if outcome == "in flight":
|
|
return "live"
|
|
if outcome == "no end logged":
|
|
return "unknown"
|
|
if outcome.startswith("ok"):
|
|
return "ok"
|
|
# "CLIENT GONE on write", "... during non-sse wait", "CLIENT GONE during keepalive",
|
|
# "no outcome (client vanished mid-request)": the client is the one who left.
|
|
if "CLIENT GONE" in outcome or "client vanished" in outcome:
|
|
return "gone"
|
|
return "fail"
|
|
|
|
|
|
def parse_feed(raw: str, last: int = 25) -> list[dict]:
|
|
"""journalctl text of the keepalive proxy -> the last requests: client, path,
|
|
size, outcome, seconds, and the guard's detail when it counted the prompt
|
|
(tokens counted vs the lane's limit) so a 400 explains itself."""
|
|
reqs: dict[str, dict] = {}
|
|
order: list[str] = []
|
|
latest_ts = None
|
|
for ln in raw.splitlines():
|
|
ts = ln[:19]
|
|
if len(ts) == 19 and ts[10] == "T":
|
|
latest_ts = ts
|
|
m = FEED_START.search(ln)
|
|
if m:
|
|
peer = m.group(1)
|
|
reqs[peer] = {"ts": ts, "peer": peer, "path": m.group(3), "bytes": int(m.group(4)),
|
|
"outcome": "in flight", "kind": "live", "secs": None, "detail": None}
|
|
order.append(peer)
|
|
continue
|
|
m = FEED_REFUSED.search(ln)
|
|
if m and m.group(1) in reqs:
|
|
reqs[m.group(1)]["detail"] = f"{m.group(2)}, limit {int(m.group(3)):,}"
|
|
continue
|
|
m = FEED_FIT.search(ln)
|
|
if m and m.group(1) in reqs:
|
|
reqs[m.group(1)]["detail"] = f"{int(m.group(2)):,} tokens counted, fits ({int(m.group(3)):,} usable)"
|
|
continue
|
|
m = FEED_END.search(ln)
|
|
if m and m.group(1) in reqs:
|
|
r = reqs[m.group(1)]
|
|
r["outcome"] = m.group(4)[:40]
|
|
r["kind"] = outcome_kind(r["outcome"])
|
|
r["secs"] = float(m.group(5))
|
|
# A start with no end cannot stay "in flight" forever: the proxy guarantees an
|
|
# end line per request since 30/08, but a proxy restart mid-request (or an older
|
|
# journal) can still orphan one. After 10 minutes of newer traffic it becomes an
|
|
# explicit unknown so the live count stays honest.
|
|
if latest_ts:
|
|
try:
|
|
latest = datetime.fromisoformat(latest_ts)
|
|
except ValueError:
|
|
latest = None
|
|
if latest:
|
|
for r in reqs.values():
|
|
if r["outcome"] != "in flight":
|
|
continue
|
|
try:
|
|
age = (latest - datetime.fromisoformat(r["ts"])).total_seconds()
|
|
except ValueError:
|
|
continue
|
|
if age > 600:
|
|
r["outcome"] = "no end logged"
|
|
r["kind"] = "unknown"
|
|
return [reqs[p] for p in order[-last:]]
|
|
|
|
|
|
# ── zombie guard: what a client that gave up cost the engine (pure) ─────────
|
|
# The engine's own line, one per output batch of a request whose client is gone
|
|
# (tokenizer_manager.py, "Received output for {rid=} but the state was deleted").
|
|
# One request that decodes to max_tokens with nobody listening writes thousands
|
|
# of these: 6,582 on the reference box on 2026-09-09, the worst single request
|
|
# 4,470 lines over 6 min 08 s. The count is the symptom; the rid is the request.
|
|
ZOMBIE_RE = re.compile(
|
|
r"\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] Received output for rid='([^']+)' "
|
|
r"but the state was deleted")
|
|
# The proxy's side of the same event, since v6.14: it either names the request to
|
|
# the engine (abort) or reads the abandoned answer to its end (drain). Both are
|
|
# an absence of zombie; which one happened says whether the engine took the rid.
|
|
# The banner names the address it listens on since the proxy learned PROXY_BIND
|
|
# ("v6.24 on 0.0.0.0:30001"); before that it was "v6.14 on :30001". Matching only the
|
|
# old shape read the last banner of that era instead, v6.20 on the reference box while
|
|
# v6.24 ran, and "no banner" on a box installed since (found in review, 2026-09-24).
|
|
GUARD_VERSION_RE = re.compile(r"\[proxy\] v([\d.]+) on \S*:(\d+)")
|
|
GUARD_BANNER_GREP = r"\[proxy\] v[0-9.]+ on " # the same line, for journalctl -g
|
|
|
|
|
|
def version_before(version, ref):
|
|
"""True when a dotted version is older than ref, False when it is not, None when
|
|
either cannot be read. Compared as numbers part by part: as floats, "6.9" is above
|
|
"6.14", so the page took v6.2 to v6.9 for proxies that abort, which they do not."""
|
|
try:
|
|
return tuple(int(p) for p in version.split(".")) < tuple(int(p) for p in ref.split("."))
|
|
except (AttributeError, ValueError):
|
|
return None
|
|
GUARD_ABORT_RE = re.compile(r"\[proxy\] aborted upstream rid=(\S+) \((.+?)\)")
|
|
GUARD_ABORT_FAIL_RE = re.compile(r"\[proxy\] abort_request failed for rid=(\S+)")
|
|
GUARD_DRAIN_RE = re.compile(r"\[proxy\] drained an abandoned (\S+) for ([\d.]+)s")
|
|
GUARD_CEILING_RE = re.compile(r"\[proxy\] drain ceiling reached after ([\d.]+)s")
|
|
|
|
|
|
def parse_zombies(raw: str) -> dict:
|
|
"""Engine log window -> what abandoned generations cost in it.
|
|
|
|
Pure counting, no judgement: the caller knows the window. `lines` is the
|
|
flood volume, `requests` the distinct rids behind it, worst first, each with
|
|
the seconds between its first and last line (that span IS the dead decode)."""
|
|
per: dict[str, dict] = {}
|
|
for m in ZOMBIE_RE.finditer(raw):
|
|
ts, rid = m.group(1), m.group(2)
|
|
r = per.setdefault(rid, {"rid": rid, "lines": 0, "first": ts, "last": ts})
|
|
r["lines"] += 1
|
|
r["last"] = ts
|
|
for r in per.values():
|
|
try:
|
|
r["secs"] = round((datetime.strptime(r["last"], "%Y-%m-%d %H:%M:%S")
|
|
- datetime.strptime(r["first"], "%Y-%m-%d %H:%M:%S")
|
|
).total_seconds(), 1)
|
|
except ValueError:
|
|
r["secs"] = None
|
|
reqs = sorted(per.values(), key=lambda r: -r["lines"])
|
|
return {"lines": sum(r["lines"] for r in reqs), "requests": reqs[:5],
|
|
"distinct": len(reqs)}
|
|
|
|
|
|
def parse_guard(raw: str) -> dict:
|
|
"""Keepalive journal window -> what the proxy did about clients that left.
|
|
|
|
`version` is the running proxy's own banner, which is the only honest source
|
|
for whether the fix is deployed: the file in the repo says nothing about the
|
|
process systemd started."""
|
|
out = {"version": None, "port": None, "aborted": 0, "abort_failed": 0,
|
|
"drained": 0, "drain_max_s": None, "ceiling": 0, "reasons": {}}
|
|
for ln in raw.splitlines():
|
|
m = GUARD_VERSION_RE.search(ln)
|
|
if m:
|
|
out["version"], out["port"] = m.group(1), int(m.group(2))
|
|
continue
|
|
m = GUARD_ABORT_RE.search(ln)
|
|
if m:
|
|
out["aborted"] += 1
|
|
why = m.group(2)[:40]
|
|
out["reasons"][why] = out["reasons"].get(why, 0) + 1
|
|
continue
|
|
if GUARD_ABORT_FAIL_RE.search(ln):
|
|
out["abort_failed"] += 1
|
|
continue
|
|
m = GUARD_DRAIN_RE.search(ln)
|
|
if m:
|
|
out["drained"] += 1
|
|
secs = float(m.group(2))
|
|
if out["drain_max_s"] is None or secs > out["drain_max_s"]:
|
|
out["drain_max_s"] = secs
|
|
continue
|
|
if GUARD_CEILING_RE.search(ln):
|
|
out["ceiling"] += 1
|
|
return out
|
|
|
|
|
|
def guard_verdict(zombies: dict, guard: dict, override_env: bool | None) -> tuple:
|
|
"""(state, sentence) for the cockpit chip. Reads the two sides together: the
|
|
engine's flood is the only proof of a real leak, the proxy's counters say
|
|
whether anything is holding the line, and the engine env says whether an
|
|
abort can even be addressed (SGLANG_ENABLE_REQUEST_HEADER_OVERRIDES: without
|
|
it the proxy cannot name a request that has not spoken yet, so it drains)."""
|
|
handled = guard["aborted"] + guard["drained"]
|
|
if zombies["lines"] >= 100:
|
|
w = zombies["requests"][0] if zombies["requests"] else None
|
|
detail = f", worst {w['lines']:,} lines over {w['secs']:.0f}s" if w and w["secs"] else ""
|
|
return "err", f"{zombies['lines']:,} flood lines from {zombies['distinct']} abandoned request(s){detail}"
|
|
if zombies["lines"]:
|
|
return "warn", f"{zombies['lines']} flood line(s) from {zombies['distinct']} abandoned request(s)"
|
|
if guard["ceiling"]:
|
|
return "warn", f"{guard['ceiling']} drain(s) hit the ceiling and were dropped"
|
|
if guard["abort_failed"]:
|
|
return "warn", f"{guard['abort_failed']} abort(s) the engine did not answer"
|
|
if handled:
|
|
bits = []
|
|
if guard["aborted"]:
|
|
bits.append(f"{guard['aborted']} aborted")
|
|
if guard["drained"]:
|
|
bits.append(f"{guard['drained']} drained")
|
|
return "ok", f"{' and '.join(bits)}, no flood"
|
|
if override_env is False:
|
|
return "", "quiet; the engine does not take the proxy's rid, so a request lost in prefill is drained"
|
|
return "ok", "no abandoned request in this window"
|
|
|
|
|
|
# opencode default model vs the lane actually serving (the cockpit panel's verdict).
|
|
LANE_PROVIDER = {"qwen38-sglang.service": "qwen38", "qwen38-flash.service": "flashnext"}
|
|
|
|
|
|
def opencode_default_follows(default_model, states: dict) -> tuple:
|
|
"""(True/False/None, reason). None when no engine is serving."""
|
|
served = [u for u, st in states.items() if u in LANE_PROVIDER and st not in ("stopped", "failed")]
|
|
if not served:
|
|
return None, "no engine serving right now"
|
|
want = LANE_PROVIDER[served[0]]
|
|
if not default_model:
|
|
return False, f"no default model set (expected {want}/...)"
|
|
if default_model.split("/")[0] == want:
|
|
return True, "follows the served lane"
|
|
return False, f"served lane wants {want}/..., default is {default_model}"
|