mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 12:54:19 +01:00
The video lane runs the v0.5.21 release's commit and wheel, as the image lane since v1.24: a 4 s 480P video at 8 and at 50 steps came out identical to the byte on both runtimes, 2.5 % faster at 50 steps. The installer notes the wheel and the source commit beside the runtime, asks the registry instead of its source text, and counts the runtime's two caches of its own (host_spill, 11.2 GiB; decode_dtype_store, 4.5 GiB) in its room check; uninstall.sh lists them. The Video view gains a Turbo switch: larryvrh's MiniMax-H3 Turbo LoRA, the cookbook's speed/quality recipe, fetched as one file at its pin and put on for one call in SGLang's dynamic mode, then taken off: 4 s at 480P in 127 s against 623 s for the base, the base's next video unchanged byte for byte. Nine steps on this pin (sgl-project/sglang#38671 counts evaluations on main), 480P and 4 s only (the adapter's memory). Never on a lane that runs another commit, or started before its runtime changed, or whose start systemd does not say (ddebc52 loads the whole DiT to put an adapter on); a base call waits while the lane cannot say an adapter this cockpit put on is off. The merged variant and LightX2V's adapter were studied and are documented. Memory figures taken from SGLang now say GiB: its "MB" and its loader's "GB" count powers of 1024. The image and video views' steps sliders put their thumb on the Turbo's steps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
856 lines
43 KiB
Python
856 lines
43 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: restarting (a crash loop between two attempts); held and refused (engine-preflight.sh
|
|
waits for, or would not start on, GPU memory the last engine has not given back); zombie (a
|
|
server process alive with no scheduler, which nothing restarts). The cockpit adds overdue (a
|
|
stage that took more than twice the 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!")),
|
|
]
|
|
|
|
# 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"),
|
|
]
|
|
|
|
# ── The video lane speaks the same dialect ────────────────────────────────────
|
|
# MiniMax-H3 is served by the same SGLang Diffusion server from the same source
|
|
# tree, so its boot prints the shared server lines. The component lines below are the
|
|
# ones this pipeline printed on the reference box on 2026-09-25 (boot 23:08:50, DiT
|
|
# 61.73 GiB in 13 shards, text encoder 48.09 GiB, audio VAE 0.56 GiB, video VAE 5.2 GiB, as
|
|
# SGLang logs them, its "GB" being 1024**3 bytes):
|
|
# a marker for a line never seen is a guess dressed as knowledge, so anything else
|
|
# still falls on the generic "Loading " arm and reads as weights without naming it.
|
|
VIDEO_STAGES = ("init", "loading-weights", "warming-up")
|
|
VIDEO_MARKERS = [
|
|
# (substring, stage it opens, what is being loaded while that line is the latest)
|
|
("Starting server...", "init", "starting the server"),
|
|
("Loading ", "loading-weights", "loading a pipeline component"),
|
|
("Loading pipeline modules...", "loading-weights", "reading the checkpoint layout"),
|
|
("Loading text_encoder from", "loading-weights", "the 48 GiB text encoder"),
|
|
("Loading MiniMaxH3DiTModel from", "loading-weights", "the 61.7 GiB DiT"),
|
|
("Loading audio_vae from", "loading-weights", "the audio VAE"),
|
|
("Loading video_vae from", "loading-weights", "the 5.2 GiB video VAE"),
|
|
("Pipeline instantiated", "loading-weights", "building the pipeline"),
|
|
("Starting FastAPI server", "warming-up", "three warmup requests"),
|
|
("fired up and ready to roll", "warming-up", "ready"),
|
|
]
|
|
|
|
|
|
def _parse_diffusion_boot_log(lines: list[str], markers: list, stages: tuple) -> dict:
|
|
"""A diffusion 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 markers:
|
|
if needle in ln:
|
|
stage, detail = st, what
|
|
if needle == "fired up and ready to roll":
|
|
fired = True
|
|
done = list(stages[:stages.index(stage)]) if stage in stages else []
|
|
if fired:
|
|
done = list(stages)
|
|
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
|
|
|
|
|
|
# ── The video lane's request in flight, from its own journal ──────────────────
|
|
# The lane's API says "queued", progress 0, from the POST until the video is done: its
|
|
# job store sets "completed" and 100 at the end and nothing in between (measured
|
|
# 2026-09-29, and read in its video_api.py). Its journal, though, logs each pipeline
|
|
# stage and one tqdm line per denoise step, each its own entry (one every 11 to 55 s).
|
|
# So the phase and the step come from there, in the engine's own words and numbers.
|
|
_ANSI = re.compile(r"\x1b\[[0-?;]*[@-~]")
|
|
_VIDEO_STAGE = re.compile(r"\[(MiniMaxH3\w+Stage)\] (started|finished)")
|
|
_VIDEO_STEP = re.compile(r"denoise:\s+\d+%\|[^|]*\|\s*(\d+)/(\d+)\s+\[([\d:]+)<([^,\]]+),\s*([^\]]+)\]")
|
|
VIDEO_PHASES = ("encode", "denoise", "decode")
|
|
VIDEO_PHASE_LABEL = {"encode": "encoding the prompt", "denoise": "denoising",
|
|
"decode": "decoding video and audio"}
|
|
_VIDEO_STAGE_PHASE = {"MiniMaxH3DenoisingStage": "denoise", "MiniMaxH3DecodingStage": "decode"}
|
|
# a line that ends a request, whatever its outcome
|
|
_VIDEO_RUN_END = ("Pixel data generated", "Error executing request", "Failed to generate")
|
|
|
|
|
|
def _clock_s(txt: str) -> float | None:
|
|
"""tqdm's [MM:SS] or [H:MM:SS] as seconds; None for its '?'."""
|
|
parts = txt.strip().split(":")
|
|
if not all(p.isdigit() for p in parts):
|
|
return None
|
|
s = 0.0
|
|
for p in parts:
|
|
s = s * 60 + int(p)
|
|
return s
|
|
|
|
|
|
def _rate_s_per_step(txt: str) -> float | None:
|
|
"""tqdm's rate as seconds per step: '14.78s/it' or '1.52it/s'; None for '?it/s'."""
|
|
t = txt.strip()
|
|
try:
|
|
if t.endswith("s/it"):
|
|
return float(t[:-4])
|
|
if t.endswith("it/s"):
|
|
v = float(t[:-4])
|
|
return 1.0 / v if v > 0 else None
|
|
except ValueError:
|
|
return None
|
|
return None
|
|
|
|
|
|
def parse_video_run(messages: list[str]) -> dict:
|
|
"""The request the video lane is working on, from its journal messages in time
|
|
order. {} when nothing runs. Otherwise the phase (encode, denoise, decode), its
|
|
label, and while denoising the step, the step count, tqdm's seconds per step and
|
|
its estimate of the time left.
|
|
|
|
A request starts at "Running pipeline stages" and ends at the line that reports its
|
|
outcome. A step line with no start before it still counts: the start can fall out of
|
|
the window read, and a step is proof enough that a request runs."""
|
|
run: dict | None = None
|
|
for raw in messages:
|
|
for part in _ANSI.sub("", raw).replace("\r", "\n").split("\n"):
|
|
if "Running pipeline stages" in part:
|
|
run = {"phase": "encode", "step": None, "steps": None,
|
|
"s_per_step": None, "elapsed_s": None, "left_s": None}
|
|
continue
|
|
if any(k in part for k in _VIDEO_RUN_END):
|
|
run = None
|
|
continue
|
|
m = _VIDEO_STAGE.search(part)
|
|
if m and m.group(2) == "started" and m.group(1) in _VIDEO_STAGE_PHASE:
|
|
run = run or {"phase": "encode", "step": None, "steps": None,
|
|
"s_per_step": None, "elapsed_s": None, "left_s": None}
|
|
run["phase"] = _VIDEO_STAGE_PHASE[m.group(1)]
|
|
continue
|
|
m = _VIDEO_STEP.search(part)
|
|
if m:
|
|
run = run or {"phase": "denoise", "step": None, "steps": None,
|
|
"s_per_step": None, "elapsed_s": None, "left_s": None}
|
|
# the 100% line closes the denoise; decode follows at once, and saying
|
|
# "denoising 49/49" for the whole decode would read as stuck
|
|
run["phase"] = run["phase"] if run["phase"] == "decode" else "denoise"
|
|
run["step"], run["steps"] = int(m.group(1)), int(m.group(2))
|
|
run["elapsed_s"] = _clock_s(m.group(3))
|
|
run["left_s"] = _clock_s(m.group(4))
|
|
run["s_per_step"] = _rate_s_per_step(m.group(5))
|
|
if not run:
|
|
return {}
|
|
run["label"] = VIDEO_PHASE_LABEL[run["phase"]]
|
|
return run
|
|
|
|
|
|
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."""
|
|
return _parse_diffusion_boot_log(lines, IMAGE_MARKERS, IMAGE_STAGES)
|
|
|
|
|
|
def parse_video_boot_log(lines: list[str]) -> dict:
|
|
"""The video lane's journal, reduced to the same shape parse_boot_log returns.
|
|
|
|
Same latest-boot rule as the image lane. Only the shared server lines are
|
|
matched; the pipeline's own component lines fall on the generic "Loading "
|
|
arm and read as weights without naming what they load."""
|
|
return _parse_diffusion_boot_log(lines, VIDEO_MARKERS, VIDEO_STAGES)
|
|
|
|
|
|
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 derive_state(*, unit_active: str, unit_sub: str, container_running: bool,
|
|
healthy: bool, boot: dict) -> dict:
|
|
"""The single source of truth the UI renders. Pure function of facts.
|
|
|
|
There was a "rebuild" flag here, raised by a launcher line announcing a PLE table
|
|
rebuild: since v1.8 the launcher deletes the table before every boot and each boot
|
|
writes it whole, so no line announces it, the flag never rose, and the boot history
|
|
kept a "rebuild" series nothing wrote (found in review, 2026-09-24)."""
|
|
flags: dict = {}
|
|
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 GiB of unified memory is the
|
|
# livelock this whole module exists to prevent. The video lane is one of them too:
|
|
# about 116 GiB of weights by measured components (48.09 + 61.73 + 0.56 + 5.2,
|
|
# docs/video-lane.md), for the same reason.
|
|
ENGINE_UNITS = ("qwen38-sglang.service", "qwen38-flash.service",
|
|
"qwen38-image.service", "qwen38-video.service")
|
|
IMAGE_UNIT = "qwen38-image.service"
|
|
VIDEO_UNIT = "qwen38-video.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 a diffusion 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 not in (IMAGE_UNIT, VIDEO_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 unit == VIDEO_UNIT and state == "ready":
|
|
# same text-door reason as the image lane; a video boot is the long one
|
|
warns.append("a video being generated right now is lost, and the Video "
|
|
"tab has nothing to talk to until this lane is back (about 12 min)")
|
|
elif state == "ready" and params.get("verb") == "restart":
|
|
# the proxy holds what reaches it while a lane's unit is on its way back (v6.28)
|
|
warns.append("requests on :30001 wait for it while it boots (a streamed one hears "
|
|
"keepalives) and go to it once it answers")
|
|
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) -> float | None:
|
|
"""Median full-boot duration for this unit (seconds)."""
|
|
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, keep: int = 12) -> dict:
|
|
lst = list(history.get(unit, []))
|
|
lst.append(round(float(seconds), 1))
|
|
history[unit] = 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}
|
|
|
|
|
|
# ── the start guard and the zombie (pure) ───────────────────────────────────
|
|
# Every engine unit runs engine-preflight.sh before its engine (issue #26). Its lines are in
|
|
# the unit's journal, never in a container's log, and while it waits there is no container:
|
|
# without them the lane read "starting" while it was held, and "keeps crashing" when it was
|
|
# refused, which sends the operator after the wrong thing.
|
|
PREFLIGHT_RE = re.compile(r"preflight: (?:NOT starting (\S+): (.+?), still after \d+ s\."
|
|
r"|(\S+) (waits|starts): (.+))")
|
|
|
|
|
|
def parse_preflight(lines: list[str]) -> dict | None:
|
|
"""The guard's last word among these journal lines: {"verdict": "waits" | "refused" |
|
|
"starts", "reason": str}, or None when it said nothing."""
|
|
last = None
|
|
for ln in lines:
|
|
m = PREFLIGHT_RE.search(ln)
|
|
if m is None:
|
|
continue
|
|
if m.group(1) is not None:
|
|
last = {"verdict": "refused", "reason": m.group(2)}
|
|
else:
|
|
last = {"verdict": m.group(4), "reason": m.group(5)}
|
|
return last
|
|
|
|
|
|
def preflight_flags(state: dict, *, unit_sub: str, preflight: dict | None) -> dict:
|
|
"""The state with what the guard said, when it is why the lane is not up: held while it
|
|
waits (the unit runs its start step and nothing else), refused once it would not start
|
|
(the unit failed, or waits for its next attempt)."""
|
|
if not preflight:
|
|
return state
|
|
out = dict(state)
|
|
if preflight["verdict"] == "waits" and unit_sub == "start-pre" and state.get("state") == "starting":
|
|
out["held"] = preflight["reason"]
|
|
elif preflight["verdict"] == "refused" and state.get("state") == "failed":
|
|
out["refused"] = preflight["reason"]
|
|
return out
|
|
|
|
|
|
def zombie_plan(*, state: str, scheduler_alive: bool | None, since: float | None, now: float,
|
|
after_s: float, enabled: bool, cooldown_ok: bool, job_running: bool) -> dict:
|
|
"""What to do this tick about an engine whose server lives on without its scheduler.
|
|
SGLang v0.5.19 ends up so after a SIGQUIT that reaches its server while the scheduler
|
|
still runs (the exit is raised inside an asyncio task and swallowed; reproduced on the
|
|
reference box, 2026-10-01): no HTTP, no scheduler, a unit systemd calls active, and
|
|
nothing restarts it. Only an engine that served and stopped answering qualifies, and only
|
|
a read that found no scheduler (None, an unreadable process list, never does). Since the
|
|
start guard, a restart cannot land on memory still held, so it is safe to make.
|
|
|
|
Returns {"zombie": bool, "since": float | None, "restart": bool, "in": float}"""
|
|
if state != "degraded" or scheduler_alive is not False:
|
|
return {"zombie": False, "since": None, "restart": False, "in": 0.0}
|
|
since = since if since is not None else now
|
|
left = max(0.0, after_s - (now - since))
|
|
restart = bool(enabled and left == 0.0 and cooldown_ok and not job_running)
|
|
return {"zombie": True, "since": since, "restart": restart, "in": left}
|
|
|
|
|
|
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")
|
|
# The proxy writes one end line per request (since 30/08), so a start loses its end only
|
|
# when the process that took it is gone, and that is logged as well: systemd says it has
|
|
# stopped or lost the process ("Stopped" names the unit only since systemd 252, its
|
|
# description before), and the next proxy introduces itself with its banner.
|
|
FEED_PROXY_GONE = re.compile(r"\]: \[proxy\] v[\d.]+ on |systemd\[\d+\]: (?:Stopped |\S+: (?:Deactivated "
|
|
r"successfully|Main process exited|Failed with result))")
|
|
|
|
|
|
# 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)
|
|
# probe the cockpit's own route probe, refused at the schema as it is meant to be
|
|
# (mark_probes): no client asked anything
|
|
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 mark_probes(rows: list[dict], path: str, size: int) -> list[dict]:
|
|
"""The cockpit's own probe of a route, in the request log: a request from this box to
|
|
`path` carrying the probe's exact body, refused with a 422 at the schema as designed
|
|
(it has no state, so no model runs). It read as a failed client request, in red, once
|
|
a minute while the Decide view was open (2026-09-30). Rows are marked in place."""
|
|
for r in rows:
|
|
if (r.get("path") == path and r.get("bytes") == size
|
|
and str(r.get("peer", "")).startswith("127.0.0.1:")
|
|
and str(r.get("outcome", "")).startswith("422")):
|
|
r["kind"] = "probe"
|
|
r["outcome"] = "422 as designed: the cockpit's probe"
|
|
return rows
|
|
|
|
|
|
def _feed_open(records: list[dict], method: str | None = None,
|
|
path: str | None = None) -> dict | None:
|
|
"""Newest still-open record for one peer, preferring the same route.
|
|
|
|
Two requests can share a peer: a reused keep-alive connection serves them
|
|
one after the other, and multiplexing serves them side by side. The old
|
|
single record per peer let the second start overwrite the first, then let
|
|
the first end mark the second as done (found live, 2026-09-29: the feed
|
|
showed 6 in flight for 7 requests on the engine)."""
|
|
open_recs = [r for r in records if r["outcome"] == "in flight"]
|
|
if method is not None or path is not None:
|
|
same = [r for r in open_recs
|
|
if (method is None or r.get("method") == method)
|
|
and (path is None or r.get("path") == path)]
|
|
if same:
|
|
return same[-1]
|
|
return open_recs[-1] if open_recs else None
|
|
|
|
|
|
def parse_feed(raw: str, last: int = 25, carry: list[dict] | None = None) -> 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.
|
|
|
|
The last `last` requests, and every older one still in flight with them. `carry` is
|
|
what the previous read left in flight: a request whose start is older than this
|
|
read's first line can still end in it. Both exist for the rail's badge and the table,
|
|
which count the rows in flight: with eight agents, a generation that outlasted the
|
|
25 newest requests (34 minutes, 2026-10-02) dropped out of both while the engine
|
|
still ran it, and the badge fell from 8 to 2."""
|
|
reqs: dict[str, list[dict]] = {}
|
|
order: list[tuple[str, int]] = []
|
|
lines = raw.splitlines()
|
|
first_ts = next((ln[:19] for ln in lines if ln[:4].isdigit()), None)
|
|
for rec in carry or ():
|
|
# a start still inside this read is read again from its own line
|
|
if rec.get("outcome") == "in flight" and (first_ts is None or str(rec.get("ts", ""))[:19] < first_ts):
|
|
reqs.setdefault(rec["peer"], []).append(dict(rec))
|
|
order.append((rec["peer"], len(reqs[rec["peer"]]) - 1))
|
|
for ln in lines:
|
|
ts = ln[:19]
|
|
# A start with no end stays "in flight" for as long as the proxy that took it runs:
|
|
# a generation has no deadline, and one queued behind seven others answered after 22
|
|
# minutes. The clock this replaced (10 minutes of newer traffic) called five live
|
|
# requests "no end logged" while the engine ran three and queued two (01/10).
|
|
if FEED_PROXY_GONE.search(ln):
|
|
for records in reqs.values():
|
|
for r in records:
|
|
if r["outcome"] == "in flight":
|
|
r["outcome"], r["kind"] = "no end logged", "unknown"
|
|
r["detail"] = "; ".join(filter(None, (r["detail"], "the proxy that took it stopped")))
|
|
continue
|
|
m = FEED_START.search(ln)
|
|
if m:
|
|
peer = m.group(1)
|
|
rec = {"ts": ts, "peer": peer, "method": m.group(2), "path": m.group(3),
|
|
"bytes": int(m.group(4)),
|
|
"outcome": "in flight", "kind": "live", "secs": None, "detail": None}
|
|
reqs.setdefault(peer, []).append(rec)
|
|
order.append((peer, len(reqs[peer]) - 1))
|
|
continue
|
|
m = FEED_REFUSED.search(ln)
|
|
if m and m.group(1) in reqs:
|
|
r = _feed_open(reqs[m.group(1)]) or reqs[m.group(1)][-1]
|
|
r["detail"] = f"{m.group(2)}, limit {int(m.group(3)):,}"
|
|
continue
|
|
m = FEED_FIT.search(ln)
|
|
if m and m.group(1) in reqs:
|
|
r = _feed_open(reqs[m.group(1)]) or reqs[m.group(1)][-1]
|
|
r["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 = _feed_open(reqs[m.group(1)], m.group(2), m.group(3))
|
|
if r is None:
|
|
continue
|
|
r["outcome"] = m.group(4)[:40]
|
|
r["kind"] = outcome_kind(r["outcome"])
|
|
r["secs"] = float(m.group(5))
|
|
older_live = [(p, i) for p, i in (order[:-last] if last > 0 else []) if reqs[p][i]["outcome"] == "in flight"]
|
|
return [reqs[p][i] for p, i in older_live + 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}"
|