Skip to content

Commit 38ec82e

Browse files
committed
Lease the park per round and add a per-round trace viewer to the site
1 parent be7cdb5 commit 38ec82e

10 files changed

Lines changed: 481 additions & 13 deletions

File tree

‎rust/coaster-bench/src/main.rs‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -256,10 +256,11 @@ impl Contender {
256256
}
257257

258258
/// MCP endpoint this contender's harness should connect to. The server
259-
/// hides tools answering outside the advertised modality set.
260-
fn mcp_url(&self, port: u16) -> String {
259+
/// hides tools answering outside the advertised modality set, and refuses
260+
/// anyone whose lease is not the one that currently owns the park.
261+
fn mcp_url(&self, port: u16, lease: &str) -> String {
261262
format!(
262-
"http://host.containers.internal:{port}/mcp?modalities={}",
263+
"http://host.containers.internal:{port}/mcp?modalities={}&lease={lease}",
263264
self.modalities.as_query_value()
264265
)
265266
}
@@ -320,12 +321,12 @@ fn openrouter_spend() -> Option<f64> {
320321

321322
/// Point the opencode sandbox at this contender's MCP endpoint. Written fresh
322323
/// per session so a mixed vision/text-only lineup can share one sandbox.
323-
fn write_opencode_config(args: &Args, contender: &Contender) -> Result<(), String> {
324+
fn write_opencode_config(args: &Args, contender: &Contender, lease: &str) -> Result<(), String> {
324325
let config = json!({
325326
"$schema": "https://opencode.ai/config.json",
326327
"model": contender.model,
327328
"mcp": {
328-
"coaster": {"type": "remote", "url": contender.mcp_url(args.port), "enabled": true}
329+
"coaster": {"type": "remote", "url": contender.mcp_url(args.port, lease), "enabled": true}
329330
}
330331
})
331332
.to_string();
@@ -381,6 +382,7 @@ fn run_agent_session(
381382
contender: &Contender,
382383
prompt: &str,
383384
round_dir: &Path,
385+
lease: &str,
384386
) -> SessionResult {
385387
let mut cmd = Command::new("openshell");
386388
let spend_before = match contender.harness {
@@ -391,7 +393,7 @@ fn run_agent_session(
391393
Harness::ClaudeCode => {
392394
let mcp_config = json!({
393395
"mcpServers": {
394-
"coaster": {"type": "http", "url": contender.mcp_url(args.port)}
396+
"coaster": {"type": "http", "url": contender.mcp_url(args.port, lease)}
395397
}
396398
});
397399
cmd.args(["sandbox", "exec", "-n", &args.sandbox, "--"])
@@ -407,7 +409,7 @@ fn run_agent_session(
407409
// sandbox, so the per-contender endpoint has to be written there
408410
// before the session starts. Model comes fully qualified on the
409411
// command line (e.g. openrouter/poolside/...).
410-
if let Err(e) = write_opencode_config(args, contender) {
412+
if let Err(e) = write_opencode_config(args, contender, lease) {
411413
return SessionResult {
412414
usage: Value::Null,
413415
error: Some(e),
@@ -585,6 +587,14 @@ fn best_excitement(report: &Value) -> Option<f64> {
585587
Some(raw * multiplier)
586588
}
587589

590+
/// Wall-clock seconds, used to make each round's lease unique across restarts.
591+
fn epoch_secs() -> u64 {
592+
SystemTime::now()
593+
.duration_since(UNIX_EPOCH)
594+
.unwrap_or_default()
595+
.as_secs()
596+
}
597+
588598
fn today() -> String {
589599
// No chrono dep for one date string: days since epoch -> civil date.
590600
let secs = SystemTime::now()
@@ -708,6 +718,10 @@ fn main() -> Result<(), String> {
708718
let mut best: Option<(u32, f64)> = None;
709719
let mut feedback: Option<String> = None;
710720
for round in 1..=args.rounds {
721+
// One lease per round: claiming it evicts any agent still alive
722+
// from an earlier round, which would otherwise build in this park.
723+
let lease = format!("{}-r{round}-{}", model, epoch_secs());
724+
client.claim("127.0.0.1", args.port, &lease);
711725
// A fresh park state for every round.
712726
let _ = client.call("demolish", json!({}));
713727
let prompt = prompt::round_prompt(
@@ -727,7 +741,7 @@ fn main() -> Result<(), String> {
727741
"[{model}] round {round}: agent session starting (log: {})",
728742
round_dir.join("session.log").display()
729743
);
730-
let session = run_agent_session(&args, contender, &prompt, &round_dir);
744+
let session = run_agent_session(&args, contender, &prompt, &round_dir, &lease);
731745
if let Some(e) = &session.error {
732746
eprintln!("[{model}] round {round}: {e}");
733747
}
@@ -818,10 +832,12 @@ mod tests {
818832
model: "claude-sonnet-5".into(),
819833
modalities: Modalities::TEXT | Modalities::IMAGE,
820834
};
821-
assert!(text_only.mcp_url(8791).ends_with("/mcp?modalities=text"));
835+
assert!(text_only
836+
.mcp_url(8791, "lease-1")
837+
.ends_with("/mcp?modalities=text&lease=lease-1"));
822838
assert!(multimodal
823-
.mcp_url(8791)
824-
.ends_with("/mcp?modalities=text,image"));
839+
.mcp_url(8791, "lease-1")
840+
.ends_with("/mcp?modalities=text,image&lease=lease-1"));
825841
}
826842

827843
#[test]

‎rust/coaster-bench/src/mcp.rs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,17 @@ impl McpClient {
1616
}
1717
}
1818

19+
/// Takes ownership of the park for `lease`, locking out any agent still
20+
/// alive from an earlier round. Every later request carries the lease.
21+
pub fn claim(&mut self, host: &str, port: u16, lease: &str) {
22+
self.url = format!("http://{host}:{port}/mcp?lease={lease}&claim=1");
23+
let claimed = self.call("get_state", json!({})).is_ok();
24+
// Ownership is taken by the claim=1 request itself; drop the flag so
25+
// the rest of the round runs as an ordinary lease holder.
26+
self.url = format!("http://{host}:{port}/mcp?lease={lease}");
27+
let _ = claimed;
28+
}
29+
1930
fn rpc(&mut self, method: &str, params: Value) -> Result<Value, String> {
2031
let id = self.next_id;
2132
self.next_id += 1;

‎rust/coaster-site/src/main.rs‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -239,6 +239,134 @@ fn model_href(run: &EvalRun, model: &str) -> String {
239239
format!("run-{}-{}.html", run.name, model::sanitise_name(model))
240240
}
241241

242+
/// One round's session trace lives on its own page: a long round runs to
243+
/// hundreds of events, which would bury the ratings on the model page.
244+
fn trace_href(run: &EvalRun, model: &str, round: u32) -> String {
245+
format!(
246+
"trace-{}-{}-r{round}.html",
247+
run.name,
248+
model::sanitise_name(model)
249+
)
250+
}
251+
252+
fn fmt_elapsed(ms: i64) -> String {
253+
let secs = ms.max(0) / 1000;
254+
format!("{}:{:02}", secs / 60, secs % 60)
255+
}
256+
257+
fn fmt_json_compact(value: &serde_json::Value, limit: usize) -> Option<String> {
258+
let text = match value {
259+
serde_json::Value::Null => return None,
260+
serde_json::Value::String(s) => s.clone(),
261+
other => other.to_string(),
262+
};
263+
let text = text.trim();
264+
if text.is_empty() || text == "{}" {
265+
return None;
266+
}
267+
Some(clamp(text, limit))
268+
}
269+
270+
/// Long tool payloads are truncated: a `valid_next_pieces` result runs to
271+
/// kilobytes and the interesting part is always at the front.
272+
fn clamp(text: &str, limit: usize) -> String {
273+
if text.chars().count() <= limit {
274+
return text.to_string();
275+
}
276+
let head: String = text.chars().take(limit).collect();
277+
format!("{head}… ({} chars)", text.chars().count())
278+
}
279+
280+
fn build_trace_page(
281+
run: &EvalRun,
282+
model: &ModelRun,
283+
round: &Round,
284+
base_url: Option<&str>,
285+
out: &Path,
286+
) -> Result<()> {
287+
let tools = round.trace.iter().filter(|e| e.is_tool()).count();
288+
let rejected = round.trace.iter().filter(|e| e.is_rejection()).count();
289+
let elapsed = round.trace.iter().filter_map(|e| e.ms).max().unwrap_or(0);
290+
let cost: f64 = round.trace.iter().filter_map(|e| e.cost_usd).sum();
291+
292+
let mut summary = vec![
293+
view::TraceSummary {
294+
label: "events".into(),
295+
value: round.trace.len().to_string(),
296+
class: String::new(),
297+
},
298+
view::TraceSummary {
299+
label: "tool calls".into(),
300+
value: tools.to_string(),
301+
class: String::new(),
302+
},
303+
view::TraceSummary {
304+
label: "rejected".into(),
305+
value: rejected.to_string(),
306+
class: if rejected > 0 { "fail" } else { "dim" }.into(),
307+
},
308+
view::TraceSummary {
309+
label: "session".into(),
310+
value: fmt_elapsed(elapsed),
311+
class: String::new(),
312+
},
313+
];
314+
if cost > 0.0 {
315+
summary.push(view::TraceSummary {
316+
label: "cost".into(),
317+
value: format!("${cost:.2}"),
318+
class: "usage".into(),
319+
});
320+
}
321+
322+
let rows = round
323+
.trace
324+
.iter()
325+
.map(|event| view::TraceRow {
326+
kind: event.kind.clone(),
327+
at: event.ms.map(fmt_elapsed).unwrap_or_default(),
328+
text: event.text.as_ref().map(|t| clamp(t, 4000)),
329+
tool: event.name.clone(),
330+
input: event
331+
.input
332+
.as_ref()
333+
.and_then(|v| fmt_json_compact(v, 1200)),
334+
output: event
335+
.output
336+
.as_ref()
337+
.and_then(|v| fmt_json_compact(v, 1200)),
338+
failed: event.is_rejection(),
339+
duration: event.dur_ms.map(|d| format!("{d} ms")),
340+
cost: event
341+
.cost_usd
342+
.filter(|c| *c > 0.0)
343+
.map(|c| format!("${c:.4}")),
344+
})
345+
.collect();
346+
347+
let path = trace_href(run, &model.model, round.number);
348+
let page = view::TracePage {
349+
chrome: Chrome::new(
350+
&format!(
351+
"Coaster Evals — {} · {} · round {}",
352+
run.name, model.model, round.number
353+
),
354+
&format!("TRACE · ROUND {}", round.number),
355+
&path,
356+
base_url,
357+
)
358+
.width(view::Width::Mid),
359+
run_name: run.name.clone(),
360+
run_href: format!("run-{}.html", run.name),
361+
model: model.model.clone(),
362+
model_href: model_href(run, &model.model),
363+
round: round.number,
364+
summary,
365+
rows,
366+
};
367+
write_page(&out.join(&path), &page.render()?)
368+
}
369+
242370
/// Builds one model's view (chart, studied designs, every round). Copies the
243371
/// round captures into the site as a side effect, so it runs once per model
244372
/// and both the run comparison and the model detail page render from it.
@@ -259,6 +387,10 @@ fn build_model_view(
259387
let stats = round_stats(round);
260388
rounds.push(RoundView {
261389
number: round.number,
390+
trace_href: (!round.trace.is_empty())
391+
.then(|| trace_href(run, &model.model, round.number)),
392+
trace_events: round.trace.len(),
393+
trace_rejections: round.trace.iter().filter(|e| e.is_rejection()).count(),
262394
badge: round_badge(round, stats.as_ref()),
263395
build_error: round.build_error.clone(),
264396
unrated_note: stats.is_none() && round.build_error.is_none(),
@@ -377,6 +509,11 @@ fn build_run_page(
377509
for (i, view) in models.iter().enumerate() {
378510
build_model_page(run, view, i + 1, base_url, out)?;
379511
}
512+
for model in &run.models {
513+
for round in model.rounds.iter().filter(|r| !r.trace.is_empty()) {
514+
build_trace_page(run, model, round, base_url, out)?;
515+
}
516+
}
380517

381518
let path = format!("run-{}.html", run.name);
382519
let page = RunPage {

‎rust/coaster-site/src/model.rs‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,9 +153,61 @@ pub struct Round {
153153
pub lookups: Vec<Lookup>,
154154
/// Token/cost accounting for the round (usage.json), when recorded.
155155
pub usage: Option<Usage>,
156+
/// Normalised agent session events (trace.jsonl), oldest first. Only rounds
157+
/// driven by coaster-bench have one.
158+
pub trace: Vec<TraceEvent>,
156159
grace: f64,
157160
}
158161

162+
/// One event from a round's trace.jsonl. Field meanings are set by
163+
/// coaster-bench's trace module; everything past `kind` is optional because a
164+
/// killed session leaves half-written events behind.
165+
#[derive(Debug, Deserialize)]
166+
pub struct TraceEvent {
167+
pub kind: String,
168+
#[serde(default)]
169+
pub ms: Option<i64>,
170+
#[serde(default)]
171+
pub text: Option<String>,
172+
#[serde(default)]
173+
pub name: Option<String>,
174+
#[serde(default)]
175+
pub input: Option<serde_json::Value>,
176+
#[serde(default)]
177+
pub output: Option<serde_json::Value>,
178+
#[serde(default)]
179+
pub status: Option<String>,
180+
#[serde(default)]
181+
pub dur_ms: Option<i64>,
182+
#[serde(default)]
183+
pub cost_usd: Option<f64>,
184+
}
185+
186+
impl TraceEvent {
187+
pub fn is_tool(&self) -> bool {
188+
self.kind == "tool"
189+
}
190+
191+
/// A tool call the game refused: the rejections are the substance of a
192+
/// trace, so they get counted and highlighted separately.
193+
pub fn is_rejection(&self) -> bool {
194+
self.is_tool() && self.status.as_deref() == Some("error")
195+
}
196+
}
197+
198+
/// Reads trace.jsonl, skipping any line that fails to parse: a session killed
199+
/// mid-write can leave a truncated last line, and a partial trace still
200+
/// explains more than no trace.
201+
fn read_trace(path: &Path) -> Vec<TraceEvent> {
202+
let Ok(raw) = std::fs::read_to_string(path) else {
203+
return Vec::new();
204+
};
205+
raw.lines()
206+
.filter(|l| l.starts_with('{'))
207+
.filter_map(|l| serde_json::from_str(l).ok())
208+
.collect()
209+
}
210+
159211
impl Round {
160212
/// Raw excitement scaled down for copying a stock library design.
161213
pub fn excitement(&self) -> f64 {
@@ -404,6 +456,7 @@ fn load_round(
404456
xray_shot: art("park-x.png"),
405457
lookups: read_json_opt(&round_dir.join("lookups.json"))?.unwrap_or_default(),
406458
usage: read_json_opt(&round_dir.join("usage.json"))?,
459+
trace: read_trace(&round_dir.join("trace.jsonl")),
407460
grace,
408461
}))
409462
}

0 commit comments

Comments
 (0)