Compare commits

...
Author SHA1 Message Date
samsjaandGitHub ef9dea1781 chore(inference): introduce admin plane abstraction (#3472)
## Summary

- consolidate the inference control path into a single `AdminPlane`
abstraction over its worker HTTP clients
- make the static plane own readiness, NCCL setup, weight updates, and
lifecycle management
- expose one typed `update_weights` operation; each receiver identifies
its transport explicitly
- route filesystem, NCCL, and NIXL receivers through the admin plane
instead of passing raw HTTP client lists
- remove the separate admin-plane protocol, unused factory argument, and
pass-through weight-update wrapper

`InferenceClient` remains the data-plane client for generation and
scoring, while `AdminPlane` coordinates control operations against one
or more inference workers. Alternate backends can specialize a transport
operation without adding backend flags to weight receivers.

## Validation

- `uv run ruff check src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights tests/unit/orchestrator/test_clients.py`
- `uv run python -m compileall -q src/prime_rl/orchestrator/clients.py
src/prime_rl/orchestrator/orchestrator.py src/prime_rl/evals/evals.py
src/prime_rl/transports/weights`
- `uv run pytest -q tests/unit/orchestrator/test_clients.py` (10 passed)

The transport test module could not be collected on this host because
its optional CUDA import chain requires `flash_attn`.

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Refactors the weight-broadcast control path (pause/resume,
NCCL/NIXL/filesystem updates) used during training; behavior should be
equivalent but mistakes here can strand engines paused or desync policy
versions.
> 
> **Overview**
> Renames **`AdminClients`** to **`AdminPlane`** and makes it the single
control-plane entry point for inference workers (readiness, NCCL init,
weight updates, LoRA load, teardown).
> 
> **NCCL setup** and **weight updates** move from module-level helpers
into **`AdminPlane.initialize_nccl`** and
**`AdminPlane.update_weights`**, with callers passing an explicit
**`transport`** (`filesystem` | `nccl` | `nixl`). Orchestrator, evals,
and all **`WeightReceiver`** implementations now take an
**`AdminPlane`** instead of raw **`httpx`** client lists;
**`load_lora_adapter`** and **`init_nixl_broadcast`** follow the same
pattern.
> 
> Unit tests are updated and **`test_admin_plane_initializes_nccl`** is
added.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
65043370b7a9c857e6e3302f665b0b8c389043f1. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-03 16:36:16 -07:00
Konstantin DunasandGitHub 6c7b1ef375 feat: visualize compaction attempts and exclude rejected branches (#3478) 2026-09-03 22:09:41 +02:00
samsjaandGitHub 608c75c0af feat(dashboard): add timed terminal trace replay (#3456)
## Summary


https://github.com/user-attachments/assets/cd2caaa1-d700-40e5-8465-911812313f15

- add a terminal-style Replay view for rollout traces using recorded
model-call and tool timing
- add play/pause, seek, restart, 0.5x-32x speed controls, and an
inference-skipping tool-timing mode
- expose recorded model thinking with a toggle and T shortcut
- support Top/Live transcript navigation with Home/End shortcuts
- document replay timing semantics and extend dashboard smoke coverage

## Rebase notes

Rebased onto main (past #3444 overlays, #3465 chunked trace streams,
#3470 task/judge evidence, and #3455 semantic traces). Resolutions:

- `app.js` view state: trace viewer now has four modes — transcript,
timeline, replay, semantic; `setTraceView` keeps main's `persist` option
(replay is never persisted as a preference) and stops replay playback on
view switches; control visibility unions both sides (token-signal /
view-mode / collapse / expand hidden in graph, evidence, and replay
modes)
- `app.js` keyboard handler: replay T/Home/End shortcuts run first, then
main's step-bar arrow-key walking
- `app.js` click handler: replay control handlers first, then the
copy-button selector (including main's task/judge copy buttons)
- `index.html`: Replay button sits alongside main's Semantic button and
its episode-nav row
- `docs/training.md` / `skills/dashboard/SKILL.md`: describe all four
trace views together

## Validation

- `node --check src/prime_rl/dashboard/static/app.js` (rebased)
- `uv run --frozen ruff check tests/integration/dashboard_smoke.py`
(rebased)
- focused Playwright checks were run on the original branch (timed
playback, inference skipping, thinking toggles, keyboard shortcuts,
Top/Live navigation)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Read-only dashboard frontend and documentation; no changes to
training, inference, or data persistence.
> 
> **Overview**
> Adds a **Replay** tab to the rollout trace viewer that plays the
selected branch as a terminal session, using recorded model-call and
message timestamps for wall-clock pacing.
> 
> Playback includes play/pause, seek, restart, **0.5×–32×** speed
(default **8×**), **Skip inference** (instant model replies while
keeping tool delays), optional **Thinking** display (**T**), and **Top**
/ **Live** scroll follow (**Home** / **End**). Response text is revealed
evenly across each model-call span and labeled as inferred when
per-token timestamps are absent; prompt nodes committed at response time
are aligned to call start to avoid false idle gaps. Transcript-only
controls are hidden in Replay mode, and integration smoke tests cover
the new UI.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
fddf8349c2f99ec4ac658b6bbfacb2e8f24532c9. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
2026-09-02 16:50:33 -07:00
Konstantin DunasandGitHub b28714289a feat(dashboard): visualize semantic agent traces (#3455) 2026-09-03 01:33:18 +02:00
Konstantin DunasandGitHub 903baaaa01 fix(dashboard): hide repeated timeline rewards (#3473) 2026-09-03 00:51:31 +02:00
Konstantin DunasandGitHub ae170acda1 feat(dashboard): surface task and judge evidence (#3470) 2026-09-03 00:45:13 +02:00
24 changed files with 2712 additions and 194 deletions
+1 -1
+1 -1
View File
@@ -354,7 +354,7 @@ tail -F <run_dir>/logs/latest/inference/router.log # multi-node only
### Dashboard
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
`uv run dashboard [output_dir ...]` (default `outputs/`) serves a local web dashboard at `http://localhost:7788` with five views per run: metrics (the W&B overview sections, read from the file monitor's `metrics.jsonl`), the resolved configs, a rollout trace viewer with per-token overlays (advantage, entropy, trainer/sampling mismatch, IPO stable mask, loss and content masks), merged component logs, and markdown reports from `<run>/reports/`. The trace viewer separates the transcript, the wall-clock timeline of physical prefix branches, a wall-clock terminal replay of model and tool activity, and a top-to-bottom semantic graph of labeled model-call relationships. Replay uses recorded model-call and message timestamps; because providers do not persist per-token timestamps, it reveals response text evenly across the measured call span and labels that cadence as inferred. Agent and context labels in the semantic graph show the latest and peak prompt lengths first, with cumulative token processing available below on hover and click. It only reads the run dirs, so it is safe to point at a live run; pass several output directories to track parallel experiments. A taken port automatically bumps to the next free one, so several dashboards coexist on one node.
A coding agent on the same machine can drive the open dashboard: `POST /api/view` with an on-disk address (`{"run", "tab", "step", "kind", "subset", "episode", "highlight": [...]}`) navigates every connected tab there and paints quote-anchored highlights in the trace viewer. Reports cite traces with `[^id]` markers whose JSON definitions carry the same address plus a verbatim quote; the dashboard re-checks each quote against the trace files and marks the citation verified or broken, so answers stay grounded in what is actually on disk. The `dashboard` skill documents the full contract.
+36
View File
@@ -15,6 +15,42 @@ The Config and Logs views default to `latest (attempt <n>)`. Select an attempt
to inspect the immutable config or log files from an earlier launch. The Config
view shows a copyable launch command above the launch TOML or resolved JSON.
The trace viewer has separate **Transcript**, **Timeline**, **Replay**, and
**Semantic** views. Timeline is a wall-clock Gantt of physical prefix branches.
Replay renders the selected agent branch as a terminal session with play/pause,
seek, restart, and speed controls. It preserves recorded model-call and
tool-result delays. Since the trace schema records a complete model-call span
but no per-token timestamps, response text is paced evenly across that measured
span and labeled as inferred; events without timestamps remain ordered and are
labeled untimed. Semantic projects Verifiers `MessageNode.semantic_parents` as a
top-to-bottom causal graph of model calls, including subagent calls, returns,
compactions, and custom edge types. Calls occupy compact causal ranks within
bounded agent lanes: the root stays centered, concurrent children fan out
symmetrically, and child slots are reused after return, so graph width reflects
peak agent concurrency rather than total subagents. Compaction starts a visibly
separate context segment. For display only, a missing continuation is recovered
when the physical parent chain proves a completed tool round-trip; fragments
that still cannot be placed are shown explicitly as unlinked instead of being
presented as contexts. Hover or click an agent or context label to see its
latest and peak prompt lengths first, followed by cumulative token processing
and cost. Exact timing remains available on model-call hover and in Timeline.
Traces without semantic parents keep the other views and disable Semantic.
Replay defaults to 8× so long coding-agent model waits remain watchable; select
1× for exact wall time or up to 32× for faster review. In-flight calls display
their measured progress and recorded output-token usage even when they produce
only tool calls. Enable **Skip inference** to collapse model calls to immediate
responses while preserving the recorded command-to-tool-output delays. This is
distinct from the speed control, which scales every delay uniformly. Recorded
model thinking is shown by default. Toggle **Thinking** in the replay controls
or press **T** while Replay is open to hide or show it without changing playback
timing. Do not advertise Ctrl+T: browsers reserve it for a new tab before the
page can handle the keypress. Use **Top** or the **Home** key to scroll to the
beginning without pausing the replay. Use **Live** or **End** to resume
following newly rendered output. Prompt-context nodes that were committed at
response time are placed at the linked call's start so their serialization
timestamp does not create a false blank wait before the replay.
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
+20 -3
View File
@@ -3,9 +3,9 @@
`uv run dashboard [output_dir ...]` — a local web dashboard for run output
directories (metrics, resolved configs, rollout traces, cited reports,
component logs) at
http://localhost:7788. The trace viewer includes transcript and synchronized
agent timeline views; timeline activities open the corresponding transcript
call. Needs the `dashboard` extra. Every instance also serves
http://localhost:7788. The trace viewer includes transcript, synchronized
agent timeline, and terminal replay views; timeline activities open the
corresponding transcript call. 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,
@@ -30,6 +30,23 @@ truth, and the viewer reports when IDs, the renderer model, or its tokenizer
are unavailable. Text, advantage, logprob, mask, and content signals apply to
both views; Rendered with Text uses the exact full-sequence decode.
**Replay** plays the selected trace branch as a terminal session. Model
responses, tool commands, and tool results follow their recorded wall-clock
spans, with play/pause, seeking, restart, and speed controls. Providers persist
the full model-call span rather than timestamps for individual tokens, so text
is revealed evenly across that measured span and the UI labels the token cadence
as inferred. Replay defaults to 8× for long coding-agent waits while preserving
their relative timing; 1× restores exact wall time, and speeds up to 32× are
available. In-flight calls show measured progress and recorded output usage even
when the response contains only a tool call. Events from older traces without
timing stay in order and are marked untimed. Prompt context committed at response
time appears at the linked model call's start rather than creating a false blank
delay. **Skip inference** makes every model response immediate while retaining
the recorded delays between tool commands and their outputs. Recorded model
thinking is visible by default and can be toggled from the controls or with
**T** while Replay is open. **Top** (or **Home**) stops following the newest
line and scrolls to the beginning; **Live** (or **End**) resumes following output.
This package is fully AI-generated and maintained by agents - it is not meant to be read or edited by humans. Change it by asking an agent, and verify through the browser smoke tests.
The integration suite covers it end to end (`tests/integration/dashboard_smoke.py`
runs after every integration test).
+263 -1
View File
@@ -884,6 +884,7 @@ def activity_spans(
if reasoning_tokens is None:
reasoning_tokens = (usage.get("completion_tokens_details") or {}).get("reasoning_tokens")
text = " ".join(message_text(node.get("message") or {}).split())
mask = node.get("mask")
spans.append(
{
"kind": "model_call",
@@ -901,6 +902,7 @@ def activity_spans(
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"cost": usage.get("cost"),
"trainable": any(mask) if isinstance(mask, list) and mask else None,
}
)
return sorted(spans, key=lambda span: span["started_at"] if span["started_at"] is not None else float("inf"))
@@ -991,6 +993,7 @@ def timeline_lane(
"total_input_tokens": total_input_tokens,
"output_tokens": output_tokens,
"reasoning_tokens": reasoning_tokens,
"latest_context_tokens": context_lengths[-1] if context_lengths else None,
"max_context_tokens": max(context_lengths, default=None),
"total_tokens": total_tokens,
"cost": total("cost"),
@@ -999,8 +1002,254 @@ def timeline_lane(
}
def trace_semantic_edges(trace: dict, trace_index: int) -> list[dict]:
"""Resolve persisted ``MessageNode.semantic_parents`` into timeline edges."""
nodes = trace.get("nodes") or []
call_order = {
node_index: call_index
for call_index, call in enumerate(trace.get("calls") or [])
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
call_nodes = set(call_order)
edges = []
for target_node, node in enumerate(nodes):
if target_node not in call_nodes:
continue
for link in node.get("semantic_parents") or []:
source_node = link.get("node")
edge_type = link.get("type")
if source_node not in call_nodes or not isinstance(edge_type, str):
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": edge_type,
}
)
if not edges:
return []
incoming = {edge["target_node"] for edge in edges}
for target_node in sorted(call_nodes - incoming, key=call_order.get):
source_node = physical_continuation_source(nodes, call_nodes, target_node)
if source_node is None or call_order[source_node] >= call_order[target_node]:
continue
edges.append(
{
"trace_index": trace_index,
"source_node": source_node,
"target_node": target_node,
"type": "continuation",
"inferred": True,
}
)
return edges
def physical_continuation_source(nodes: list[dict], call_nodes: set[int], target_node: int) -> int | None:
"""Recover a missing continuation only from a completed tool round-trip."""
between = []
visited = {target_node}
cursor = nodes[target_node].get("parent")
while isinstance(cursor, int) and 0 <= cursor < len(nodes) and cursor not in visited:
if cursor in call_nodes:
source_node = cursor
break
visited.add(cursor)
between.append(cursor)
cursor = nodes[cursor].get("parent")
else:
return None
source_message = nodes[source_node].get("message") or {}
tool_call_ids = {
tool_call.get("id")
for tool_call in source_message.get("tool_calls") or []
if isinstance(tool_call, dict) and isinstance(tool_call.get("id"), str)
}
if not tool_call_ids or not between:
return None
for node_index in between:
message = nodes[node_index].get("message") or {}
if message.get("role") != "tool" or message.get("tool_call_id") not in tool_call_ids:
return None
return source_node
def semantic_context_lanes(
trace: dict,
trace_index: int,
role: str,
edges: list[dict],
) -> list[dict]:
"""Project continuation components as execution-context timeline lanes.
``continuation`` keeps calls in one context. ``subagent_call`` creates a child
agent, ``compaction_attempt`` creates a summary leaf beside its source context,
and ``compaction`` starts a new context for the same agent. Other edge labels
remain visible but do not invent session semantics.
"""
nodes = trace.get("nodes") or []
call_nodes = {
node_index
for call in trace.get("calls") or []
if isinstance((node_index := call.get("node")), int) and 0 <= node_index < len(nodes)
}
if not call_nodes or not edges:
return []
representatives = {node_index: node_index for node_index in call_nodes}
def find(node_index: int) -> int:
while representatives[node_index] != node_index:
representatives[node_index] = representatives[representatives[node_index]]
node_index = representatives[node_index]
return node_index
def union(left: int, right: int) -> None:
left_root = find(left)
right_root = find(right)
if left_root != right_root:
representatives[right_root] = left_root
for edge in edges:
if edge["type"] == "continuation":
union(edge["source_node"], edge["target_node"])
components: dict[int, set[int]] = {}
for node_index in call_nodes:
components.setdefault(find(node_index), set()).add(node_index)
component_for = {
node_index: component for component, node_indexes in components.items() for node_index in node_indexes
}
component_activities = {
component: activity_spans(trace, node_indexes) for component, node_indexes in components.items()
}
def component_start(component: int) -> float:
activities = component_activities[component]
starts = [span["started_at"] for span in activities if span["started_at"] is not None]
timestamps = [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
]
return min(starts or timestamps, default=float("inf"))
ordered_components = sorted(components, key=lambda component: (component_start(component), component))
cross_edges = [edge for edge in edges if component_for[edge["source_node"]] != component_for[edge["target_node"]]]
created_components = {
component_for[edge["target_node"]]
for edge in cross_edges
if edge["type"] in {"subagent_call", "compaction_attempt", "compaction"}
}
root_components = [component for component in ordered_components if component not in created_components]
# component -> (agent label, depth, context index)
identities: dict[int, tuple[str, int, int]] = {}
unlinked_components = set()
if root_components:
identities[root_components[0]] = (role, 0, 0)
for index, component in enumerate(root_components[1:], start=1):
identities[component] = (f"unlinked {index}", 0, 0)
unlinked_components.add(component)
subagent_number = 0
changed = True
while changed:
changed = False
for edge in cross_edges:
source = component_for[edge["source_node"]]
target = component_for[edge["target_node"]]
if source not in identities or target in identities:
continue
agent_label, depth, context_index = identities[source]
if edge["type"] == "subagent_call":
subagent_number += 1
identities[target] = (f"subagent {subagent_number}", depth + 1, 0)
elif edge["type"] == "compaction_attempt":
identities[target] = (agent_label, depth, context_index)
elif edge["type"] == "compaction":
identities[target] = (agent_label, depth, context_index + 1)
else:
continue
changed = True
unlinked_index = len(unlinked_components)
for component in ordered_components:
if component not in identities:
unlinked_index += 1
identities[component] = (f"unlinked {unlinked_index}", 0, 0)
unlinked_components.add(component)
lanes = []
accepted_attempt_nodes = {edge["source_node"] for edge in cross_edges if edge["type"] == "compaction"}
attempt_by_component = {
component_for[edge["target_node"]]: {
"source_node": edge["source_node"],
"target_node": edge["target_node"],
"accepted": edge["target_node"] in accepted_attempt_nodes,
}
for edge in cross_edges
if edge["type"] == "compaction_attempt"
}
for component in ordered_components:
agent_label, depth, context_index = identities[component]
activities = component_activities[component]
start = component_start(component)
end = max(
[span["ended_at"] for span in activities if span.get("ended_at") is not None]
+ [
nodes[node_index].get("timestamp")
for node_index in components[component]
if nodes[node_index].get("timestamp") is not None
],
default=None,
)
completed = bool(trace.get("is_completed"))
label = f"{agent_label} · context {context_index}"
lifecycle = (
[
{
"kind": "agent",
"label": label,
"track": "lifecycle",
"started_at": start,
"ended_at": end if completed else None,
"status": "completed" if completed else "running",
}
]
if start != float("inf")
else []
)
lane = timeline_lane(
trace,
trace_index,
label=label,
depth=depth + 1,
branch=True,
lifecycle=lifecycle,
activities=activities,
)
lane["context"] = {
"agent": agent_label,
"index": context_index,
}
if component in unlinked_components:
lane["context"]["unlinked"] = True
if component in attempt_by_component:
lane["compaction_attempt"] = attempt_by_component[component]
lanes.append(lane)
return lanes
def project_episode_timeline(episode: dict) -> dict:
lane_groups = []
semantic_lane_groups = []
semantic_edges = []
for trace_index, trace in enumerate(episode.get("traces") or []):
nodes = trace.get("nodes") or []
branch_paths = branch_node_paths(nodes)
@@ -1085,9 +1334,22 @@ def project_episode_timeline(episode: dict) -> dict:
)
branches.sort(key=lambda item: (item[0] if item[0] is not None else float("inf"), item[1]))
lane_groups.append((parent, [lane for _, _, lane in branches]))
trace_edges = trace_semantic_edges(trace, trace_index)
semantic_lanes = semantic_context_lanes(trace, trace_index, role, trace_edges)
if semantic_lanes:
semantic_lane_groups.append((parent, semantic_lanes))
semantic_edges.extend(trace_edges)
lane_groups.sort(key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf"))
lanes = [lane for parent, children in lane_groups for lane in (parent, *children)]
return {"lanes": lanes}
semantic_lane_groups.sort(
key=lambda group: group[0]["started_at"] if group[0]["started_at"] is not None else float("inf")
)
semantic_lanes = [lane for parent, children in semantic_lane_groups for lane in (parent, *children)]
return {
"lanes": lanes,
"semantic_lanes": semantic_lanes,
"semantic_edges": semantic_edges,
}
NICE_BINS = [1, 2, 5, 10, 15, 30, 60, 120, 300, 600, 900, 1800, 3600, 7200, 10800, 21600, 43200, 86400]
File diff suppressed because it is too large Load Diff
+16
View File
@@ -232,6 +232,13 @@
<div class="seg" id="tm-view">
<button data-view="transcript" class="active">Transcript</button>
<button data-view="timeline">Timeline</button>
<button data-view="replay">Replay</button>
<button data-view="semantic">Semantic</button>
</div>
<div id="tm-semantic-nav" class="tm-semantic-nav" hidden>
<button id="tm-episode-prev" class="btn tm-nav" title="previous episode">‹</button>
<span id="tm-episode-label"></span>
<button id="tm-episode-next" class="btn tm-nav" title="next episode">›</button>
</div>
<div class="spacer"></div>
<div class="seg" id="trace-view-mode">
@@ -254,9 +261,18 @@
<div class="tm-head tm-tabs-row" id="tm-tabs-row" hidden>
<div id="tm-trace-tabs" class="seg" hidden></div>
<div id="tm-branch-tabs" class="seg" hidden></div>
<div id="tm-evidence-tabs" class="seg" hidden></div>
</div>
<div id="tm-messages"></div>
<div id="tm-timeline" hidden></div>
<aside id="sg-inspector" hidden>
<div class="sg-inspector-head">
<span id="sg-inspector-title">Model call</span>
<button id="sg-inspector-close" class="btn" title="close inspector">✕</button>
</div>
<div id="sg-inspector-body"></div>
<button id="sg-open-transcript" class="btn">open in transcript</button>
</aside>
</section>
<aside id="tm-right">
<div class="tm-head"><span class="tm-title">Overview</span></div>
+415 -4
View File
@@ -680,6 +680,10 @@ mark.hit {
display: grid;
grid-template-columns: 280px minmax(0, 1fr) 320px;
}
#trace-modal.semantic-view { grid-template-columns: minmax(0, 1fr); }
#trace-modal.semantic-view #tm-left,
#trace-modal.semantic-view #tm-right { display: none; }
#trace-modal.semantic-view #tm-main { grid-column: 1; position: relative; }
.tm-head {
display: flex;
align-items: center;
@@ -694,7 +698,19 @@ mark.hit {
overflow-y: hidden;
scrollbar-width: thin;
}
#tm-evidence-tabs [data-evidence="task"].active { color: var(--chart-3); }
#tm-evidence-tabs [data-evidence="judge"].active { color: #7adfff; }
#tm-evidence-tabs { margin-left: auto; }
.tm-title { font-size: 12px; font-weight: 500; color: var(--grey-6); white-space: nowrap; }
.tm-semantic-nav { display: flex; align-items: center; gap: 7px; min-width: 0; }
#tm-episode-label {
max-width: 260px;
overflow: hidden;
color: var(--grey-5);
font-size: 10.5px;
text-overflow: ellipsis;
white-space: nowrap;
}
#tm-left { border-right: 1px solid var(--hairline); display: flex; flex-direction: column; min-height: 0; }
#tm-left .search { margin: 10px 14px 6px; }
#tm-list { flex: 1; overflow-y: auto; padding: 4px 8px 10px; }
@@ -738,11 +754,39 @@ mark.hit {
#tm-messages { display: flex; flex: 1; flex-direction: column; overflow-y: auto; padding: 14px 16px; }
#tm-messages > * { flex-shrink: 0; }
#tm-timeline { flex: 1; min-height: 0; overflow: auto; padding: 14px 16px 24px; }
#tm-timeline.semantic-canvas { padding: 0; background: var(--grey-1); }
#tm-right { border-left: 1px solid var(--hairline); overflow-y: auto; min-height: 0; }
#tm-meta { padding: 12px 14px; }
/* episode timeline: lifecycle spans above exact model-call activity */
.tl-shell { min-width: 780px; border: 1px solid var(--hairline); }
.tl-shell { position: relative; min-width: 780px; border: 1px solid var(--hairline); }
.tl-edge-legend {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 14px;
min-height: 34px;
padding: 7px 10px;
border-bottom: 1px solid var(--hairline);
color: var(--grey-4);
font-size: 9px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.tl-edge-legend-title { color: var(--grey-5); }
.tl-edge-key { color: var(--grey-5); white-space: nowrap; }
.tl-edge-key i {
display: inline-block;
width: 18px;
margin-right: 6px;
vertical-align: 3px;
border-top: 2px solid var(--grey-4);
}
.tl-edge-key i.subagent-call { border-color: var(--infra); }
.tl-edge-key i.subagent-return { border-color: var(--risk); }
.tl-edge-key i.compaction-attempt { border-color: var(--chart-2); border-top-style: dotted; }
.tl-edge-key i.compaction { border-color: var(--chart-2); border-top-style: dashed; }
.tl-edge-key i.custom { border-color: var(--accent); border-top-style: dotted; }
.tl-head, .tl-lane {
display: grid;
grid-template-columns: minmax(160px, 220px) minmax(390px, 1fr) 105px 150px;
@@ -773,7 +817,7 @@ mark.hit {
.tl-label-meta { color: var(--grey-4); font-size: 9.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tl-track { position: relative; height: 42px; margin: 11px 0; border: 1px solid var(--hairline); overflow: hidden; }
.tl-gridline { position: absolute; top: 0; bottom: 0; border-left: 1px solid var(--hairline-faint); pointer-events: none; }
.tl-span { position: absolute; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span { position: absolute; z-index: 2; min-width: 3px; cursor: pointer; border: 0; padding: 0; }
.tl-span.lifecycle { top: 7px; height: 13px; opacity: 0.78; }
.tl-span.activity { top: 28px; height: 6px; background: var(--grey-4); }
.tl-span.activity.shared { opacity: 0.28; }
@@ -787,11 +831,10 @@ mark.hit {
.tl-time { color: var(--grey-5); font-size: 11px; }
.tl-time .muted { display: block; font-size: 9.5px; }
.tl-outcome { display: flex; flex-direction: column; align-items: flex-start; gap: 5px; font-size: 9.5px; }
.tl-state, .tl-reward { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state { border: 1px solid var(--grey-3); padding: 1px 5px; white-space: nowrap; }
.tl-state.completed { color: var(--positive); }
.tl-state.failed { color: var(--negative); }
.tl-state.running { color: var(--infra); }
.tl-reward { color: var(--chart-3); }
.tl-tooltip {
position: fixed;
z-index: 60;
@@ -809,6 +852,221 @@ mark.hit {
.tl-tooltip dd { color: var(--grey-6); margin: 0; }
.tl-tooltip-hint { color: var(--grey-4); border-top: 1px solid var(--hairline); margin-top: 9px; padding-top: 7px; font-size: 9.5px; }
/* Semantic view: ordinal causal flow down the page. Agent identities occupy
reusable concurrency slots, so width reflects peak fan-out rather than the
total number of children created over a rollout. */
.semantic-canvas > .tl-edge-legend {
position: sticky;
top: 0;
left: 0;
z-index: 9;
width: max-content;
min-width: 100%;
box-sizing: border-box;
background: var(--grey-1);
font-size: 11px;
}
.sg-shell {
position: relative;
min-width: 100%;
overflow: clip;
background: var(--grey-1);
}
.sg-lane-band {
position: absolute;
inset-block: 0;
z-index: 0;
border-inline: 1px solid rgba(255, 255, 255, 0.035);
background: rgba(255, 255, 255, 0.009);
pointer-events: none;
}
.sg-lane-band.root {
border-inline-color: rgba(182, 255, 60, 0.07);
background: rgba(182, 255, 60, 0.012);
}
.sg-edge-layer { position: absolute; inset: 0; z-index: 1; pointer-events: none; overflow: visible; }
.sg-lifeline {
fill: none;
stroke: var(--lane-color);
stroke-width: 1.5;
vector-effect: non-scaling-stroke;
opacity: 0.38;
}
.sg-edge {
fill: none;
stroke: var(--grey-4);
stroke-width: 1.4;
stroke-linecap: round;
stroke-linejoin: round;
vector-effect: non-scaling-stroke;
opacity: 0.68;
}
.sg-edge.continuation { opacity: 0.34; }
.sg-edge.subagent-call { stroke: var(--infra); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.subagent-return { stroke: var(--risk); stroke-width: 2.2; opacity: 0.9; }
.sg-edge.compaction-attempt { stroke: var(--chart-2); stroke-dasharray: 2 4; opacity: 0.66; }
.sg-edge.compaction { stroke: var(--chart-2); stroke-dasharray: 5 4; opacity: 0.9; }
.sg-edge.custom { stroke: var(--accent); stroke-dasharray: 2 4; opacity: 0.9; }
#sg-arrow-continuation path { fill: var(--grey-4); }
#sg-arrow-subagent-call path { fill: var(--infra); }
#sg-arrow-subagent-return path { fill: var(--risk); }
#sg-arrow-compaction-attempt path { fill: var(--chart-2); }
#sg-arrow-compaction path { fill: var(--chart-2); }
#sg-arrow-custom path { fill: var(--accent); }
.sg-agent-label {
position: absolute;
z-index: 6;
display: flex;
flex-direction: column;
align-items: center;
gap: 1px;
padding: 2px 6px;
background: var(--grey-1);
pointer-events: none;
white-space: nowrap;
}
.sg-agent-label.unlinked {
outline: 1px dashed var(--grey-3);
}
.sg-agent-label.unlinked .sg-agent-name,
.sg-agent-label.unlinked .sg-context-name {
color: var(--grey-5);
}
.sg-agent-name,
.sg-context-name {
padding: 0;
border: 0;
background: transparent;
cursor: pointer;
font: inherit;
white-space: nowrap;
pointer-events: auto;
}
.sg-agent-name {
display: flex;
align-items: center;
gap: 6px;
color: var(--grey-6);
font-size: 15px;
font-weight: 600;
}
.sg-agent-name i { width: 8px; height: 8px; flex: none; }
.sg-context-name { color: var(--grey-5); font-size: 10.5px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-agent-label.compacted .sg-context-name { color: var(--chart-2); }
.sg-agent-name:hover,
.sg-agent-name:focus-visible,
.sg-context-name:hover,
.sg-context-name:focus-visible { color: var(--accent); outline: none; }
.sg-agent-name:focus-visible,
.sg-context-name:focus-visible { text-decoration: underline; text-underline-offset: 3px; }
.sg-agent-label.side-left { align-items: flex-end; text-align: right; }
.sg-agent-label.side-right { align-items: flex-start; text-align: left; }
.sg-turn {
position: absolute;
z-index: 3;
padding: 0;
border: 0;
background: transparent;
color: var(--grey-4);
cursor: pointer;
font: inherit;
outline: none;
}
.sg-turn-mark {
position: absolute;
left: 50%;
top: 50%;
width: var(--turn-mark-width, 44px);
height: var(--turn-mark-height, 12px);
background: var(--turn-color);
transform: translate(-50%, -50%);
transition: width 100ms ease, height 100ms ease, background 100ms ease;
}
.sg-turn-index {
position: absolute;
top: 50%;
left: calc(50% + var(--turn-label-offset, 31px));
color: var(--grey-5);
font-size: 12.5px;
transform: translateY(-50%);
white-space: nowrap;
}
.sg-turn:hover,
.sg-turn:focus-visible { z-index: 4; }
.sg-turn:hover .sg-turn-mark,
.sg-turn:focus-visible .sg-turn-mark {
width: calc(var(--turn-mark-width, 44px) + 6px);
height: calc(var(--turn-mark-height, 12px) + 2px);
background: var(--accent);
}
.sg-turn:focus-visible .sg-turn-mark { outline: 1px solid var(--grey-6); outline-offset: 2px; }
.sg-turn.compaction-attempt.accepted .sg-turn-mark {
outline: 1px solid var(--chart-2);
outline-offset: 2px;
}
.sg-turn.compaction-attempt.rejected .sg-turn-mark {
border: 1px dashed var(--chart-2);
background: var(--grey-1);
opacity: 0.72;
}
.sg-turn.compaction-attempt.rejected .sg-turn-index { color: var(--grey-4); }
.sg-turn.compaction-attempt.rejected:hover .sg-turn-mark,
.sg-turn.compaction-attempt.rejected:focus-visible .sg-turn-mark {
border-color: var(--grey-6);
background: var(--grey-2);
opacity: 1;
}
.sg-turn-run {
position: absolute;
z-index: 5;
padding: 0 7px;
border: 0;
border-block: 1px solid color-mix(in srgb, var(--turn-color) 56%, var(--grey-3));
background: var(--grey-1);
color: var(--grey-5);
cursor: pointer;
font: 10.5px/1 var(--font-mono);
letter-spacing: 0.04em;
white-space: nowrap;
}
.sg-turn-run.collapsed {
box-shadow: 0 0 0 4px var(--grey-1);
}
.sg-turn-run.expanded {
border: 1px dashed color-mix(in srgb, var(--turn-color) 45%, var(--grey-3));
color: var(--grey-4);
}
.sg-turn-run:hover,
.sg-turn-run:focus-visible {
color: var(--grey-6);
outline: none;
}
.sg-turn-run.collapsed:hover,
.sg-turn-run.collapsed:focus-visible { border-block-color: var(--turn-color); }
.sg-turn-run:focus-visible { box-shadow: 0 0 0 2px var(--grey-1), 0 0 0 3px var(--turn-color); }
#sg-inspector {
position: absolute;
top: 62px;
right: 14px;
bottom: 14px;
z-index: 20;
display: flex;
flex-direction: column;
width: min(330px, calc(100% - 28px));
border: 1px solid var(--grey-4);
background: rgba(25, 25, 25, 0.98);
}
.sg-inspector-head { display: flex; align-items: center; gap: 8px; min-height: 46px; padding: 0 12px; border-bottom: 1px solid var(--hairline); color: var(--grey-6); font-size: 11px; }
.sg-inspector-head button { margin-left: auto; }
#sg-inspector-body { flex: 1; min-height: 0; overflow-y: auto; padding: 4px 13px 14px; }
.sg-inspector-section { margin: 13px 0 6px; color: var(--accent); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
.sg-inspector-row { display: flex; gap: 12px; padding: 3px 0; font-size: 10.5px; }
.sg-inspector-row span { color: var(--grey-4); }
.sg-inspector-row strong { margin-left: auto; color: var(--grey-6); font-weight: 400; }
.sg-inspector-snippet { color: var(--grey-5); font-size: 10.5px; line-height: 1.5; white-space: pre-wrap; word-break: break-word; }
#sg-open-transcript { margin: 0 12px 12px; min-height: 30px; }
/* the banners lead the transcript, so they stand off the first entry */
.trace-errors { margin-top: auto; padding-top: 12px; margin-bottom: 14px; }
.trace-error-banner {
@@ -844,6 +1102,13 @@ mark.hit {
/* numbered collapsible message entries */
details.entry { border: 1px solid var(--hairline); margin-bottom: 8px; }
details.entry.semantic-origin {
border-color: var(--accent);
outline: 1px solid rgba(182, 255, 60, 0.55);
outline-offset: 2px;
scroll-margin-block: 80px;
}
details.entry.semantic-origin > summary { background: rgba(182, 255, 60, 0.08); }
details.entry > summary {
display: flex;
align-items: center;
@@ -915,6 +1180,80 @@ details.tool-definitions, .rendered-transcript {
margin-bottom: 12px;
background: rgba(183, 166, 250, 0.025);
}
.task-evidence {
border: 1px solid color-mix(in srgb, var(--chart-3) 42%, var(--grey-3));
margin-bottom: 12px;
background: color-mix(in srgb, var(--chart-3) 3%, transparent);
}
.task-evidence.standalone,
.judging-view .judging-divider { margin-top: 0; }
.task-evidence > summary {
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
padding: 7px 12px;
background: var(--grey-2);
}
.task-evidence .context-label { color: var(--chart-3); }
.task-evidence[open] > summary { border-bottom: 1px solid var(--hairline); }
.task-evidence[open] > summary .entry-chev { transform: rotate(90deg); }
.evidence-fields { display: grid; gap: 8px; padding: 10px 12px 12px; }
.evidence-field { min-width: 0; border: 1px solid var(--hairline); background: rgba(0, 0, 0, 0.08); }
.evidence-field > header {
display: flex;
align-items: center;
padding: 5px 9px;
border-bottom: 1px solid var(--hairline);
color: var(--chart-3);
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.evidence-field > header .icon-btn { margin-left: auto; }
.evidence-field > pre,
.judge-result > pre {
max-height: 360px;
margin: 0;
overflow: auto;
padding: 9px 11px;
color: var(--grey-5);
font: 400 11px/1.55 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.judging-divider {
display: flex;
align-items: center;
gap: 10px;
margin: 20px 0 8px;
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judging-divider::after { content: ""; flex: 1; height: 1px; background: var(--hairline); }
.judging-divider > :last-child { order: 2; color: var(--grey-4); }
.judge-entry { border-color: color-mix(in srgb, #7adfff 38%, var(--grey-3)); }
.judge-entry .entry-role { color: #7adfff; }
.judge-call-grid { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; padding: 10px 12px 12px; }
.judge-request,
.judge-result { min-width: 0; border: 1px solid var(--hairline); }
.judge-request > header,
.judge-result > header {
padding: 6px 10px;
border-bottom: 1px solid var(--hairline);
color: #7adfff;
font-size: 10px;
letter-spacing: var(--track-caps);
text-transform: uppercase;
}
.judge-result.parsed > header { color: var(--chart-2); }
.judge-message { display: grid; grid-template-columns: 72px minmax(0, 1fr); border-bottom: 1px solid var(--hairline-faint); }
.judge-message:last-child { border-bottom: 0; }
.judge-message > header { display: flex; gap: 8px; padding: 9px 10px; color: var(--grey-4); font-size: 10px; }
.judge-message > header strong { color: var(--grey-5); font-weight: 500; text-transform: uppercase; }
.judge-message > div { min-width: 0; padding: 9px 11px; border-left: 1px solid var(--hairline); color: var(--grey-5); font-size: 11.5px; white-space: pre-wrap; overflow-wrap: anywhere; }
details.tool-definitions > summary, details.rendered-transcript > summary,
details.tool-definition > summary {
display: flex;
@@ -978,6 +1317,78 @@ details.meta-fold > pre { margin: 0; border: none; border-top: 1px solid var(--h
word-break: break-word;
}
/* terminal replay follows the trace's wall clock; message text is revealed
across its recorded model-call span because providers do not persist per-token timestamps */
.replay-shell {
display: flex;
flex: 1 1 auto !important;
min-height: 420px;
flex-direction: column;
overflow: hidden;
border: 1px solid var(--grey-3);
background: #080b07;
}
.replay-bar, .replay-controls {
display: flex;
align-items: center;
gap: 10px;
min-height: 40px;
padding: 7px 12px;
border-bottom: 1px solid rgba(182, 255, 60, 0.12);
background: #0d110c;
}
.replay-lights { color: var(--grey-3); letter-spacing: 3px; font-size: 8px; }
.replay-title { color: var(--grey-6); font-size: 11px; }
.replay-bar .chip { margin-left: auto; }
.replay-controls .btn { min-width: 48px; }
#replay-top, #replay-live { min-width: 52px; }
#replay-top.active, #replay-live.active { color: var(--accent); border-color: rgba(182, 255, 60, 0.35); }
#replay-restart { min-width: 30px; }
#replay-progress { flex: 1; min-width: 80px; accent-color: var(--accent); }
#replay-time { color: var(--grey-4); font: 400 10.5px var(--font-mono); white-space: nowrap; }
.replay-skip { display: flex; align-items: center; gap: 5px; color: var(--grey-5); font-size: 10.5px; white-space: nowrap; }
.replay-skip input { accent-color: var(--accent); }
.replay-skip kbd { color: var(--grey-4); font: 400 8.5px var(--font-mono); border: 1px solid var(--grey-3); padding: 1px 3px; }
.replay-control-label { color: var(--grey-4); font-size: 9px; letter-spacing: var(--track-caps); text-transform: uppercase; }
#replay-speed {
border: 1px solid var(--grey-3);
background: var(--grey-1);
color: var(--grey-5);
font: 400 10.5px var(--font-mono);
padding: 4px 6px;
}
.replay-output-pane {
flex: 1;
overflow: auto;
padding: 16px 18px 40px;
color: #c8d1c5;
font: 400 12px/1.6 var(--font-mono);
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.replay-event { display: grid; grid-template-columns: 64px minmax(0, 1fr); gap: 12px; margin-bottom: 14px; }
.replay-event > div > span { display: block; }
.replay-stamp { color: #52604e; font-size: 9.5px; padding-top: 2px; }
.replay-system { color: #7c8978; }
.replay-user { color: #f1f5ef; }
.replay-assistant { color: #c8d1c5; }
.replay-command { margin-top: 7px; color: var(--accent); }
.replay-output { padding-left: 10px; border-left: 1px solid #33432d; color: #9dac98; }
.replay-wait, .replay-running { color: #70806c; }
.replay-model-wait {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 4px 16px;
margin-bottom: 8px;
color: #70806c;
font-size: 10.5px;
}
.replay-model-wait > i { grid-column: 1 / -1; height: 2px; overflow: hidden; background: #1c2719; }
.replay-model-wait > i > b { display: block; height: 100%; background: var(--accent); }
.replay-running { display: flex; align-items: center; gap: 8px; margin: 0 0 14px 76px; }
.replay-spinner { width: 7px; height: 7px; border: 1px solid #52604e; border-top-color: var(--accent); border-radius: 50%; animation: replay-spin 0.8s linear infinite; }
@keyframes replay-spin { to { transform: rotate(360deg); } }
.tok { padding: 0 1px; }
.tok:hover { outline: 1px solid var(--grey-6); }
.tok-tip {
+9 -9
View File
@@ -37,7 +37,7 @@ from prime_rl.configs.evals import EvalsConfig
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig
from prime_rl.evals.ckpt import CheckpointManager
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs
@@ -99,7 +99,7 @@ class Evals:
# Assigned in setup(); None-initialized so stop() can tear down a
# partially completed setup with plain attribute checks.
self.clients: InferenceClient | None = None
self.admin_clients: AdminClients | None = None
self.admin_plane: AdminPlane | None = None
self.dispatcher: Dispatcher | None = None
self.inference_metrics: InferenceMetricsCollector | None = None
self.periodic_logger: PeriodicLogger | None = None
@@ -125,7 +125,7 @@ class Evals:
get_logger().info(f"Initializing inference pool (base_url={config.eval.client.base_url}, model={config.model})")
self.clients = InferenceClient(config.eval.client, model_name=config.model)
self.admin_clients = AdminClients(config.eval.client)
self.admin_plane = AdminPlane(config.eval.client)
self.spawn_env_servers()
@@ -135,7 +135,7 @@ class Evals:
get_logger().success(f"Eval environment(s) ready ({', '.join(self.eval_envs.names)})")
get_logger().info("Waiting for inference pool to be ready")
await self.admin_clients.wait_for_ready(config.model)
await self.admin_plane.wait_for_ready(config.model)
get_logger().success("Inference pool ready")
self.receiver: WeightReceiver | None = None
@@ -148,7 +148,7 @@ class Evals:
self.receiver = setup_weight_receiver(
config.online.broadcasts_dir,
weight_broadcast,
admin_clients=self.admin_clients.clients,
admin_plane=self.admin_plane,
model_name=config.model,
)
await self.receiver.initialize()
@@ -201,7 +201,7 @@ class Evals:
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor.
self.inference_metrics = InferenceMetricsCollector(
self.admin_clients.clients,
self.admin_plane.clients,
on_load=self.concurrency.observe,
)
# Fail fast when adaptivity has no signal: external API endpoints
@@ -212,7 +212,7 @@ class Evals:
if not await self.inference_metrics.probe():
concurrency = config.eval.concurrency
if concurrency.min_inflight != concurrency.max_inflight:
urls = ", ".join(str(client.base_url) for client in self.admin_clients.clients)
urls = ", ".join(str(client.base_url) for client in self.admin_plane.clients)
raise ValueError(
f"No engine metrics at {urls} - adaptive concurrency has no load signal. "
"The endpoint does not expose vLLM /metrics (e.g. an external inference API); "
@@ -579,8 +579,8 @@ class Evals:
await self.dispatcher.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
cleanup_processes(self.env_server_procs)
+3 -2
View File
@@ -9,8 +9,9 @@ from prime_rl.transports.batch import TrainingSample
def assign_advantages(trace: vf.Trace, values: float | list[float]) -> None:
"""Assign credit in compact sampled-token order across the trace graph."""
nodes = [node for node in trace.nodes if any(node.mask)]
"""Assign credit in compact sampled-token order across trainable graph paths."""
trainable_nodes = {id(node) for branch in trace.branches if branch.trainable for node in branch.nodes}
nodes = [node for node in trace.nodes if id(node) in trainable_nodes and any(node.mask)]
for node in nodes:
if len(node.mask) != len(node.token_ids):
raise ValueError(
+1 -1
View File
@@ -43,7 +43,7 @@ def stamp_batch(episodes: list[vf.Episode], step: int) -> list[dict[str, Any]]:
branches = {
branch.index: {"advantages": advantages}
for branch in trace.branches
if (advantages := branch.advantages) is not None
if branch.trainable and (advantages := branch.advantages) is not None
}
updates.append(make_update(trace.id, info=info, branches=branches))
return updates
+80 -96
View File
@@ -4,6 +4,7 @@ import asyncio
import os
from collections.abc import Callable
from pathlib import Path
from typing import Literal
import httpx
import verifiers.v1 as vf
@@ -73,16 +74,15 @@ class InferenceClient:
await self._scorer.aclose()
class AdminClients:
class AdminPlane:
"""Admin plane of the policy inference deployment: one httpx client per
engine process. The router serves no admin routes (pause/resume,
update_weights, init_broadcaster, load_lora_adapter live on the engines),
so these clients bypass it via ``admin_base_url``.
The client order is load-bearing: ``admin_base_url`` order must match the
GPU rank order — the ``rank_offset`` math in ``init_nccl_broadcast`` /
``init_nixl_broadcast`` and the metrics collector's role list index into
it."""
GPU rank order used by NCCL/NIXL initialization and the metrics collector's
role list index."""
def __init__(self, client_config: ClientConfig):
self.clients = setup_admin_clients(client_config)
@@ -107,6 +107,77 @@ class AdminClients:
)
await maybe_check_has_model(self.clients, model_name, skip_model_check=self._skip_model_check)
async def initialize_nccl(
self,
*,
host: str,
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
gpus_per_server = inference_world_size // len(self.clients)
get_logger().info(
f"Initializing NCCL broadcast: {len(self.clients)} servers, "
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
)
async def initialize_client(admin_client: AsyncClient, rank_offset: int) -> None:
try:
response = await admin_client.post(
"/init_broadcaster",
json={
"host": host,
"port": port,
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
except httpx.HTTPStatusError as error:
if error.response.status_code == 404:
get_logger().warning(
"The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization."
)
await asyncio.gather(
*(
initialize_client(admin_client, client_num * gpus_per_server)
for client_num, admin_client in enumerate(self.clients)
)
)
async def update_weights(
self,
weight_dir: Path | None,
*,
transport: Literal["filesystem", "nccl", "nixl"],
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update every inference engine through its configured weight transport."""
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
await _pause_engines(self.clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in self.clients
]
)
finally:
await _resume_engines(self.clients)
async def aclose(self) -> None:
for client in self.clients + self._router_clients:
await client.aclose()
@@ -116,7 +187,7 @@ async def check_inference_ready(client_config: ClientConfig, model_name: str) ->
"""One-shot readiness check of an inference endpoint (health + model
listing) with transient clients — for frozen endpoints that never need a
persistent admin plane."""
admin = AdminClients(client_config)
admin = AdminPlane(client_config)
try:
await admin.wait_for_ready(model_name)
finally:
@@ -300,44 +371,6 @@ async def _resume_engines(admin_clients: list[AsyncClient]) -> None:
logger.debug("All inference engines resumed")
async def update_weights(
admin_clients: list[AsyncClient],
weight_dir: Path | None,
step: int = 0,
on_paused: Callable[[], None] | None = None,
) -> None:
"""Update weights on static inference servers.
Pauses all engines first to drain in-flight requests, then performs the
weight update, then resumes. This ensures all DP workers are idle and can
participate in the collective weight transfer. ``on_paused`` runs between
the pause and the update RPC — the NCCL receiver signals the trainer there.
Note: the prefix cache is intentionally not reset on weight update. The orchestrator
salts the prefix cache per weight version (``cache_salt`` in the sampling request, see
``orchestrator/envs.py``), so KV computed under old weights is never reused.
"""
weight_dir_posix = weight_dir.as_posix() if weight_dir is not None else None
await _pause_engines(admin_clients, step=step)
try:
if on_paused is not None:
on_paused()
await asyncio.gather(
*[
_admin_post(
admin_client,
"/update_weights",
json={"weight_dir": weight_dir_posix},
timeout_s=UPDATE_WEIGHTS_TIMEOUT_S,
)
for admin_client in admin_clients
]
)
finally:
await _resume_engines(admin_clients)
def _is_retryable_lora_error(exception: BaseException) -> bool:
"""Check if an exception should trigger a retry for LoRA loading."""
if isinstance(exception, httpx.HTTPStatusError):
@@ -362,7 +395,7 @@ LORA_LOAD_READ_TIMEOUT_S = 30.0
LORA_LOAD_TOTAL_TIMEOUT_S = 120.0
async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lora_path: Path) -> None:
async def load_lora_adapter(admin_plane: AdminPlane, lora_name: str, lora_path: Path) -> None:
"""Make a HTTP post request to the vLLM server to load a LoRA adapter.
Uses our wrapper around vLLM's /v1/load_lora_adapter. The prefix cache is not reset
@@ -390,61 +423,11 @@ async def load_lora_adapter(admin_clients: list[AsyncClient], lora_name: str, lo
)
response.raise_for_status()
await asyncio.gather(*[_load_lora_adapter(admin_client) for admin_client in admin_clients])
async def init_nccl_broadcast(
admin_clients: list[AsyncClient],
host: str,
port: int,
timeout: int,
inference_world_size: int,
quantize_in_weight_transfer: bool = False,
) -> None:
"""Initialize NCCL broadcast on all inference servers.
Each admin client represents one vLLM server. The function computes
per-server rank_offset and gpus_per_server so that every inference GPU
gets a unique rank in the NCCL broadcast group.
"""
logger = get_logger()
gpus_per_server = inference_world_size // len(admin_clients)
logger.info(
f"Initializing NCCL broadcast: {len(admin_clients)} servers, "
f"inference_world_size={inference_world_size}, gpus_per_server={gpus_per_server}"
)
async def _init_nccl_broadcast(admin_client: AsyncClient, rank_offset: int) -> None:
try:
response = await admin_client.post(
"/init_broadcaster",
json={
"host": host,
"port": port,
"rank_offset": rank_offset,
"inference_world_size": inference_world_size,
"timeout": timeout,
"quantize_in_weight_transfer": quantize_in_weight_transfer,
},
)
response.raise_for_status()
except httpx.HTTPStatusError as e:
if e.response.status_code == 404:
logger.warning("The route /init_broadcaster does not exist. Skipping NCCL broadcast initialization.")
return
await asyncio.gather(
*[
_init_nccl_broadcast(admin_client, client_num * gpus_per_server)
for client_num, admin_client in enumerate(admin_clients)
]
)
await asyncio.gather(*[_load_lora_adapter(client) for client in admin_plane.clients])
async def init_nixl_broadcast(
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
host: str,
port: int,
timeout: int,
@@ -452,6 +435,7 @@ async def init_nixl_broadcast(
session_id: str,
) -> None:
"""Configure every vLLM worker for NIXL + ModelExpress pulls."""
admin_clients = admin_plane.clients
workers_per_server = inference_world_size // len(admin_clients)
async def initialize(admin_client: AsyncClient, rank_offset: int) -> None:
+9 -9
View File
@@ -39,7 +39,7 @@ from prime_rl.configs.orchestrator import OrchestratorConfig
from prime_rl.orchestrator.algo.routing import is_trainable
from prime_rl.orchestrator.annotations import stamp_arrival, stamp_batch
from prime_rl.orchestrator.ckpt import setup_ckpt_manager
from prime_rl.orchestrator.clients import AdminClients, InferenceClient
from prime_rl.orchestrator.clients import AdminPlane, InferenceClient
from prime_rl.orchestrator.concurrency import ConcurrencyController
from prime_rl.orchestrator.dispatcher import Dispatcher, DispatcherMetrics, DispatcherMode
from prime_rl.orchestrator.envs import EvalEnvs, TrainEnvs
@@ -119,7 +119,7 @@ class Orchestrator:
# Always set by ``setup()``
tokenizer: PreTrainedTokenizer
clients: InferenceClient | None
admin_clients: AdminClients | None
admin_plane: AdminPlane | None
sender: BatchSender | None
packer: BatchPacker
train_envs: TrainEnvs
@@ -172,7 +172,7 @@ class Orchestrator:
# Always assigned by ``setup()``; None-initialized so teardown can run
# on a partially completed setup with plain attribute checks
self.clients = None
self.admin_clients = None
self.admin_plane = None
# Optional attributes — ``setup()`` populates them when the relevant
# config is present
@@ -208,7 +208,7 @@ class Orchestrator:
eval_client_type="openai_chat_completions",
renderer_config=config.renderer,
)
self.admin_clients = AdminClients(config.model.client)
self.admin_plane = AdminPlane(config.model.client)
await monitors.setup(
producer="orch",
@@ -290,7 +290,7 @@ class Orchestrator:
get_logger().info("Waiting for policy inference pool to be ready")
t0 = time.perf_counter()
await self.admin_clients.wait_for_ready(config.model.name)
await self.admin_plane.wait_for_ready(config.model.name)
get_logger().success(f"Policy inference pool ready after {format_time(time.perf_counter() - t0)}")
# Build + ready pools for each env's frozen generation source and the
# algorithm's frozen reference model
@@ -307,7 +307,7 @@ class Orchestrator:
self.receiver = setup_weight_receiver(
get_broadcast_dir(config.output_dir),
config.weight_broadcast,
admin_clients=self.admin_clients.clients,
admin_plane=self.admin_plane,
model_name=config.model.name,
)
await self.receiver.initialize()
@@ -360,7 +360,7 @@ class Orchestrator:
# The collector always polls — it feeds the concurrency controller;
# metrics fan out to every registered monitor when collection is on.
self.inference_metrics = InferenceMetricsCollector(
self.admin_clients.clients,
self.admin_plane.clients,
roles=config.inference_metrics_roles,
on_load=self.concurrency.observe,
log_metrics=config.collect_inference_metrics,
@@ -1056,8 +1056,8 @@ class Orchestrator:
await self.inference_metrics.stop()
if self.clients is not None:
await self.clients.aclose()
if self.admin_clients is not None:
await self.admin_clients.aclose()
if self.admin_plane is not None:
await self.admin_plane.aclose()
if self.train_envs is not None:
get_logger().debug("Stopping generation source and algorithm clients")
for env in self.train_envs:
@@ -91,6 +91,7 @@ def _encode_sampling_mask(mask: vf.SamplingMask | None, num_tokens: int) -> Samp
def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[bool]]]:
"""Yield each branch that yields a training sample, with its trainable-token mask.
Branches excluded by trace semantics are skipped before shared-node accounting.
The mask is `branch.sampled_mask` except that a sampled node shared by several branches
(a mid-trajectory fork) is trainable only in the first branch containing it; later
branches carry its tokens as context (mask False). Branches left with no trainable
@@ -99,6 +100,8 @@ def iter_trainable_branches(trace: vf.Trace) -> Iterator[tuple[vf.Branch, list[b
"""
trained_nodes: set[int] = set()
for branch in trace.branches:
if not branch.trainable:
continue
mask: list[bool] = []
for node in branch.nodes:
if node.sampled and any(node.mask) and id(node) in trained_nodes:
+5 -5
View File
@@ -1,9 +1,9 @@
from pathlib import Path
import torch
from httpx import AsyncClient
from prime_rl.configs.trainer import LoRAConfig, WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender, prune_broadcasts_beyond
from prime_rl.transports.weights.filesystem import FileSystemWeightReceiver, FileSystemWeightSender
@@ -38,14 +38,14 @@ def setup_weight_sender(
def setup_weight_receiver(
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
model_name: str,
) -> WeightReceiver:
if config.type == "nccl":
return NCCLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return NCCLWeightReceiver(broadcast_dir, config, admin_plane, model_name)
elif config.type == "filesystem":
return FileSystemWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return FileSystemWeightReceiver(broadcast_dir, config, admin_plane, model_name)
elif config.type == "nixl":
return NIXLWeightReceiver(broadcast_dir, config, admin_clients, model_name)
return NIXLWeightReceiver(broadcast_dir, config, admin_plane, model_name)
else:
raise ValueError(f"Invalid weight broadcast type: {config.type}")
+4 -4
View File
@@ -7,9 +7,9 @@ from pathlib import Path
from typing import final
import torch.nn as nn
from httpx import AsyncClient
from prime_rl.configs.trainer import WeightBroadcastConfig
from prime_rl.orchestrator.clients import AdminPlane
from prime_rl.trainer.world import get_world
from prime_rl.utils.logger import get_logger
from prime_rl.utils.pathing import get_all_ckpt_steps, get_broadcast_dir, get_step_path
@@ -115,19 +115,19 @@ class WeightReceiver(ABC):
watcher, the orchestrator's startup rendezvous, and the evals process all
drive the same object instead of hand-rolling transport branches. The
engines' in-process receive hooks are its data plane, reached through the
admin clients."""
admin plane."""
def __init__(
self,
broadcast_dir: Path,
config: WeightBroadcastConfig,
admin_clients: list[AsyncClient],
admin_plane: AdminPlane,
model_name: str,
) -> None:
self.logger = get_logger()
self.broadcast_dir = broadcast_dir
self.config = config
self.admin_clients = admin_clients
self.admin_plane = admin_plane
self.model_name = model_name
async def initialize(self) -> None:
@@ -5,7 +5,7 @@ import torch.nn as nn
from torch.distributed.tensor import DTensor
from prime_rl.configs.trainer import FileSystemWeightBroadcastConfig, LoRAConfig
from prime_rl.orchestrator.clients import load_lora_adapter, update_weights
from prime_rl.orchestrator.clients import load_lora_adapter
from prime_rl.trainer.lora import get_lora_state, save_lora_config
from prime_rl.transports.weights.base import FINISHED_MARKER, WeightReceiver, WeightSender
from prime_rl.utils.pathing import wait_for_path
@@ -70,6 +70,6 @@ class FileSystemWeightReceiver(WeightReceiver):
self._ack(step)
await wait_for_path(weights_dir / FINISHED_MARKER)
if (weights_dir / "adapter_config.json").exists():
await load_lora_adapter(self.admin_clients, self.model_name, weights_dir)
await load_lora_adapter(self.admin_plane, self.model_name, weights_dir)
else:
await update_weights(self.admin_clients, weights_dir, step=step)
await self.admin_plane.update_weights(weights_dir, transport="filesystem", step=step)
+6 -8
View File
@@ -11,7 +11,6 @@ from vllm.distributed.device_communicators.pynccl import PyNcclCommunicator
from vllm.distributed.utils import StatelessProcessGroup
from prime_rl.configs.trainer import NCCLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nccl_broadcast, update_weights
from prime_rl.trainer.conversion_utils import get_max_layer_num
from prime_rl.trainer.models import PreTrainedModelPrimeRL
from prime_rl.trainer.utils import get_world
@@ -202,19 +201,18 @@ class NCCLWeightReceiver(WeightReceiver):
marker."""
async def initialize(self) -> None:
await init_nccl_broadcast(
self.admin_clients,
self.config.host,
self.config.port,
self.config.timeout,
await self.admin_plane.initialize_nccl(
host=self.config.host,
port=self.config.port,
timeout=self.config.timeout,
inference_world_size=self.config.inference_world_size,
quantize_in_weight_transfer=self.config.quantize_in_weight_transfer,
)
async def receive(self, step: int) -> None:
await update_weights(
self.admin_clients,
await self.admin_plane.update_weights(
self.step_dir(step),
transport="nccl",
step=step,
on_paused=lambda: self._ack(step),
)
+3 -3
View File
@@ -20,7 +20,7 @@ from torch.distributed.tensor import DTensor
from torch.distributed.tensor._utils import compute_local_shape_and_global_offset
from prime_rl.configs.trainer import NIXLWeightBroadcastConfig
from prime_rl.orchestrator.clients import init_nixl_broadcast, update_weights
from prime_rl.orchestrator.clients import init_nixl_broadcast
from prime_rl.trainer.models.base import PreTrainedModelPrimeRL
from prime_rl.trainer.parallel_dims import ParallelDims
from prime_rl.transports.weights.base import WeightReceiver, WeightSender
@@ -465,7 +465,7 @@ class NIXLWeightReceiver(WeightReceiver):
async def initialize(self) -> None:
await init_nixl_broadcast(
self.admin_clients,
self.admin_plane,
self.config.host,
self.config.port,
self.config.timeout,
@@ -495,7 +495,7 @@ class NIXLWeightReceiver(WeightReceiver):
policy_notification(step, "ready"),
timeout=self.config.timeout,
)
await update_weights(self.admin_clients, None, step=step)
await self.admin_plane.update_weights(None, transport="nixl", step=step)
self.nixl_agent.send_notification(
trainer_peer,
policy_notification(step, "complete"),
+14
View File
@@ -127,6 +127,20 @@ def check_dashboard_smoke(output_dir: Path, run_name: str) -> None:
assert entries > 0, "episode viewer rendered no messages"
reward = page.locator(".tm-reward-big").first.inner_text()
assert reward not in ("", "n/a"), f"episode reward did not render: {reward!r}"
page.click("#tm-view [data-view=replay]")
page.wait_for_timeout(250)
assert page.locator(".replay-shell").count() == 1, "terminal replay did not render"
assert page.locator("#replay-output .replay-event").count() > 0, "terminal replay showed no events"
assert page.locator("#replay-speed").input_value() == "8"
page.check("#replay-skip-inference")
assert "inference skipped" in page.locator("#replay-timing-badge").inner_text()
assert page.locator("#replay-show-thinking").is_checked()
page.keyboard.press("t")
assert not page.locator("#replay-show-thinking").is_checked()
page.keyboard.press("Home")
assert page.locator("#replay-top").get_attribute("class").find("active") >= 0
page.keyboard.press("End")
assert page.locator("#replay-live").get_attribute("class").find("active") >= 0
page.keyboard.press("Escape")
# logs: the merged pane shows lines
@@ -213,6 +213,93 @@ def test_assign_advantages_full_length_stream():
assert trace_to_samples(trace)[0].advantages == [0.0, 0.0, 0.5, -0.5, 0.0, 1.0]
def test_compaction_retries_train_only_causally_used_generations():
nodes = [
MessageNode(
parent=None,
message=UserMessage(content="work"),
sampled=False,
token_ids=[1],
mask=[False],
),
MessageNode(
parent=0,
message=AssistantMessage(content="evidence"),
sampled=True,
token_ids=[2],
mask=[True],
logprobs=[-0.1],
),
MessageNode(
parent=1,
message=UserMessage(content="summarize"),
sampled=False,
token_ids=[3],
mask=[False],
),
MessageNode(
parent=2,
semantic_parents=[vf.ParentLink(node=1, type="compaction_attempt")],
message=AssistantMessage(content="rejected tool call"),
sampled=True,
token_ids=[4],
mask=[True],
logprobs=[-0.2],
),
MessageNode(
parent=2,
semantic_parents=[vf.ParentLink(node=1, type="compaction_attempt")],
message=AssistantMessage(content="accepted summary"),
sampled=True,
token_ids=[5],
mask=[True],
logprobs=[-0.3],
),
MessageNode(
parent=None,
message=UserMessage(content="compacted context"),
sampled=False,
token_ids=[6],
mask=[False],
),
MessageNode(
parent=5,
semantic_parents=[vf.ParentLink(node=4, type="compaction")],
message=AssistantMessage(content="answer"),
sampled=True,
token_ids=[7],
mask=[True],
logprobs=[-0.4],
),
]
trace = vf.Trace(
task=vf.TraceTask(type="Task", data=vf.TaskData(idx=0, prompt=None)),
agent=vf.AgentInfo(config=vf.AgentConfig()),
nodes=nodes,
rewards={},
ok=True,
)
branches = {branch.nodes[-1].message.content: branch for branch in trace.branches}
assert branches["rejected tool call"].trainable is False
assert branches["accepted summary"].trainable is True
assert branches["answer"].trainable is True
assign_advantages(trace, 1.0)
assert trace.nodes[1].advantages == [1.0]
assert trace.nodes[3].advantages is None
assert trace.nodes[4].advantages == [1.0]
assert trace.nodes[6].advantages == [1.0]
trainable_ids = [
token_id
for sample in trace_to_samples(trace)
for token_id, trainable in zip(sample.token_ids, sample.mask, strict=True)
if trainable
]
assert sorted(trainable_ids) == [2, 5, 7]
def test_assign_advantages_slices_across_nodes():
trace = _make_episode().traces[0]
assign_advantages(trace, [1.0, 2.0, 3.0])
+40 -2
View File
@@ -6,7 +6,13 @@ import httpx
from verifiers.v1.configs.client import EvalClientConfig
from prime_rl.configs.shared import ClientConfig
from prime_rl.orchestrator.clients import _is_retryable_lora_error, check_health, load_lora_adapter, setup_client
from prime_rl.orchestrator.clients import (
AdminPlane,
_is_retryable_lora_error,
check_health,
load_lora_adapter,
setup_client,
)
def test_is_retryable_lora_error_returns_true_for_404():
@@ -36,11 +42,12 @@ def test_is_retryable_lora_error_returns_false_for_non_http_error():
def test_load_lora_adapter_succeeds_on_first_attempt():
mock_client = AsyncMock()
admin_plane = MagicMock(clients=[mock_client])
mock_response = MagicMock()
mock_response.raise_for_status = MagicMock()
mock_client.post.return_value = mock_response
asyncio.run(load_lora_adapter([mock_client], "test-lora", Path("/test/path")))
asyncio.run(load_lora_adapter(admin_plane, "test-lora", Path("/test/path")))
mock_client.post.assert_called_once_with(
"/load_lora_adapter",
@@ -49,6 +56,37 @@ def test_load_lora_adapter_succeeds_on_first_attempt():
)
def test_admin_plane_initializes_nccl():
admin_plane = AdminPlane(ClientConfig())
client = AsyncMock()
response = MagicMock()
response.raise_for_status.return_value = None
client.post.return_value = response
admin_plane.clients = [client]
asyncio.run(
admin_plane.initialize_nccl(
host="trainer",
port=29501,
timeout=1200,
inference_world_size=1,
)
)
client.post.assert_awaited_once_with(
"/init_broadcaster",
json={
"host": "trainer",
"port": 29501,
"rank_offset": 0,
"inference_world_size": 1,
"timeout": 1200,
"quantize_in_weight_transfer": False,
},
)
asyncio.run(admin_plane.aclose())
def test_setup_client_creates_renderer_client():
from renderers import Qwen3VLRendererConfig
+276
View File
@@ -0,0 +1,276 @@
from prime_rl.dashboard.server import project_episode_timeline
def _node(
parent: int | None,
timestamp: float,
semantic_parents: list[dict] | None = None,
message: dict | None = None,
) -> dict:
return {
"parent": parent,
"semantic_parents": semantic_parents or [],
"timestamp": timestamp,
"message": message or {"role": "assistant", "content": f"node {timestamp}"},
}
def _call(
node: int,
start: float,
end: float,
*,
prompt_tokens: int = 100,
cached_tokens: int = 20,
) -> dict:
return {
"node": node,
"time": {"start": start, "end": end},
"usage": {
"prompt_tokens": prompt_tokens,
"cached_input_tokens": cached_tokens,
"completion_tokens": 10,
},
}
def _episode(nodes: list[dict], calls: list[dict]) -> dict:
return {
"traces": [
{
"nodes": nodes,
"calls": calls,
"is_completed": True,
"agent": {"name": "root", "config": {"model": "test-model"}},
"timing": {"agent": {"start": 0.0, "end": 10.0}},
}
]
}
def test_semantic_timeline_projects_concurrent_fork_join() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(0, 4.0, [{"node": 1, "type": "subagent_call"}]),
_node(0, 4.1, [{"node": 1, "type": "subagent_call"}]),
_node(
1,
7.0,
[
{"node": 1, "type": "continuation"},
{"node": 2, "type": "subagent_return"},
{"node": 3, "type": "subagent_return"},
{"node": 2, "type": "vendor:review"},
],
),
]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(3, 3.1, 4.1),
_call(4, 6.0, 7.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"subagent 1 · context 0",
"subagent 2 · context 0",
]
assert [lane["usage"]["model_calls"] for lane in timeline["semantic_lanes"][1:]] == [
2,
1,
1,
]
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
260,
130,
130,
]
assert [lane["usage"]["latest_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
120,
120,
120,
]
assert [lane["context"] for lane in timeline["semantic_lanes"][1:]] == [
{"agent": "root", "index": 0},
{"agent": "subagent 1", "index": 0},
{"agent": "subagent 2", "index": 0},
]
assert [edge["type"] for edge in timeline["semantic_edges"]] == [
"subagent_call",
"subagent_call",
"continuation",
"subagent_return",
"subagent_return",
"vendor:review",
]
def test_semantic_timeline_starts_new_context_after_compaction() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "continuation"}]),
_node(2, 6.0, [{"node": 2, "type": "compaction"}]),
]
calls = [
_call(1, 1.0, 2.0, prompt_tokens=150),
_call(2, 3.0, 4.0),
_call(3, 5.0, 6.0, prompt_tokens=50, cached_tokens=10),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"root · context 1",
]
assert [lane["usage"]["model_calls"] for lane in timeline["semantic_lanes"][1:]] == [
2,
1,
]
assert [lane["usage"]["total_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
310,
70,
]
assert [lane["usage"]["latest_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
120,
60,
]
assert [lane["usage"]["max_context_tokens"] for lane in timeline["semantic_lanes"][1:]] == [
170,
60,
]
assert [lane["context"] for lane in timeline["semantic_lanes"][1:]] == [
{"agent": "root", "index": 0},
{"agent": "root", "index": 1},
]
assert [edge["type"] for edge in timeline["semantic_edges"]] == [
"continuation",
"compaction",
]
def test_semantic_timeline_keeps_rejected_and_accepted_compaction_attempts() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "compaction_attempt"}]),
_node(1, 5.0, [{"node": 1, "type": "compaction_attempt"}]),
_node(0, 7.0, [{"node": 3, "type": "compaction"}]),
]
nodes[2]["mask"] = [True]
nodes[3]["mask"] = [True]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(3, 4.0, 5.0),
_call(4, 6.0, 7.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
attempts = [lane for lane in timeline["semantic_lanes"] if lane.get("compaction_attempt")]
assert [attempt["compaction_attempt"]["accepted"] for attempt in attempts] == [
False,
True,
]
assert [attempt["spans"][1]["trainable"] for attempt in attempts] == [
True,
True,
]
assert [attempt["context"] for attempt in attempts] == [
{"agent": "root", "index": 0},
{"agent": "root", "index": 0},
]
assert timeline["semantic_lanes"][-1]["context"] == {
"agent": "root",
"index": 1,
}
def test_semantic_timeline_falls_back_to_physical_only() -> None:
nodes = [_node(None, 0.0), _node(0, 2.0)]
timeline = project_episode_timeline(_episode(nodes, [_call(1, 1.0, 2.0)]))
assert timeline["lanes"]
assert timeline["semantic_lanes"] == []
assert timeline["semantic_edges"] == []
def test_semantic_timeline_recovers_interrupted_tool_continuation() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(
0,
4.0,
[{"node": 1, "type": "subagent_call"}],
{"role": "assistant", "tool_calls": [{"id": "first-tool"}]},
),
_node(
2,
5.0,
message={"role": "tool", "tool_call_id": "first-tool", "content": "result"},
),
_node(
3,
6.0,
[{"node": 2, "type": "continuation"}],
{"role": "assistant", "tool_calls": [{"id": "interrupted-tool"}]},
),
_node(
4,
7.0,
message={"role": "tool", "tool_call_id": "interrupted-tool", "content": "result"},
),
_node(5, 8.0),
]
calls = [
_call(1, 1.0, 2.0),
_call(2, 3.0, 4.0),
_call(4, 5.0, 6.0),
_call(6, 7.0, 8.0),
]
timeline = project_episode_timeline(_episode(nodes, calls))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"subagent 1 · context 0",
]
assert timeline["semantic_lanes"][2]["usage"]["model_calls"] == 3
assert timeline["semantic_edges"][-1] == {
"trace_index": 0,
"source_node": 4,
"target_node": 6,
"type": "continuation",
"inferred": True,
}
def test_semantic_timeline_labels_unrecoverable_components_as_unlinked() -> None:
nodes = [
_node(None, 0.0),
_node(0, 2.0),
_node(1, 4.0, [{"node": 1, "type": "continuation"}]),
_node(0, 6.0),
]
timeline = project_episode_timeline(_episode(nodes, [_call(1, 1.0, 2.0), _call(2, 3.0, 4.0), _call(3, 5.0, 6.0)]))
assert [lane["label"] for lane in timeline["semantic_lanes"]] == [
"root",
"root · context 0",
"unlinked 1 · context 0",
]
assert timeline["semantic_lanes"][2]["context"] == {
"agent": "unlinked 1",
"index": 0,
"unlinked": True,
}
Generated
+9 -3
View File
@@ -7648,16 +7648,16 @@ requires-dist = [{ name = "verifiers", specifier = ">=0.3.1" }]
[[package]]
name = "uvicorn"
version = "0.48.0"
version = "0.52.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "click", version = "8.4.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux'" },
{ name = "click", version = "8.4.2", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux'" },
{ name = "h11" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e6/bf/f6544ba992ddb9a6077343a576f9844f7f8f06ab819aefd00206e9255f18/uvicorn-0.48.0.tar.gz", hash = "sha256:a5504207195d08c2511bf9125ede5ac4a4b71725d519e758d01dcf0bc2d31c37", size = 91074, upload-time = "2026-05-24T12:08:41.925Z" }
sdist = { url = "https://files.pythonhosted.org/packages/f2/0f/3f86e61397dd33bf2ccf28188c40db6a740658aeebbbf6e7dbc101a1f487/uvicorn-0.52.4.tar.gz", hash = "sha256:73acfee47a0b133c5de13d219492d62d8a31e935f4fe6e41a232451a15379f86", size = 100627, upload-time = "2026-08-19T06:27:41.821Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/01/be/72532be3da7acc5fdfbccdb95215cd04f995a0886532a5b423f929cda4cc/uvicorn-0.48.0-py3-none-any.whl", hash = "sha256:48097851328b87ec36117d3d575234519eb58c2b22d79666e9bbc6c49a761dad", size = 71410, upload-time = "2026-05-24T12:08:40.258Z" },
{ url = "https://files.pythonhosted.org/packages/f1/79/4a20b54ab0491485ccd8c077db2d39187c7f12b3e15485d38a7be37c81b4/uvicorn-0.52.4-py3-none-any.whl", hash = "sha256:f86e41a149d7d05a9969337e3946a9c171c06a5d42680896daaba624aeac8da1", size = 79871, upload-time = "2026-08-19T06:27:40.36Z" },
]
[package.optional-dependencies]
@@ -7705,7 +7705,9 @@ dependencies = [
{ name = "aiohttp" },
{ name = "anthropic" },
{ name = "gepa" },
{ name = "h11" },
{ name = "httpx" },
{ name = "httpx2" },
{ name = "loguru" },
{ name = "math-verify" },
{ name = "mcp" },
@@ -7722,6 +7724,7 @@ dependencies = [
{ name = "tenacity" },
{ name = "tomli-w" },
{ name = "typing-extensions" },
{ name = "uvicorn" },
]
[package.optional-dependencies]
@@ -7739,8 +7742,10 @@ requires-dist = [
{ name = "anthropic", specifier = ">=1.0.0" },
{ name = "datasets", marker = "extra == 'lean'", specifier = ">=3.3.0,<6.0.0" },
{ name = "gepa", specifier = ">=0.0.6" },
{ name = "h11", specifier = ">=0.16.0" },
{ name = "harbor", marker = "python_full_version >= '3.12' and extra == 'harbor'", specifier = "==0.21.0" },
{ name = "httpx", specifier = ">=0.27.0" },
{ name = "httpx2", specifier = ">=2.12.0" },
{ name = "loguru", specifier = ">=0.7.0" },
{ name = "math-verify", specifier = ">=0.8.0" },
{ name = "mcp", specifier = "==2.0.0" },
@@ -7761,6 +7766,7 @@ requires-dist = [
{ name = "textarena", marker = "extra == 'ta'", specifier = "==0.7.4" },
{ name = "tomli-w", specifier = ">=1.0.0" },
{ name = "typing-extensions", specifier = ">=4.12.2" },
{ name = "uvicorn", specifier = ">=0.52.0" },
]
provides-extras = ["harbor", "lean", "modal", "openenv", "ta"]