feat: read derived trace values from the record (#4415)

## Summary
- Bump `deps/verifiers` to PrimeIntellect-ai/verifiers#3102. That PR
serializes derived trace and episode values as computed fields:
`reward`, `usage`, `is_truncated`, `num_turns`, `num_branches`,
`last_reply`, `has_error`, `is_format_violation`, span `duration` and
policy `drift`.
- Stream the new trace fields to live watchers (`SCALAR_FIELDS` in
`env/delta.py`).
- The episode index (`monitors/file/traces/index.py`) reads `reward`,
`is_truncated`, `num_turns`, `num_branches` and `usage.cost` from the
record, and timing from span `duration`. The copied `TRUNCATING_STOPS`
rule and the node and call walks are gone. The index record now leaves
out model calls.
- The dashboard timeline (`server.py`) and trace viewer (`app.js`) read
`reward`, `is_truncated` and `usage` from the trace instead of
recomputing them. The viewer still walks calls for max context length.
- `uv.lock`: `prime-sandboxes` 0.5.5 → 0.5.7. The bump pulls in that
floor from verifiers.

## Breaking
- Trace records written before this bump have none of these fields. In
the dashboard's trace viewer, such a trace shows no reward,
`is_truncated` reads false, and the usage totals and finished timing
phases are empty. Episode index rows that were already written keep
their values.

## Verification
- `pytest tests/unit`: dashboard, monitors, env delta and eval tests
pass. This includes the guard test that every serialized `Trace` field
is streamed. The only failures come from modules missing in the slim
test venv (`torch` and env tasksets).
- `test_episode_summary_excludes_copied_assistant_context_from_turns`
now builds a real `WireEpisode` and summarizes its record.
- I have not checked the trace viewer in a browser.

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

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Backward-incompatible dashboard/index behavior for legacy traces
missing new serialized fields; bumps a core dependency version.
> 
> **Overview**
> **Serialized trace fields are now the source of truth** for rewards,
usage, truncation, and counts across the file monitor index, live
deltas, and dashboard (API + UI).
> 
> The episode **index builder** stops walking `nodes`/`calls`; it reads
`reward`, `usage.cost`, `is_truncated`, `num_turns`, and `num_branches`
from each trace, derives timing only from `duration`, and simplifies
truncation detection. **`SCALAR_FIELDS`** in `env/delta.py` now includes
these fields so live streams stay in sync.
> 
> The **dashboard** timeline exposes `trace.reward` directly, the trace
viewer shows **aggregated `usage`** and `is_truncated` from the record,
**truncation-rate tiles** rely on `series.truncated` only, and timing
rendering is adjusted for open spans. **Tests** build a real
`WireEpisode` via `index_record`. **`uv.lock`** bumps
**`prime-sandboxes` to 0.5.7** (floor aligned with verifiers).
> 
> **Breaking:** Older traces without these serialized fields may show
empty reward/usage and false truncation in the viewer; existing index
rows are unaffected.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
418d5b0572ebebb154c6d530acd70182fa8e5d2d. 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 Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Mika Senghaas
2026-11-06 14:45:28 -08:00
committed by GitHub
co-authored by Claude Opus 5.5
parent c82ef25941
commit f7a365fe2c
7 changed files with 57 additions and 112 deletions
+1 -1
+1 -11
View File
@@ -838,16 +838,6 @@ def timeline_status(trace: dict) -> str:
return "completed"
def timeline_reward(trace: dict) -> float | None:
rewards = [reward for reward in (trace.get("rewards") or {}).values() if isinstance(reward, dict)]
if not rewards:
return None
return sum(
(reward.get("score") or 0) * (reward.get("weight") if reward.get("weight") is not None else 1)
for reward in rewards
)
def annotation_streams(run_dir: Path) -> list[Path]:
"""The annotation streams, one chunk directory per producer, each indexed beside it."""
directory = get_annotations_dir(run_dir)
@@ -1066,7 +1056,7 @@ def timeline_lane(
"ended_at": ended,
"status": status,
"outcome": status if branch else (trace.get("stop_condition") or status),
"reward": timeline_reward(trace),
"reward": trace.get("reward") if trace.get("rewards") else None,
"usage": {
"model_calls": len(activities),
"input_tokens": input_tokens,
+13 -41
View File
@@ -1207,7 +1207,7 @@ function summaryTilesHtml(idx, all, scoreEntries) {
// the timeout rate reads yellow as soon as any episode timed out
if (all.length) {
const errored = all.filter((i) => series.ok?.[i] === false).length;
const truncated = all.filter((i) => (series.truncated?.[i] ?? TRUNCATING_STOPS.has(series.stop_condition?.[i])) === true).length;
const truncated = all.filter((i) => series.truncated?.[i] === true).length;
const timedOut = all.filter((i) => series.timeout?.[i] === true).length;
for (const [label, n, what, cls] of [
["error rate", errored, "errored", rateClass],
@@ -3841,12 +3841,6 @@ function currentPath(trace, branches) {
return branches[Math.min(currentBranchIdx, branches.length - 1)] || [];
}
function traceReward(trace) {
return Object.values(trace.rewards || {}).reduce(
(acc, r) => acc + ((r?.score ?? 0) * (r?.weight ?? 1)), 0
);
}
function messageText(message) {
const content = message?.content;
if (typeof content === "string") return content;
@@ -4567,23 +4561,13 @@ function metaRow(key, value, asId = false) {
);
}
const TRUNCATING_STOPS = new Set(["max_turns", "max_input_tokens", "max_output_tokens", "max_total_tokens", "max_turn_tokens", "compaction_failed"]);
/* mirrors verifiers Trace.is_truncated (not serialized): framework limits or a
length-finished final response */
function traceTruncated(trace) {
if (TRUNCATING_STOPS.has(trace.stop_condition)) return true;
const last = [...(trace.calls || [])].reverse().find((c) => !c.error);
return !!(last && last.finish_reason === "length");
}
function renderMeta(ep, trace, branches) {
const parts = [];
const headline = (label, value) =>
`<div class="meta-row"><span class="k">${label}</span>` +
`<span class="tm-reward-big${value != null && value < 0 ? " neg" : ""}${value == null ? " na" : ""}" style="margin-left:auto">` +
`${value != null ? fmtReward(value) : "n/a"}</span></div>`;
const rewardValue = trace && Object.keys(trace.rewards || {}).length ? traceReward(trace) : null;
const rewardValue = trace && Object.keys(trace.rewards || {}).length ? trace.reward ?? null : null;
parts.push(headline("reward", rewardValue));
parts.push(headline("advantage", trace?.info?.advantage ?? null));
@@ -4611,22 +4595,11 @@ function renderMeta(ep, trace, branches) {
const judgeRecords = Array.isArray(trace.info?.judge_calls) ? trace.info.judge_calls : [];
if (judgeRecords.length) parts.push(metaRow("judge calls", judgeRecords.length));
const usage = { input: null, output: null, reasoning: null, cached: null, maxContext: null, cost: null };
const addUsage = (field, value) => {
if (value != null) usage[field] = (usage[field] ?? 0) + value;
};
for (const call of trace.calls || []) {
const current = normalizedCallUsage(call.usage);
addUsage("input", current.input);
addUsage("cached", current.cached);
addUsage("output", current.output);
addUsage("reasoning", current.reasoning);
addUsage("cost", current.cost);
if (current.input != null) {
const context = current.input + (current.cached ?? 0);
usage.maxContext = Math.max(usage.maxContext ?? 0, context);
}
}
const contexts = (trace.calls || [])
.map((call) => normalizedCallUsage(call.usage))
.filter((current) => current.input != null)
.map((current) => current.input + (current.cached ?? 0));
const usage = { ...normalizedCallUsage(trace.usage ?? {}), maxContext: contexts.length ? Math.max(...contexts) : null };
const totalInput = usage.input == null ? null : usage.input + (usage.cached ?? 0);
const totalTokens = totalInput == null || usage.output == null ? null : totalInput + usage.output;
const hasUsage = usage.input != null || usage.cached != null || usage.output != null;
@@ -4645,19 +4618,18 @@ function renderMeta(ep, trace, branches) {
parts.push(`<div class="meta-sec">state</div>`);
parts.push(metaRow("stop_condition", trace.stop_condition));
parts.push(metaRow("is_completed", trace.is_completed));
parts.push(metaRow("is_truncated", traceTruncated(trace)));
parts.push(metaRow("is_truncated", !!trace.is_truncated));
parts.push(metaRow("is_timeout", !!trace.is_timeout));
parts.push(metaRow("ok", trace.ok));
const durations = [];
(function walkTiming(obj, prefix) {
if (!obj || typeof obj !== "object") return;
if (typeof obj.duration === "number") durations.push([prefix, obj.duration]);
else if (typeof obj.start === "number" && obj.start > 0) {
// an open span (no end yet) of a live trace shows its elapsed time
if (obj.end) durations.push([prefix, obj.end - obj.start]);
else if (currentLive) durations.push([prefix, Date.now() / 1000 - obj.start]);
}
const started = !("start" in obj) || obj.start > 0;
// an open span (no end yet) of a live trace shows its elapsed time
if (started && "start" in obj && !obj.end) {
if (currentLive) durations.push([prefix, Date.now() / 1000 - obj.start]);
} else if (started && typeof obj.duration === "number") durations.push([prefix, obj.duration]);
for (const [k, v] of Object.entries(obj)) if (typeof v === "object") walkTiming(v, prefix ? `${prefix}/${k}` : k);
})(trace.timing, "");
if (durations.length) {
+8
View File
@@ -67,6 +67,14 @@ SCALAR_FIELDS = (
"num_input_tokens",
"num_output_tokens",
"num_total_tokens",
"reward",
"usage",
"is_truncated",
"num_turns",
"num_branches",
"last_reply",
"has_error",
"is_format_violation",
)
"""Re-sent whole whenever their dumped value changes."""
+14 -48
View File
@@ -17,26 +17,19 @@ if TYPE_CHECKING:
def index_record(episode: vf.Episode) -> dict[str, Any]:
"""The part of the episode's record (`to_record`) that `summarize_episode` reads:
everything but the nodes' payloads. Built one trace at a time, so no single call
holds the GIL for a whole long episode."""
everything but the nodes and model calls. Built one trace at a time, so no single
call holds the GIL for a whole long episode."""
record = episode.model_dump(mode="json", exclude={"traces"}, exclude_none=True)
record["traces"] = []
for trace in episode.traces:
head = trace.model_dump(mode="json", exclude={"nodes"}, exclude_none=True)
head["nodes"] = [
{"sampled": node.sampled} if node.parent is None else {"parent": node.parent, "sampled": node.sampled}
for node in trace.nodes
]
record["traces"].append(head)
record["traces"] = [
trace.model_dump(mode="json", exclude={"nodes", "calls"}, exclude_none=True) for trace in episode.traces
]
return record
def walk_timing(obj: dict, prefix: str, out: dict[str, float]) -> None:
"""Flatten a trace timing tree to phase -> seconds (same walk as the viewer)."""
"""Flatten a trace timing tree to phase -> seconds."""
if isinstance(obj.get("duration"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + obj["duration"]
elif isinstance(obj.get("start"), (int, float)) and isinstance(obj.get("end"), (int, float)):
out[prefix] = out.get(prefix, 0.0) + (obj["end"] - obj["start"])
for key, value in obj.items():
if isinstance(value, dict):
walk_timing(value, f"{prefix}/{key}" if prefix else key, out)
@@ -52,21 +45,6 @@ def episode_kind(rec: dict) -> str:
return (run.get("work") or {}).get("type") or run.get("type") or "eval"
TRUNCATING_STOPS = frozenset(
{"max_turns", "max_input_tokens", "max_output_tokens", "max_total_tokens", "max_turn_tokens", "compaction_failed"}
)
"""The stop conditions ``verifiers.v1.Trace.is_truncated`` counts as truncation."""
def trace_truncated(trace: dict) -> bool:
"""``Trace.is_truncated`` for a dumped trace: a framework limit stopped it, or its
last successful model call ran out of length."""
if trace.get("stop_condition") in TRUNCATING_STOPS:
return True
last = next((call for call in reversed(trace.get("calls") or []) if call.get("error") is None), None)
return bool(last and last.get("finish_reason") == "length")
def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
"""One index row: what the table, the filters, the chart and the sort need.
@@ -84,22 +62,13 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
timing: dict[str, float] = {}
costs: list[float] = []
for trace in rec.get("traces") or []:
costs.extend(
usage["cost"]
for call in trace.get("calls") or []
if isinstance(usage := call.get("usage") or {}, dict) and isinstance(usage.get("cost"), (int, float))
)
nodes = trace.get("nodes") or []
parents = {node.get("parent") for node in nodes if "parent" in node}
branches += max(0, len(nodes) - len(parents))
if trace.get("rewards"): # skip reward-less seats (e.g. a judge) in the episode mean
rewards.append(
sum(
(r.get("score") or 0) * (r.get("weight") if r.get("weight") is not None else 1)
for r in trace["rewards"].values()
if isinstance(r, dict)
)
)
if isinstance(cost := (trace.get("usage") or {}).get("cost"), (int, float)):
costs.append(cost)
branches += trace.get("num_branches") or 0
turns += trace.get("num_turns") or 0
# skip reward-less seats (e.g. a judge) in the episode mean
if trace.get("rewards") and isinstance(trace.get("reward"), (int, float)):
rewards.append(trace["reward"])
for name, r in (trace.get("rewards") or {}).items():
if isinstance(r, dict) and isinstance(r.get("score"), (int, float)):
reward_parts.setdefault(name, []).append(r["score"])
@@ -111,11 +80,8 @@ def summarize_episode(line: int, rec: dict, offset: int | None = None) -> dict:
advantage = (trace.get("info") or {}).get("advantage")
if advantage is not None:
advantages.append(advantage)
for node in nodes:
if node.get("sampled"):
turns += 1
stop_condition = trace.get("stop_condition", stop_condition)
truncated = truncated or trace_truncated(trace)
truncated = truncated or bool(trace.get("is_truncated"))
timeout = timeout or bool(trace.get("is_timeout"))
first_info = ((rec.get("traces") or [{}])[0].get("info")) or {}
return {
+16 -7
View File
@@ -1,5 +1,7 @@
import verifiers.v1 as vf
from prime_rl.dashboard.server import project_episode_timeline
from prime_rl.monitors.file.traces.index import index_row, summarize_episode
from prime_rl.monitors.file.traces.index import index_record, index_row, summarize_episode
def _node(
@@ -55,17 +57,24 @@ def test_episode_summary_excludes_copied_assistant_context_from_turns() -> None:
{"parent": None, "message": {"role": "user", "content": "Find a property"}},
{"parent": 0, "message": response, "sampled": True},
{"parent": 0, "message": response.copy(), "sampled": False},
{"parent": 2, "message": {"role": "tool", "content": "Property details"}},
{"parent": 2, "message": {"role": "tool", "tool_call_id": "call-0", "content": "Property details"}},
{"parent": 3, "message": {"role": "assistant", "content": "Found it"}, "sampled": True},
{"parent": 0, "message": response.copy()},
]
episode = _episode(nodes, [_call(1, 0.0, 1.0), _call(4, 2.0, 3.0)])
episode["traces"].append(
{"nodes": [{"parent": None, "message": response.copy(), "sampled": True}], "calls": [_call(0, 0.0, 1.0)]}
task = {"type": "Task", "data": {"idx": 0}}
trace = {"task": task, "agent": {"config": {}}}
episode = vf.WireEpisode.model_validate(
{
"task": task,
"traces": [
{**trace, "nodes": nodes},
{**trace, "nodes": [{"parent": None, "message": response.copy(), "sampled": True}]},
],
}
)
assert summarize_episode(1, episode)["turns"] == 3
assert index_row(1, episode, chunk=0, offset=0)["turns"] == 3
assert summarize_episode(1, episode.to_record())["turns"] == 3
assert index_row(1, index_record(episode), chunk=0, offset=0)["turns"] == 3
def test_semantic_timeline_projects_concurrent_fork_join() -> None:
Generated
+4 -4
View File
@@ -5493,7 +5493,7 @@ train = [
[[package]]
name = "prime-sandboxes"
version = "0.5.5"
version = "0.5.7"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiofiles" },
@@ -5505,9 +5505,9 @@ dependencies = [
{ name = "pyqwest" },
{ name = "tenacity" },
]
sdist = { url = "https://files.pythonhosted.org/packages/e2/de/d46a1e0ccb7ba380c2149056a34a4d59f659c326a4b16f0f5905252aaed4/prime_sandboxes-0.5.5.tar.gz", hash = "sha256:06d882de77ce60862b085f81379a47a1650b6b9c9dc8675d26075c34d563e7b6", size = 163390, upload-time = "2026-11-03T01:00:10.124Z" }
sdist = { url = "https://files.pythonhosted.org/packages/db/86/9c99e77c78fdc7bd42342ee30e694789bf29b82b291e4e4bf3873a363067/prime_sandboxes-0.5.7.tar.gz", hash = "sha256:17db3cdd885088821c8b2d0af3262ef153a8f6e14727abdf4b3b7424faf869e0", size = 169870, upload-time = "2026-11-06T00:50:55.852Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/5c/10/dd5b4b4be6127492c16da5b41a5009386aabfa30864529de19728a2323cd/prime_sandboxes-0.5.5-py3-none-any.whl", hash = "sha256:c0edefb060e1b0345c99cc8219d58e7567f7297ec1018dc0bbd80b35c1abb226", size = 88574, upload-time = "2026-11-03T01:00:08.28Z" },
{ url = "https://files.pythonhosted.org/packages/d7/3d/6687eeb0e6937ede5ef7ba39ce6eb7261077742e2664802077a442df1a6a/prime_sandboxes-0.5.7-py3-none-any.whl", hash = "sha256:5daa25e9206aede20e052889eb62590ba10b2b9f827621b0258d3f725db1415e", size = 91919, upload-time = "2026-11-06T00:50:54.273Z" },
]
[[package]]
@@ -8039,7 +8039,7 @@ requires-dist = [
{ name = "openenv", marker = "extra == 'openenv'", specifier = ">=0.4.1" },
{ name = "orjson", specifier = ">=3.10.0" },
{ name = "prime-pydantic-config", extras = ["toml"], specifier = ">=0.4.3" },
{ name = "prime-sandboxes", specifier = ">=0.5.5" },
{ name = "prime-sandboxes", specifier = ">=0.5.7" },
{ name = "prime-tunnel", specifier = ">=0.1.17" },
{ name = "pydantic", specifier = ">=2.12.3" },
{ name = "renderers", extras = ["multimodal"], specifier = ">=0.2.0" },