Files
alzeo/dashboard/lifecycle.py
T
Hasan BasbunarandClaude Opus 5.5 ac4212d78a embeddings lanes: what the review of their memory guard found
MemAvailable is of one instant, and three lanes take more under their longest prompts than at rest: beside the flash lane at
rest both lanes started, with 1 GiB left under its prompts. The Clipstral lane does not start beside the flash lane, Super VL
or Kolibri-1 FP8, nor while the box boots one of the last two, whose Load stops it first; pplx-embed's Load says what the
flash lane leaves. A start of systemd's own, after a death, asks for what the lane holds and the 3 GiB floor alone. A refusal
has a flag and a word of its own (its card read "a file is missing"), its reason is in the past and waits a second to reach the
journal as its unit's, a restart it would not come back from is said, the reading is cut and not rounded, and the pages say
what was measured: an SGLang lane's pool, the cap with the model's file read from the disk.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 22:00:20 +01:00

1744 lines
100 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); cannot (the
flash launcher's GPU is outside its ATS addressing mode, issue #54); zombie (a server process
alive with no scheduler, which nothing restarts). A start under way is watched as well: normal, longer
than usual, or barely moving (boot_usual, boot_watch).
"""
from __future__ import annotations
import math
import re
from datetime import datetime
import statistics
# ── Boot-log stage markers (real lines, see tests/test_lifecycle.py) ─────────
# SGLang's prefix is its time, then on some images the process that wrote the line: "[2026-11-29 02:34:51 PID135] "
# on the Inkling 2 Mini lane's, whose boots read "starting" to the end for want of it (found on the two that never got
# past their weights, 2026-11-29). Its arguments are a dict on every image served today and were a ServerArgs( before,
# and a model with a sliding window names its pools ("Full KV Cache is allocated.", "SWA KV Cache is allocated.").
_TS = r"^\[(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})(?: [A-Z][A-Z0-9 ]*)?\] "
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"(?:\w+ )?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"),
]
# ── The MiniMax-H3-Image lane speaks it too ────────────────────────────────────
# The same server again, at another commit (SGLang main): the component lines below are the
# ones it printed in the study that measured it on the reference box (2026-11-11, boot 03:55:13
# to 04:02:25 local, 451 s from the external SSD): the text encoder 48.09 GB, the DiT 38.6 GB,
# the VAE 1.42 GB, as SGLang logs them (its "GB" being 1024**3 bytes). Its VAE is loaded as the
# shared H3 stages' video_vae. Then one throwaway 512 x 512 image, made on a 2048 x 2048 canvas.
# the stages of an image lane's start are the same for both image lanes: one tuple, IMAGE_STAGES (review of v1.50)
IMAGE_H3_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 38.6 GiB DiT"),
("Loading video_vae from", "loading-weights", "the 1.4 GiB 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 Kolibri lane speaks vLLM ────────────────────────────────────────────────
# vLLM 0.29.0 serving Kolibri-1 on the reference box, one boot from the container's start to
# its API (2026-10-14, the official FP8 from the USB SSD; the NVFP4 the same lines, 30 % sooner):
# 0 s Initializing a V1 LLM engine 10 s Loading safetensors checkpoint shards (32 of them,
# a progress line per shard, about 14 s each) 440 s Loading weights took 470 s
# torch.compile took (0.7 s once its cache is warm) 485 s GPU KV cache size: N tokens
# 500 s init engine (profile, create kv cache, warmup model) took 520 s Application startup complete
# Its tqdm lines carry the shard count, so the weights stage says how far it is.
KOLIBRI_STAGES = ("init", "loading-weights", "allocating-kv", "capturing-graphs", "warming-up")
KOLIBRI_MARKERS = [
# (substring, stage it opens, what is being done while that line is the latest)
("Initializing a V1 LLM engine", "init", "starting vLLM"),
("Loading safetensors checkpoint shards", "loading-weights", "the checkpoint, shard by shard"),
("Loading weights took", "allocating-kv", "compiling the model and measuring its memory"),
("GPU KV cache size:", "capturing-graphs", "capturing the CUDA graphs"),
("init engine (profile, create kv cache, warmup model) took", "warming-up", "starting the API"),
("Application startup complete", "warming-up", "ready"),
]
_KOLIBRI_SHARDS = re.compile(r"Loading safetensors checkpoint shards:\s+(\d+)% Completed \| (\d+)/(\d+)")
def parse_kolibri_boot_log(lines: list[str]) -> dict:
"""The Kolibri lane's container log, reduced to the shape parse_boot_log returns, the
shard being read in `detail`. Only the latest boot counts (the last engine start)."""
start = 0
for i, ln in enumerate(lines):
if "Initializing a V1 LLM engine" in ln:
start = i
stage, detail, fired = None, "", False
for ln in lines[start:]:
for needle, st, what in KOLIBRI_MARKERS:
if needle in ln:
stage, detail = st, what
if needle == "Application startup complete":
fired = True
m = _KOLIBRI_SHARDS.search(ln) # a shard line is a weights line: the marker above set it
if m:
detail = f"shard {m.group(2)} of {m.group(3)} ({m.group(1)} %)"
done = list(KOLIBRI_STAGES[:KOLIBRI_STAGES.index(stage)]) if stage in KOLIBRI_STAGES else []
if fired:
done = list(KOLIBRI_STAGES)
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
# ── The Nemotron lanes speak vLLM too ───────────────────────────────────────────
# Bolt's boot on the vLLM nightly writes Kolibri's lines (the reference box, 2026-10-15), with a
# drafter's after the model's: its 90 checkpoint shards and "Loading weights took", the drafter's
# one shard and its own "Loading weights took", then "Model loading took" for the two. Read with
# Kolibri's markers, the drafter's shard put the boot back from allocating-kv to loading-weights,
# "shard 1 of 1" after the 90 (found in review, 2026-10-16): here the weights stage lasts until
# "Model loading took", and the drafter's load is named as its.
NEMOTRON_STAGES = KOLIBRI_STAGES
NEMOTRON_MARKERS = [
("Initializing a V1 LLM engine", "init", "starting vLLM"),
("Loading safetensors checkpoint shards", "loading-weights", "the checkpoint, shard by shard"),
("Loading weights took", "loading-weights", "preparing the weights, then the drafter"),
("Model loading took", "allocating-kv", "compiling the model and measuring its memory"),
("GPU KV cache size:", "capturing-graphs", "capturing the CUDA graphs"),
("init engine (profile, create kv cache, warmup model) took", "warming-up", "starting the API"),
("Application startup complete", "warming-up", "ready"),
]
# The Liquid AI LFM3 lane's container log: vLLM's own nightly, no drafter, and an extensible KV cache sized after the
# warmup, so its size comes after the CUDA graphs (the reference box's first boot, 2026-11-16: the model in 1 s, its
# compile and FlashInfer's NVFP4 tuning, the graphs, then "GPU KV cache size:"). Read with the Nemotron markers, the
# weights' end said "then the drafter" of a lane that has none, and the cache's line came after the graphs' capture.
LFM3_MARKERS = [
("Initializing a V1 LLM engine", "init", "starting vLLM"),
("Loading safetensors checkpoint shards", "loading-weights", "the checkpoint"),
("Model loading took", "allocating-kv", "compiling the model and tuning its NVFP4 kernels"),
("Capturing CUDA graphs", "capturing-graphs", "capturing the CUDA graphs"),
("GPU KV cache size:", "warming-up", "sizing the KV cache to its share"),
("init engine (profile, create kv cache, warmup model) took", "warming-up", "starting the API"),
("Application startup complete", "warming-up", "ready"),
]
def parse_nemotron_boot_log(lines: list[str], markers=None) -> dict:
"""The Nemotron lane's container log, in the shape parse_kolibri_boot_log returns, the shard
being read in `detail` (the drafter's named so). Only the latest boot counts. markers: another
vLLM lane's (LFM3_MARKERS), read the same way."""
start = 0
for i, ln in enumerate(lines):
if "Initializing a V1 LLM engine" in ln:
start = i
stage, detail, fired, drafter = None, "", False, False
for ln in lines[start:]:
for needle, st, what in (markers or NEMOTRON_MARKERS):
if needle in ln:
if needle == "Loading safetensors checkpoint shards" and drafter:
what = "the drafter"
stage, detail = st, what
if needle == "Loading weights took": # the model's: what loads next is the drafter
drafter = True
if needle == "Application startup complete":
fired = True
m = _KOLIBRI_SHARDS.search(ln) # a shard line is a weights line: the marker above set it
if m:
detail = f"{'the drafter, ' if drafter else ''}shard {m.group(2)} of {m.group(3)} ({m.group(1)} %)"
done = list(NEMOTRON_STAGES[:NEMOTRON_STAGES.index(stage)]) if stage in NEMOTRON_STAGES else []
if fired:
done = list(NEMOTRON_STAGES)
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
# ── The Flash FP4-Local lane: vLLM with b12x's own loader ───────────────────────────────────────
# NVIDIA's FP4-Local checkpoint is read by b12x's loader, which writes lines of its own instead of
# vLLM's: "b12x routing checkpoint shards: 10/21 shards routed, 48.58 GB selected on rank 0", the
# model's 21 shards and then the MTP head's 3, each ended by vLLM's "Loading weights took". After
# "Model loading took", b12x tunes its kernels for this GPU, at the first boot only ("b12x
# compiling ...", "autotuning ...", thousands of candidates measured: 12 min on the reference box,
# 2026-10-19), and loads its choices at the boots after ("b12x priming ...", nothing measured, a
# few seconds); a second round, for the GDN prefill, comes after "GPU KV cache size:". Read with
# the Nemotron markers, the whole load read as "starting vLLM" and the tuning as a silent compile.
FLASH_LOCAL_STAGES = KOLIBRI_STAGES
FLASH_LOCAL_MARKERS = [
("Initializing a V1 LLM engine", "init", "starting vLLM"),
("b12x routing checkpoint shards", "loading-weights", "the checkpoint, shard by shard"),
("Model loading took", "allocating-kv", "preparing b12x's kernels for this GPU"),
("GPU KV cache size:", "capturing-graphs", "capturing the CUDA graphs"),
("init engine (profile, create kv cache, warmup model) took", "warming-up", "starting the API"),
("Application startup complete", "warming-up", "ready"),
]
_B12X_SHARDS = re.compile(r"b12x routing checkpoint shards: (\d+)/(\d+) shards routed, ([\d.]+) GB selected")
_B12X_KERNELS = re.compile(r"b12x (planning|compiling|autotuning|priming|ready) ([\w.]+): (\d+)/(\d+) ready.*?(\d+) measured")
def parse_flash_local_boot_log(lines: list[str]) -> dict:
"""The Flash FP4-Local lane's container log, in the shape parse_kolibri_boot_log returns: the
shard being read, the MTP head's after the model's, and b12x's tuning in `detail`, the first
boot's named as such. Only the latest boot counts."""
start = 0
for i, ln in enumerate(lines):
if "Initializing a V1 LLM engine" in ln:
start = i
stage, detail, fired, head, tuned = None, "", False, False, False
for ln in lines[start:]:
for needle, st, what in FLASH_LOCAL_MARKERS:
if needle in ln:
stage, detail = st, what
if needle == "Application startup complete":
fired = True
if "Loading weights took" in ln: # the model's: the MTP head's shards come next
head = True
m = _B12X_SHARDS.search(ln)
if m:
stage = "loading-weights"
detail = f"{'the MTP head, ' if head else ''}shard {m.group(1)} of {m.group(2)} ({m.group(3)} GB)"
k = _B12X_KERNELS.search(ln)
if k and stage in ("allocating-kv", "capturing-graphs"):
verb, family, ready, total, measured = k.groups()
tuned = tuned or verb in ("compiling", "autotuning") or int(measured) > 0
if tuned:
detail = (f"tuning b12x's kernels for this GPU, at its first boot only "
f"({family}: {ready} of {total} ready)")
else:
detail = f"loading b12x's kernel choices ({family}: {ready} of {total})"
done = list(FLASH_LOCAL_STAGES[:FLASH_LOCAL_STAGES.index(stage)]) if stage in FLASH_LOCAL_STAGES else []
if fired:
done = list(FLASH_LOCAL_STAGES)
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
# ── The llama.cpp lanes speak llama-server ──────────────────────────────────────────────────
# Its container log at its default verbosity, read on the reference box (llama.cpp's images b12282 and b12316, the
# pinned one, serving Unsloth's GGUF of the flash model with its DFlash2 draft, 2026-11-12, the same lines in both):
# "llama_server: initializing ...", "load_model: loading
# model '<the first GGUF part>'", then nothing for the 3 to 7 min the weights take, "loading draft model '<the
# draft>'", "load_model: initializing, n_slots = 1, n_ctx_slot = 262144", "model loaded", "listening on http://...".
# Its /health answers 503 until "model loaded" and 200 after (its server-http.cpp). It writes no progress through the
# weights, so the stage says which file is read and the bar the time, from the lane's usual boot.
LLAMACPP_STAGES = ("init", "loading-weights", "loading-draft", "allocating-kv", "warming-up")
TRANSCRIBE_STAGES = tuple(s for s in LLAMACPP_STAGES if s != "loading-draft") # the same server, with no draft
LLAMACPP_MARKERS = [
# (substring, stage it opens, what is being done while that line is the latest)
("llama_server: initializing", "init", "starting llama.cpp"),
("load_model: loading model", "loading-weights", "the GGUF's weights, its n-gram table left on the disk"),
("loading draft model", "loading-draft", "the DFlash2 draft"),
("load_model: initializing, n_slots", "allocating-kv", "the KV cache of its window"),
("model loaded", "warming-up", "starting the API"),
("listening on", "warming-up", "ready"),
]
def parse_llamacpp_boot_log(lines: list[str]) -> dict:
"""A llama.cpp lane's container log, in the shape parse_kolibri_boot_log returns. Only the latest boot counts (the
last "initializing"); fired up once the server says it listens."""
start = 0
for i, ln in enumerate(lines):
if "llama_server: initializing" in ln:
start = i
stage, detail, fired = None, "", False
for ln in lines[start:]:
for needle, st, what in LLAMACPP_MARKERS:
if needle in ln:
stage, detail = st, what
if needle == "listening on":
fired = True
done = list(LLAMACPP_STAGES[:LLAMACPP_STAGES.index(stage)]) if stage in LLAMACPP_STAGES else []
if fired:
done = list(LLAMACPP_STAGES)
return {"stage": stage, "done": done, "fired_up": fired, "detail": detail}
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_image_h3_boot_log(lines: list[str]) -> dict:
"""The MiniMax-H3-Image lane's journal, reduced to the same shape parse_boot_log returns, by
the image lane's latest-boot rule."""
return _parse_diffusion_boot_log(lines, IMAGE_H3_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 GiB 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. So is the Kolibri lane: 73.6 GiB of weights
# (42.8 for its NVFP4 variant) and a KV cache beside them; the Nemotron lane, 24.1 GiB of
# weights and a KV cache set by its memory share, 85 GiB in all; the Nemotron Super lane,
# 70 GiB of weights, 91 in all at its share; the Flash FP4-Local lane, 70 GiB of weights and the
# rest of its share, 97 GiB, in KV cache; and the Ornith 1.5 122B lane, 72.6 GiB of weights at a
# share of 97 GiB too; and the Qwen3.8 Flash-Next Unsloth GGUF lane, llama.cpp's, 76.9 GiB of weights and a KV cache
# for each of its two windows, 95.3 GiB of GPU memory in all with its draft (97,552 MiB by nvidia-smi on the reference
# box, 2026-11-12; 100,881 MiB in its 1M mode), its n-gram table read from the disk. And the MiniMax-H3-Image lane,
# a second image lane: 92.3 GB at its peak on the reference box, its recipe asking 106 GiB free at its start. And the
# NVIDIA Nemotron Transcribe lane, llama.cpp's, 36.5 GB of weights, which left 76 GiB available at its lowest with nothing
# else serving (2026-11-14). And the Liquid AI LFM2.5 24B-A2B lane, SGLang's, a static share of 0.7 of the memory
# SGLang sees, which left 24 GiB available at its lowest (2026-11-14). And the Liquid AI LFM3 lane, vLLM's, its weights
# 1.8 GB and its KV cache extended into its share of 0.75 of the memory vLLM sees. And the Inkling 2 Mini lane, SGLang's,
# a static share of 0.76, 84.4 GiB of GPU memory once ready, 24.37 GiB available at its lowest while it loaded
# (2026-11-24).
ENGINE_UNITS = ("qwen38-sglang.service", "qwen38-flash.service",
"qwen38-image.service", "qwen38-video.service", "qwen38-kolibri.service",
"qwen38-nemotron.service", "qwen38-nemotron-super.service", "qwen38-flash-local.service",
"qwen38-ornith-122b.service", "qwen38-flash-unsloth.service", "qwen38-image-h3.service",
"qwen38-transcribe.service", "qwen38-lfm25.service", "qwen38-lfm3.service", "qwen38-inkling.service")
IMAGE_UNIT = "qwen38-image.service"
IMAGE_H3_UNIT = "qwen38-image-h3.service"
VIDEO_UNIT = "qwen38-video.service"
KOLIBRI_UNIT = "qwen38-kolibri.service"
NEMOTRON_UNIT = "qwen38-nemotron.service"
NEMOTRON_SUPER_UNIT = "qwen38-nemotron-super.service"
FLASH_LOCAL_UNIT = "qwen38-flash-local.service"
ORNITH_UNIT = "qwen38-ornith-122b.service"
FLASH_UNSLOTH_UNIT = "qwen38-flash-unsloth.service"
TRANSCRIBE_UNIT = "qwen38-transcribe.service"
LFM3_UNIT = "qwen38-lfm3.service"
# The SGLang engines that serve text on ENGINE_BASE: the 27B's, the flash's, the Liquid AI LFM2.5 24B-A2B lane's, on the
# 27B's image, and the Inkling 2 Mini lane's, on its own. 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. The
# Kolibri lane serves text on that port too, from vLLM, which none of those belts know
# (its routes, its log and its model names are not SGLang's): the cockpit follows it on
# its own facts, as it does the image and the video lanes. So do the Nemotron lanes, the Flash
# FP4-Local lane, the Ornith lane and the Liquid AI LFM3 lane, vLLM too, and the Unsloth GGUF lane, llama.cpp's; the
# NVIDIA Nemotron Transcribe lane, llama.cpp's too, serves no text, on a port of its own.
TEXT_UNITS = tuple(u for u in ENGINE_UNITS
if u not in (IMAGE_UNIT, VIDEO_UNIT, KOLIBRI_UNIT, NEMOTRON_UNIT, NEMOTRON_SUPER_UNIT, FLASH_LOCAL_UNIT,
ORNITH_UNIT, FLASH_UNSLOTH_UNIT, IMAGE_H3_UNIT, TRANSCRIBE_UNIT, LFM3_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 engine units (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", "prepare"):
# prepare: a first Load's pip and docker pull beside a lane loading its weights, on the
# same unified memory (found in review, 2026-10-15)
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, proxy_port: int = 30001) -> 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 == IMAGE_H3_UNIT and state == "ready":
# the same, with the boot of the MiniMax-H3-Image lane (451 s from the external SSD)
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 8 min)")
elif unit == TRANSCRIBE_UNIT and state == "ready":
# on a port of its own: nothing reaches it through the proxy on :30001
warns.append("a transcription the NVIDIA Nemotron Transcribe lane is making right now is lost, and "
"nothing answers on its port until this lane is back (about 15 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(f"requests on :{proxy_port} wait for it while it boots (a streamed one hears "
"keepalives) and go to it once it answers")
elif state == "ready":
warns.append(f"clients on :{proxy_port} will get errors until an engine "
"is back")
return warns
# ── Stage timing: history + ETA (median of real observed durations) ─────────
def boot_key(unit: str, target: str | None) -> str:
"""History key for one unit's boot durations, per served target. A boot depends on the
checkpoint as the pool does (pool_key): the Kolibri lane's FP8 boots in 8 min 40 s to
10 min 03 s and its NVFP4 in 6 min 34 s to 7 min 10 s, and one median of both told
neither (found in review, 2026-10-14)."""
return f"{unit}:boot:{target}"
def boots_for(history: dict, unit: str, target: str | None = None) -> list:
"""The boot durations that speak for this target: its own once it has one, else the
unit's, which every boot fed before they were kept per target."""
own = history.get(boot_key(unit, target), []) if target else []
return [v for v in (own or history.get(unit, [])) if isinstance(v, (int, float))]
def eta_for(history: dict, unit: str, target: str | None = None) -> float | None:
"""Median full-boot duration for this unit's target (seconds)."""
vals = boots_for(history, unit, target)
return statistics.median(vals) if vals else None
# The boot each lane took on the reference box, for a box that has recorded none of its own: the page's READY_DEFAULT,
# which a test holds to these.
REFERENCE_BOOT_S = {"qwen38-sglang.service": 540.0, "qwen38-flash.service": 780.0, "qwen38-flash-local.service": 1020.0,
"qwen38-kolibri.service": 600.0, "qwen38-nemotron.service": 450.0,
"qwen38-nemotron-super.service": 660.0, "qwen38-ornith-122b.service": 420.0,
"qwen38-flash-unsloth.service": 420.0, "qwen38-image.service": 70.0,
"qwen38-image-h3.service": 451.0, "qwen38-video.service": 720.0, "qwen38-transcribe.service": 15.0,
"qwen38-lfm25.service": 290.0, "qwen38-lfm3.service": 160.0, "qwen38-inkling.service": 180.0}
def boot_usual(history: dict, unit: str, target: str | None = None) -> dict:
"""What a start of this lane usually takes: {"s": the median, "n": of how many starts recorded here, "long": the
seconds past which it is longer than usual}. n is 0 on a box that has recorded none: s is then the reference box's
time, and twice that is long (two minutes more at the least), as a first start reads a cold disk, compiles and tunes
what the next ones load (377 s then 232 on the Inkling 2 Mini lane, 359 then 151 on Ornith).
Long is a quarter more than the median, half a minute more on a short start, and more than every start but the
slowest, a tenth over: the spread counts (27B 208 to 230 s, flash 733 to 963, image 72 to 171), and one start that
went wrong must not hide the next (Inkling's 377, LFM3's 172 under NVIDIA driver 615.71.09). Replayed on the 733
starts of the reference box's timeline that served (2026-08-29 to 2026-11-29), each against the 12 before it: 26 were
long, the flash lane's 1,480 s where 830 was usual, the image lane's 190 for 77, LFM3's 171 for 97. Twice the median,
the rule before it, missed the last one, and said nothing of Inkling's until 7 min 44 s."""
vals = sorted(boots_for(history, unit, target))
if not vals:
s = REFERENCE_BOOT_S.get(unit, 600.0)
return {"s": s, "n": 0, "long": max(2 * s, s + 120.0)}
s = statistics.median(vals)
others = vals[:-1] if len(vals) >= 4 else vals
return {"s": s, "n": len(vals), "long": round(max(1.25 * s, s + 30.0, 1.1 * others[-1]), 1)}
def record_boot(history: dict, unit: str, seconds: float, keep: int = 12,
target: str | None = None) -> dict:
"""One boot, in the unit's series and, when its target is known, in the target's."""
for key in (unit, boot_key(unit, target)) if target else (unit,):
lst = list(history.get(key, []))
lst.append(round(float(seconds), 1))
history[key] = lst[-keep:]
return history
# The starts of a lane, beside its series of durations and under keys of their own, which an older cockpit neither reads
# nor touches: the ones that served (when, driver, kernel, what they took) and the ones that ended before.
STATE_WORDS = {"starting": "starting", "loading-weights": "loading its weights", "loading-draft": "loading its draft head",
"allocating-kv": "allocating its KV pool", "capturing-graphs": "capturing its CUDA graphs",
"warming-up": "warming up"}
def _dicts(history: dict, key: str) -> list[dict]:
lst = history.get(key)
return [x for x in lst if isinstance(x, dict) and isinstance(x.get("at"), (int, float))] if isinstance(lst, list) else []
def record_start(history: dict, unit: str, start: dict, keep: int = 12) -> dict:
"""A start that served. The same run again (a cockpit that restarted meets it serving) changes nothing."""
lst = _dicts(history, f"{unit}:starts")
if not any(x.get("run") == start.get("run") for x in lst):
history[f"{unit}:starts"] = (lst + [start])[-keep:]
return history
def record_cut(history: dict, unit: str, cut: dict, keep: int = 6) -> dict:
"""A start that ended before it was ready."""
history[f"{unit}:cuts"] = (_dicts(history, f"{unit}:cuts") + [cut])[-keep:]
return history
def last_start(history: dict, unit: str) -> dict | None:
"""The last start of a lane that served, with its day."""
lst = _dicts(history, f"{unit}:starts")
return {**lst[-1], "day": datetime.fromtimestamp(lst[-1]["at"]).strftime("%Y-%m-%d")} if lst else None
def last_cut(history: dict, unit: str) -> dict | None:
lst = _dicts(history, f"{unit}:cuts")
return lst[-1] if lst else None
def cut_words(cut: dict) -> str:
"""stopped after 7 min 33 s while loading its weights, barely moving, NVIDIA driver 615.71.09"""
return (f"{cut.get('how', 'stopped')} after {dur_words(cut.get('s') or 0)} while "
f"{STATE_WORDS.get(cut.get('stage'), 'starting')}" + (", barely moving" if cut.get("still") else "")
+ (f", NVIDIA driver {cut['driver']}" if cut.get("driver") else ""))
def cut_since(history: dict, unit: str) -> str | None:
"""What the last start was, in words, when it ended before it was ready; None when a later one served."""
cut, start = last_cut(history, unit), last_start(history, unit)
return cut_words(cut) if cut and (start is None or start.get("end", start["at"]) < cut.get("end", cut["at"])) else None
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|cannot start|lacks its files|lacks its model|lacks room): (.+))")
def parse_preflight(lines: list[str]) -> dict | None:
"""The guard's last word among these journal lines: {"verdict": "waits" | "refused" |
"starts" | "cannot start" | "lacks its files" | "lacks its model" | "lacks room", "reason": str}, or None when it said nothing.
"cannot start" is the flash launcher's: a GPU outside its ATS addressing mode, which no wait
or reboot changes (flash-ats-check.sh, issue #54). "lacks its files" is the Flash FP4-Local
unit's: its checkpoint or a copy of its n-gram table is missing, which its Load brings back; "lacks its model" and "lacks
room" are the lanes' beside every lane: their model is missing, or the box has too little memory left for their start."""
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
# The flags preflight_flags may add, which the cockpit hands the page: one list, as the collector
# copied them by hand and left "cannot" out (found on the reference box, 2026-10-19).
GUARD_FLAGS = ("held", "refused", "cannot", "lacks", "room")
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), cannot when this GPU cannot start it
(the unit failed and systemd does not start it again), lacks when a file the engine reads is
missing (failed too, until a Load fetches it), room when the box had too little memory for its start (failed too, until
it is started again)."""
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"]
elif preflight["verdict"] == "cannot start" and state.get("state") == "failed":
out["cannot"] = preflight["reason"]
elif preflight["verdict"] in ("lacks its files", "lacks its model") and state.get("state") == "failed":
out["lacks"] = preflight["reason"]
elif preflight["verdict"] == "lacks room" and state.get("state") == "failed":
out["room"] = 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}
# ── a start, watched: what moves, and when it barely does (pure) ────────────────────────────────────────
# On 2026-11-29, under NVIDIA driver 615.71.09, the Inkling 2 Mini lane sat in its weights for 7 min 33 s, then for
# 6 min 41 s, where 232 s is usual: no log line, 3 MiB/s of memory, the GPU at 942 MHz and 5 W, nothing read from the
# disk (sysstat, the second start), and the page said "about 0 s left". While a lane starts, the cockpit reads every 2 s
# what moves when weights load, all of it in files already there: the lane's own disk bytes and memory (its container's
# cgroup, or its unit's), the box's available memory, and, from the GPU panel's own reading, the GPU's memory, use and
# power; and the last line of its log.
# A lane barely moves once none of them did for STILL_S while it loads its weights: under STILL_B of disk, of its own
# memory and of GPU memory (4 MiB/s), under STILL_BOX_B of the box's, no log line, the GPU at rest. Only then: a compile,
# a graph capture, a warm-up and a tuning are silent and still for minutes in a good boot, and the guard's wait for memory
# is said as one. Only when each of them was read: what cannot be read (another cgroup driver, nvidia-smi silent) is never
# taken for still. And only with a fault beside it (the GPU's clock held low, an Xid) or past what the lane's starts take
# (boot_usual): weights already in the page cache go to memory taken at once, and the Unsloth lane's 77 GB did for 46 s
# with the box's memory moving by 8 MiB/s and nothing else (2026-11-30). Measured:
# - both starts under 615: the box's memory moved by 211 to 671 MiB in any minute, where a good load of the same lane
# moved 7,863 at the least, at 155 MiB/s, on 595 with its clock held low as without;
# - the 27B's weights, read live on 2026-11-30: 168 MB/s of its own memory, 0 from the disk (the page cache had them), one
# core busy, the GPU at 2 % and 14 W throughout;
# - 472 starts of 15 lanes with their telemetry (2026-10-31 to 2026-11-30): good loads of the flash, FP4-Local, Unsloth,
# Bolt, Ornith and H3-Image lanes move under 1 GiB of the box's memory for minutes, their weights coming from the disk
# (the flash lane's on 2026-11-22: 248.7 MB/s) into memory taken at once. Their disk, or a shard line, tells them.
STILL_S = 60.0
STILL_HOLE_S = 20.0 # reads further apart than this (the cockpit stood still) prove nothing of the lane
STILL_B = 256 * 2 ** 20
STILL_BOX_B = 2 ** 30
STILL_USE_PCT, STILL_W = 10, 25.0 # the GPU at rest: the cockpit's GPU_REST_W
STILL_STATES = ("loading-weights", "loading-draft")
RATE_S = 20.0 # a rate is said over this long
_ACCESS_LINE = re.compile(r'"(?:GET|POST|HEAD|OPTIONS) \S+ HTTP/[\d.]+"')
def last_log_line(lines: list[str], limit: int = 200) -> str:
"""The last of these log lines that says something: no escape bytes, no carriage return, not blank, not a request the
cockpit's own probes write (a server that answers /health while it warms up writes one every 2 s). Cut to limit."""
for ln in reversed(lines):
txt = _ANSI.sub("", ln).replace("\r", "\n").rstrip().split("\n")[-1].strip()
if txt and not _ACCESS_LINE.search(txt) and any(c.isalnum() for c in txt):
return txt[:limit]
return ""
def boot_window(samples: list[dict], now: float, span: float = STILL_S) -> list[dict]:
"""The samples of the last span seconds, [] when they do not cover them: the first is older than that, none is
further from the next than STILL_HOLE_S."""
first = next((i for i in range(len(samples) - 1, -1, -1) if samples[i]["t"] <= now - span), None)
if first is None:
return []
win = samples[first:]
times = [s["t"] for s in win] + [now]
return win if all(b - a <= STILL_HOLE_S for a, b in zip(times, times[1:])) else []
def _span(win: list[dict], key: str):
"""The most this moved over the window, None when a sample does not have it."""
vals = [s.get(key) for s in win]
return max(vals) - min(vals) if vals and all(v is not None for v in vals) else None
def boot_moved(win: list[dict]) -> dict:
"""What moved over a window, each None when it could not be read all along: disk (bytes read and written by the
lane), own (its memory), gpu_mem, box (the box's available memory), gpu ("rest" or "work"), line (whether its log's
last line changed)."""
out = {"disk": None, "own": _span(win, "own"), "gpu_mem": _span(win, "gpu_mem"), "box": _span(win, "avail"),
"gpu": None, "line": None}
if not win:
return out
a, b = win[0], win[-1]
if None not in (a.get("read"), a.get("written"), b.get("read"), b.get("written")):
disk = b["read"] + b["written"] - a["read"] - a["written"]
out["disk"] = disk if disk >= 0 else None # counters that went back are another life's
gpu = [(s.get("use"), s.get("watts")) for s in win]
known = [g for g in gpu if None not in g]
if any((u or 0) > STILL_USE_PCT or (w or 0) >= STILL_W for u, w in gpu):
out["gpu"] = "work"
elif len(known) == len(win):
out["gpu"] = "rest"
if a.get("line") is not None:
out["line"] = any(s.get("line") != a["line"] for s in win)
return out
def boot_still(moved: dict, box: bool = True) -> bool:
"""True when nothing of what boot_moved reads moved, and all of it was read. box=False leaves the box's memory out,
which other programs move too: a lane found still stays so until something of its own moves."""
return (None not in (moved["disk"], moved["own"], moved["gpu_mem"], moved["box"]) and moved["line"] is False
and moved["gpu"] == "rest" and max(moved["disk"], moved["own"], moved["gpu_mem"]) < STILL_B
and (not box or moved["box"] < STILL_BOX_B))
def boot_rates(samples: list[dict], now: float) -> dict:
"""What the lane reads from the disk and takes in memory now, in bytes a second over the last RATE_S: {"read",
"memory"}, each None when it cannot be said. Memory is the lane's own, what it gained (its loader fills a shard's
buffer and gives it back), the box's when its own is unknown."""
win = boot_window(samples, now, RATE_S)
out = {"read": None, "memory": None}
if len(win) < 2 or win[-1]["t"] <= win[0]["t"]:
return out
dt = win[-1]["t"] - win[0]["t"]
if None not in (win[0].get("read"), win[-1].get("read")) and win[-1]["read"] >= win[0]["read"]:
out["read"] = (win[-1]["read"] - win[0]["read"]) / dt
for key, sign in (("own", 1), ("avail", -1)):
vals = [s.get(key) for s in win]
if all(v is not None for v in vals):
out["memory"] = sum(max(0, sign * (b - a)) for a, b in zip(vals, vals[1:])) / dt
break
return out
def boot_watch(watch: dict, sample: dict, *, state: str, elapsed: float | None, usual: dict, fault: bool = False,
held: bool = False) -> dict:
"""Fold one sample into watch, which the cockpit keeps for one activation, and say what it means: {"level":
"normal", "long" past the usual (boot_usual), "still" when it barely moves; "still_s": for how long; "moved":
boot_moved over the last STILL_S; "rates"}. fault: something is wrong beside it (the GPU's clock held low, an Xid).
held: the start guard waits for memory. The samples kept are those of the state the lane is in: what moved before it
loaded its weights says nothing of whether they load."""
now = sample["t"]
if watch.get("state") != state:
watch.update(state=state, state_at=now, samples=[], still_at=None)
samples = watch["samples"]
samples.append(sample)
while len(samples) > 2 and samples[1]["t"] < now - STILL_S - STILL_HOLE_S:
samples.pop(0)
past = elapsed is not None and elapsed > usual["long"] and not held
moved = boot_moved(boot_window(samples, now)) if state in STILL_STATES and not held else boot_moved([])
was = watch["still_at"]
if boot_still(moved, box=was is None) and (was is not None or fault or past):
watch["still_at"] = was if was is not None else now - STILL_S
else:
watch["still_at"] = None
level = "still" if watch["still_at"] is not None else "long" if past else "normal"
return {"level": level, "still_s": round(now - watch["still_at"]) if watch["still_at"] is not None else None,
"moved": moved, "rates": boot_rates(samples, now)}
def boot_pace(rates: dict, size) -> int | None:
"""The seconds the whole checkpoint takes at the pace of now, the faster of what is read from the disk and what the
lane's memory takes: said of a start that is long or barely moves, as what it is, a pace. None when there is no pace
(under 0.5 MB/s) or no size to say it of."""
rate = max(rates.get("read") or 0, rates.get("memory") or 0)
return round(size / rate) if size and rate >= 5e5 else None
# ── the GPU's clock: what the driver says limits it, and when it is held low (pure) ───────────────────────────
# clocks_event_reasons.active is a mask: NVML's names for its bits (nvml.h), the last two since NVML 13.5 (CUDA 13.5,
# 2026-11; NVIDIA/go-nvml's nvml.h and the NVML reference of 2026-11-11). The reference box's driver 615.71.09 set the
# reliability bit for the whole day of 2026-11-29, the GPU at 942 MHz at most; nvidia-smi 595 prints it and has no name
# for it. A bit no name is known for is said by its number.
CLOCK_REASONS = ((0x1, "idle"), (0x2, "applications clocks setting"), (0x4, "software power cap"),
(0x8, "hardware slowdown"), (0x10, "sync boost"), (0x20, "software thermal slowdown"),
(0x40, "hardware thermal slowdown"), (0x80, "hardware power brake"), (0x100, "display clock setting"),
(0x200, "board limit policy"), (0x400, "reliability policy"))
# A GB10 whose lane loads or serves reads 1,989 MHz at the least (its cap of 2,000) and 2,411 with none, the GPU at 1 %
# as at 96: no read was under 1,200 in 306 loads and 16 days of serving (2026-10-31 to 2026-11-28, a line every 2 s),
# and all were in the four starts of 2026-11-29 whose clock was held, at 942 MHz: under 615.71.09, which gave a reason,
# and under 595.99.02 after it, which gave none. Below 40 % of its maximum (3,003 MHz) for half a minute, it is held.
GPU_LOW = 0.4
GPU_LOW_MHZ = 1200 # when nvidia-smi gives no maximum
GPU_LOW_S = 30.0
GPU_LOW_USE_PCT, GPU_LOW_W = 50, 7.0 # serving: a GPU at work (LFM3 under 615: 910 to 929 MHz, 7 to 17 W, 2 min 38)
def clock_reasons(mask) -> list[str]:
"""The names of what limits the GPU's clock, from the mask, each with its bit when nvidia-smi may have no name for it."""
if not isinstance(mask, int) or mask <= 0:
return []
out = [name + (f" (0x{bit:x})" if bit >= 0x200 else "") for bit, name in CLOCK_REASONS if mask & bit]
rest = mask & ~sum(bit for bit, _ in CLOCK_REASONS)
return out + ([f"a reason with no name known (0x{rest:x})"] if rest else [])
def clock_limits(mask, resting: bool) -> list[str]:
"""What limits the clock, as the Machine view says it: at rest, a GPU that drops its clocks says idle or a software
power cap (a GB10 at 208 MHz and 4 W), which is no limit to anything."""
if resting and isinstance(mask, int):
mask &= ~(0x1 | 0x4)
return clock_reasons(mask)
def gpu_held(reads: list[dict], now: float, *, busy: str | None, since: float | None) -> dict | None:
"""The GPU's clock held low while a lane loads or serves: {"mhz" (the most it read), "max_mhz", "watts", "reasons"}
over the last GPU_LOW_S, or None. busy is "loading" (its weights or past them: a container that starts has no CUDA
context yet, and the GPU is at rest at 208 MHz), "serving" (then only a GPU at work counts) or None; since, when
that began. reads: {"t", "mhz", "max_mhz", "watts", "use", "reasons"}, every 3 s."""
if busy is None or since is None or now - since < GPU_LOW_S:
return None
win = boot_window(reads, now, GPU_LOW_S)
if len(win) < 2 or any(r.get("mhz") is None for r in win):
return None
top = next((r["max_mhz"] for r in reversed(win) if r.get("max_mhz")), None)
if any(r["mhz"] >= (GPU_LOW * top if top else GPU_LOW_MHZ) for r in win):
return None
if busy == "serving" and any((r.get("use") or 0) < GPU_LOW_USE_PCT or (r.get("watts") or 0) < GPU_LOW_W for r in win):
return None
watts = [r["watts"] for r in win if r.get("watts") is not None]
mask = 0
for r in win:
mask |= r.get("reasons") or 0
return {"mhz": max(r["mhz"] for r in win), "max_mhz": top, "watts": max(watts) if watts else None, "reasons": mask}
# ── why a start may not move, in facts, and what to do (pure) ────────────────────────────────────────────────
def dur_words(s) -> str:
"""Seconds in words, as the page writes them, with their unit: 41 s, 7 min 33 s, 1 h 05."""
r = max(0, round(s))
return f"{r} s" if r < 90 else f"{r // 60} min {r % 60:02d} s" if r < 3600 else f"{r // 3600} h {r % 3600 // 60:02d}"
def _gb(b) -> str:
return f"{b / 1e9:.1f} GB"
def held_words(held: dict, doing: str) -> str:
"""The clock held low, in a sentence."""
why = clock_reasons(held["reasons"])
return (f"The GPU's clock is held at {held['mhz']:,} MHz" + (f" of {held['max_mhz']:,}" if held.get("max_mhz") else "")
+ (f", {held['watts']:.0f} W," if held.get("watts") is not None else "") + f" while {doing}; the driver "
+ (f"says what limits it: {', '.join(why)}" if why else "gives no reason") + ".")
def boot_causes(*, held: dict | None, driver: str | None, kernel: str | None, last: dict | None, smi: str | None,
foreign: list[dict], xid: dict | None, refused: int, disk: dict | None) -> list[str]:
"""What is known to be unlike a start that served, a sentence each, the most telling first: the GPU's clock held low,
an Xid or allocations the driver refused since this start, a driver or a kernel that is not the one this lane last
started under, GPU memory another program holds, nvidia-smi that does not answer, a disk that gives little. Facts
the cockpit read, never a guess at the one that matters."""
out = []
if held:
out.append(held_words(held, "this lane loads"))
if xid and xid.get("n"):
out.append(f"The GPU driver logged {xid['n']} Xid error{'s' if xid['n'] > 1 else ''} since this start, the last: "
f"{xid['last'].rstrip('.')}.")
if refused:
out.append(f"The GPU driver refused {refused} allocation{'s' if refused > 1 else ''} since this start "
"(NV_ERR_NO_MEMORY in the kernel log).")
if last:
for what, now_is, was in (("NVIDIA driver", driver, last.get("driver")), ("kernel", kernel, last.get("kernel"))):
if now_is and was and now_is != was:
out.append(f"The {what} is {now_is}; this lane last started under {was}, on {last['day']}.")
for p in foreign:
out.append(f"{p['name'] or 'A program'} (pid {p['pid']}) holds {_gb(p['bytes'])} of GPU memory and is not this lane's.")
if smi:
out.append(f"nvidia-smi does not answer: {smi}.")
if disk:
out.append(f"The disk gives it {disk['rate'] / 1e6:.1f} MB/s: {_gb(disk['read'])} read of a checkpoint of "
f"{_gb(disk['size'])}.")
return out
def boot_todo(*, held: dict | None, driver: str | None, kernel: str | None, last: dict | None) -> list[str]:
"""What to do about a start that barely moves: the two buttons first, then what the facts point at."""
out = ["Read its journal, then stop it."]
was = (last or {}).get("driver")
if driver and was and driver != was:
same = not (kernel and last.get("kernel")) or kernel == last["kernel"]
out.append(f"If it happens again, go back to NVIDIA driver {was}: "
+ ("the one thing read here that changed since it last started." if same
else "it and the kernel are what changed since it last started."))
if held:
out.append("If the clock stays low after the stop, shut the box down and cut its power for a minute (on the "
"reference box, a change of driver and reboots did not bring it back).")
return out
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:]]
def feed_ages(rows: list[dict], now: float) -> list[dict]:
"""Each request still in flight gets "age", the seconds since its start line (the box's local
time, as journalctl writes it). Its Took cell stayed empty for as long as it ran: a prompt of
494,089 tokens the cache could not serve took 19 min before its first token on the Ornith
lane, and nothing on the page told that from a hang (issue #61, 2026-10-30)."""
for r in rows:
if r.get("outcome") != "in flight":
continue
try:
start = datetime.strptime(str(r.get("ts", ""))[:19], "%Y-%m-%dT%H:%M:%S").timestamp()
except ValueError:
continue
r["age"] = round(max(0.0, now - start), 1)
return rows
# ── a prompt being computed, on the vLLM lanes (pure) ────────────────────────
# A prompt the prefix cache cannot serve is computed whole before its first token. On the Ornith
# lane one of 494,089 tokens took 19 min, 2.8 of them for its first 200,000 tokens and 11.3 for
# 400,000: each token attends to all those before it. All that time the page said "1 running",
# its last five minutes "quiet", and vLLM's log 0.0 prompt tokens a second, as its counters of
# prompt tokens move only once a prompt is done: a user took it for a hang (issue #61). What does
# move while vLLM computes a prompt: its KV cache fills, chunk after chunk, while its count of
# generated tokens stands still, and its prefix cache counted every token of the prompt when the
# request was admitted. The KV cache runs ahead of the work by a few blocks (up to 519,866 tokens
# held for that prompt before its first token, 5 % over), so the share is held under 100 %.
# The time left is a floor, never a promise. The time a prompt takes grows as N^k, k from 2.1 to
# 2.5 on that run, and nearer 1 on a lane whose layers mostly do not attend: k is read off the
# request's own curve (the time and the tokens held since its admission, at a tenth of it and
# now), held between 1 and 2, and elapsed * ((total / held)^k - 1) said only as "at least".
# Replayed on that run's counters (every 5 s), it said 13.7 min when 17.0 were left and 7.0 when
# 9.0 were, and never more than 85 % of the time that was left.
PROMPT_IDLE_S = 10 # no token written for this long: the request is still on its prompt
PROMPT_MIN_SHARE = 0.10 # under a tenth of the prompt held, no floor is said
PROMPT_POINT_S = 5 # one point of the request's curve every 5 s at most
# The cockpit reads the engine twice a second, so an admission is seen up to half a second late:
# its curve starts that much earlier than the time read, which read alone puts k too high (a
# floor of 266 s where 260 were left, on a lane whose prompt time grows as N). k is read with
# that half second put back, and the floor without it. The KV cache is read in whole blocks
# (1,056 tokens of the Ornith lane's pool), rounded up as vLLM allocates them: the first point
# counts a block less in k (the smallest step seen between two reads of this request), which a
# lane whose prompt time grows as N otherwise read as 1.03 and a floor of 277 s where 263 were left.
PROMPT_READ_S = 0.5
# A prompt is followed only from an admission that is certainly one request: one more request running
# at the next read, none waiting at either, and none finished and none preempted between the two (vLLM
# counts every finish, an abort included). Then the jump of the prompts admitted is that prompt, to the
# token. Any other admission is another request's, kept as the largest jump since the engine was last
# seen empty, as are the requests running when the prompt came. Once another has run beside it, the time
# the prompt took is not its own any more (no floor), and the one request left is said to be the prompt
# only if it holds more than any other could, twice its prompt and 8,192 tokens past it (a request holds
# up to 5 % more than its prompt, and the reads round to whole blocks). A cockpit that starts while the
# engine runs says nothing until it has seen it empty. With 10 clients sending small requests during a
# long prompt (issue #61), the one admitted last would have been taken for the prompt being computed:
# "99 % of 4,812 tokens, almost done" while one of 388,753 went on (found in review, 2026-10-31).
PROMPT_OTHER_MARGIN = 8192
# A read the cockpit could not make (a timeout, an engine that answered badly) is no read: what was known
# stays, and is said no longer once the last read is this old. One failed read under a long prompt had
# wiped everything, and the next read, a request running, took it for one admitted unseen: nothing was
# said for the rest of a prompt of 19 min (code review, 2026-10-31).
PROMPT_STALE_S = 10
def _grew(before: dict, after: dict, key: str) -> bool:
"""A counter of the engine went up between two reads (False when either read lacks it)."""
return before.get(key) is not None and after.get(key) is not None and after[key] > before[key]
def prompt_read(state: dict, now: float, row: dict | None) -> None:
"""Fold one read of the engine's load into `state`, which the cockpit keeps between reads. A read
the cockpit could not make changes nothing; a row without vLLM's counters (an SGLang lane) forgets
everything."""
if not row:
return
if row.get("gen_tokens") is None or row.get("prefix_queries") is None:
state.clear()
return
try:
waiting = int(row.get("num_waiting_reqs", 0))
cur = {"t": now, "running": int(row.get("num_reqs", 0)) - waiting, "waiting": waiting,
"used": int(row.get("num_used_tokens", 0)), "gen": float(row["gen_tokens"]),
"q": float(row["prefix_queries"])}
for key, name in (("done", "finished"), ("preempted", "preemptions")):
cur[key] = None if row.get(name) is None else float(row[name])
except (TypeError, ValueError):
return
prev = state.get("last")
if prev is not None and (cur["q"] < prev["q"] or cur["gen"] < prev["gen"]
or _grew(cur, prev, "done") or _grew(cur, prev, "preempted")):
state.clear() # counters back to zero: the engine restarted
prev = None
if prev is None:
# what runs now was admitted unseen: nothing is said until the engine is seen empty
state["blind"] = cur["running"] + cur["waiting"] > 0
else:
if cur["q"] > prev["q"]:
tokens = int(cur["q"] - prev["q"])
admit = state.get("admit")
one = (cur["running"] - prev["running"] == 1 and prev["waiting"] == 0 and cur["waiting"] == 0
and not _grew(prev, cur, "done") and not _grew(prev, cur, "preempted"))
if one and (admit is None or prev["running"] == 0 or tokens >= admit["tokens"]):
# one request admitted between the two reads: its whole prompt, to the token
if admit is not None and prev["running"] > 0:
state["others"] = max(state.get("others", 0), admit["tokens"])
state.update(admit={"t": now, "tokens": tokens}, points=[], shared=prev["running"] > 0)
state.pop("quantum", None)
else:
state["others"] = max(state.get("others", 0), tokens)
state["shared"] = True
elif cur["used"] > prev["used"] and "admit" in state:
step = cur["used"] - prev["used"]
state["quantum"] = min(step, state.get("quantum", step))
if cur["running"] > 1 or cur["waiting"] > 0 or _grew(prev, cur, "preempted"):
state["shared"] = True
if cur["gen"] > prev["gen"]:
state["wrote"] = now
if (cur["running"] == 1 and prev["running"] <= 1 and cur["waiting"] == 0 and prev["waiting"] == 0
and not _grew(prev, cur, "done") and not _grew(prev, cur, "preempted")):
# one request in the engine across the two reads, and it wrote: its prompt is done
state["solo_wrote"] = now
if cur["running"] == 0 and cur["waiting"] == 0:
# an empty engine: nothing unseen, no other request, and the prompt followed is over
for key in ("admit", "points", "quantum", "shared", "solo_wrote"):
state.pop(key, None)
state["blind"] = False
state["others"] = 0
points = state.setdefault("points", [])
admit = state.get("admit")
# the floor reads one point of the curve, the first past a tenth of the prompt: none is kept past it
if admit and (not points or (points[-1][1] < PROMPT_MIN_SHARE * admit["tokens"]
and now - points[-1][0] >= PROMPT_POINT_S)):
points.append((now, cur["used"]))
state["last"] = cur
def prompt_progress(state: dict, now: float) -> dict | None:
"""What the one running request's prompt has got to: {"tokens", "share", "elapsed", "left_min_s"},
or None when no prompt is being computed that this can say anything true about (none running,
more than one, one waiting, a token written in the last PROMPT_IDLE_S, no admission seen, its
first token already written, no read for PROMPT_STALE_S, or another request that may be the one
left). No floor once the engine was shared."""
last, admit = state.get("last"), state.get("admit")
if (not last or last["running"] != 1 or last["waiting"] or state.get("blind") or not admit
or admit["tokens"] <= 0 or now - last["t"] > PROMPT_STALE_S):
return None
if now - max(state.get("wrote", 0.0), admit["t"]) < PROMPT_IDLE_S:
return None
if state.get("solo_wrote", float("-inf")) >= admit["t"]:
return None # it wrote its first token: what stalls now is no prompt
others = state.get("others", 0)
if others and last["used"] <= max(2 * others, others + PROMPT_OTHER_MARGIN):
return None # the one request left may be one of the others
total = admit["tokens"]
held = min(last["used"], int(total * 0.99))
share = held / total
elapsed = now - admit["t"] # at least PROMPT_IDLE_S, by the test above
left = None
# held past 99 %, the share stands still at its cap and a floor read off it would not shrink:
# it said 23 s through the last 20 s of that run
if not state.get("shared") and share >= PROMPT_MIN_SHARE and last["used"] < total * 0.99:
# the request's own curve: its first point past a tenth of the prompt, and now
first = next(((t, u) for t, u in state.get("points", ()) if u >= PROMPT_MIN_SHARE * total), None)
k = 1.0
if first is not None and first[0] > admit["t"] and held >= 1.2 * first[1]:
low = first[1] - state.get("quantum", 0)
if low > 0:
k = (math.log((elapsed + PROMPT_READ_S) / (first[0] - admit["t"] + PROMPT_READ_S))
/ math.log(held / low))
k = min(2.0, max(1.0, k))
left = math.floor(elapsed * ((total / held) ** k - 1)) # a floor rounds down
return {"tokens": total, "held": held, "share": round(share, 3), "elapsed": round(elapsed),
"left_min_s": left}
# ── 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")
# Role 8 of the proxy (v6.48): a tool call whose arguments name a host of Cohere's report, said
# with its host family and its tool, never its arguments (docs/agents-and-network.md). Read with
# journalctl -o short-unix, so each line starts with its time; a peer comes before the words.
# A named client's peer carries its key label too, as on every line of its request (_KEY above):
# without it, the lines of the clients the identity wall names never matched (found in review).
# Anchored on the journal's own header (time, host, process): a client's text the proxy logs
# (a dropped schema pattern) could hold a second "[proxy] x TOOL TARGET ..." that a looser
# pattern counted (found in review).
TOOL_TARGET_RE = re.compile(r"^(\d+(?:\.\d+)?) \S+ [^\s:]+: \[proxy\] \S+" + _KEY
+ r" TOOL TARGET (.+?) in an? (\S+) call on (\S+),")
def parse_tool_targets(raw: str, since: float = 0.0) -> dict:
"""journalctl -o short-unix lines -> how many tool calls named a host of Cohere's report from
`since` on, and the newest one: its time, hosts, tool and route."""
out = {"count": 0, "last": None}
for ln in raw.splitlines():
m = TOOL_TARGET_RE.search(ln)
if not m or float(m.group(1)) < since:
continue
out["count"] += 1
at = float(m.group(1))
if out["last"] is None or at >= out["last"]["at"]:
out["last"] = {"at": at, "hosts": m.group(2), "tool": m.group(3), "path": m.group(4)}
return out
# Role 9 of the proxy (v6.49, issue #61): a long prompt its client left without an answer, sent
# again. Its line says after how long, how many times in a row, the client's name from its
# User-Agent, and what widens that client's timeout (docs/clients.md). Anchored as TOOL_TARGET_RE.
RESENT_RE = re.compile(r"^(\d+(?:\.\d+)?) \S+ [^\s:]+: \[proxy\] \S+" + _KEY
+ r" RESENT the prompt its client left without an answer after (\d+) s "
+ r"\((\d+) times? in a row, ([^)]{1,80})\): (.{1,400})$")
def parse_resent(raw: str, since: float = 0.0) -> dict:
"""journalctl -o short-unix lines -> how many long prompts were sent again after their client
left them, from `since` on, and the newest: its time, the wait, the count in a row, the client
and the proxy's advice."""
out = {"count": 0, "last": None}
for ln in raw.splitlines():
m = RESENT_RE.search(ln)
if not m or float(m.group(1)) < since:
continue
out["count"] += 1
at = float(m.group(1))
if out["last"] is None or at >= out["last"]["at"]:
out["last"] = {"at": at, "secs": int(m.group(2)), "n": int(m.group(3)), "who": m.group(4),
"advice": m.group(5)}
return out
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",
"qwen38-kolibri.service": "kolibri", "qwen38-nemotron.service": "nemotron",
"qwen38-nemotron-super.service": "nemotron-super",
"qwen38-flash-local.service": "flash-local", "qwen38-ornith-122b.service": "ornith-122b",
"qwen38-flash-unsloth.service": "flash-unsloth", "qwen38-lfm25.service": "lfm25",
"qwen38-lfm3.service": "lfm3", "qwen38-inkling.service": "inkling"}
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}"