From 39b041425eb6d9010ac647079ffee8841d20fcf7 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Thu, 19 Nov 2026 19:37:56 -0500 Subject: [PATCH 01/10] Reuse a deleted benchmark database's identity when it is republished --- .../src/bench/publishers.rs | 43 ++++++++++++++++++- 1 file changed, 41 insertions(+), 2 deletions(-) diff --git a/tools/xtask-llm-benchmark/src/bench/publishers.rs b/tools/xtask-llm-benchmark/src/bench/publishers.rs index 33d6e386384..d649cf84ed5 100644 --- a/tools/xtask-llm-benchmark/src/bench/publishers.rs +++ b/tools/xtask-llm-benchmark/src/bench/publishers.rs @@ -3,11 +3,12 @@ use crate::eval::spacetime_command; use anyhow::{bail, Context, Result}; use regex::Regex; use std::borrow::Cow; +use std::collections::BTreeMap; use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use std::sync::LazyLock; +use std::sync::{LazyLock, Mutex}; use std::time::{SystemTime, UNIX_EPOCH}; static CLI_SESSION_TAG: LazyLock = LazyLock::new(|| { @@ -130,6 +131,14 @@ fn resolve_node_exe(nodejs_dir: Option<&Path>) -> Option { }) } +// A deleted database keeps its name owner, so a republish under the same name +// (a C# reference rebuilt for a retry) must log in as the same identity. +static REMOVED_CLI_CONFIGS: Mutex> = Mutex::new(BTreeMap::new()); + +fn cli_config_path(root: &Path) -> PathBuf { + root.join("config/cli.toml") +} + struct CliRootDir { path: PathBuf, remove_on_drop: bool, @@ -141,6 +150,12 @@ impl CliRootDir { } fn remove(&self) -> Result<()> { + if let Ok(config) = fs::read_to_string(cli_config_path(&self.path)) { + REMOVED_CLI_CONFIGS + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .insert(self.path.clone(), config); + } match fs::remove_dir_all(&self.path) { Ok(()) => Ok(()), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), @@ -364,6 +379,15 @@ fn database_cli_root(module_name: &str, remove_on_drop: bool) -> Result bool { #[cfg(test)] mod tests { - use super::{is_transient_build_error, CliRootDir}; + use super::{cli_config_path, database_cli_root, database_owner_token, is_transient_build_error, CliRootDir}; use std::fs; #[test] @@ -491,6 +515,21 @@ mod tests { assert!(!path.exists()); } + #[test] + fn republish_after_removal_reuses_the_identity() { + let module = format!("identity-reuse-test-{}", std::process::id()); + let root = database_cli_root(&module, true).unwrap(); + let config = cli_config_path(root.path()); + fs::create_dir_all(config.parent().unwrap()).unwrap(); + fs::write(&config, "spacetimedb_token = \"owner\"\n").unwrap(); + drop(root); + assert!(!config.exists()); + + let root = database_cli_root(&module, true).unwrap(); + assert_eq!(database_owner_token(&module).unwrap(), "owner"); + drop(root); + } + #[test] fn cli_root_can_relinquish_cleanup_to_a_republish() { let path = std::env::temp_dir().join(format!("stdb-cli-root-republish-test-{}", std::process::id())); From e817ad8b3d2ba7fca674261936c84768b4c73546 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 09:49:57 -0500 Subject: [PATCH 02/10] Keep the benchmark Discord post to our problems and attach the details --- .github/workflows/llm-benchmark-periodic.yml | 9 +- .../llm-benchmark-summary/src/main.rs | 306 +++++++++++++----- .../llm-benchmark-summary/tests/cli.rs | 9 +- 3 files changed, 234 insertions(+), 90 deletions(-) diff --git a/.github/workflows/llm-benchmark-periodic.yml b/.github/workflows/llm-benchmark-periodic.yml index e3f23bc7d9f..1f1b7095dc6 100644 --- a/.github/workflows/llm-benchmark-periodic.yml +++ b/.github/workflows/llm-benchmark-periodic.yml @@ -343,6 +343,7 @@ jobs: --run-url "$RUN_URL" --run-label "$RUN_LABEL" --output discord-payload.json + --attachment analysis.md - name: Post Discord summary if: github.event_name == 'schedule' || inputs.post_discord @@ -355,7 +356,11 @@ jobs: exit 0 fi + attachment=() + if [ -s analysis.md ]; then + attachment=(--form 'files[0]=@analysis.md;type=text/markdown') + fi curl --fail --silent --show-error \ - --header 'Content-Type: application/json' \ - --data-binary @discord-payload.json \ + --form 'payload_json=, - other_findings: Vec, + actions: Vec, + infrastructure: Vec, } fn field<'a>(text: &'a str, name: &str) -> &'a str { @@ -48,6 +60,37 @@ fn language_name(language: &str) -> &str { } } +fn severity_rank(severity: &str) -> u8 { + match severity.to_ascii_lowercase().as_str() { + "critical" => 0, + "high" => 1, + "medium" => 2, + "low" => 3, + _ => 4, + } +} + +/// Splits `**[Category | Severity] Title.** Details` into its parts. +fn parse_action(prefix: &str, item: &str) -> Action { + let parts = item.strip_prefix("**[").and_then(|rest| { + let (tag, rest) = rest.split_once(']')?; + let (title, _) = rest.split_once("**")?; + let (category, severity) = tag.split_once('|').unwrap_or((tag, "")); + Some((category.trim(), severity.trim(), title.trim().trim_end_matches('.'))) + }); + let (category, severity, title) = parts.unwrap_or(("Other", "", item)); + Action { + category: category.to_owned(), + severity: severity.to_owned(), + headline: if severity.is_empty() { + format!("- {prefix}: {title}") + } else { + format!("- {prefix}: [{severity}] {title}") + }, + line: format!("- {prefix}: {item}"), + } +} + fn parse_report(text: &str) -> Report { let language = field(text, "Language"); let mode = field(text, "Mode"); @@ -62,7 +105,7 @@ fn parse_report(text: &str) -> Report { passed_tasks, total_tasks, actions: Vec::new(), - other_findings: Vec::new(), + infrastructure: Vec::new(), }; let language = language_name(language); let mut section = ""; @@ -72,7 +115,9 @@ fn parse_report(text: &str) -> Report { section = heading; title = ""; } else if section == "Recommended actions" && line.starts_with("- **[") { - report.actions.push(format!("- {language} / {mode}: {}", &line[2..])); + report + .actions + .push(parse_action(&format!("{language} / {mode}"), &line[2..])); } else if section == "Failure patterns" { if let Some(heading) = line.strip_prefix("### ") { title = heading @@ -84,16 +129,10 @@ fn parse_report(text: &str) -> Report { .is_some_and(|count| count.parse::().is_ok()) }) .map_or(heading, |(title, _)| title); - } else if let Some(classification) = line.strip_prefix("- **Classification:** ") - && !title.is_empty() - && matches!( - classification, - "Model limitation" | "Infrastructure/provider problem" | "No action" - ) - { + } else if line.strip_prefix("- **Classification:** ") == Some(INFRASTRUCTURE) && !title.is_empty() { report - .other_findings - .push(format!("- {language} / {mode} / {model}: {title} - {classification}")); + .infrastructure + .push(format!("- {language} / {mode} / {model}: {title}")); } } } @@ -131,67 +170,130 @@ fn rate(passed: u64, total: u64) -> String { format!("{passed}/{total} ({percent:.1}%)") } -fn field_value(lines: &[String], empty: &str, overflow_label: &str) -> String { +fn utf16_len(text: &str) -> usize { + text.encode_utf16().count() +} + +/// Keeps as many whole lines as Discord allows in a field, then says how many were left out. +fn field_value(lines: &[String], empty: &str, max_items: usize) -> String { let mut seen = BTreeSet::new(); let unique: Vec<_> = lines.iter().filter(|line| seen.insert(line.as_str())).collect(); - let mut value = if unique.is_empty() { - empty.to_owned() - } else { - unique + if unique.is_empty() { + return empty.to_owned(); + } + let more = |hidden: usize| (hidden > 0).then(|| format!("- ...and {hidden} more")); + for shown in (1..=unique.len().min(max_items)).rev() { + let mut value = unique[..shown] .iter() - .take(MAX_ITEMS) .map(|line| line.as_str()) .collect::>() - .join("\n") - }; - if unique.len() > MAX_ITEMS { - value.push_str(&format!( - "\n- ...and {} more {overflow_label}(s)", - unique.len() - MAX_ITEMS - )); + .join("\n"); + if let Some(more) = more(unique.len() - shown) { + value = format!("{value}\n{more}"); + } + // Discord counts UTF-16 units. + if utf16_len(&value) <= MAX_FIELD_LENGTH { + return value; + } } - // Discord counts UTF-16 units; keep Unicode text intact when limiting a field. - if value.encode_utf16().count() > MAX_FIELD_LENGTH { - let suffix = "\n... View the full analysis."; - let mut length = 0; - value = value - .chars() - .take_while(|ch| { - length += ch.len_utf16(); - length <= MAX_FIELD_LENGTH - suffix.len() - }) - .collect(); - value.truncate(value.trim_end().len()); - value.push_str(suffix); + // Even the first line is too long: cut it at a word. + let tail = more(unique.len() - 1).map_or(String::new(), |more| format!("\n{more}")); + let budget = MAX_FIELD_LENGTH.saturating_sub(utf16_len(&tail) + 1); + let mut length = 0; + let first: String = unique[0] + .chars() + .take_while(|ch| { + length += ch.len_utf16(); + length <= budget + }) + .collect(); + let first = first + .rsplit_once(' ') + .map_or(first.as_str(), |(head, _)| head) + .trim_end(); + format!("{first}…{tail}") +} + +fn action_lines(actions: &[&Action]) -> Vec { + let mut by_category = BTreeMap::<&str, Vec<&Action>>::new(); + for action in actions { + by_category.entry(&action.category).or_default().push(action); + } + let mut categories: Vec<_> = by_category.into_iter().collect(); + categories.sort_by_key(|(_, items)| Reverse(items.len())); + let mut lines = Vec::new(); + for (category, items) in &categories { + let high = items + .iter() + .filter(|action| severity_rank(&action.severity) <= 1) + .count(); + lines.push(if high > 0 { + format!("- {category}: {} ({high} high)", items.len()) + } else { + format!("- {category}: {}", items.len()) + }); + } + // The most severe headline of each category, most common category first. + for (_, items) in &categories { + if let Some(action) = items.iter().min_by_key(|action| severity_rank(&action.severity)) { + lines.push(action.headline.clone()); + } + } + lines +} + +fn attachment(actions: &[&Action], infrastructure: &[&String]) -> String { + let mut actions = actions.to_vec(); + actions.sort_by_key(|action| severity_rank(&action.severity)); + let sections = [ + ( + "Action items", + actions.iter().map(|action| action.line.as_str()).collect::>(), + ), + ( + "Infrastructure/provider problems", + infrastructure.iter().map(|line| line.as_str()).collect(), + ), + ]; + let mut text = String::new(); + for (name, lines) in sections { + let mut seen = BTreeSet::new(); + let lines: Vec<_> = lines.into_iter().filter(|line| seen.insert(*line)).collect(); + if !lines.is_empty() { + text.push_str(&format!( + "## {name} + +{} + +", + lines.join( + " +" + ) + )); + } } - value + text } -fn build_payload(reports: &[Report], run_url: &str, run_label: &str) -> Value { +fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) { let (mut passed, mut total) = (0, 0); let mut by_language = BTreeMap::<&str, (u64, u64)>::new(); - let mut actions = Vec::new(); - let mut other_findings = Vec::new(); for report in reports { passed += report.passed_tasks; total += report.total_tasks; let counts = by_language.entry(&report.language).or_default(); counts.0 += report.passed_tasks; counts.1 += report.total_tasks; - actions.extend(report.actions.iter().cloned()); - other_findings.extend(report.other_findings.iter().cloned()); } + let actions: Vec<_> = reports.iter().flat_map(|report| &report.actions).collect(); + let infrastructure: Vec<_> = reports.iter().flat_map(|report| &report.infrastructure).collect(); let percent = if total == 0 { 0.0 } else { passed as f64 * 100.0 / total as f64 }; - let color = if total == 0 - || percent < 90.0 - || other_findings - .iter() - .any(|item| item.contains("Infrastructure/provider problem")) - { + let color = if total == 0 || percent < 90.0 || !infrastructure.is_empty() { RED } else if !actions.is_empty() || percent < 95.0 { YELLOW @@ -202,7 +304,15 @@ fn build_payload(reports: &[Report], run_url: &str, run_label: &str) -> Value { .into_iter() .map(|(language, (passed, total))| format!("- **{}:** {}", language_name(language), rate(passed, total))) .collect(); - json!({ + let mut fields = vec![ + json!({"name": "By language", "value": field_value(&language_rates, "No analysis reports were produced.", usize::MAX), "inline": false}), + json!({"name": "Action items", "value": field_value(&action_lines(&actions), "None", usize::MAX), "inline": false}), + ]; + if !infrastructure.is_empty() { + let lines: Vec<_> = infrastructure.iter().map(|line| (*line).clone()).collect(); + fields.push(json!({"name": "Infrastructure/provider problems", "value": field_value(&lines, "None", MAX_ITEMS), "inline": false})); + } + let payload = json!({ "username": "SpacetimeDB LLM Benchmarks", "allowed_mentions": {"parse": []}, "embeds": [{ @@ -210,22 +320,21 @@ fn build_payload(reports: &[Report], run_url: &str, run_label: &str) -> Value { "url": run_url, "description": format!("**{}** task runs passed", rate(passed, total)), "color": color, - "fields": [ - {"name": "By language", "value": field_value(&language_rates, "No analysis reports were produced.", "language"), "inline": false}, - {"name": "Action items", "value": field_value(&actions, "None", "action"), "inline": false}, - {"name": "Other failures", "value": field_value(&other_findings, "None", "finding"), "inline": false} - ], + "fields": fields, "footer": {"text": run_label} }] - }) + }); + (payload, attachment(&actions, &infrastructure)) } fn main() -> Result<()> { let args = Cli::parse(); let reports = load_reports(&args.reports_dir)?; - let payload = build_payload(&reports, &args.run_url, &args.run_label); + let (payload, attachment) = build(&reports, &args.run_url, &args.run_label); fs::write(&args.output, serde_json::to_vec(&payload)?) - .with_context(|| format!("writing Discord payload {}", args.output.display())) + .with_context(|| format!("writing Discord payload {}", args.output.display()))?; + fs::write(&args.attachment, attachment) + .with_context(|| format!("writing Discord attachment {}", args.attachment.display())) } #[cfg(test)] @@ -239,12 +348,12 @@ mod tests { } #[test] - fn aggregates_rates_and_formats_findings() { + fn aggregates_rates_and_leaves_out_model_limitations() { let reports = [ report("csharp", "36/37 (97.3%)", "", ""), report("rust", "34/37 (91.9%)", "", "Model limitation"), ]; - let payload = build_payload(&reports, "https://example.com/run", "Weekly run"); + let (payload, attachment) = build(&reports, "https://example.com/run", "Weekly run"); let embed = &payload["embeds"][0]; assert_eq!(embed["description"], "**70/74 (94.6%)** task runs passed"); assert_eq!(embed["color"], YELLOW); @@ -252,15 +361,48 @@ mod tests { embed["fields"][0]["value"], "- **C#:** 36/37 (97.3%)\n- **Rust:** 34/37 (91.9%)" ); - assert_eq!( - embed["fields"][2]["value"], - "- Rust / guidelines / test-model: Incorrect sum-type syntax - Model limitation" - ); + assert_eq!(embed["fields"][1]["value"], "None"); + assert_eq!(embed["fields"].as_array().unwrap().len(), 2); + assert_eq!(attachment, ""); assert_eq!(payload["allowed_mentions"], json!({"parse": []})); assert_eq!(embed["url"], "https://example.com/run"); assert_eq!(embed["footer"]["text"], "Weekly run"); } + #[test] + fn groups_actions_by_category_and_attaches_the_details() { + let reports = [ + report( + "csharp", + "37/37", + "- **[Eval problem | Medium] Keep publish errors.** Store all stderr.\n- **[API/ergonomics problem | Low] Rename Index.** It collides.", + "", + ), + report( + "rust", + "37/37", + "- **[Eval problem | High] Capture build output** — Evidence: t_001.", + INFRASTRUCTURE, + ), + ]; + let (payload, attachment) = build(&reports, "", ""); + let fields = &payload["embeds"][0]["fields"]; + assert_eq!( + fields[1]["value"], + "- Eval problem: 2 (1 high)\n- API/ergonomics problem: 1\n- Rust / guidelines: [High] Capture build output\n- C# / guidelines: [Low] Rename Index" + ); + assert_eq!(fields[2]["name"], "Infrastructure/provider problems"); + assert_eq!( + fields[2]["value"], + "- Rust / guidelines / test-model: Incorrect sum-type syntax" + ); + assert_eq!(payload["embeds"][0]["color"], RED); + assert_eq!( + attachment, + "## Action items\n\n- Rust / guidelines: **[Eval problem | High] Capture build output** — Evidence: t_001.\n- C# / guidelines: **[Eval problem | Medium] Keep publish errors.** Store all stderr.\n- C# / guidelines: **[API/ergonomics problem | Low] Rename Index.** It collides.\n\n## Infrastructure/provider problems\n\n- Rust / guidelines / test-model: Incorrect sum-type syntax\n\n" + ); + } + #[test] fn colors_reflect_pass_rate_actions_and_infrastructure() { for (tasks, action, classification, color) in [ @@ -269,41 +411,37 @@ mod tests { ("30/37", "", "Model limitation", RED), ( "37/37", - "- **[Skill problem | High] Clarify transactions** — Update the skill. Evidence: t_075.", - "Skill problem", + "- **[Skill problem | High] Clarify transactions** — Update the skill.", + "", YELLOW, ), - ("37/37", "", "Infrastructure/provider problem", RED), + ("37/37", "", INFRASTRUCTURE, RED), ] { - let payload = build_payload(&[report("csharp", tasks, action, classification)], "", ""); + let (payload, _) = build(&[report("csharp", tasks, action, classification)], "", ""); assert_eq!(payload["embeds"][0]["color"], color); - if !action.is_empty() { - assert_eq!( - payload["embeds"][0]["fields"][1]["value"], - format!("- C# / guidelines: {}", &action[2..]) - ); - assert_eq!(payload["embeds"][0]["fields"][2]["value"], "None"); - } } } #[test] fn empty_and_long_fields_stay_valid() { - let payload = build_payload(&[], "", ""); + let (payload, _) = build(&[], "", ""); assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( payload["embeds"][0]["fields"][0]["value"], "No analysis reports were produced." ); let lines: Vec<_> = (0..6).map(|i| format!("- {i} {}", "🦀".repeat(400))).collect(); - let value = field_value(&lines, "None", "finding"); - assert!(value.encode_utf16().count() <= MAX_FIELD_LENGTH); - assert!(value.ends_with("... View the full analysis.")); + let value = field_value(&lines, "None", usize::MAX); + assert!(utf16_len(&value) <= MAX_FIELD_LENGTH); + assert!(value.ends_with("\n- ...and 5 more")); + let value = field_value(&["word ".repeat(300)], "None", usize::MAX); + assert!(utf16_len(&value) <= MAX_FIELD_LENGTH); + assert!(value.ends_with("word…")); let mut lines: Vec<_> = (0..6).map(|i| format!("- {i}")).collect(); lines.insert(1, "- 0".to_owned()); assert_eq!( - field_value(&lines, "None", "finding"), - "- 0\n- 1\n- 2\n- 3\n- 4\n- ...and 1 more finding(s)" + field_value(&lines, "None", 5), + "- 0\n- 1\n- 2\n- 3\n- 4\n- ...and 1 more" ); } } diff --git a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs index a8e7f81bf14..cb92a7bd7ca 100644 --- a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs +++ b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs @@ -15,6 +15,7 @@ fn formats_downloaded_reports_and_reports_io_errors() { let reports = root.join("reports"); fs::create_dir_all(&root).unwrap(); let output = root.join("payload.json"); + let attachment = root.join("analysis.md"); // Nextest archives relocate binaries, so prefer its runtime path over the compile-time one. let exe = std::env::var_os("NEXTEST_BIN_EXE_ci-llm-benchmark-summary") .unwrap_or_else(|| env!("CARGO_BIN_EXE_ci-llm-benchmark-summary").into()); @@ -25,6 +26,8 @@ fn formats_downloaded_reports_and_reports_io_errors() { .args(["--run-url", "https://example.com/run", "--run-label", "Manual run"]) .arg("--output") .arg(&output) + .arg("--attachment") + .arg(&attachment) .output() .unwrap() }; @@ -50,10 +53,8 @@ fn formats_downloaded_reports_and_reports_io_errors() { embed["fields"][0]["value"], "- **Rust:** 1/1 (100.0%)\n- **TypeScript:** 2/3 (66.7%)" ); - assert_eq!( - embed["fields"][2]["value"], - "- TypeScript / guidelines / test-model: API usage - Model limitation" - ); + assert_eq!(embed["fields"][1]["value"], "None"); + assert_eq!(fs::read_to_string(&attachment).unwrap(), ""); let broken = reports.join("broken.md"); fs::write(&broken, [0xff]).unwrap(); From ef97656d7f1be5047120b17e4cade8a9e76a3b66 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 09:53:35 -0500 Subject: [PATCH 03/10] Attach the benchmark details as plain text so Discord shows a short preview --- .github/workflows/llm-benchmark-periodic.yml | 6 +-- .../llm-benchmark-summary/src/main.rs | 51 ++++++++++--------- .../llm-benchmark-summary/tests/cli.rs | 2 +- 3 files changed, 32 insertions(+), 27 deletions(-) diff --git a/.github/workflows/llm-benchmark-periodic.yml b/.github/workflows/llm-benchmark-periodic.yml index 1f1b7095dc6..f674e567a88 100644 --- a/.github/workflows/llm-benchmark-periodic.yml +++ b/.github/workflows/llm-benchmark-periodic.yml @@ -343,7 +343,7 @@ jobs: --run-url "$RUN_URL" --run-label "$RUN_LABEL" --output discord-payload.json - --attachment analysis.md + --attachment analysis.txt - name: Post Discord summary if: github.event_name == 'schedule' || inputs.post_discord @@ -357,8 +357,8 @@ jobs: fi attachment=() - if [ -s analysis.md ]; then - attachment=(--form 'files[0]=@analysis.md;type=text/markdown') + if [ -s analysis.txt ]; then + attachment=(--form 'files[0]=@analysis.txt;type=text/plain') fi curl --fail --silent --show-error \ --form 'payload_json= u8 { fn parse_action(prefix: &str, item: &str) -> Action { let parts = item.strip_prefix("**[").and_then(|rest| { let (tag, rest) = rest.split_once(']')?; - let (title, _) = rest.split_once("**")?; + let (title, details) = rest.split_once("**")?; let (category, severity) = tag.split_once('|').unwrap_or((tag, "")); - Some((category.trim(), severity.trim(), title.trim().trim_end_matches('.'))) + Some(( + category.trim(), + severity.trim(), + title.trim().trim_end_matches('.'), + details.trim_start_matches([' ', '—', '–', '-']).trim(), + )) }); - let (category, severity, title) = parts.unwrap_or(("Other", "", item)); + let (category, severity, title, details) = parts.unwrap_or(("Other", "", item, "")); + let label = if severity.is_empty() { + format!("{category}, {prefix}") + } else { + format!("[{severity}] {category}, {prefix}") + }; + // Plain text, because Discord shows a .txt attachment as a short preview that expands. + let mut text = format!("{label}\n{title}."); + if !details.is_empty() { + text = format!("{text}\n{}", details.replace("**", "")); + } Action { category: category.to_owned(), severity: severity.to_owned(), @@ -87,7 +102,7 @@ fn parse_action(prefix: &str, item: &str) -> Action { } else { format!("- {prefix}: [{severity}] {title}") }, - line: format!("- {prefix}: {item}"), + text, } } @@ -247,30 +262,20 @@ fn attachment(actions: &[&Action], infrastructure: &[&String]) -> String { actions.sort_by_key(|action| severity_rank(&action.severity)); let sections = [ ( - "Action items", - actions.iter().map(|action| action.line.as_str()).collect::>(), + "ACTION ITEMS", + actions.iter().map(|action| action.text.as_str()).collect::>(), ), ( - "Infrastructure/provider problems", + "INFRASTRUCTURE/PROVIDER PROBLEMS", infrastructure.iter().map(|line| line.as_str()).collect(), ), ]; let mut text = String::new(); - for (name, lines) in sections { + for (name, items) in sections { let mut seen = BTreeSet::new(); - let lines: Vec<_> = lines.into_iter().filter(|line| seen.insert(*line)).collect(); - if !lines.is_empty() { - text.push_str(&format!( - "## {name} - -{} - -", - lines.join( - " -" - ) - )); + let items: Vec<_> = items.into_iter().filter(|item| seen.insert(*item)).collect(); + if !items.is_empty() { + text.push_str(&format!("{name}\n\n{}\n\n", items.join("\n\n"))); } } text @@ -399,7 +404,7 @@ mod tests { assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( attachment, - "## Action items\n\n- Rust / guidelines: **[Eval problem | High] Capture build output** — Evidence: t_001.\n- C# / guidelines: **[Eval problem | Medium] Keep publish errors.** Store all stderr.\n- C# / guidelines: **[API/ergonomics problem | Low] Rename Index.** It collides.\n\n## Infrastructure/provider problems\n\n- Rust / guidelines / test-model: Incorrect sum-type syntax\n\n" + "ACTION ITEMS\n\n[High] Eval problem, Rust / guidelines\nCapture build output.\nEvidence: t_001.\n\n[Medium] Eval problem, C# / guidelines\nKeep publish errors.\nStore all stderr.\n\n[Low] API/ergonomics problem, C# / guidelines\nRename Index.\nIt collides.\n\nINFRASTRUCTURE/PROVIDER PROBLEMS\n\n- Rust / guidelines / test-model: Incorrect sum-type syntax\n\n" ); } diff --git a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs index cb92a7bd7ca..6db1f43e08d 100644 --- a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs +++ b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs @@ -15,7 +15,7 @@ fn formats_downloaded_reports_and_reports_io_errors() { let reports = root.join("reports"); fs::create_dir_all(&root).unwrap(); let output = root.join("payload.json"); - let attachment = root.join("analysis.md"); + let attachment = root.join("analysis.txt"); // Nextest archives relocate binaries, so prefer its runtime path over the compile-time one. let exe = std::env::var_os("NEXTEST_BIN_EXE_ci-llm-benchmark-summary") .unwrap_or_else(|| env!("CARGO_BIN_EXE_ci-llm-benchmark-summary").into()); From a654c1df12b77e86d312e9824e24f385936d0bb5 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 09:59:35 -0500 Subject: [PATCH 04/10] Post the benchmark details after the Discord card --- .github/workflows/llm-benchmark-periodic.yml | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/.github/workflows/llm-benchmark-periodic.yml b/.github/workflows/llm-benchmark-periodic.yml index f674e567a88..8e875f62020 100644 --- a/.github/workflows/llm-benchmark-periodic.yml +++ b/.github/workflows/llm-benchmark-periodic.yml @@ -356,11 +356,15 @@ jobs: exit 0 fi - attachment=() - if [ -s analysis.txt ]; then - attachment=(--form 'files[0]=@analysis.txt;type=text/plain') - fi curl --fail --silent --show-error \ - --form 'payload_json= Date: Fri, 20 Nov 2026 10:00:27 -0500 Subject: [PATCH 05/10] Revert "Post the benchmark details after the Discord card" This reverts commit a654c1df12b77e86d312e9824e24f385936d0bb5. --- .github/workflows/llm-benchmark-periodic.yml | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/.github/workflows/llm-benchmark-periodic.yml b/.github/workflows/llm-benchmark-periodic.yml index 8e875f62020..f674e567a88 100644 --- a/.github/workflows/llm-benchmark-periodic.yml +++ b/.github/workflows/llm-benchmark-periodic.yml @@ -356,15 +356,11 @@ jobs: exit 0 fi - curl --fail --silent --show-error \ - --header 'Content-Type: application/json' \ - --data-binary @discord-payload.json \ - "$DISCORD_WEBHOOK_URL" - - # Discord shows attachments above the card, so the details follow in their own message. + attachment=() if [ -s analysis.txt ]; then - curl --fail --silent --show-error \ - --form 'payload_json={"username":"SpacetimeDB LLM Benchmarks","allowed_mentions":{"parse":[]}};type=application/json' \ - --form 'files[0]=@analysis.txt;type=text/plain' \ - "$DISCORD_WEBHOOK_URL" + attachment=(--form 'files[0]=@analysis.txt;type=text/plain') fi + curl --fail --silent --show-error \ + --form 'payload_json= Date: Fri, 20 Nov 2026 10:54:42 -0500 Subject: [PATCH 06/10] Fold the benchmark Discord card into one short description --- .../llm-benchmark-summary/src/main.rs | 283 ++++++------------ .../llm-benchmark-summary/tests/cli.rs | 11 +- 2 files changed, 99 insertions(+), 195 deletions(-) diff --git a/tools/ci/commands/llm-benchmark-summary/src/main.rs b/tools/ci/commands/llm-benchmark-summary/src/main.rs index 04bfdfa55b8..93e5ed3c42f 100644 --- a/tools/ci/commands/llm-benchmark-summary/src/main.rs +++ b/tools/ci/commands/llm-benchmark-summary/src/main.rs @@ -9,8 +9,6 @@ use std::path::{Path, PathBuf}; const GREEN: u32 = 0x57F287; const YELLOW: u32 = 0xFEE75C; const RED: u32 = 0xED4245; -const MAX_ITEMS: usize = 5; -const MAX_FIELD_LENGTH: usize = 1000; const INFRASTRUCTURE: &str = "Infrastructure/provider problem"; #[derive(Parser)] @@ -29,10 +27,11 @@ struct Cli { attachment: PathBuf, } -struct Action { +/// A problem on our side: a recommended action or an infrastructure failure. +struct Problem { category: String, severity: String, - headline: String, + title: String, text: String, } @@ -40,8 +39,7 @@ struct Report { language: String, passed_tasks: u64, total_tasks: u64, - actions: Vec, - infrastructure: Vec, + problems: Vec, } fn field<'a>(text: &'a str, name: &str) -> &'a str { @@ -70,42 +68,43 @@ fn severity_rank(severity: &str) -> u8 { } } -/// Splits `**[Category | Severity] Title.** Details` into its parts. -fn parse_action(prefix: &str, item: &str) -> Action { - let parts = item.strip_prefix("**[").and_then(|rest| { - let (tag, rest) = rest.split_once(']')?; - let (title, details) = rest.split_once("**")?; - let (category, severity) = tag.split_once('|').unwrap_or((tag, "")); - Some(( - category.trim(), - severity.trim(), - title.trim().trim_end_matches('.'), - details.trim_start_matches([' ', '—', '–', '-']).trim(), - )) - }); - let (category, severity, title, details) = parts.unwrap_or(("Other", "", item, "")); +fn problem(category: &str, severity: &str, source: &str, title: &str, details: &str) -> Problem { + let title = title.trim().trim_end_matches('.'); let label = if severity.is_empty() { - format!("{category}, {prefix}") + format!("{category}, {source}") } else { - format!("[{severity}] {category}, {prefix}") + format!("[{severity}] {category}, {source}") }; // Plain text, because Discord shows a .txt attachment as a short preview that expands. let mut text = format!("{label}\n{title}."); if !details.is_empty() { text = format!("{text}\n{}", details.replace("**", "")); } - Action { + Problem { category: category.to_owned(), severity: severity.to_owned(), - headline: if severity.is_empty() { - format!("- {prefix}: {title}") - } else { - format!("- {prefix}: [{severity}] {title}") - }, + title: title.to_owned(), text, } } +/// Splits `**[Category | Severity] Title.** Details` into its parts. +fn parse_action(source: &str, item: &str) -> Problem { + let parts = item.strip_prefix("**[").and_then(|rest| { + let (tag, rest) = rest.split_once(']')?; + let (title, details) = rest.split_once("**")?; + let (category, severity) = tag.split_once('|').unwrap_or((tag, "")); + Some(( + category.trim(), + severity.trim(), + title, + details.trim_start_matches([' ', '—', '–', '-']).trim(), + )) + }); + let (category, severity, title, details) = parts.unwrap_or(("Other", "", item, "")); + problem(category, severity, source, title, details) +} + fn parse_report(text: &str) -> Report { let language = field(text, "Language"); let mode = field(text, "Mode"); @@ -119,8 +118,7 @@ fn parse_report(text: &str) -> Report { language: language.to_owned(), passed_tasks, total_tasks, - actions: Vec::new(), - infrastructure: Vec::new(), + problems: Vec::new(), }; let language = language_name(language); let mut section = ""; @@ -131,7 +129,7 @@ fn parse_report(text: &str) -> Report { title = ""; } else if section == "Recommended actions" && line.starts_with("- **[") { report - .actions + .problems .push(parse_action(&format!("{language} / {mode}"), &line[2..])); } else if section == "Failure patterns" { if let Some(heading) = line.strip_prefix("### ") { @@ -145,9 +143,13 @@ fn parse_report(text: &str) -> Report { }) .map_or(heading, |(title, _)| title); } else if line.strip_prefix("- **Classification:** ") == Some(INFRASTRUCTURE) && !title.is_empty() { - report - .infrastructure - .push(format!("- {language} / {mode} / {model}: {title}")); + report.problems.push(problem( + INFRASTRUCTURE, + "", + &format!("{language} / {mode} / {model}"), + title, + "", + )); } } } @@ -176,109 +178,45 @@ fn load_reports(directory: &Path) -> Result> { Ok(reports) } -fn rate(passed: u64, total: u64) -> String { - let percent = if total == 0 { +fn percent(passed: u64, total: u64) -> f64 { + if total == 0 { 0.0 } else { passed as f64 * 100.0 / total as f64 - }; - format!("{passed}/{total} ({percent:.1}%)") -} - -fn utf16_len(text: &str) -> usize { - text.encode_utf16().count() -} - -/// Keeps as many whole lines as Discord allows in a field, then says how many were left out. -fn field_value(lines: &[String], empty: &str, max_items: usize) -> String { - let mut seen = BTreeSet::new(); - let unique: Vec<_> = lines.iter().filter(|line| seen.insert(line.as_str())).collect(); - if unique.is_empty() { - return empty.to_owned(); } - let more = |hidden: usize| (hidden > 0).then(|| format!("- ...and {hidden} more")); - for shown in (1..=unique.len().min(max_items)).rev() { - let mut value = unique[..shown] - .iter() - .map(|line| line.as_str()) - .collect::>() - .join("\n"); - if let Some(more) = more(unique.len() - shown) { - value = format!("{value}\n{more}"); - } - // Discord counts UTF-16 units. - if utf16_len(&value) <= MAX_FIELD_LENGTH { - return value; - } - } - // Even the first line is too long: cut it at a word. - let tail = more(unique.len() - 1).map_or(String::new(), |more| format!("\n{more}")); - let budget = MAX_FIELD_LENGTH.saturating_sub(utf16_len(&tail) + 1); - let mut length = 0; - let first: String = unique[0] - .chars() - .take_while(|ch| { - length += ch.len_utf16(); - length <= budget - }) - .collect(); - let first = first - .rsplit_once(' ') - .map_or(first.as_str(), |(head, _)| head) - .trim_end(); - format!("{first}…{tail}") } -fn action_lines(actions: &[&Action]) -> Vec { - let mut by_category = BTreeMap::<&str, Vec<&Action>>::new(); - for action in actions { - by_category.entry(&action.category).or_default().push(action); +/// One line per category, most common first, with its most severe title. +fn problem_lines(problems: &[&Problem]) -> Vec { + let mut by_category = BTreeMap::<&str, Vec<&Problem>>::new(); + for problem in problems { + by_category.entry(&problem.category).or_default().push(problem); } let mut categories: Vec<_> = by_category.into_iter().collect(); categories.sort_by_key(|(_, items)| Reverse(items.len())); - let mut lines = Vec::new(); - for (category, items) in &categories { - let high = items - .iter() - .filter(|action| severity_rank(&action.severity) <= 1) - .count(); - lines.push(if high > 0 { - format!("- {category}: {} ({high} high)", items.len()) - } else { - format!("- {category}: {}", items.len()) - }); - } - // The most severe headline of each category, most common category first. - for (_, items) in &categories { - if let Some(action) = items.iter().min_by_key(|action| severity_rank(&action.severity)) { - lines.push(action.headline.clone()); - } - } - lines + categories + .into_iter() + .filter_map(|(category, items)| { + let top = items.iter().min_by_key(|problem| severity_rank(&problem.severity))?; + Some(format!("- {category} ({}): {}", items.len(), top.title)) + }) + .collect() } -fn attachment(actions: &[&Action], infrastructure: &[&String]) -> String { - let mut actions = actions.to_vec(); - actions.sort_by_key(|action| severity_rank(&action.severity)); - let sections = [ - ( - "ACTION ITEMS", - actions.iter().map(|action| action.text.as_str()).collect::>(), - ), - ( - "INFRASTRUCTURE/PROVIDER PROBLEMS", - infrastructure.iter().map(|line| line.as_str()).collect(), - ), - ]; - let mut text = String::new(); - for (name, items) in sections { - let mut seen = BTreeSet::new(); - let items: Vec<_> = items.into_iter().filter(|item| seen.insert(*item)).collect(); - if !items.is_empty() { - text.push_str(&format!("{name}\n\n{}\n\n", items.join("\n\n"))); - } +fn attachment(problems: &[&Problem]) -> String { + let mut problems = problems.to_vec(); + problems.sort_by_key(|problem| severity_rank(&problem.severity)); + let mut seen = BTreeSet::new(); + let texts: Vec<_> = problems + .iter() + .map(|problem| problem.text.as_str()) + .filter(|text| seen.insert(*text)) + .collect(); + if texts.is_empty() { + String::new() + } else { + format!("{}\n", texts.join("\n\n")) } - text } fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) { @@ -291,45 +229,39 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) counts.0 += report.passed_tasks; counts.1 += report.total_tasks; } - let actions: Vec<_> = reports.iter().flat_map(|report| &report.actions).collect(); - let infrastructure: Vec<_> = reports.iter().flat_map(|report| &report.infrastructure).collect(); - let percent = if total == 0 { - 0.0 - } else { - passed as f64 * 100.0 / total as f64 - }; - let color = if total == 0 || percent < 90.0 || !infrastructure.is_empty() { + let problems: Vec<_> = reports.iter().flat_map(|report| &report.problems).collect(); + let rate = percent(passed, total); + let color = if total == 0 || rate < 90.0 || problems.iter().any(|problem| problem.category == INFRASTRUCTURE) { RED - } else if !actions.is_empty() || percent < 95.0 { + } else if !problems.is_empty() || rate < 95.0 { YELLOW } else { GREEN }; - let language_rates: Vec<_> = by_language - .into_iter() - .map(|(language, (passed, total))| format!("- **{}:** {}", language_name(language), rate(passed, total))) - .collect(); - let mut fields = vec![ - json!({"name": "By language", "value": field_value(&language_rates, "No analysis reports were produced.", usize::MAX), "inline": false}), - json!({"name": "Action items", "value": field_value(&action_lines(&actions), "None", usize::MAX), "inline": false}), - ]; - if !infrastructure.is_empty() { - let lines: Vec<_> = infrastructure.iter().map(|line| (*line).clone()).collect(); - fields.push(json!({"name": "Infrastructure/provider problems", "value": field_value(&lines, "None", MAX_ITEMS), "inline": false})); + let mut description = if total == 0 { + "No analysis reports were produced.".to_owned() + } else { + let languages: Vec<_> = by_language + .into_iter() + .map(|(language, (passed, total))| format!("{} {:.1}%", language_name(language), percent(passed, total))) + .collect(); + format!("**{rate:.1}%** passed ({passed}/{total}) · {}", languages.join(" · ")) + }; + let lines = problem_lines(&problems); + if !lines.is_empty() { + description = format!("{description}\n\n{}", lines.join("\n")); } let payload = json!({ "username": "SpacetimeDB LLM Benchmarks", "allowed_mentions": {"parse": []}, "embeds": [{ - "title": "LLM Benchmark Analysis", + "title": format!("LLM Benchmark Analysis · {run_label}"), "url": run_url, - "description": format!("**{}** task runs passed", rate(passed, total)), - "color": color, - "fields": fields, - "footer": {"text": run_label} + "description": description, + "color": color }] }); - (payload, attachment(&actions, &infrastructure)) + (payload, attachment(&problems)) } fn main() -> Result<()> { @@ -353,29 +285,23 @@ mod tests { } #[test] - fn aggregates_rates_and_leaves_out_model_limitations() { + fn summarizes_rates_and_leaves_out_model_limitations() { let reports = [ report("csharp", "36/37 (97.3%)", "", ""), report("rust", "34/37 (91.9%)", "", "Model limitation"), ]; let (payload, attachment) = build(&reports, "https://example.com/run", "Weekly run"); let embed = &payload["embeds"][0]; - assert_eq!(embed["description"], "**70/74 (94.6%)** task runs passed"); + assert_eq!(embed["description"], "**94.6%** passed (70/74) · C# 97.3% · Rust 91.9%"); assert_eq!(embed["color"], YELLOW); - assert_eq!( - embed["fields"][0]["value"], - "- **C#:** 36/37 (97.3%)\n- **Rust:** 34/37 (91.9%)" - ); - assert_eq!(embed["fields"][1]["value"], "None"); - assert_eq!(embed["fields"].as_array().unwrap().len(), 2); + assert_eq!(embed["title"], "LLM Benchmark Analysis · Weekly run"); + assert_eq!(embed["url"], "https://example.com/run"); assert_eq!(attachment, ""); assert_eq!(payload["allowed_mentions"], json!({"parse": []})); - assert_eq!(embed["url"], "https://example.com/run"); - assert_eq!(embed["footer"]["text"], "Weekly run"); } #[test] - fn groups_actions_by_category_and_attaches_the_details() { + fn lists_one_line_per_category_and_attaches_the_details() { let reports = [ report( "csharp", @@ -391,25 +317,19 @@ mod tests { ), ]; let (payload, attachment) = build(&reports, "", ""); - let fields = &payload["embeds"][0]["fields"]; - assert_eq!( - fields[1]["value"], - "- Eval problem: 2 (1 high)\n- API/ergonomics problem: 1\n- Rust / guidelines: [High] Capture build output\n- C# / guidelines: [Low] Rename Index" - ); - assert_eq!(fields[2]["name"], "Infrastructure/provider problems"); assert_eq!( - fields[2]["value"], - "- Rust / guidelines / test-model: Incorrect sum-type syntax" + payload["embeds"][0]["description"], + "**100.0%** passed (74/74) · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" ); assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( attachment, - "ACTION ITEMS\n\n[High] Eval problem, Rust / guidelines\nCapture build output.\nEvidence: t_001.\n\n[Medium] Eval problem, C# / guidelines\nKeep publish errors.\nStore all stderr.\n\n[Low] API/ergonomics problem, C# / guidelines\nRename Index.\nIt collides.\n\nINFRASTRUCTURE/PROVIDER PROBLEMS\n\n- Rust / guidelines / test-model: Incorrect sum-type syntax\n\n" + "[High] Eval problem, Rust / guidelines\nCapture build output.\nEvidence: t_001.\n\n[Medium] Eval problem, C# / guidelines\nKeep publish errors.\nStore all stderr.\n\n[Low] API/ergonomics problem, C# / guidelines\nRename Index.\nIt collides.\n\nInfrastructure/provider problem, Rust / guidelines / test-model\nIncorrect sum-type syntax.\n" ); } #[test] - fn colors_reflect_pass_rate_actions_and_infrastructure() { + fn colors_reflect_pass_rate_problems_and_infrastructure() { for (tasks, action, classification, color) in [ ("37/37", "", "", GREEN), ("35/37", "", "Model limitation", YELLOW), @@ -425,28 +345,11 @@ mod tests { let (payload, _) = build(&[report("csharp", tasks, action, classification)], "", ""); assert_eq!(payload["embeds"][0]["color"], color); } - } - - #[test] - fn empty_and_long_fields_stay_valid() { let (payload, _) = build(&[], "", ""); assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( - payload["embeds"][0]["fields"][0]["value"], + payload["embeds"][0]["description"], "No analysis reports were produced." ); - let lines: Vec<_> = (0..6).map(|i| format!("- {i} {}", "🦀".repeat(400))).collect(); - let value = field_value(&lines, "None", usize::MAX); - assert!(utf16_len(&value) <= MAX_FIELD_LENGTH); - assert!(value.ends_with("\n- ...and 5 more")); - let value = field_value(&["word ".repeat(300)], "None", usize::MAX); - assert!(utf16_len(&value) <= MAX_FIELD_LENGTH); - assert!(value.ends_with("word…")); - let mut lines: Vec<_> = (0..6).map(|i| format!("- {i}")).collect(); - lines.insert(1, "- 0".to_owned()); - assert_eq!( - field_value(&lines, "None", 5), - "- 0\n- 1\n- 2\n- 3\n- 4\n- ...and 1 more" - ); } } diff --git a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs index 6db1f43e08d..e41fe81c0e7 100644 --- a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs +++ b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs @@ -35,7 +35,10 @@ fn formats_downloaded_reports_and_reports_io_errors() { // A failed benchmark job can leave no report artifact to download. assert!(run().status.success()); - assert_eq!(payload()["embeds"][0]["description"], "**0/0 (0.0%)** task runs passed"); + assert_eq!( + payload()["embeds"][0]["description"], + "No analysis reports were produced." + ); fs::create_dir_all(reports.join("nested")).unwrap(); fs::write( @@ -48,12 +51,10 @@ fn formats_downloaded_reports_and_reports_io_errors() { assert!(run().status.success()); let result = payload(); let embed = &result["embeds"][0]; - assert_eq!(embed["description"], "**3/4 (75.0%)** task runs passed"); assert_eq!( - embed["fields"][0]["value"], - "- **Rust:** 1/1 (100.0%)\n- **TypeScript:** 2/3 (66.7%)" + embed["description"], + "**75.0%** passed (3/4) · Rust 100.0% · TypeScript 66.7%" ); - assert_eq!(embed["fields"][1]["value"], "None"); assert_eq!(fs::read_to_string(&attachment).unwrap(), ""); let broken = reports.join("broken.md"); From 84d56afc6e338868c3e6f93e3ce81c53d0d2735d Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 10:57:02 -0500 Subject: [PATCH 07/10] Post benchmark summaries as Spacetime LLM Benchmarks --- tools/ci/commands/llm-benchmark-summary/src/main.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/ci/commands/llm-benchmark-summary/src/main.rs b/tools/ci/commands/llm-benchmark-summary/src/main.rs index 93e5ed3c42f..2573d983aa0 100644 --- a/tools/ci/commands/llm-benchmark-summary/src/main.rs +++ b/tools/ci/commands/llm-benchmark-summary/src/main.rs @@ -252,7 +252,7 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) description = format!("{description}\n\n{}", lines.join("\n")); } let payload = json!({ - "username": "SpacetimeDB LLM Benchmarks", + "username": "Spacetime LLM Benchmarks", "allowed_mentions": {"parse": []}, "embeds": [{ "title": format!("LLM Benchmark Analysis · {run_label}"), From 308a3df2feb9e674cfa28d52ceb89a2029d52952 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 11:33:38 -0500 Subject: [PATCH 08/10] Split benchmark pass rates by mode and color the card by guidelines --- .../llm-benchmark-summary/src/main.rs | 70 ++++++++++++++----- .../llm-benchmark-summary/tests/cli.rs | 2 +- 2 files changed, 55 insertions(+), 17 deletions(-) diff --git a/tools/ci/commands/llm-benchmark-summary/src/main.rs b/tools/ci/commands/llm-benchmark-summary/src/main.rs index 2573d983aa0..75f4830a5bb 100644 --- a/tools/ci/commands/llm-benchmark-summary/src/main.rs +++ b/tools/ci/commands/llm-benchmark-summary/src/main.rs @@ -37,6 +37,7 @@ struct Problem { struct Report { language: String, + mode: String, passed_tasks: u64, total_tasks: u64, problems: Vec, @@ -49,6 +50,14 @@ fn field<'a>(text: &'a str, name: &str) -> &'a str { .unwrap_or("unknown") } +fn mode_name(mode: &str) -> &str { + match mode { + "guidelines" => "Guidelines", + "no_context" => "No context", + other => other, + } +} + fn language_name(language: &str) -> &str { match language { "csharp" => "C#", @@ -116,6 +125,7 @@ fn parse_report(text: &str) -> Report { .unwrap_or((0, 0)); let mut report = Report { language: language.to_owned(), + mode: mode.to_owned(), passed_tasks, total_tasks, problems: Vec::new(), @@ -220,16 +230,22 @@ fn attachment(problems: &[&Problem]) -> String { } fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) { - let (mut passed, mut total) = (0, 0); - let mut by_language = BTreeMap::<&str, (u64, u64)>::new(); + type Counts = (u64, u64); + let mut by_mode = BTreeMap::<&str, (Counts, BTreeMap<&str, Counts>)>::new(); for report in reports { - passed += report.passed_tasks; - total += report.total_tasks; - let counts = by_language.entry(&report.language).or_default(); - counts.0 += report.passed_tasks; - counts.1 += report.total_tasks; + let (totals, languages) = by_mode.entry(&report.mode).or_default(); + let counts = languages.entry(&report.language).or_default(); + for counts in [totals, counts] { + counts.0 += report.passed_tasks; + counts.1 += report.total_tasks; + } } let problems: Vec<_> = reports.iter().flat_map(|report| &report.problems).collect(); + let all = by_mode + .values() + .fold((0, 0), |sum, (counts, _)| (sum.0 + counts.0, sum.1 + counts.1)); + // Guidelines is what people get from our docs; no-context rates are expected to be low. + let (passed, total) = by_mode.get("guidelines").map_or(all, |(counts, _)| *counts); let rate = percent(passed, total); let color = if total == 0 || rate < 90.0 || problems.iter().any(|problem| problem.category == INFRASTRUCTURE) { RED @@ -238,14 +254,27 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) } else { GREEN }; - let mut description = if total == 0 { + let mut description = if all.1 == 0 { "No analysis reports were produced.".to_owned() } else { - let languages: Vec<_> = by_language - .into_iter() - .map(|(language, (passed, total))| format!("{} {:.1}%", language_name(language), percent(passed, total))) - .collect(); - format!("**{rate:.1}%** passed ({passed}/{total}) · {}", languages.join(" · ")) + by_mode + .iter() + .map(|(mode, ((passed, total), languages))| { + let languages: Vec<_> = languages + .iter() + .map(|(language, (passed, total))| { + format!("{} {:.1}%", language_name(language), percent(*passed, *total)) + }) + .collect(); + format!( + "**{} {:.1}%** · {}", + mode_name(mode), + percent(*passed, *total), + languages.join(" · ") + ) + }) + .collect::>() + .join("\n") }; let lines = problem_lines(&problems); if !lines.is_empty() { @@ -279,8 +308,12 @@ mod tests { use super::*; fn report(language: &str, tasks: &str, action: &str, classification: &str) -> Report { + report_in("guidelines", language, tasks, action, classification) + } + + fn report_in(mode: &str, language: &str, tasks: &str, action: &str, classification: &str) -> Report { parse_report(&format!( - "# LLM Benchmark Analysis\n\n- Language: {language}\n- Mode: guidelines\n- Model: test-model\n- Tasks: {tasks}\n- Scorers: 100/100 (100.0%)\n\n## Recommended actions\n\n{action}\n\n## Failure patterns\n\n### Incorrect sum-type syntax (1 task)\n\n- **Classification:** {classification}\n" + "# LLM Benchmark Analysis\n\n- Language: {language}\n- Mode: {mode}\n- Model: test-model\n- Tasks: {tasks}\n- Scorers: 100/100 (100.0%)\n\n## Recommended actions\n\n{action}\n\n## Failure patterns\n\n### Incorrect sum-type syntax (1 task)\n\n- **Classification:** {classification}\n" )) } @@ -289,10 +322,15 @@ mod tests { let reports = [ report("csharp", "36/37 (97.3%)", "", ""), report("rust", "34/37 (91.9%)", "", "Model limitation"), + report_in("no_context", "rust", "20/37 (54.1%)", "", "Model limitation"), ]; let (payload, attachment) = build(&reports, "https://example.com/run", "Weekly run"); let embed = &payload["embeds"][0]; - assert_eq!(embed["description"], "**94.6%** passed (70/74) · C# 97.3% · Rust 91.9%"); + assert_eq!( + embed["description"], + "**Guidelines 94.6%** · C# 97.3% · Rust 91.9%\n**No context 54.1%** · Rust 54.1%" + ); + // A low no-context rate alone does not turn the card red. assert_eq!(embed["color"], YELLOW); assert_eq!(embed["title"], "LLM Benchmark Analysis · Weekly run"); assert_eq!(embed["url"], "https://example.com/run"); @@ -319,7 +357,7 @@ mod tests { let (payload, attachment) = build(&reports, "", ""); assert_eq!( payload["embeds"][0]["description"], - "**100.0%** passed (74/74) · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" + "**Guidelines 100.0%** · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" ); assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( diff --git a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs index e41fe81c0e7..bc71fe715e3 100644 --- a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs +++ b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs @@ -53,7 +53,7 @@ fn formats_downloaded_reports_and_reports_io_errors() { let embed = &result["embeds"][0]; assert_eq!( embed["description"], - "**75.0%** passed (3/4) · Rust 100.0% · TypeScript 66.7%" + "**Guidelines 66.7%** · TypeScript 66.7%\n**unknown 100.0%** · Rust 100.0%" ); assert_eq!(fs::read_to_string(&attachment).unwrap(), ""); From 6bb06e64affea496019c492d1ee8481f0fa67303 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 11:44:21 -0500 Subject: [PATCH 09/10] Mark each benchmark mode's pass rate with a colored dot instead of the card color --- .../llm-benchmark-summary/src/main.rs | 63 ++++++------------- .../llm-benchmark-summary/tests/cli.rs | 2 +- 2 files changed, 21 insertions(+), 44 deletions(-) diff --git a/tools/ci/commands/llm-benchmark-summary/src/main.rs b/tools/ci/commands/llm-benchmark-summary/src/main.rs index 75f4830a5bb..3f7f1a00b9c 100644 --- a/tools/ci/commands/llm-benchmark-summary/src/main.rs +++ b/tools/ci/commands/llm-benchmark-summary/src/main.rs @@ -6,9 +6,6 @@ use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::{Path, PathBuf}; -const GREEN: u32 = 0x57F287; -const YELLOW: u32 = 0xFEE75C; -const RED: u32 = 0xED4245; const INFRASTRUCTURE: &str = "Infrastructure/provider problem"; #[derive(Parser)] @@ -229,6 +226,16 @@ fn attachment(problems: &[&Problem]) -> String { } } +fn dot(rate: f64) -> &'static str { + if rate >= 95.0 { + "🟢" + } else if rate >= 90.0 { + "🟡" + } else { + "🔴" + } +} + fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) { type Counts = (u64, u64); let mut by_mode = BTreeMap::<&str, (Counts, BTreeMap<&str, Counts>)>::new(); @@ -241,20 +248,8 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) } } let problems: Vec<_> = reports.iter().flat_map(|report| &report.problems).collect(); - let all = by_mode - .values() - .fold((0, 0), |sum, (counts, _)| (sum.0 + counts.0, sum.1 + counts.1)); - // Guidelines is what people get from our docs; no-context rates are expected to be low. - let (passed, total) = by_mode.get("guidelines").map_or(all, |(counts, _)| *counts); - let rate = percent(passed, total); - let color = if total == 0 || rate < 90.0 || problems.iter().any(|problem| problem.category == INFRASTRUCTURE) { - RED - } else if !problems.is_empty() || rate < 95.0 { - YELLOW - } else { - GREEN - }; - let mut description = if all.1 == 0 { + let total: u64 = by_mode.values().map(|((_, total), _)| total).sum(); + let mut description = if total == 0 { "No analysis reports were produced.".to_owned() } else { by_mode @@ -266,10 +261,11 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) format!("{} {:.1}%", language_name(language), percent(*passed, *total)) }) .collect(); + let rate = percent(*passed, *total); format!( - "**{} {:.1}%** · {}", + "{} **{} {rate:.1}%** · {}", + dot(rate), mode_name(mode), - percent(*passed, *total), languages.join(" · ") ) }) @@ -286,8 +282,7 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) "embeds": [{ "title": format!("LLM Benchmark Analysis · {run_label}"), "url": run_url, - "description": description, - "color": color + "description": description }] }); (payload, attachment(&problems)) @@ -328,10 +323,8 @@ mod tests { let embed = &payload["embeds"][0]; assert_eq!( embed["description"], - "**Guidelines 94.6%** · C# 97.3% · Rust 91.9%\n**No context 54.1%** · Rust 54.1%" + "🟡 **Guidelines 94.6%** · C# 97.3% · Rust 91.9%\n🔴 **No context 54.1%** · Rust 54.1%" ); - // A low no-context rate alone does not turn the card red. - assert_eq!(embed["color"], YELLOW); assert_eq!(embed["title"], "LLM Benchmark Analysis · Weekly run"); assert_eq!(embed["url"], "https://example.com/run"); assert_eq!(attachment, ""); @@ -357,9 +350,8 @@ mod tests { let (payload, attachment) = build(&reports, "", ""); assert_eq!( payload["embeds"][0]["description"], - "**Guidelines 100.0%** · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" + "🟢 **Guidelines 100.0%** · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" ); - assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( attachment, "[High] Eval problem, Rust / guidelines\nCapture build output.\nEvidence: t_001.\n\n[Medium] Eval problem, C# / guidelines\nKeep publish errors.\nStore all stderr.\n\n[Low] API/ergonomics problem, C# / guidelines\nRename Index.\nIt collides.\n\nInfrastructure/provider problem, Rust / guidelines / test-model\nIncorrect sum-type syntax.\n" @@ -367,24 +359,9 @@ mod tests { } #[test] - fn colors_reflect_pass_rate_problems_and_infrastructure() { - for (tasks, action, classification, color) in [ - ("37/37", "", "", GREEN), - ("35/37", "", "Model limitation", YELLOW), - ("30/37", "", "Model limitation", RED), - ( - "37/37", - "- **[Skill problem | High] Clarify transactions** — Update the skill.", - "", - YELLOW, - ), - ("37/37", "", INFRASTRUCTURE, RED), - ] { - let (payload, _) = build(&[report("csharp", tasks, action, classification)], "", ""); - assert_eq!(payload["embeds"][0]["color"], color); - } + fn dots_follow_the_rate() { + assert_eq!([dot(95.0), dot(94.9), dot(90.0), dot(89.9)], ["🟢", "🟡", "🟡", "🔴"]); let (payload, _) = build(&[], "", ""); - assert_eq!(payload["embeds"][0]["color"], RED); assert_eq!( payload["embeds"][0]["description"], "No analysis reports were produced." diff --git a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs index bc71fe715e3..b7f2c69b2d7 100644 --- a/tools/ci/commands/llm-benchmark-summary/tests/cli.rs +++ b/tools/ci/commands/llm-benchmark-summary/tests/cli.rs @@ -53,7 +53,7 @@ fn formats_downloaded_reports_and_reports_io_errors() { let embed = &result["embeds"][0]; assert_eq!( embed["description"], - "**Guidelines 66.7%** · TypeScript 66.7%\n**unknown 100.0%** · Rust 100.0%" + "🔴 **Guidelines 66.7%** · TypeScript 66.7%\n🟢 **unknown 100.0%** · Rust 100.0%" ); assert_eq!(fs::read_to_string(&attachment).unwrap(), ""); From be573f8590feaa15fbe64d0a3900d233dae86221 Mon Sep 17 00:00:00 2001 From: bradleyshep Date: Fri, 20 Nov 2026 13:52:47 -0500 Subject: [PATCH 10/10] Attach a Spacetime-themed HTML benchmark report, with md and txt as options --- .github/workflows/llm-benchmark-periodic.yml | 17 +- .../llm-benchmark-summary/src/logo.svg | 5 + .../llm-benchmark-summary/src/main.rs | 621 ++++++++++++++---- .../llm-benchmark-summary/tests/cli.rs | 27 +- 4 files changed, 546 insertions(+), 124 deletions(-) create mode 100644 tools/ci/commands/llm-benchmark-summary/src/logo.svg diff --git a/.github/workflows/llm-benchmark-periodic.yml b/.github/workflows/llm-benchmark-periodic.yml index f674e567a88..6841529e6c4 100644 --- a/.github/workflows/llm-benchmark-periodic.yml +++ b/.github/workflows/llm-benchmark-periodic.yml @@ -49,6 +49,15 @@ on: required: false type: boolean default: false + attachment_format: + description: 'File format of the details attached to the Discord post' + required: false + type: choice + options: + - html + - md + - txt + default: html permissions: contents: read @@ -337,19 +346,21 @@ jobs: env: RUN_URL: https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }} RUN_LABEL: ${{ github.event_name == 'schedule' && 'Weekly scheduled run' || 'Manual run' }} + ATTACHMENT: analysis.${{ inputs.attachment_format || 'html' }} run: > cargo ci other-workflows llm-benchmark-summary --reports-dir reports --run-url "$RUN_URL" --run-label "$RUN_LABEL" --output discord-payload.json - --attachment analysis.txt + --attachment "$ATTACHMENT" - name: Post Discord summary if: github.event_name == 'schedule' || inputs.post_discord continue-on-error: true env: DISCORD_WEBHOOK_URL: ${{ secrets.LLM_BENCHMARK_DISCORD_WEBHOOK_URL }} + ATTACHMENT: analysis.${{ inputs.attachment_format || 'html' }} run: | if [ -z "$DISCORD_WEBHOOK_URL" ]; then echo "::warning::LLM_BENCHMARK_DISCORD_WEBHOOK_URL is not configured" @@ -357,8 +368,8 @@ jobs: fi attachment=() - if [ -s analysis.txt ]; then - attachment=(--form 'files[0]=@analysis.txt;type=text/plain') + if [ -s "$ATTACHMENT" ]; then + attachment=(--form "files[0]=@$ATTACHMENT") fi curl --fail --silent --show-error \ --form 'payload_json= + + + + diff --git a/tools/ci/commands/llm-benchmark-summary/src/main.rs b/tools/ci/commands/llm-benchmark-summary/src/main.rs index 3f7f1a00b9c..d027981dd03 100644 --- a/tools/ci/commands/llm-benchmark-summary/src/main.rs +++ b/tools/ci/commands/llm-benchmark-summary/src/main.rs @@ -1,12 +1,17 @@ -use anyhow::{Context, Result}; +use anyhow::{bail, Context, Result}; use clap::Parser; use serde_json::{json, Value}; use std::cmp::Reverse; -use std::collections::{BTreeMap, BTreeSet}; +use std::collections::BTreeMap; use std::fs; use std::path::{Path, PathBuf}; const INFRASTRUCTURE: &str = "Infrastructure/provider problem"; +const LOGO: &str = include_str!("logo.svg"); +/// Discord rejects embed descriptions longer than this, counted in UTF-16 units. +const DESCRIPTION_LIMIT: usize = 4096; +const TITLE_LIMIT: usize = 200; +const CATEGORY_LIMIT: usize = 60; #[derive(Parser)] #[command(about = "Build a Discord embed and attachment from LLM benchmark analysis reports.")] @@ -19,17 +24,26 @@ struct Cli { run_label: String, #[arg(long)] output: PathBuf, - /// Full text of the problems on our side; left empty when there are none. + /// Details of the problems on our side, as .html, .md or .txt by extension; empty when there are none. #[arg(long)] attachment: PathBuf, } +#[derive(Clone, Copy)] +enum Format { + Html, + Markdown, + Text, +} + /// A problem on our side: a recommended action or an infrastructure failure. struct Problem { category: String, - severity: String, + /// How sure the analyst is, not how bad the problem is. + confidence: String, + source: String, title: String, - text: String, + details: Vec, } struct Report { @@ -40,6 +54,14 @@ struct Report { problems: Vec, } +type Counts = (u64, u64); + +struct Summary<'a> { + by_mode: BTreeMap<&'a str, (Counts, BTreeMap<&'a str, Counts>)>, + /// Most common category first; within one, most confident first. + categories: Vec<(&'a str, Vec<&'a Problem>)>, +} + fn field<'a>(text: &'a str, name: &str) -> &'a str { let prefix = format!("- {name}: "); text.lines() @@ -64,51 +86,63 @@ fn language_name(language: &str) -> &str { } } -fn severity_rank(severity: &str) -> u8 { - match severity.to_ascii_lowercase().as_str() { - "critical" => 0, - "high" => 1, - "medium" => 2, - "low" => 3, - _ => 4, +fn confidence_rank(confidence: &str) -> u8 { + match confidence.to_ascii_lowercase().as_str() { + "high" => 0, + "medium" => 1, + "low" => 2, + _ => 3, } } -fn problem(category: &str, severity: &str, source: &str, title: &str, details: &str) -> Problem { - let title = title.trim().trim_end_matches('.'); - let label = if severity.is_empty() { - format!("{category}, {source}") - } else { - format!("[{severity}] {category}, {source}") - }; - // Plain text, because Discord shows a .txt attachment as a short preview that expands. - let mut text = format!("{label}\n{title}."); - if !details.is_empty() { - text = format!("{text}\n{}", details.replace("**", "")); - } - Problem { - category: category.to_owned(), - severity: severity.to_owned(), - title: title.to_owned(), - text, +fn clip(text: &str, limit: usize) -> String { + match text.char_indices().nth(limit) { + Some((end, _)) => format!("{}…", text[..end].trim_end()), + None => text.to_owned(), } } -/// Splits `**[Category | Severity] Title.** Details` into its parts. +/// Splits `**[Category | Confidence] Title.** Details` into its parts. fn parse_action(source: &str, item: &str) -> Problem { + const SEPARATORS: [char; 5] = [' ', '—', '–', '-', ':']; let parts = item.strip_prefix("**[").and_then(|rest| { let (tag, rest) = rest.split_once(']')?; let (title, details) = rest.split_once("**")?; - let (category, severity) = tag.split_once('|').unwrap_or((tag, "")); + let (category, confidence) = tag.split_once('|').unwrap_or((tag, "")); Some(( category.trim(), - severity.trim(), - title, - details.trim_start_matches([' ', '—', '–', '-']).trim(), + confidence.trim(), + title.trim(), + details.trim_start_matches(SEPARATORS).trim(), )) }); - let (category, severity, title, details) = parts.unwrap_or(("Other", "", item, "")); - problem(category, severity, source, title, details) + let (category, confidence, mut title, mut details) = parts.unwrap_or(("Other", "", item.trim(), "")); + if title.is_empty() { + // The bold closed right after the tag, so the title is the first clause of the details. + (title, details) = details + .split_once(" — ") + .or_else(|| details.split_once(": ")) + .map_or((details, ""), |(title, rest)| (title.trim(), rest.trim())); + } + Problem { + category: clip(category, CATEGORY_LIMIT), + confidence: confidence.to_owned(), + source: source.to_owned(), + title: clip(title.replace("**", "").trim_end_matches('.'), TITLE_LIMIT), + details: (!details.is_empty()) + .then(|| details.replace("**", "")) + .into_iter() + .collect(), + } +} + +fn is_infrastructure(classification: &str) -> bool { + classification + .trim() + .trim_matches('`') + .trim_end_matches('.') + .trim() + .eq_ignore_ascii_case(INFRASTRUCTURE) } fn parse_report(text: &str) -> Report { @@ -127,17 +161,27 @@ fn parse_report(text: &str) -> Report { total_tasks, problems: Vec::new(), }; - let language = language_name(language); + let source = format!("{} / {mode} / {model}", language_name(language)); let mut section = ""; let mut title = ""; + // Indented lines right after an action belong to it. + let mut in_action = false; for line in text.lines() { if let Some(heading) = line.strip_prefix("## ") { section = heading; title = ""; - } else if section == "Recommended actions" && line.starts_with("- **[") { - report - .problems - .push(parse_action(&format!("{language} / {mode}"), &line[2..])); + in_action = false; + } else if section == "Recommended actions" { + if let Some(item) = line.strip_prefix("- **[").map(|_| &line[2..]) { + report.problems.push(parse_action(&source, item)); + in_action = true; + } else if in_action && line.starts_with([' ', '\t']) && !line.trim().is_empty() { + if let Some(problem) = report.problems.last_mut() { + problem.details.push(line.trim().replace("**", "")); + } + } else { + in_action = false; + } } else if section == "Failure patterns" { if let Some(heading) = line.strip_prefix("### ") { title = heading @@ -149,14 +193,18 @@ fn parse_report(text: &str) -> Report { .is_some_and(|count| count.parse::().is_ok()) }) .map_or(heading, |(title, _)| title); - } else if line.strip_prefix("- **Classification:** ") == Some(INFRASTRUCTURE) && !title.is_empty() { - report.problems.push(problem( - INFRASTRUCTURE, - "", - &format!("{language} / {mode} / {model}"), - title, - "", - )); + } else if line + .strip_prefix("- **Classification:**") + .is_some_and(is_infrastructure) + && !title.is_empty() + { + report.problems.push(Problem { + category: INFRASTRUCTURE.to_owned(), + confidence: String::new(), + source: source.clone(), + title: clip(title, TITLE_LIMIT), + details: Vec::new(), + }); } } } @@ -185,60 +233,37 @@ fn load_reports(directory: &Path) -> Result> { Ok(reports) } -fn percent(passed: u64, total: u64) -> f64 { +/// Rounded to one decimal, so the shown rate and its color always agree. +fn percent((passed, total): Counts) -> f64 { if total == 0 { 0.0 } else { - passed as f64 * 100.0 / total as f64 + (passed as f64 * 1000.0 / total as f64).round() / 10.0 } } -/// One line per category, most common first, with its most severe title. -fn problem_lines(problems: &[&Problem]) -> Vec { - let mut by_category = BTreeMap::<&str, Vec<&Problem>>::new(); - for problem in problems { - by_category.entry(&problem.category).or_default().push(problem); - } - let mut categories: Vec<_> = by_category.into_iter().collect(); - categories.sort_by_key(|(_, items)| Reverse(items.len())); - categories - .into_iter() - .filter_map(|(category, items)| { - let top = items.iter().min_by_key(|problem| severity_rank(&problem.severity))?; - Some(format!("- {category} ({}): {}", items.len(), top.title)) - }) - .collect() -} - -fn attachment(problems: &[&Problem]) -> String { - let mut problems = problems.to_vec(); - problems.sort_by_key(|problem| severity_rank(&problem.severity)); - let mut seen = BTreeSet::new(); - let texts: Vec<_> = problems - .iter() - .map(|problem| problem.text.as_str()) - .filter(|text| seen.insert(*text)) - .collect(); - if texts.is_empty() { - String::new() +/// `good`, `warn` or `bad`; also the CSS class for the HTML report. +fn state(rate: f64) -> &'static str { + if rate >= 95.0 { + "good" + } else if rate >= 90.0 { + "warn" } else { - format!("{}\n", texts.join("\n\n")) + "bad" } } fn dot(rate: f64) -> &'static str { - if rate >= 95.0 { - "🟢" - } else if rate >= 90.0 { - "🟡" - } else { - "🔴" + match state(rate) { + "good" => "🟢", + "warn" => "🟡", + _ => "🔴", } } -fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) { - type Counts = (u64, u64); +fn summarize(reports: &[Report]) -> Summary<'_> { let mut by_mode = BTreeMap::<&str, (Counts, BTreeMap<&str, Counts>)>::new(); + let mut by_category = BTreeMap::<&str, Vec<&Problem>>::new(); for report in reports { let (totals, languages) = by_mode.entry(&report.mode).or_default(); let counts = languages.entry(&report.language).or_default(); @@ -246,22 +271,32 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) counts.0 += report.passed_tasks; counts.1 += report.total_tasks; } + for problem in &report.problems { + by_category.entry(&problem.category).or_default().push(problem); + } } - let problems: Vec<_> = reports.iter().flat_map(|report| &report.problems).collect(); - let total: u64 = by_mode.values().map(|((_, total), _)| total).sum(); - let mut description = if total == 0 { + let mut categories: Vec<_> = by_category.into_iter().collect(); + categories.sort_by_key(|(_, problems)| Reverse(problems.len())); + for (_, problems) in &mut categories { + problems.sort_by_key(|problem| confidence_rank(&problem.confidence)); + } + Summary { by_mode, categories } +} + +fn payload(summary: &Summary, run_url: &str, run_label: &str) -> Value { + let total: u64 = summary.by_mode.values().map(|((_, total), _)| total).sum(); + let rates = if total == 0 { "No analysis reports were produced.".to_owned() } else { - by_mode + summary + .by_mode .iter() - .map(|(mode, ((passed, total), languages))| { + .map(|(mode, (counts, languages))| { let languages: Vec<_> = languages .iter() - .map(|(language, (passed, total))| { - format!("{} {:.1}%", language_name(language), percent(*passed, *total)) - }) + .map(|(language, counts)| format!("{} {:.1}%", language_name(language), percent(*counts))) .collect(); - let rate = percent(*passed, *total); + let rate = percent(*counts); format!( "{} **{} {rate:.1}%** · {}", dot(rate), @@ -272,11 +307,27 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) .collect::>() .join("\n") }; - let lines = problem_lines(&problems); - if !lines.is_empty() { - description = format!("{description}\n\n{}", lines.join("\n")); - } - let payload = json!({ + let mut lines: Vec<_> = summary + .categories + .iter() + .map(|(category, problems)| format!("- {category} ({}): {}", problems.len(), problems[0].title)) + .collect(); + let mut hidden = 0; + let description = loop { + let mut description = rates.clone(); + if !lines.is_empty() || hidden > 0 { + description = format!("{description}\n\n{}", lines.join("\n")); + } + if hidden > 0 { + description = format!("{description}\n- ...and {hidden} more"); + } + if lines.is_empty() || description.encode_utf16().count() <= DESCRIPTION_LIMIT { + break description; + } + lines.pop(); + hidden += 1; + }; + json!({ "username": "Spacetime LLM Benchmarks", "allowed_mentions": {"parse": []}, "embeds": [{ @@ -284,18 +335,259 @@ fn build(reports: &[Report], run_url: &str, run_label: &str) -> (Value, String) "url": run_url, "description": description }] - }); - (payload, attachment(&problems)) + }) +} + +fn escape(text: &str) -> String { + text.replace('&', "&") + .replace('<', "<") + .replace('>', ">") + .replace('"', """) +} + +/// Escapes text and turns `code` spans into elements. +fn inline_html(text: &str) -> String { + text.split('`') + .enumerate() + .map(|(index, part)| { + if index % 2 == 1 { + format!("{}", escape(part)) + } else { + escape(part) + } + }) + .collect() +} + +/// Paragraphs, with runs of `- ` lines as a list. +fn details_html(lines: &[String]) -> String { + let mut html = String::new(); + let mut in_list = false; + for line in lines { + match line.strip_prefix("- ") { + Some(item) => { + if !in_list { + html.push_str("
    "); + in_list = true; + } + html.push_str(&format!("
  • {}
  • ", inline_html(item))); + } + None => { + if in_list { + html.push_str("
"); + in_list = false; + } + html.push_str(&format!("

{}

", inline_html(line))); + } + } + } + if in_list { + html.push_str(""); + } + html +} + +const STYLE: &str = r#" +:root{--bg:#0b0e12;--panel:#0f191f;--raised:#121e24;--line:#162d38;--text:#e6e9f0;--soft:#b6c0cf;--muted:#76808f;--green:#4cf490;--yellow:#fbdc8e;--red:#ff4c4c;--purple:#a880ff;--blue:#02befa} +*{box-sizing:border-box} +body{margin:0;min-height:100vh;color:var(--text);font:15px/1.55 Inter,system-ui,sans-serif;background:radial-gradient(900px 520px at 85% -12%,rgba(138,56,245,.22),transparent 65%),radial-gradient(760px 460px at -8% -6%,rgba(76,244,144,.12),transparent 60%),var(--bg)} +main{max-width:960px;margin:0 auto;padding:40px 20px 72px} +header{display:flex;align-items:center;gap:14px;margin-bottom:36px} +header svg{flex:none;width:32px;height:30px} +h1{margin:0;font-size:22px;font-weight:600;letter-spacing:-.01em} +.label{color:var(--muted);font:13px "Source Code Pro",ui-monospace,monospace} +header a{margin-left:auto;padding:7px 14px;border:1px solid rgba(76,244,144,.35);border-radius:8px;color:var(--green);font:500 13px "Source Code Pro",ui-monospace,monospace;text-decoration:none;white-space:nowrap} +header a:hover{background:rgba(76,244,144,.1)} +.modes{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;margin-bottom:44px} +.mode{padding:20px 22px;background:var(--panel);border:1px solid var(--line);border-radius:14px} +.mode h2{margin:0 0 4px;color:var(--muted);font:500 12px "Source Code Pro",ui-monospace,monospace;letter-spacing:.08em;text-transform:uppercase} +.rate{margin-bottom:16px;font-size:44px;font-weight:700;letter-spacing:-.03em} +.good{--tone:var(--green)}.warn{--tone:var(--yellow)}.bad{--tone:var(--red)} +.rate.good,.rate.warn,.rate.bad{color:var(--tone)} +.bar{display:grid;grid-template-columns:92px 1fr 52px;align-items:center;gap:12px;margin-top:8px;font-size:13px} +.bar span:last-child{text-align:right;color:var(--soft);font-family:"Source Code Pro",ui-monospace,monospace} +.track{height:6px;overflow:hidden;background:var(--raised);border-radius:3px} +.fill{height:100%;background:var(--tone);border-radius:3px} +section{margin-top:32px} +section h2{display:flex;align-items:center;gap:10px;margin:0 0 12px;font-size:16px;font-weight:600} +.count{padding:1px 9px;color:var(--purple);background:rgba(168,128,255,.14);border-radius:999px;font:500 12px "Source Code Pro",ui-monospace,monospace} +details,.row{margin:8px 0;background:var(--panel);border:1px solid var(--line);border-radius:10px} +details[open]{border-color:#1d3a48} +summary,.row{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px 10px;padding:12px 16px} +summary{cursor:pointer;list-style:none} +summary::-webkit-details-marker{display:none} +summary::before,.row::before{width:8px;color:var(--muted)} +summary::before{content:"›";transition:transform .15s} +.row::before{content:""} +details[open] summary::before{transform:rotate(90deg)} +.title{flex:1 1 320px;font-weight:500} +.conf{padding:1px 8px;border-radius:999px;font:500 11px "Source Code Pro",ui-monospace,monospace;color:var(--muted);background:var(--raised)} +.conf.high{color:var(--purple);background:rgba(168,128,255,.16)} +.conf.medium{color:#c9b3ff;background:rgba(168,128,255,.08)} +.source{color:var(--muted);font:12px "Source Code Pro",ui-monospace,monospace} +.body{padding:0 16px 14px 34px;color:var(--soft)} +.body p{margin:0 0 8px} +.body ul{margin:0 0 8px;padding-left:18px} +code{padding:1px 5px;color:var(--green);background:var(--raised);border:1px solid var(--line);border-radius:4px;font:.88em "Source Code Pro",ui-monospace,monospace} +@media (max-width:560px){header{flex-wrap:wrap}header a{margin-left:0}.rate{font-size:36px}} +"#; + +fn html(summary: &Summary, run_url: &str, run_label: &str) -> String { + let modes: String = summary + .by_mode + .iter() + .map(|(mode, (counts, languages))| { + let rate = percent(*counts); + let bars: String = languages + .iter() + .map(|(language, counts)| { + let rate = percent(*counts); + format!( + r#"
{}
{rate:.1}%
"#, + state(rate), + escape(language_name(language)) + ) + }) + .collect(); + format!( + r#"

{}

{rate:.1}%
{bars}
"#, + escape(mode_name(mode)), + state(rate) + ) + }) + .collect(); + let sections: String = summary + .categories + .iter() + .map(|(category, problems)| { + let items: String = problems + .iter() + .map(|problem| { + let confidence = if problem.confidence.is_empty() { + String::new() + } else { + format!( + r#"{} confidence"#, + escape(&problem.confidence.to_ascii_lowercase()), + escape(&problem.confidence) + ) + }; + let line = format!( + r#"{confidence}{}{}"#, + inline_html(&problem.title), + escape(&problem.source) + ); + if problem.details.is_empty() { + format!(r#"
{line}
"#) + } else { + format!( + r#"
{line}
{}
"#, + details_html(&problem.details) + ) + } + }) + .collect(); + format!( + r#"

{}{}

{items}
"#, + escape(category), + problems.len() + ) + }) + .collect(); + let link = if run_url.is_empty() { + String::new() + } else { + format!(r#"View run"#, escape(run_url)) + }; + format!( + r#" + +LLM Benchmark Analysis · {label} + + + +
{LOGO}

LLM Benchmark Analysis

{label}
{link}
+
{modes}
{sections}
+"#, + label = escape(run_label) + ) +} + +fn attachment(summary: &Summary, format: Format, run_url: &str, run_label: &str) -> String { + if summary.categories.is_empty() { + return String::new(); + } + let problems = || summary.categories.iter().flat_map(|(_, problems)| problems); + let join = |items: Vec| format!("{}\n", items.join("\n\n")); + match format { + Format::Html => html(summary, run_url, run_label), + Format::Markdown => join( + problems() + .map(|problem| { + let tag = if problem.confidence.is_empty() { + problem.category.clone() + } else { + format!("{} | {}", problem.category, problem.confidence) + }; + let mut text = format!("- {}: **[{tag}] {}.**", problem.source, problem.title); + for (index, line) in problem.details.iter().enumerate() { + text.push_str(&if index == 0 { + format!(" {line}") + } else { + format!("\n {line}") + }); + } + text + }) + .collect(), + ), + // Plain text, because Discord shows a .txt attachment as a short preview that expands. + Format::Text => join( + problems() + .map(|problem| { + let label = if problem.confidence.is_empty() { + format!("{}, {}", problem.category, problem.source) + } else { + format!( + "[{} confidence] {}, {}", + problem.confidence, problem.category, problem.source + ) + }; + [label, format!("{}.", problem.title)] + .into_iter() + .chain(problem.details.iter().cloned()) + .collect::>() + .join("\n") + }) + .collect(), + ), + } +} + +fn format_of(path: &Path) -> Result { + Ok(match path.extension().and_then(|extension| extension.to_str()) { + Some("html") => Format::Html, + Some("md") => Format::Markdown, + Some("txt") => Format::Text, + _ => bail!("attachment {} must end in .html, .md or .txt", path.display()), + }) } fn main() -> Result<()> { let args = Cli::parse(); + let format = format_of(&args.attachment)?; let reports = load_reports(&args.reports_dir)?; - let (payload, attachment) = build(&reports, &args.run_url, &args.run_label); - fs::write(&args.output, serde_json::to_vec(&payload)?) - .with_context(|| format!("writing Discord payload {}", args.output.display()))?; - fs::write(&args.attachment, attachment) - .with_context(|| format!("writing Discord attachment {}", args.attachment.display())) + let summary = summarize(&reports); + fs::write( + &args.output, + serde_json::to_vec(&payload(&summary, &args.run_url, &args.run_label))?, + ) + .with_context(|| format!("writing Discord payload {}", args.output.display()))?; + fs::write( + &args.attachment, + attachment(&summary, format, &args.run_url, &args.run_label), + ) + .with_context(|| format!("writing Discord attachment {}", args.attachment.display())) } #[cfg(test)] @@ -312,6 +604,10 @@ mod tests { )) } + fn only_problem(action: &str) -> Problem { + report("csharp", "1/1", action, "").problems.remove(0) + } + #[test] fn summarizes_rates_and_leaves_out_model_limitations() { let reports = [ @@ -319,7 +615,8 @@ mod tests { report("rust", "34/37 (91.9%)", "", "Model limitation"), report_in("no_context", "rust", "20/37 (54.1%)", "", "Model limitation"), ]; - let (payload, attachment) = build(&reports, "https://example.com/run", "Weekly run"); + let summary = summarize(&reports); + let payload = payload(&summary, "https://example.com/run", "Weekly run"); let embed = &payload["embeds"][0]; assert_eq!( embed["description"], @@ -327,8 +624,10 @@ mod tests { ); assert_eq!(embed["title"], "LLM Benchmark Analysis · Weekly run"); assert_eq!(embed["url"], "https://example.com/run"); - assert_eq!(attachment, ""); assert_eq!(payload["allowed_mentions"], json!({"parse": []})); + for format in [Format::Html, Format::Markdown, Format::Text] { + assert_eq!(attachment(&summary, format, "", ""), ""); + } } #[test] @@ -337,7 +636,7 @@ mod tests { report( "csharp", "37/37", - "- **[Eval problem | Medium] Keep publish errors.** Store all stderr.\n- **[API/ergonomics problem | Low] Rename Index.** It collides.", + "- **[Eval problem | Medium] Keep publish errors.** Store all `stderr`.\n - Keep every line.\n Evidence: t_002.\n- **[API/ergonomics problem | Low] Rename Index.** It collides.", "", ), report( @@ -347,23 +646,107 @@ mod tests { INFRASTRUCTURE, ), ]; - let (payload, attachment) = build(&reports, "", ""); + let summary = summarize(&reports); assert_eq!( - payload["embeds"][0]["description"], + payload(&summary, "", "")["embeds"][0]["description"], "🟢 **Guidelines 100.0%** · C# 100.0% · Rust 100.0%\n\n- Eval problem (2): Capture build output\n- API/ergonomics problem (1): Rename Index\n- Infrastructure/provider problem (1): Incorrect sum-type syntax" ); assert_eq!( - attachment, - "[High] Eval problem, Rust / guidelines\nCapture build output.\nEvidence: t_001.\n\n[Medium] Eval problem, C# / guidelines\nKeep publish errors.\nStore all stderr.\n\n[Low] API/ergonomics problem, C# / guidelines\nRename Index.\nIt collides.\n\nInfrastructure/provider problem, Rust / guidelines / test-model\nIncorrect sum-type syntax.\n" + attachment(&summary, Format::Text, "", ""), + "[High confidence] Eval problem, Rust / guidelines / test-model\nCapture build output.\nEvidence: t_001.\n\n[Medium confidence] Eval problem, C# / guidelines / test-model\nKeep publish errors.\nStore all `stderr`.\n- Keep every line.\nEvidence: t_002.\n\n[Low confidence] API/ergonomics problem, C# / guidelines / test-model\nRename Index.\nIt collides.\n\nInfrastructure/provider problem, Rust / guidelines / test-model\nIncorrect sum-type syntax.\n" ); + assert_eq!( + attachment(&summary, Format::Markdown, "", ""), + "- Rust / guidelines / test-model: **[Eval problem | High] Capture build output.** Evidence: t_001.\n\n- C# / guidelines / test-model: **[Eval problem | Medium] Keep publish errors.** Store all `stderr`.\n - Keep every line.\n Evidence: t_002.\n\n- C# / guidelines / test-model: **[API/ergonomics problem | Low] Rename Index.** It collides.\n\n- Rust / guidelines / test-model: **[Infrastructure/provider problem] Incorrect sum-type syntax.**\n" + ); + let html = attachment(&summary, Format::Html, "", ""); + assert!(html.contains( + "

Store all stderr.

  • Keep every line.

Evidence: t_002.

" + )); + assert!(html.contains(r#"High confidence"#)); + // An infrastructure problem has no details, so it does not expand. + assert!(html.contains(r#"
Incorrect sum-type syntax"#)); + } + + #[test] + fn parses_loosely_formatted_items() { + let problem = only_problem("- **[Eval problem | Medium] Capture diagnostics**: Each error is cut."); + assert_eq!( + (problem.title.as_str(), problem.details[0].as_str()), + ("Capture diagnostics", "Each error is cut.") + ); + let problem = only_problem("- **[Eval problem | High]** Bold closes early — details here"); + assert_eq!( + (problem.title.as_str(), problem.details[0].as_str()), + ("Bold closes early", "details here") + ); + let problem = only_problem(&format!("- **[Eval problem | High] {}", "x".repeat(4200))); + assert_eq!(problem.category, "Other"); + assert_eq!(problem.title.chars().count(), TITLE_LIMIT + 1); + for classification in ["`Infrastructure/provider problem`", "Infrastructure/provider problem."] { + assert_eq!( + report("rust", "1/1", "", classification).problems[0].category, + INFRASTRUCTURE + ); + } } #[test] - fn dots_follow_the_rate() { + fn description_stays_within_discord_limit() { + let actions: String = (0..60) + .map(|index| { + format!( + "- **[Category {index} {} | High] {}.** Text.\n", + "c".repeat(80), + "t".repeat(300) + ) + }) + .collect(); + let reports = [report("csharp", "1/1", &actions, "")]; + let description = payload(&summarize(&reports), "", "")["embeds"][0]["description"] + .as_str() + .unwrap() + .to_owned(); + assert!(description.encode_utf16().count() <= DESCRIPTION_LIMIT); + assert!(description.ends_with(" more")); + } + + #[test] + fn html_escapes_report_text() { + let reports = [report( + "csharp", + "1/2", + "- **[Eval problem | High] Fix