Compare commits

...
Author SHA1 Message Date
01994b8168 fix: misc dashboard improvs (#3374)
## Summary

- refresh live metrics and trace rows on the same five-second cadence
- better `no data yet` for unavailable overview data
- show episode and trace errors at the bottom of the trace viewer
- add the task key as `task ID` to the identity section of the trace
overview pane
- use `n/a` for missing value uniformly; some spots showed an en dash.
- allow filter from trace viewer

## Verification

### Overview empty state

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 54 20
PM"
src="https://github.com/user-attachments/assets/02e06087-5286-435e-9776-52ec9502f7f5"
/>

### Errors

<img width="1608" height="1045" alt="Screenshot 2026-08-24 at 3 52 29
PM"
src="https://github.com/user-attachments/assets/b39a28cc-c50d-467c-b7f7-39c354a5e008"
/>

### Task ID

<img width="318" height="151" alt="Screenshot 2026-08-24 at 3 52 42 PM"
src="https://github.com/user-attachments/assets/f12f50b5-685d-4ca5-8b80-5c89877cab43"
/>

### Checks

- `node --check src/prime_rl/dashboard/static/app.js`
- `git diff --check`
- dashboard browser smoke against `outputs/reverse-text-rl`
- live append browser repro for metrics, trace rows, and new trace steps
- fake inference URL eval and browser layout check with a full traceback
- headless browser render of a synthetic `ProviderError` episode:
collapsed and expanded traceback, `task ID` row, consistent `n/a`
placeholders, red-marked error rows in the sidebar

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Frontend-only dashboard static assets; no API or training-path
changes. Risk is limited to UI regressions in metrics/traces polling and
the trace modal.
> 
> **Overview**
> This PR tightens **live updates** and **trace UX** in the static
dashboard (`app.js`, `index.html`, `style.css`).
> 
> **Polling & loading:** Poll interval moves to **5s**; metrics and
traces refresh when switching tabs with live on, on tab visibility, and
when re-enabling live. Metrics streaming stops retrying the same offset
when a partial JSONL line sits at EOF; `fetching` guards avoid
overlapping metrics/trace loads.
> 
> **Traces:** Step selection **follows the latest preferred step** while
you’re on the tail (historical picks and an open modal stay put). Empty
trace/metrics states use shorter labels and the episode table keeps its
chrome with an in-table empty row to avoid layout shift. Overview panels
show **“no data yet”** for configured eval sections before data lands.
> 
> **Trace viewer:** Episode/trace **errors render as banners** at the
bottom of the message column (with expandable tracebacks); **task ID**
appears in the identity pane. The modal gets the same
**filter/sort/env/errors** controls as the traces tab, synced through
shared state. Error episodes are highlighted in the sidebar list.
> 
> **Polish:** Missing numeric/overview fields use **`n/a`** instead of
en dashes (empty eval env list still shows **–**). Run overview merges
the full run record from the runs list on refresh.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
239dc7797d996fb0b17badb9dd60b640474b431d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 16:11:11 -07:00
e6b5e4de5d feat: auto-started dashboard daemon (#3371)
## Summary

- Launchers (`rl`, `sft`) register their output dir in
`~/.cache/prime-rl/dashboard/dirs.json` and make sure one dashboard
serves it (`ensure_dashboard` in the new `entrypoints/dashboard.py`,
kept free of `dashboard`-extra imports). Every dashboard instance serves
its CLI dirs **plus** the registry, re-read live — a run in a new output
dir appears on the one live URL without a restart: one dashboard per
host per user.
- Discovery goes through `daemon.json` (pid + **actual** url), so it
survives port spillover — nothing ever probes port 7788. A live daemon's
URL is logged (`Dashboard running at <url>`); interactive sessions spawn
a detached daemon (own session — killing a run never takes it down) when
none is live (`Dashboard started at <url>`); non-tty launches (CI,
nohup) only register. A stale claim from a dead process is taken over on
the next start.
- `--isolated` is the escape hatch: serve only the given dirs, no
registry read/write, no discovery claim (launchers ignore the instance).
`dashboard: bool = True` on RL/SFT opts a run out via `--no-dashboard`.
- The daemon carries the process title `PRL::Dashboard` via the shared
`set_proc_title`. `psutil` is promoted from transitive to a core
dependency so `prime_rl.utils.process` imports in the slim GPU-free env.
- Launcher startup now ends with a `Dashboard · <url>` banner (blank
lines around, green url) as the last log, after `Launcher complete` (was
`Startup complete. Showing ... logs`). The launcher no longer tails
orchestrator/trainer logs into its terminal - the dashboard is the
monitoring surface.
- New `skills/dashboard/SKILL.md` teaches agents discovery, liveness
checks, and kill/restart commands; `monitor-run` and `start-run` skills
point at it.

Supersedes #3368, rebuilt on the (now merged) stack #3369 (PRL prefix) →
#3370 (GPU extra; the server is a normal package member, so no
setproctitle fallback and no duplicated cache-dir logic); targets
`main`.

## Verification

E2E on this box: daemon claims `daemon.json` with pid + url and shows
`PRL::Dashboard` in `ps`; `ensure_dashboard` from a second process
registers a fresh output dir and the live dashboard absorbs it (run
count grows without restart); a second instance spills to port 7789 and
does **not** steal the claim; `--isolated` serves only its dirs and
leaves the registry untouched; a pty-spawned launcher starts a detached
daemon that survives the launcher's exit; slim `uv sync --extra
dashboard` env (no torch/vllm) imports `entrypoints.dashboard`,
`dashboard.server`, and `set_proc_title`, and `dashboard --help` works;
`tests/unit/test_configs.py` passes (122).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are local dev/monitoring UX and read-only dashboard serving;
training paths are unchanged aside from optional subprocess spawn and
registry file writes.
> 
> **Overview**
> **RL and SFT launchers** now register each run’s `output_dir` in a
per-user registry and ensure a single local dashboard serves it. New
`dashboard: bool = True` (disable with `--no-dashboard`) drives
`ensure_dashboard` in `entrypoints/dashboard.py`, which reuses a live
daemon via `~/.cache/prime-rl/dashboard/daemon.json` or spawns a
detached process in interactive TTY sessions only.
> 
> The **dashboard server** merges CLI dirs with `dirs.json` (live
re-read), claims/releases daemon discovery, adds **`--isolated`** to opt
out of the registry, and moves sidecar cache under the shared dashboard
state dir. The **`dashboard` console script** now enters through
`entrypoints.dashboard.main`.
> 
> **Launcher UX** drops `tail -F` on orchestrator/trainer logs; startup
ends with **Launcher complete** and a **Dashboard · url** banner.
**`psutil`** is a direct dependency so process titles work without the
GPU stack. Agent skills/docs describe discovery, liveness, and
kill/restart.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
035e7ec4c1a2671db778a85a42147d332a8a73ed. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 15:12:09 -07:00
15 changed files with 581 additions and 137 deletions
@@ -299,6 +299,10 @@ class RLConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. If None, runs locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
@@ -285,6 +285,10 @@ class SFTConfig(BaseConfig):
slurm: SlurmConfig | None = None
"""SLURM configuration. When set, the run is submitted as a SLURM job instead of running locally."""
dashboard: bool = True
"""Make sure a local dashboard daemon serves this run's output dir (started on
demand in interactive sessions; an already-running daemon's URL is logged)."""
dry_run: bool = False
"""Only validate and dump resolved configs, then exit early."""
+2 -1
View File
@@ -22,6 +22,7 @@ dependencies = [
"tenacity>=8.2.0",
"openai>=1.106.1",
"orjson>=3.11.0",
"psutil>=7.0.0",
"rich>=14.0.0",
"setproctitle>=1.3.0",
"uvloop>=0.21.0",
@@ -41,7 +42,7 @@ trainer = "prime_rl.entrypoints.trainer:main"
orchestrator = "prime_rl.entrypoints.orchestrator:main"
evals = "prime_rl.entrypoints.evals:main"
env-server = "prime_rl.entrypoints.env_server:main"
dashboard = "prime_rl.dashboard.server:main"
dashboard = "prime_rl.entrypoints.dashboard:main"
[project.entry-points."vllm.general_plugins"]
prime_rl = "prime_rl.inference.patches:apply_shared_vllm_patches"
+53
View File
@@ -0,0 +1,53 @@
---
name: dashboard
description: Find, start, use, and stop the local run dashboard — the web UI for run output dirs (metrics, configs, traces, logs). Use when asked for the dashboard URL, when a run needs watching in the browser, or when a dashboard must be restarted or killed.
---
# Run dashboard
`uv sync --extra dashboard && uv run dashboard [output_dir ...]` (default
`outputs/`) serves a web UI at `http://localhost:7788`. It only reads run
dirs — safe against live runs — and installs anywhere (cluster head node,
laptop against a mounted outputs dir): GPU dependencies live behind the
`gpu` extra.
Every dashboard instance serves the dirs it was started with **plus** every dir
in the per-user registry (`~/.cache/prime-rl/dashboard/dirs.json`, re-read
live). Launchers (`rl`, `sft`) register their output dir on every
start and, in interactive sessions, auto-start a dashboard only when none is
live — an already-running one absorbs the new dir automatically, whatever port
it is on. `--no-dashboard` opts a run out; non-interactive launches (CI, nohup)
register their dir but never spawn.
## Isolated mode
`--isolated` serves only the given dirs: no registry read or write, no
discovery claim, and launchers ignore the instance. Use it for focused views
(demos, debugging one run dir) or to keep a scratch dir out of the registry.
## Finding the live dashboard
The live port can differ from 7788 (a taken port bumps to the next free one),
so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
curl -sf $(jq -r .url ~/.cache/prime-rl/dashboard/daemon.json)/api/runs > /dev/null && echo live
ps aux | grep PRL::Dashboard # process title
```
Hand the researcher the `url` from `daemon.json`. Launcher logs also print it:
startup ends with a `Dashboard · <url>` banner. The auto-started instance logs
to `~/.cache/prime-rl/dashboard/daemon.log`.
## Stopping / restarting
```bash
kill $(jq -r .pid ~/.cache/prime-rl/dashboard/daemon.json) # the discovered instance
pkill -f PRL::Dashboard # every dashboard on the host
```
A clean exit releases `daemon.json`; a stale file from a dead process is taken
over by the next start. Killing a dashboard never affects runs (it only reads),
and killing a run never takes the dashboard down (it runs in its own session).
Restart by launching any run, or directly: `uv run dashboard`.
+12
View File
@@ -64,6 +64,18 @@ free one, so several dashboards run side by side without coordination. GPU deps
behind the `gpu` extra, so `uv sync --extra dashboard && uv run dashboard` works
without the training stack (e.g. on a head node).
**Daemon (auto-start)**: launchers auto-start one dashboard per host per user and a
live one absorbs each new run's output dir automatically — see the `dashboard` skill
for discovery, kill/restart commands, and `--isolated`. The short version: the live
port can differ from 7788 (a taken port bumps), so read the discovery file:
```bash
cat ~/.cache/prime-rl/dashboard/daemon.json # {"pid": ..., "url": "http://localhost:<actual port>"}
ps aux | grep PRL::Dashboard # the daemon's process title
```
Verify liveness with `curl -sf <url>/api/runs` and hand the researcher the `url`.
### Logs
```
+9
View File
@@ -139,3 +139,12 @@ env.agent.runtime.type = "subprocess"
- `packages/prime-rl-configs/src/prime_rl/configs/` — all config classes
- `configs/debug/` — minimal debug configs
- `examples/` — full example configs (e.g. `reverse-text/`)
## Dashboard
Interactive launches auto-start one shared dashboard daemon per user (process title
`PRL::Dashboard`) and end startup with a `Dashboard · <url>` banner. Relay
that URL to the researcher. Discovery: `~/.cache/prime-rl/dashboard/daemon.json` holds
the live `url` (the port can differ from 7788 when it was taken). `--no-dashboard`
opts a run out.
+5 -1
View File
@@ -2,7 +2,11 @@
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, component logs) at
http://localhost:7788. Needs the `dashboard` extra.
http://localhost:7788. Needs the `dashboard` extra. Every instance also serves
the dirs registered by launchers in `~/.cache/prime-rl/dashboard/dirs.json`
(one dashboard per host per user); `--isolated` serves only the given dirs and
skips the registry. See `skills/dashboard/SKILL.md` for discovery and
kill/restart commands.
GPU dependencies live behind the `gpu` extra, so this works anywhere — a
cluster head node, a laptop against a mounted outputs dir:
+100 -7
View File
@@ -12,6 +12,7 @@ Multiple output directories can be tracked at once.
import argparse
import hashlib
import os
import sys
import threading
import time
@@ -20,7 +21,8 @@ from pathlib import Path
import orjson
from prime_rl.utils.pathing import CACHE_DIR
from prime_rl.entrypoints.dashboard import DAEMON_FILE, DIRS_FILE, STATE_DIR, registry_lock
from prime_rl.utils.process import set_proc_title
try:
import uvicorn
@@ -76,10 +78,61 @@ def is_run_dir(path: Path) -> bool:
return any((path / marker).exists() for marker in ("configs", "logs", "metrics.jsonl", "rollouts"))
_dirs_file_state: tuple[float, list[Path]] = (0.0, [])
def registered_dirs() -> list[Path]:
"""Output dirs registered in dirs.json (by launchers and by every dashboard's
own CLI dirs), re-read when the file changes so a run in a new output dir
appears on the one live dashboard without a restart."""
global _dirs_file_state
try:
mtime = DIRS_FILE.stat().st_mtime
except OSError:
return []
if mtime != _dirs_file_state[0]:
try:
dirs = [Path(d) for d in orjson.loads(DIRS_FILE.read_bytes())]
except (OSError, ValueError):
dirs = []
_dirs_file_state = (mtime, dirs)
return _dirs_file_state[1]
def register_dirs(dirs: list[Path]) -> None:
"""Add dirs to the shared registry (idempotent, atomic)."""
with registry_lock():
try:
known = list(orjson.loads(DIRS_FILE.read_bytes()))
except (OSError, ValueError):
known = []
fresh = [str(d.resolve()) for d in dirs if str(d.resolve()) not in known]
if not fresh:
return
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_bytes(orjson.dumps(known + fresh))
tmp.replace(DIRS_FILE)
isolated = False
def tracked_dirs() -> list[Path]:
"""One dashboard per user serves everything: the dirs it was started with
plus every dir any launcher (or other dashboard start) has registered.
--isolated opts out: only the CLI dirs, no registry."""
dirs = list(output_dirs)
if isolated:
return dirs
known = {d.resolve() for d in dirs}
dirs.extend(d for d in registered_dirs() if d.resolve() not in known and d.is_dir())
return dirs
def scan_runs() -> dict[str, Path]:
global _run_registry
by_name: dict[str, list[Path]] = {}
for base in output_dirs:
for base in tracked_dirs():
if not base.is_dir():
continue
for run_dir in sorted(base.iterdir()):
@@ -602,7 +655,7 @@ def episode_summaries(path: Path) -> list[dict]:
# Parsing a step's traces file for the table can mean reading gigabytes; the
# result is persisted outside the run dir (the dashboard never writes there),
# so a revisit — or a dashboard restart — skips the parse entirely.
SIDECAR_DIR = CACHE_DIR / "dashboard"
SIDECAR_DIR = STATE_DIR
SIDECAR_WRITE_INTERVAL_S = 20.0
_sidecar_written: dict[Path, tuple[float, int]] = {} # path -> (last write time, count)
@@ -784,7 +837,7 @@ def render_status(url: str):
text.append(" · ", style="dim")
text.append(url + "\n", style="underline #B6FF3C")
runs = scan_runs()
for base in output_dirs:
for base in tracked_dirs():
text.append(f"\n {base.resolve()}/\n", style="dim")
names = sorted(name for name, run_dir in runs.items() if run_dir.parent == base) or ["(no runs yet)"]
for i, name in enumerate(names):
@@ -808,23 +861,61 @@ def free_port(host: str, start: int) -> int:
raise SystemExit(f"no free port in [{start}, {start + 100})")
def claim_daemon(url: str) -> bool:
"""Record this process as THE dashboard daemon (pid + actual url, port
spillover included) so launchers can find it instead of starting another."""
with registry_lock():
existing = read_json(DAEMON_FILE)
if existing.get("pid") and existing.get("pid") != os.getpid():
try:
os.kill(existing["pid"], 0)
print(f"another dashboard daemon is already running at {existing.get('url')}", file=sys.stderr)
return False
except OSError:
pass # stale file from a dead daemon
tmp = DAEMON_FILE.with_suffix(".tmp")
tmp.write_bytes(orjson.dumps({"pid": os.getpid(), "url": url, "started": time.time()}))
tmp.replace(DAEMON_FILE)
return True
def release_daemon() -> None:
with registry_lock():
if read_json(DAEMON_FILE).get("pid") == os.getpid():
DAEMON_FILE.unlink(missing_ok=True)
def main() -> None:
global output_dirs
global output_dirs, isolated
parser = argparse.ArgumentParser(description="prime-rl run dashboard")
parser.add_argument("output_dirs", nargs="*", default=[Path("outputs")], type=Path, metavar="output_dir")
parser.add_argument("--port", type=int, default=7788)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument(
"--isolated",
action="store_true",
help="serve only the given dirs: don't join the per-user registry, don't remember "
"these dirs, and don't claim discovery (launchers will ignore this instance)",
)
args = parser.parse_args()
isolated = args.isolated
output_dirs = [d for d in args.output_dirs if d.is_dir()]
for missing in set(args.output_dirs) - set(output_dirs):
print(f"warning: output dir {missing} does not exist", file=sys.stderr)
if not output_dirs:
raise SystemExit("no existing output dir given")
if not isolated:
# this instance's dirs join the per-user registry, and it serves the union -
# one dashboard per host per user covers every run
register_dirs(output_dirs)
if not tracked_dirs():
raise SystemExit("no existing output dir given" + ("" if isolated else " (and none registered)"))
set_proc_title("Dashboard")
port = free_port(args.host, args.port)
if port != args.port:
print(f"port {args.port} is taken - serving on {port}", file=sys.stderr)
args.port = port
url = f"http://localhost:{args.port}"
# first non-isolated instance owns discovery; extras and --isolated still serve
claimed = False if isolated else claim_daemon(url)
live = None
stop = threading.Event()
if sys.stdout.isatty():
@@ -853,6 +944,8 @@ def main() -> None:
stop.set()
if live is not None:
live.stop()
if claimed:
release_daemon()
if __name__ == "__main__":
+170 -96
View File
@@ -12,7 +12,7 @@ const api = async (path) => {
/* accent-first line palette, then the prime-context chart palette */
const PALETTE = ["#b6ff3c", "#b7a6fa", "#78f8a5", "#fcdaa4", "#4a9eff", "#ff6b4a", "#bcbcbc"];
const SINGLE_SERIES = "#b6ff3c";
const POLL_MS = 3000;
const POLL_MS = 5000;
const prefs = JSON.parse(localStorage.getItem("prl-dash") || "{}");
const state = {
@@ -49,7 +49,7 @@ const state = {
};
function fmtNum(v) {
if (v == null || Number.isNaN(v)) return "–";
if (v == null || Number.isNaN(v)) return "n/a";
if (v === 0) return "0";
const abs = Math.abs(v);
if (abs >= 1e6 || abs < 1e-3) return v.toExponential(2);
@@ -57,10 +57,10 @@ function fmtNum(v) {
if (Number.isInteger(v)) return String(v);
return v.toPrecision(4).replace(/(\.\d*?)0+$/, "$1").replace(/\.$/, "");
}
const fmtReward = (v) => (v == null || Number.isNaN(v) ? "–" : v.toFixed(3));
const fmtReward = (v) => (v == null || Number.isNaN(v) ? "n/a" : v.toFixed(3));
/* compact human counts that never overflow: 1.1K, 2.2M, 3.3B */
function fmtCompact(n) {
if (n == null || Number.isNaN(n)) return "–";
if (n == null || Number.isNaN(n)) return "n/a";
const abs = Math.abs(n);
if (abs >= 1e9) return `${+(n / 1e9).toFixed(abs >= 1e10 ? 0 : 1)}B`;
if (abs >= 1e6) return `${+(n / 1e6).toFixed(abs >= 1e7 ? 0 : 1)}M`;
@@ -68,7 +68,7 @@ function fmtCompact(n) {
return String(n);
}
function fmtCost(v) {
if (v == null || Number.isNaN(v)) return "–";
if (v == null || Number.isNaN(v)) return "n/a";
return `$${v >= 1 ? v.toFixed(2) : v.toFixed(4)}`;
}
@@ -120,7 +120,7 @@ async function loadRuns() {
syncDressedSelects();
const fresh = state.runs.find((r) => r.name === current);
if (fresh && state.meta) {
Object.assign(state.meta, { updated: fresh.updated, started: fresh.started, last_step: fresh.last_step });
Object.assign(state.meta, fresh);
renderOverview();
}
}
@@ -167,9 +167,8 @@ function applyRunTypeControls() {
$("#trace-subset").hidden = isEval;
$("#tm-step-prev").hidden = isEval;
$("#tm-step-next").hidden = isEval;
$("#tm-kind").hidden = isEval || state.meta?.type === "sft";
$("#tm-subset").hidden = isEval;
$(".tm-filterhead").hidden = isEval;
$("#tm-kind-row").hidden = isEval || state.meta?.type === "sft";
$("#tm-subset-row").hidden = isEval;
}
async function selectRun(name) {
@@ -181,14 +180,18 @@ async function selectRun(name) {
state.meta = state.runs.find((r) => r.name === name) ?? (await api(`/api/runs/${encodeURIComponent(name)}`));
state.metrics = {
...state.metrics,
loaded: false, offset: 0, byKey: new Map(), charts: [], renderedKeys: -1,
loaded: false, fetching: false, offset: 0, byKey: new Map(), charts: [], renderedKeys: -1,
timeKeys: new Set(), timeZero: null, maxStep: null,
evalEtag: null, evalCount: 0, evalCost: null,
};
if (state.meta?.type === "eval") fetchEvalSeries(); // populates the overview cost early
state.config = { loaded: false, files: [], file: null, fmt: state.config.fmt, cache: new Map() };
state.logs = { ...state.logs, loaded: false, attempt: "latest", files: [], paneFile: {}, maximized: null, buffers: new Map() };
state.traces = { ...state.traces, loaded: false, steps: [], step: null, env: "", episodes: [], etag: null, kind: "train", subset: state.traces.preferred };
state.traces = {
...state.traces,
loaded: false, fetching: false, steps: [], step: null, env: "", episodes: [], etag: null,
kind: "train", subset: state.traces.preferred,
};
applyRunTypeControls();
renderOverview();
renderCompareMenu();
@@ -197,7 +200,7 @@ async function selectRun(name) {
}
function fmtDuration(secs) {
if (secs == null || !isFinite(secs) || secs < 0) return "–";
if (secs == null || !isFinite(secs) || secs < 0) return "n/a";
const d = Math.floor(secs / 86400);
const h = Math.floor((secs % 86400) / 3600);
const m = Math.floor((secs % 3600) / 60);
@@ -211,7 +214,7 @@ function fmtDuration(secs) {
}
function fmtAgo(ts) {
if (!ts) return "–";
if (!ts) return "n/a";
const secs = Date.now() / 1000 - ts;
if (secs < 90) return "just now";
if (secs < 3600) return `${Math.round(secs / 60)} min ago`;
@@ -233,8 +236,8 @@ function runStatus(step) {
/* unbounded env lists: show the first two, fold the rest into "+N" (full list
in the tooltip) */
function envListField(envs) {
if (!envs?.length) return `<span class="val">–</span>`;
function envListField(envs, empty = "n/a") {
if (!envs?.length) return `<span class="val">${empty}</span>`;
const display = envs.length > 2 ? `${envs.slice(0, 2).join(", ")} +${envs.length - 2}` : envs.join(", ");
return `<span class="val" title="${esc(envs.join(", "))}">${esc(display)}</span>`;
}
@@ -250,7 +253,7 @@ function renderOverview() {
const step = currentStep();
const status = runStatus(step);
const durationEnd = status === "running" ? Date.now() / 1000 : meta.updated;
const duration = meta.started && durationEnd ? fmtDuration(durationEnd - meta.started) : "–";
const duration = meta.started && durationEnd ? fmtDuration(durationEnd - meta.started) : "n/a";
const field = ([label, value]) => `<div class="ov-field"><span class="lbl">${label}</span>${value}</div>`;
// rollout dirs can run one step past max_steps (the final ship drains late
// arrivals), so the headline caps at the configured horizon
@@ -258,18 +261,19 @@ function renderOverview() {
const stepText = `${shownStep != null ? shownStep.toLocaleString() : "–"}/${meta.max_steps ? meta.max_steps.toLocaleString() : "∞"}`;
const left = [
["status", `<span class="badge st-${status}">${status}</span>`],
["type", `<span class="val">${esc((meta.type ?? "–").toUpperCase())}</span>`],
["type", `<span class="val">${esc((meta.type ?? "n/a").toUpperCase())}</span>`],
meta.type === "eval"
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "–"}</span>`]
? ["episodes", `<span class="val">${step != null ? step.toLocaleString() : "n/a"}</span>`]
: ["step", `<span class="val">${stepText}</span>`],
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "–")}</span>`],
["model", `<span class="val" title="${esc(meta.model ?? "")}">${esc(meta.model ?? "n/a")}</span>`],
...(meta.type === "eval"
? [["env", `<span class="val" title="${esc(meta.env ?? "")}">${esc(meta.env ?? "–")}</span>`]]
? [["env", `<span class="val" title="${esc(meta.env ?? "")}">${esc(meta.env ?? "n/a")}</span>`]]
: [
meta.type === "sft"
? ["dataset", `<span class="val" title="${esc(meta.dataset ?? "")}">${esc(meta.dataset ?? "–")}</span>`]
? ["dataset", `<span class="val" title="${esc(meta.dataset ?? "")}">${esc(meta.dataset ?? "n/a")}</span>`]
: ["train envs", envListField(meta.train_envs)],
["eval envs", envListField(meta.eval_envs)],
// an empty eval env list is a known "none", not missing data
["eval envs", envListField(meta.eval_envs, "–")],
]),
];
const right = [
@@ -297,10 +301,16 @@ async function activateTab(tab, force = false) {
setActive("#tabs", "tab", tab);
document.querySelectorAll("main > section").forEach((s) => (s.hidden = s.id !== `tab-${tab}`));
updateHash();
if (tab === "metrics" && !state.metrics.loaded) await initMetrics();
if (tab === "metrics") {
if (!state.metrics.loaded) await initMetrics();
else if (state.live) await fetchMetrics();
}
if (tab === "config" && !state.config.loaded) await initConfig();
if (tab === "logs" && !state.logs.loaded) await initLogs();
if (tab === "traces" && !state.traces.loaded) await initTraces();
if (tab === "traces") {
if (!state.traces.loaded) await initTraces();
else if (state.live) await refreshTraces();
}
}
/* ---------------------------------------------------------------- metrics */
@@ -384,6 +394,7 @@ async function fetchMetrics() {
let showedProgress = false;
try {
for (let first = true; ; first = false) {
const requestedOffset = m.offset;
const [data, compared] = await Promise.all([
api(`/api/runs/${encodeURIComponent(state.run)}/metrics?offset=${m.offset}`),
first ? fetchCompares() : false,
@@ -400,7 +411,9 @@ async function fetchMetrics() {
if (m.byKey.size !== m.renderedKeys) renderMetricsBody();
else updateCharts(compared ? null : touched); // compares may touch any panel
}
if (data.offset >= (data.size ?? data.offset)) break;
// A writer can leave one incomplete JSONL record at EOF. Wait for the
// next poll instead of repeatedly requesting the same partial record.
if (data.offset >= (data.size ?? data.offset) || data.offset === requestedOffset) break;
showedProgress = true;
$("#metrics-status").textContent = `loading metrics · ${Math.round((data.offset / data.size) * 100)}%`;
}
@@ -464,7 +477,7 @@ function renderEvalCards(body) {
);
}
const fmtVal = (key, v) => {
if (v == null) return "–";
if (v == null) return "n/a";
if (key === "cost") return fmtCost(v);
if (key.startsWith("timing/")) return fmtDuration(v);
if (key.endsWith("tokens")) return fmtCompact(Math.round(v));
@@ -1107,7 +1120,7 @@ function renderMetricsBody() {
if (state.meta?.type === "eval") return renderEvalCards(body);
activeFilter = makeFilter(state.metrics.search.trim());
if (!state.meta?.has_metrics && !m.byKey.size) {
body.innerHTML = emptyState("no metrics", "this run has no metrics.jsonl yet");
body.innerHTML = emptyState("no metrics yet");
$("#metrics-status").textContent = "";
return;
}
@@ -1121,7 +1134,7 @@ function renderMetricsBody() {
}
if (!grid.children.length) {
// a configured eval env stays visible before its first eval fires
if (section.configured && !activeFilter) grid.innerHTML = `<div class="chart-empty">no eval data yet</div>`;
if (section.configured && !activeFilter) grid.innerHTML = `<div class="chart-empty">no data yet</div>`;
else div.remove();
} else applyPaneOrder(grid);
}
@@ -1726,28 +1739,27 @@ async function initLogs() {
async function loadRollouts() {
const traces = state.traces;
const previousTarget = latestPreferredStep(traces.steps, traces.kind, traces.preferred);
const wasFollowing = traces.step == null || traces.step === previousTarget?.step;
const data = await api(`/api/runs/${encodeURIComponent(state.run)}/rollouts`);
traces.steps = data.steps;
if (traces.step == null && data.steps.length) {
// default to the newest step that already shipped the preferred subset —
// the newest step is usually in-flight with only "all" (no advantages yet)
const preferred = traces.preferred;
const newestFirst = [...data.steps].reverse();
const shipped =
newestFirst.find((s) => s.available[`${traces.kind}/${preferred}`]) ??
newestFirst.find((s) => Object.keys(s.available).some((k) => k.endsWith(`/${preferred}`)));
traces.step = (shipped ?? data.steps[data.steps.length - 1]).step;
adjustKindSubset();
} else if (traces.step != null) {
// the preferred subset may have shipped since the last poll (a live step's
// effective file lands late) — re-adjust and reload when it changes
const before = `${traces.kind}/${traces.subset}`;
adjustKindSubset();
if (`${traces.kind}/${traces.subset}` !== before) await loadEpisodes();
}
const target = latestPreferredStep(data.steps, traces.kind, traces.preferred);
// Follow new work while the user is on the latest preferred step. Keep a
// manually selected historical step stable, especially while its modal is open.
if (target && wasFollowing && $("#trace-modal").hidden) traces.step = target.step;
adjustKindSubset();
renderStepControl();
}
function latestPreferredStep(steps, kind, preferred) {
const newestFirst = [...steps].reverse();
return (
newestFirst.find((s) => s.available[`${kind}/${preferred}`]) ??
newestFirst.find((s) => Object.keys(s.available).some((key) => key.endsWith(`/${preferred}`))) ??
newestFirst[0]
);
}
function stepInfo(step) {
return state.traces.steps.find((s) => s.step === step);
}
@@ -1793,6 +1805,7 @@ function renderStepControl() {
` title="${title}${hasEval ? " · eval" : ""}"></span>`
);
}
if (!cells.length) cells.push(`<span class="sb-cell placeholder"></span>`);
const signature = cells.join("");
if (signature === traces.stepControlSignature) return;
traces.stepControlSignature = signature;
@@ -1803,7 +1816,7 @@ function renderStepControl() {
const hasEval = info && (info.available["eval/all"] || info.available["eval/effective"]);
$("#step-label").innerHTML =
traces.step == null
? ""
? `<span class="muted">no steps yet</span>`
: `step ${traces.step}${steps.length > 1 ? `<span class="muted">/${steps[steps.length - 1].step}</span>` : ""}` +
(hasEval ? ' <span class="eval-dot" title="eval rollouts"></span>' : "");
}
@@ -1817,19 +1830,18 @@ function selectStepByIndex(index) {
loadEpisodes();
}
// the table chrome stays in place; the message renders as a spanning row so
// arriving traces cause no layout shift
function showTraceEmpty(title, detail) {
$("#episode-table-wrap").hidden = true;
const el = $("#trace-empty");
el.hidden = false;
el.innerHTML = emptyState(title, detail);
$("#episode-table tbody").innerHTML = `<tr class="empty"><td colspan="10">${emptyState(title, detail)}</td></tr>`;
}
async function loadEpisodes() {
const traces = state.traces;
updateTraceFilterBtn();
syncTraceFilterControls();
if (traces.step == null) {
$("#trace-status").textContent = "";
showTraceEmpty("no traces", "this run has no saved traces yet");
showTraceEmpty("no traces yet");
return;
}
const qs = new URLSearchParams({ sort: traces.sort, order: traces.order, errors_only: traces.errorsOnly });
@@ -1851,13 +1863,12 @@ async function loadEpisodes() {
traces.etag = data.etag;
traces.etagKey = etagKey;
traces.episodes = data.episodes;
$("#trace-empty").hidden = true;
$("#episode-table-wrap").hidden = false;
const envSel = $("#trace-env");
const currentEnv = traces.env;
envSel.innerHTML =
`<option value="">all envs</option>` +
data.envs.map((e) => `<option value="${esc(e)}" ${e === currentEnv ? "selected" : ""}>${esc(e)}</option>`).join("");
for (const sel of ["#trace-env", "#tm-env"])
$(sel).innerHTML =
`<option value="">all envs</option>` +
data.envs.map((e) => `<option value="${esc(e)}" ${e === currentEnv ? "selected" : ""}>${esc(e)}</option>`).join("");
syncDressedSelects();
if (!data.total) {
$("#trace-status").textContent = "";
showTraceEmpty("no episodes", "nothing matches the current filters");
@@ -1914,9 +1925,20 @@ function renderEpisodeRows(reset = false) {
async function initTraces() {
state.traces.loaded = true;
await loadRollouts();
adjustKindSubset();
await loadEpisodes();
await refreshTraces();
}
async function refreshTraces() {
const traces = state.traces;
if (traces.fetching) return;
traces.fetching = true;
try {
await loadRollouts();
if (state.traces !== traces) return;
await loadEpisodes();
} finally {
traces.fetching = false;
}
}
/* ----------------------------------------------------------- episode view */
@@ -1946,7 +1968,7 @@ function filteredRollouts() {
function tmItemHtml(e) {
return (
`<div class="tm-item ${e.line === currentLine ? "active" : ""}" data-line="${e.line}">` +
`<div class="tm-item ${e.line === currentLine ? "active" : ""}${e.num_errors || !e.ok ? " err" : ""}" data-line="${e.line}">` +
`<span class="tm-num">#${e.line}</span><span class="tm-env muted" title="${esc(e.env ?? "")}">${esc(e.env ?? "")}</span>` +
`<span class="tm-reward ${rewardClass(e.reward)}">${fmtReward(e.reward)}</span></div>`
);
@@ -2185,11 +2207,40 @@ function reasoningBlock(content) {
let entriesObserver = null;
function renderMessages(trace, branches) {
function episodeErrors(ep, trace) {
return [...(ep.errors || []), ...(trace?.errors || [])];
}
function errorBannersHtml(errors) {
if (!errors.length) return "";
return (
`<div class="trace-errors">` +
errors
.map((error) => {
const record = error && typeof error === "object" ? error : { message: String(error) };
const type = record.type ?? "Error";
const message = record.message ?? "No error message";
const traceback = Array.isArray(record.traceback) ? record.traceback.join("") : record.traceback;
return (
`<section class="trace-error-banner">` +
`<div class="trace-error-message"><span class="trace-error-type">${esc(type)}</span> ${esc(message)}</div>` +
(traceback
? `<details class="trace-error-tb"><summary><span>traceback</span><span class="entry-chev">›</span></summary><pre>${esc(traceback)}</pre></details>`
: "") +
`</section>`
);
})
.join("") +
`</div>`
);
}
function renderMessages(ep, trace, branches) {
const container = $("#tm-messages");
entriesObserver?.disconnect();
const errorsHtml = errorBannersHtml(episodeErrors(ep, trace));
if (!trace) {
container.innerHTML = emptyState("no traces", "this episode carries no trace data");
container.innerHTML = emptyState("no traces", "this episode carries no trace data") + errorsHtml;
return;
}
const signal = $("#token-signal").value;
@@ -2235,7 +2286,8 @@ function renderMessages(trace, branches) {
let rendered = Math.min(path.length, CHUNK);
container.innerHTML =
path.slice(0, rendered).map(entryHtml).join("") +
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "");
(rendered < path.length ? `<div id="tm-more" class="chart-empty">scroll for ${path.length - rendered} more entries</div>` : "") +
errorsHtml;
if (rendered < path.length) {
const sentinel = container.querySelector("#tm-more");
entriesObserver = new IntersectionObserver((hits) => {
@@ -2361,15 +2413,9 @@ function renderMeta(ep, trace, branches) {
parts.push(metaRow("episode ID", ep.id, true));
if (trace?.id) parts.push(metaRow("trace ID", trace.id, true));
if (ep.group?.id) parts.push(metaRow("group ID", ep.group.id, true));
if (ep.task?.key) parts.push(metaRow("task ID", ep.task.key, true));
if (trace?.agent?.runtime?.id) parts.push(metaRow("runtime ID", trace.agent.runtime.id, true));
const errors = [...(ep.errors || []), ...(trace?.errors || [])];
if (errors.length)
parts.push(
`<details class="meta-fold" open><summary>errors (${errors.length})</summary>` +
`<pre class="json">${esc(JSON.stringify(errors, null, 2))}</pre></details>`
);
$("#tm-meta").innerHTML = parts.join("");
}
@@ -2404,14 +2450,17 @@ function renderEpisode() {
: "";
$("#tm-tabs-row").hidden = traceTabs.hidden && branchTabs.hidden;
renderRolloutList();
renderMessages(trace, branches);
renderMessages(ep, trace, branches);
renderMeta(ep, trace, branches);
}
/* ---------------------------------------------------------------- wiring */
$("#run-select").addEventListener("change", (e) => selectRun(e.target.value));
$("#live-toggle").addEventListener("change", (e) => (state.live = e.target.checked));
$("#live-toggle").addEventListener("change", async (e) => {
state.live = e.target.checked;
if (state.live) await pollDashboard();
});
$("#compare-menu").addEventListener("change", (e) => {
const box = e.target.closest("[data-compare]");
if (box) toggleCompare(box.dataset.compare, box.checked);
@@ -2480,9 +2529,16 @@ function dressSelect(select) {
dressedSelects.add(select);
syncDressedSelects();
}
function updateTraceFilterBtn() {
/* the table and the trace viewer carry the same filter dropdown over one
shared state — a change in either view shows up in both */
function syncTraceFilterControls() {
const t = state.traces;
$("#trace-filter-btn").classList.toggle("active", !!(t.env || t.errorsOnly || t.sort !== "line"));
for (const sel of ["#trace-env", "#tm-env"]) $(sel).value = t.env;
for (const sel of ["#trace-sort", "#tm-sort"]) $(sel).value = `${t.sort}:${t.order}`;
for (const sel of ["#trace-errors", "#tm-errors"]) $(sel).checked = t.errorsOnly;
for (const sel of ["#trace-filter-btn", "#tm-filter-btn"])
$(sel).classList.toggle("active", !!(t.env || t.errorsOnly || t.sort !== "line"));
syncDressedSelects();
}
document.querySelectorAll("#tabs button").forEach((b) => b.addEventListener("click", () => activateTab(b.dataset.tab)));
@@ -2717,6 +2773,14 @@ async function setTraceSubset(subset, inModal = false) {
if (inModal) await reopenFirstEpisode();
}
/* filter changes keep the open viewer in sync: hold the current episode when
it survives the filter, land on the first one otherwise */
async function refreshModalList() {
if ($("#trace-modal").hidden) return;
if (filteredRollouts().some((e) => e.line === currentLine)) renderRolloutList();
else await reopenFirstEpisode();
}
/* after a filter change inside the viewer, land on the first episode of the
new subset (line numbers don't correspond across files) */
async function reopenFirstEpisode() {
@@ -2744,13 +2808,26 @@ for (const [sel, inModal] of [["#trace-subset", false], ["#tm-subset", true]])
setTraceSubset(b.dataset.subset, inModal);
})
);
$("#trace-env").addEventListener("change", (e) => { state.traces.env = e.target.value; loadEpisodes(); });
$("#trace-errors").addEventListener("change", (e) => { state.traces.errorsOnly = e.target.checked; loadEpisodes(); savePrefs(); });
$("#trace-sort").addEventListener("change", (e) => {
[state.traces.sort, state.traces.order] = e.target.value.split(":");
loadEpisodes();
savePrefs();
});
for (const sel of ["#trace-env", "#tm-env"])
$(sel).addEventListener("change", async (e) => {
state.traces.env = e.target.value;
await loadEpisodes();
await refreshModalList();
});
for (const sel of ["#trace-errors", "#tm-errors"])
$(sel).addEventListener("change", async (e) => {
state.traces.errorsOnly = e.target.checked;
await loadEpisodes();
savePrefs();
await refreshModalList();
});
for (const sel of ["#trace-sort", "#tm-sort"])
$(sel).addEventListener("change", async (e) => {
[state.traces.sort, state.traces.order] = e.target.value.split(":");
await loadEpisodes();
savePrefs();
await refreshModalList();
});
$("#episode-table").addEventListener("click", (e) => {
const row = e.target.closest("tr[data-line]");
if (row) openEpisode(+row.dataset.line);
@@ -2817,8 +2894,6 @@ $("#tm-list").addEventListener("click", (e) => {
const item = e.target.closest("[data-line]");
if (item) openEpisode(+item.dataset.line);
});
$("#tm-prev").addEventListener("click", () => stepRollout(-1));
$("#tm-next").addEventListener("click", () => stepRollout(1));
$("#tm-collapse").addEventListener("click", () =>
document.querySelectorAll("#tm-messages details.entry").forEach((d) => (d.open = false))
);
@@ -2885,12 +2960,10 @@ $("#smooth-range").addEventListener("input", (e) => {
savePrefs();
});
let tickCount = 0;
let ticking = false;
setInterval(async () => {
async function pollDashboard() {
if (!state.live || ticking) return;
ticking = true;
tickCount++;
try {
// keep the run list fresh so new runs register without a page refresh;
// it runs concurrently with the tab poll (they're independent requests)
@@ -2905,17 +2978,19 @@ setInterval(async () => {
syncDressedSelects();
if (state.tab === "metrics" && state.metrics.loaded) await fetchMetrics();
else if (state.tab === "logs" && state.logs.loaded) await pollLogs();
else if (state.tab === "traces" && state.traces.loaded) {
await loadRollouts();
if (tickCount % 5 === 0) await loadEpisodes();
}
else if (state.tab === "traces" && state.traces.loaded) await refreshTraces();
await runsRefresh;
} catch (err) {
console.warn("poll failed", err);
} finally {
ticking = false;
}
}, POLL_MS);
}
setInterval(pollDashboard, POLL_MS);
document.addEventListener("visibilitychange", () => {
if (!document.hidden) pollDashboard();
});
(async function init() {
$("#smooth-range").value = state.metrics.smooth;
@@ -2926,10 +3001,9 @@ setInterval(async () => {
$("#log-search").value = prefs.logSearch ?? "";
$("#config-search").value = prefs.configSearch ?? "";
$("#token-signal").value = prefs.tokenSignal ?? "";
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#attempt-select", "#token-signal"])
for (const sel of ["#run-select", "#trace-env", "#trace-sort", "#tm-env", "#tm-sort", "#attempt-select", "#token-signal"])
dressSelect($(sel));
$("#trace-sort").value = `${state.traces.sort}:${state.traces.order}`;
$("#trace-errors").checked = state.traces.errorsOnly;
syncTraceFilterControls();
setActive("#metrics-mode", "mode", state.metrics.mode);
setActive("#all-layout", "layout", state.metrics.allLayout);
$("#all-layout").hidden = state.metrics.mode !== "all";
+35 -15
View File
@@ -71,16 +71,6 @@
<span id="step-label" class="t-label"></span>
</div>
<div class="controls">
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
<div class="spacer"></div>
<div id="trace-filter-wrap" class="dd-wrap">
<button id="trace-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
@@ -102,8 +92,16 @@
<label class="toggle"><input type="checkbox" id="trace-errors"><span class="dot"></span>errors only</label>
</div>
</div>
<div class="seg" id="trace-kind">
<button data-kind="train" class="active">Train</button>
<button data-kind="eval">Eval</button>
</div>
<div class="seg" id="trace-subset">
<button data-subset="all">All</button>
<button data-subset="effective" class="active">Effective</button>
</div>
<span id="trace-status" class="muted"></span>
</div>
<div id="trace-empty" hidden></div>
<div id="episode-table-wrap">
<table id="episode-table">
<thead><tr>
@@ -147,11 +145,36 @@
<span id="tm-step-label"></span>
<button id="tm-step-next" class="btn tm-nav" title="next step">›</button>
</div>
<div class="tm-head tm-filterhead">
<div class="tm-head tm-ctlrow">
<div id="tm-filter-wrap" class="dd-wrap">
<button id="tm-filter-btn" class="btn dd-btn" title="filter &amp; sort">
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18l-7 8v6l-4-2v-4L3 5z"></path></svg>
filter
</button>
<div id="tm-filter-menu" class="dd-menu" hidden>
<label class="t-label">env</label>
<select id="tm-env"><option value="">all envs</option></select>
<label class="t-label">sort</label>
<select id="tm-sort">
<option value="line:asc">order: arrival</option>
<option value="reward:desc">reward ↓</option>
<option value="reward:asc">reward ↑</option>
<option value="advantage:desc">advantage ↓</option>
<option value="advantage:asc">advantage ↑</option>
<option value="output_tokens:desc">tokens ↓</option>
<option value="group:asc">group</option>
</select>
<label class="toggle"><input type="checkbox" id="tm-errors"><span class="dot"></span>errors only</label>
</div>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-kind-row">
<div class="seg" id="tm-kind">
<button data-kind="train">Train</button>
<button data-kind="eval">Eval</button>
</div>
</div>
<div class="tm-head tm-ctlrow" id="tm-subset-row">
<div class="seg" id="tm-subset">
<button data-subset="all">All</button>
<button data-subset="effective">Effective</button>
@@ -160,9 +183,6 @@
<div class="tm-head">
<span class="t-label">episodes</span>
<span id="tm-count" class="badge"></span>
<div class="spacer"></div>
<button id="tm-prev" class="btn tm-nav" title="previous episode">↑</button>
<button id="tm-next" class="btn tm-nav" title="next episode">↓</button>
</div>
<div id="tm-list"></div>
</aside>
+42 -3
View File
@@ -570,6 +570,8 @@ mark.hit {
#step-blocks { flex: 1; display: flex; gap: 2px; height: 16px; min-width: 0; margin-bottom: 4px; }
.sb-cell { position: relative; flex: 1; min-width: 0; background: var(--grey-2); border: 1px solid var(--hairline); cursor: pointer; }
.sb-cell:hover { border-color: var(--grey-6); }
.sb-cell.placeholder { cursor: default; }
.sb-cell.placeholder:hover { border-color: var(--hairline); }
.sb-cell.on { background: var(--accent); border-color: var(--accent); }
/* eval steps carry a small dot under the block (same mark as the step label) */
.sb-cell.eval::after {
@@ -613,6 +615,9 @@ mark.hit {
#episode-table td { padding: 5px 10px; border-bottom: 1px solid var(--hairline-faint); white-space: nowrap; }
#episode-table tbody tr { cursor: pointer; }
#episode-table tbody tr:hover { background: var(--grey-2); }
#episode-table tr.empty { cursor: default; }
#episode-table tr.empty:hover { background: none; }
#episode-table tr.empty td { border-bottom: 0; }
.r-pos { color: var(--positive); }
.r-neg { color: var(--negative); }
.r-zero { color: var(--grey-4); }
@@ -659,13 +664,14 @@ mark.hit {
.tm-item .tm-reward { flex-shrink: 0; }
.tm-item:hover { background: var(--grey-2); }
.tm-item.active { background: var(--grey-2); border-color: var(--grey-3); color: var(--grey-6); }
.tm-item.err { background: rgba(255, 69, 57, 0.08); border-color: var(--negative); }
.tm-item.err:hover, .tm-item.err.active { background: rgba(255, 69, 57, 0.16); }
.tm-item .tm-reward { margin-left: auto; }
.tm-nav { padding: 0 8px; height: 24px; }
.tm-stephead { justify-content: space-between; background: var(--grey-2); min-height: 40px; }
#step-label, #tm-step-label { white-space: nowrap; }
#tm-step-label { color: var(--grey-6); }
.tm-filterhead { gap: 8px; }
.tm-filterhead .seg button { height: 22px; padding: 0 9px; font-size: 10px; }
.tm-ctlrow { min-height: 0; padding: 8px 14px; }
#tm-step-label {
font-size: 11px;
letter-spacing: var(--track-caps);
@@ -678,10 +684,43 @@ mark.hit {
#tm-step-label .muted { text-transform: none; letter-spacing: var(--track-mono); }
#tm-main { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
#tm-messages { flex: 1; overflow-y: auto; padding: 14px 16px; }
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
.trace-errors { margin-top: auto; padding-top: 12px; }
.trace-error-banner {
border: 1px solid var(--negative);
background: rgba(255, 69, 57, 0.08);
color: var(--grey-6);
}
.trace-error-banner + .trace-error-banner { margin-top: 8px; }
.trace-error-message { padding: 10px 12px; font-size: 12px; white-space: pre-wrap; word-break: break-word; }
.trace-error-type { font-weight: 500; color: var(--negative); }
.trace-error-tb > summary {
display: flex;
align-items: center;
gap: 10px;
padding: 6px 12px;
border-top: 1px solid rgba(255, 69, 57, 0.2);
color: var(--grey-4);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.trace-error-tb > summary:hover { color: var(--grey-6); }
.trace-error-tb[open] .entry-chev { transform: rotate(90deg); }
.trace-error-tb > pre {
margin: 0;
padding: 10px 12px;
border-top: 1px solid rgba(255, 69, 57, 0.2);
color: var(--grey-5);
font: 400 11px/1.5 var(--font-mono);
white-space: pre-wrap;
word-break: break-word;
}
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry > summary {
+127
View File
@@ -0,0 +1,127 @@
"""Launcher-side dashboard auto-start.
Every launcher registers its output dir in a shared registry and makes sure one
dashboard is running: every dashboard instance serves its own dirs plus the
registry (re-read live), so each new run shows up on one URL - one dashboard
per host per user. If a live daemon already exists, its URL is reused instead
of starting another. Discovery goes through
``~/.cache/prime-rl/dashboard/daemon.json`` (pid + actual url), which survives
port spillover. The daemon also carries the process title ``PRL::Dashboard``.
Kept free of ``dashboard``-extra imports on purpose: the launcher must work
without the extra (then it registers the dir and points at the missing extra
instead of spawning). ``main`` is the ``dashboard`` console script, delegating
to the actual server.
"""
import fcntl
import importlib.util
import json
import os
import shutil
import subprocess
import sys
import time
import urllib.request
from contextlib import contextmanager
from pathlib import Path
from prime_rl.utils.pathing import CACHE_DIR
STATE_DIR = CACHE_DIR / "dashboard"
DAEMON_FILE = STATE_DIR / "daemon.json"
DIRS_FILE = STATE_DIR / "dirs.json"
DAEMON_LOG = STATE_DIR / "daemon.log"
SPAWN_TIMEOUT_S = 10.0
@contextmanager
def registry_lock():
"""Serialize read-modify-write cycles on the shared registry files: concurrent
launchers (or dashboard starts) must not drop each other's entries."""
STATE_DIR.mkdir(parents=True, exist_ok=True)
with open(STATE_DIR / ".lock", "w") as lock_file:
fcntl.flock(lock_file, fcntl.LOCK_EX)
yield
def register_output_dir(output_dir: Path) -> None:
"""Add the dir to the daemon's registry (idempotent, atomic)."""
with registry_lock():
try:
dirs = json.loads(DIRS_FILE.read_text())
except (OSError, ValueError):
dirs = []
entry = str(output_dir.resolve())
if entry in dirs:
return
dirs.append(entry)
tmp = DIRS_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(dirs))
tmp.replace(DIRS_FILE)
def find_daemon(timeout: float = 1.0) -> dict | None:
"""The live daemon's record ({pid, url, ...}), or None."""
try:
info = json.loads(DAEMON_FILE.read_text())
os.kill(info["pid"], 0)
except (OSError, ValueError, KeyError, TypeError):
return None
try:
with urllib.request.urlopen(f"{info['url']}/api/runs", timeout=timeout):
return info
except OSError:
return None
def ensure_dashboard(output_dir: Path, logger) -> str | None:
"""Register the run's output dir and make sure one dashboard daemon serves it.
Returns the dashboard URL (log it with ``log_dashboard_url``), or None when no
daemon could be found or started (missing extra, non-interactive session, or
startup failure).
"""
# The dir may not exist yet on a first run: create it up front, because the
# daemon only serves registered dirs that exist (and refuses to start with none).
output_dir.mkdir(parents=True, exist_ok=True)
register_output_dir(output_dir)
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if not sys.stdout.isatty():
logger.warning("Non-interactive session - not auto-starting a dashboard (the output dir stays registered)")
return None
# The console script exists even without the extra, so check the actual imports.
if importlib.util.find_spec("fastapi") is None or importlib.util.find_spec("uvicorn") is None:
logger.warning("Dashboard extra not installed - install with `uv sync --extra dashboard`")
return None
binary = shutil.which("dashboard")
if binary is None:
logger.warning("Dashboard entry point not found - install with `uv sync --extra dashboard`")
return None
with open(DAEMON_LOG, "ab") as log_file:
process = subprocess.Popen([binary], stdout=log_file, stderr=log_file, start_new_session=True)
deadline = time.monotonic() + SPAWN_TIMEOUT_S
while time.monotonic() < deadline:
daemon = find_daemon()
if daemon is not None:
return daemon["url"]
if process.poll() is not None:
break
time.sleep(0.25)
logger.warning(f"Dashboard daemon did not come up - see {DAEMON_LOG}")
return None
def log_dashboard_url(logger, url: str | None) -> None:
"""Banner pointing at the dashboard - meant as the launcher's last startup log."""
if url is None:
return
logger.opt(raw=True, colors=True).info(f"\n <b>Dashboard</b> · <green><u>{url}</u></green>\n\n")
def main() -> None:
from prime_rl.dashboard.server import main as server_main
server_main()
+8 -8
View File
@@ -14,6 +14,7 @@ from prime_rl.configs.algorithm import FrozenModelConfig
from prime_rl.configs.inference import VllmRouterConfig
from prime_rl.configs.orchestrator import EnvConfig
from prime_rl.configs.rl import RLConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.entrypoints.inference import vllm_overrides_fragment
from prime_rl.utils.config import cli, dump_resolved_config
from prime_rl.utils.logger import get_logger, setup_logger
@@ -129,6 +130,8 @@ def rl_local(config: RLConfig):
logger.success("Dry run complete. To start an RL run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
# Derive launcher-local GPU IDs from deployment config
gpu_offset = 0
num_infer_gpus = config.deployment.num_infer_gpus if config.inference is not None else 0
@@ -367,14 +370,8 @@ def rl_local(config: RLConfig):
monitor_thread.start()
monitor_threads.append(monitor_thread)
# Monitor all processes for failures
logger.success("Startup complete. Showing orchestrator logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'orchestrator.log'}'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Check for errors from monitor threads
while not (stop_events["orchestrator"].is_set() and stop_events["trainer"].is_set()):
@@ -604,6 +601,8 @@ def rl_slurm(config: RLConfig):
logger.success(f"Dry run complete. To submit manually:\n\n sbatch {script_path}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
logger.info(f"Submitting: sbatch {script_path}")
result = subprocess.run(["sbatch", str(script_path)], capture_output=True, text=True)
if result.returncode != 0:
@@ -611,6 +610,7 @@ def rl_slurm(config: RLConfig):
sys.exit(1)
logger.success(f"{result.stdout.strip()}\n\n{log_message}")
log_dashboard_url(logger, dashboard_url)
def rl(config: RLConfig):
+8 -6
View File
@@ -12,6 +12,7 @@ from prime_rl.configs.evals import EvalsConfig, OnlineConfig
from prime_rl.configs.orchestrator import EvalSourceConfig
from prime_rl.configs.sft import SFTConfig
from prime_rl.configs.shared import LogConfig
from prime_rl.entrypoints.dashboard import ensure_dashboard, log_dashboard_url
from prime_rl.utils.config import cli, dump_resolved_config, find_package_resource
from prime_rl.utils.logger import setup_logger
from prime_rl.utils.pathing import (
@@ -322,6 +323,8 @@ def sft_slurm(config: SFTConfig):
logger.success(f"Dry run complete. To submit manually:\n\n{submit}{note}\n\n{log_message}")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
submitted_job_ids: list[str] = []
for path in script_paths:
# --parsable prints ``<job_id>[;<cluster>]`` — the human-readable format varies
@@ -346,6 +349,7 @@ def sft_slurm(config: SFTConfig):
logger.success(f"Submitted batch job {job_id}")
logger.success(log_message)
log_dashboard_url(logger, dashboard_url)
def sft_local(config: SFTConfig):
@@ -368,6 +372,8 @@ def sft_local(config: SFTConfig):
logger.success("Dry run complete. To start an SFT run locally, remove --dry-run from your command.")
return
dashboard_url = ensure_dashboard(config.output_dir, logger) if config.dashboard else None
log_dir = create_attempt_log_dir(config.run_dir)
# Derive launcher-local GPU IDs (inference first, then the trainer) only when the
@@ -506,12 +512,8 @@ def sft_local(config: SFTConfig):
trainer_env["CUDA_VISIBLE_DEVICES"] = ",".join(map(str, trainer_gpu_ids))
trainer_process = start_process("trainer", trainer_cmd, env=trainer_env, log_path=log_dir / "trainer.log")
logger.success("Startup complete. Showing trainer logs...")
tail_process = Popen(
f"tail -F '{log_dir / 'trainer.log'}' | sed -u 's/^\\[[a-zA-Z]*[0-9]*\\]://'",
shell=True,
)
processes.append(tail_process)
logger.success("Launcher complete")
log_dashboard_url(logger, dashboard_url)
# Wait for the trainer (and the evals process, which drains its final evals after
# the trainer's last checkpoint) while surfacing any process failure.
Generated
+2
View File
@@ -4980,6 +4980,7 @@ dependencies = [
{ name = "prime" },
{ name = "prime-pydantic-config" },
{ name = "prime-rl-configs" },
{ name = "psutil" },
{ name = "pyarrow" },
{ name = "pybase64" },
{ name = "pyzmq" },
@@ -5139,6 +5140,7 @@ requires-dist = [
{ name = "prime-rl", extras = ["gpu"], marker = "extra == 'all'" },
{ name = "prime-rl", extras = ["quack"], marker = "extra == 'all'" },
{ name = "prime-rl-configs", editable = "packages/prime-rl-configs" },
{ name = "psutil", specifier = ">=7.0.0" },
{ name = "pyarrow", specifier = ">=21.0.0" },
{ name = "pybase64", specifier = ">=1.4.2" },
{ name = "pyzmq", specifier = ">=27.1.0" },