From 796d00e23e3140cdf947e5ba5bfebd6196677666 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:18:46 +0000 Subject: [PATCH 01/11] One-shot speedups divide query time, not wall time with process start DuckDB, psql and PilotDB start a process for every run, so their wall time includes starting it (for PilotDB also Python, its imports and a row count of every table), while ClickHouse and Druid keep a connection. Each engine now names its query time: the time it reports for the three that start a process, as ClickBench reports them, and the harness wall time otherwise. speedup_over_* and the leaderboard data divide it; the wall columns stay. Co-Authored-By: Claude Opus 5.5 --- aqpbm-core/src/harness/one_shot.rs | 26 +++++++ aqpbm-core/src/harness/one_shot_report.rs | 75 +++++++++++++++++-- aqpbm-core/tests/harness_one_shot_report.rs | 72 +++++++++++++++++- scripts/system-leaderboard-data.py | 13 +++- .../engines_external/duckdb_command_line.rs | 6 +- system-bench/src/engines_external/pilotdb.rs | 7 +- .../postgresql_command_line.rs | 6 +- 7 files changed, 187 insertions(+), 18 deletions(-) diff --git a/aqpbm-core/src/harness/one_shot.rs b/aqpbm-core/src/harness/one_shot.rs index 31448549..b3d59eca 100644 --- a/aqpbm-core/src/harness/one_shot.rs +++ b/aqpbm-core/src/harness/one_shot.rs @@ -156,6 +156,26 @@ pub struct QueryRun { pub details: BTreeMap, } +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum QueryTime { + HarnessWall, + EngineReported, +} + +impl QueryTime { + pub fn describe(self) -> &'static str { + match self { + QueryTime::HarnessWall => { + "the harness's wall time around the run, as the adapter keeps its connection between runs" + } + QueryTime::EngineReported => { + "the time the engine reports, as ClickBench reports it, which leaves out starting the process the adapter starts for each run" + } + } + } +} + #[derive(Debug, Clone)] pub enum OneShotCpuAccounting { Cgroup(CgroupSource), @@ -166,6 +186,9 @@ pub trait OneShotQueryEngine { fn description(&self) -> EngineDescription; fn dialect(&self) -> SqlDialect; fn engine_time_covers(&self) -> Option<&'static str>; + fn query_time(&self) -> QueryTime { + QueryTime::HarnessWall + } fn configuration(&self) -> serde_json::Value { serde_json::Value::Null } @@ -224,6 +247,8 @@ pub struct OneShotResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub engine_time_covers: Option, #[serde(default, skip_serializing_if = "Option::is_none")] + pub query_time: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu_and_memory_source: Option, pub tables: Vec, pub queries: Vec, @@ -721,6 +746,7 @@ pub fn run_one_shot_queries( query_variant: schedule.query_variant.clone(), cold_first_run: schedule.cold_first_run, engine_time_covers: engine.engine_time_covers().map(str::to_string), + query_time: Some(engine.query_time()), cpu_and_memory_source: cpu_and_memory.as_ref().map(CpuAndMemory::source), tables, queries, diff --git a/aqpbm-core/src/harness/one_shot_report.rs b/aqpbm-core/src/harness/one_shot_report.rs index d6ccdfcb..b6033780 100644 --- a/aqpbm-core/src/harness/one_shot_report.rs +++ b/aqpbm-core/src/harness/one_shot_report.rs @@ -1,7 +1,7 @@ use std::collections::BTreeMap; use crate::harness::benchmark_external::{median_of, relative_error}; -use crate::harness::one_shot::{OneShotResult, QueryRecord, ResultTable, RunRecord}; +use crate::harness::one_shot::{OneShotResult, QueryRecord, QueryTime, ResultTable, RunRecord}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct ConfigurationName { @@ -141,6 +141,11 @@ pub struct OneShotReportRow { pub runs: usize, pub first_run_cold: bool, pub engine_time_covers: Option, + pub query_time: QueryTime, + pub first_run_query_seconds: Option, + pub hot_min_query_seconds: Option, + pub hot_median_query_seconds: Option, + pub hot_max_query_seconds: Option, pub first_run_wall_seconds: Option, pub hot_min_wall_seconds: Option, pub hot_median_wall_seconds: Option, @@ -199,6 +204,7 @@ struct FirstAndHot { } struct Timing { + query: FirstAndHot, wall: FirstAndHot, engine: FirstAndHot, engine_cpu: FirstAndHot, @@ -232,8 +238,16 @@ fn first_and_hot(query: &QueryRecord, value: impl Fn(&RunRecord) -> Option) } } -fn timing_of(query: &QueryRecord) -> Timing { +fn query_time_of(result: &OneShotResult) -> QueryTime { + result.query_time.unwrap_or(QueryTime::HarnessWall) +} + +fn timing_of(query: &QueryRecord, query_time: QueryTime) -> Timing { Timing { + query: first_and_hot(query, |run| match query_time { + QueryTime::HarnessWall => Some(run.wall_seconds), + QueryTime::EngineReported => run.engine_reported_seconds, + }), wall: first_and_hot(query, |run| Some(run.wall_seconds)), engine: first_and_hot(query, |run| run.engine_reported_seconds), engine_cpu: first_and_hot(query, |run| run.engine_reported_cpu_seconds), @@ -285,8 +299,9 @@ pub fn one_shot_report( data_size_bytes: table.data_size_bytes, }); } + let query_time = query_time_of(result); for query in &result.queries { - let timing = timing_of(query); + let timing = timing_of(query, query_time); let failed = query.runs.iter().find_map(|run| run.error.clone()); let status = match (&query.skipped, failed) { (Some(reason), _) => format!("skipped: {reason}"), @@ -296,10 +311,19 @@ pub fn one_shot_report( let speedups = baselines .iter() .map(|baseline| { - let speedup = find(baseline, &result.workload) + let other_result = find(baseline, &result.workload); + let speedup = other_result .and_then(|other| other.queries.iter().find(|other| other.id == query.id)) - .and_then(|other| timing_of(other).wall.hot_median) - .zip(timing.wall.hot_median) + .zip(other_result) + .and_then(|(other, other_result)| { + timing_of(other, query_time_of(other_result)) + .query + .hot_median + }) + .zip(timing.query.hot_median) + .filter(|(baseline_seconds, seconds)| { + *baseline_seconds > 0.0 && *seconds > 0.0 + }) .map(|(baseline_seconds, seconds)| baseline_seconds / seconds); (baseline.clone(), speedup) }) @@ -312,6 +336,11 @@ pub fn one_shot_report( runs: query.runs.len(), first_run_cold: result.cold_first_run, engine_time_covers: result.engine_time_covers.clone(), + query_time, + first_run_query_seconds: timing.query.first, + hot_min_query_seconds: timing.query.hot_min, + hot_median_query_seconds: timing.query.hot_median, + hot_max_query_seconds: timing.query.hot_max, first_run_wall_seconds: timing.wall.first, hot_min_wall_seconds: timing.wall.hot_min, hot_median_wall_seconds: timing.wall.hot_median, @@ -435,6 +464,13 @@ fn accuracy( row.differing_text_cells = Some(text_cells); } +fn query_time_name(query_time: QueryTime) -> &'static str { + match query_time { + QueryTime::HarnessWall => "harness_wall", + QueryTime::EngineReported => "engine_reported", + } +} + fn format_number(value: Option) -> String { value.map_or_else(String::new, |value| format!("{value}")) } @@ -516,6 +552,11 @@ impl OneShotReport { "hot_max_engine_seconds", "hot_min_engine_cpu_seconds", "hot_max_engine_cpu_seconds", + "query_time", + "first_run_query_seconds", + "hot_min_query_seconds", + "hot_median_query_seconds", + "hot_max_query_seconds", ] .map(str::to_string), ); @@ -569,6 +610,11 @@ impl OneShotReport { format_number(row.hot_max_engine_seconds), format_number(row.hot_min_engine_cpu_seconds), format_number(row.hot_max_engine_cpu_seconds), + query_time_name(row.query_time).into(), + format_number(row.first_run_query_seconds), + format_number(row.hot_min_query_seconds), + format_number(row.hot_median_query_seconds), + format_number(row.hot_max_query_seconds), ]); fields }) @@ -611,8 +657,21 @@ impl OneShotReport { text.push_str(&format!("Accuracy against {truth}.\n\n")); } text.push_str( - "Wall time is measured by the harness around each run, from handing the query to the adapter to getting the parsed answer back, so it includes starting a process or connecting when the adapter does that for each run; speedups divide hot median wall times.\n\n", + "Wall time is measured by the harness around each run, from handing the query to the adapter to getting the parsed answer back, so it includes starting a process or connecting when the adapter does that for each run. Query time is what speedups divide, hot median by hot median; it leaves out starting a process, as ClickBench does.\n\n", ); + let query_times: BTreeMap = self + .rows + .iter() + .filter(|row| row.query_time != QueryTime::HarnessWall) + .map(|row| (row.configuration.to_string(), row.query_time)) + .collect(); + if !query_times.is_empty() { + text.push_str("Query time is the harness's wall time, except:\n\n"); + for (configuration, query_time) in query_times { + text.push_str(&format!("- {configuration}: {}\n", query_time.describe())); + } + text.push('\n'); + } let covers: BTreeMap = self .rows .iter() @@ -655,6 +714,7 @@ impl OneShotReport { "first run wall s".into(), "hot median wall s".into(), "hot median engine s".into(), + "hot median query s".into(), ]; header.extend( self.baselines @@ -680,6 +740,7 @@ impl OneShotReport { format_for_reading(row.first_run_wall_seconds), format_for_reading(row.hot_median_wall_seconds), format_for_reading(row.hot_median_engine_seconds), + format_for_reading(row.hot_median_query_seconds), ]; cells.extend( row.speedups diff --git a/aqpbm-core/tests/harness_one_shot_report.rs b/aqpbm-core/tests/harness_one_shot_report.rs index 91531709..a19ffb2f 100644 --- a/aqpbm-core/tests/harness_one_shot_report.rs +++ b/aqpbm-core/tests/harness_one_shot_report.rs @@ -2,7 +2,8 @@ use std::collections::{BTreeMap, BTreeSet}; use aqpbm_core::harness::engine::EngineDescription; use aqpbm_core::harness::one_shot::{ - ErrorTarget, OneShotResult, QueryRecord, ResultTable, ResultValue, RunRecord, TableRecord, + ErrorTarget, OneShotResult, QueryRecord, QueryTime, ResultTable, ResultValue, RunRecord, + TableRecord, }; use aqpbm_core::harness::one_shot_report::{compare_tables, one_shot_report, ConfigurationName}; @@ -94,6 +95,7 @@ fn result( query_variant: None, cold_first_run: true, engine_time_covers: None, + query_time: None, cpu_and_memory_source: None, tables: vec![TableRecord { name: "hits".into(), @@ -189,7 +191,7 @@ fn the_report_times_hot_runs_scores_against_the_truth_and_counts_misses() { .collect(); assert_eq!( table[0], - "| workload | engine/configuration | query | status | first run wall s | hot median wall s | hot median engine s | speedup over duckdb/exact | max relative error | runs over target | truth runs agree | answered exactly | hot median harness CPU s | hot median peak memory MiB |" + "| workload | engine/configuration | query | status | first run wall s | hot median wall s | hot median engine s | hot median query s | speedup over duckdb/exact | max relative error | runs over target | truth runs agree | answered exactly | hot median harness CPU s | hot median peak memory MiB |" ); assert!(table[2..] .iter() @@ -321,6 +323,63 @@ fn speedups_divide_wall_times_whatever_each_engine_reports() { assert_eq!(druid.speedups[0].1, Some(3.0 / 2.0)); } +#[test] +fn speedups_divide_each_configurations_query_time() { + let mut duckdb = result( + "duckdb", + "exact", + vec![run(4.0, 100.0, None), run(2.0, 100.0, None)], + None, + ); + duckdb.query_time = Some(QueryTime::EngineReported); + let mut druid_run = run(9.0, 100.0, None); + druid_run.engine_reported_seconds = None; + druid_run.wall_seconds = 1.0; + let druid = result( + "druid", + "exact", + vec![run(4.0, 100.0, None), druid_run], + None, + ); + let baseline = ConfigurationName::parse("duckdb/exact").unwrap(); + let report = one_shot_report(&[duckdb, druid], None, std::slice::from_ref(&baseline)).unwrap(); + assert_eq!(report.rows[0].query_time, QueryTime::EngineReported); + assert_eq!(report.rows[0].hot_median_query_seconds, Some(2.0)); + assert_eq!(report.rows[0].hot_median_wall_seconds, Some(3.0)); + assert_eq!(report.rows[1].query_time, QueryTime::HarnessWall); + assert_eq!(report.rows[1].hot_median_query_seconds, Some(1.0)); + assert_eq!(report.rows[1].speedups[0].1, Some(2.0)); + let csv = report.summary_csv(); + let header: Vec<&str> = csv.lines().next().unwrap().split(',').collect(); + let column = |name: &str| header.iter().position(|field| *field == name).unwrap(); + let duckdb_row: Vec<&str> = csv.lines().nth(1).unwrap().split(',').collect(); + assert_eq!(duckdb_row[column("query_time")], "engine_reported"); + assert_eq!(duckdb_row[column("hot_median_query_seconds")], "2"); + assert!(report + .summary_markdown() + .contains("- duckdb/exact: the time the engine reports")); + let mut below_the_timer = report_input_with_zero(); + below_the_timer[0].query_time = Some(QueryTime::EngineReported); + let report = one_shot_report(&below_the_timer, None, std::slice::from_ref(&baseline)).unwrap(); + assert_eq!(report.rows[0].hot_median_query_seconds, Some(0.0)); + assert_eq!(report.rows[0].speedups[0].1, None); + assert_eq!(report.rows[1].speedups[0].1, None); +} + +fn report_input_with_zero() -> Vec { + let mut zero = run(0.0, 100.0, None); + zero.wall_seconds = 0.1; + vec![ + result("duckdb", "exact", vec![run(4.0, 100.0, None), zero], None), + result( + "druid", + "exact", + vec![run(4.0, 100.0, None), run(1.0, 100.0, None)], + None, + ), + ] +} + const SUMMARY_COLUMNS_BEFORE_HARNESS_CPU: [&str; 24] = [ "workload", "engine", @@ -428,12 +487,17 @@ fn harness_cpu_and_peak_memory_are_reported_after_the_existing_columns() { assert_eq!(field(2, "memory_peak_since_group_started_bytes"), "9000"); assert_eq!(field(2, "hot_median_peak_memory_bytes"), ""); assert_eq!( - header[header.len() - 4..], + header[header.len() - 9..], [ "hot_max_wall_seconds", "hot_max_engine_seconds", "hot_min_engine_cpu_seconds", - "hot_max_engine_cpu_seconds" + "hot_max_engine_cpu_seconds", + "query_time", + "first_run_query_seconds", + "hot_min_query_seconds", + "hot_median_query_seconds", + "hot_max_query_seconds" ] ); assert_eq!(field(0, "hot_max_wall_seconds"), "4"); diff --git a/scripts/system-leaderboard-data.py b/scripts/system-leaderboard-data.py index fa42e8e0..93d1bb63 100755 --- a/scripts/system-leaderboard-data.py +++ b/scripts/system-leaderboard-data.py @@ -66,6 +66,11 @@ def machine_text(machine): return f"{machine.get('cpu_model')}, {machine.get('logical_cores')} logical cores{memory}, {machine.get('os')}" +def query_seconds(row, which): + query = row.get(f"{which}_query_seconds") + return number(query) if query is not None else number(row[f"{which}_wall_seconds"]) + + def one_shot_baseline(system, configuration, configurations): if configuration == "exact": return None @@ -93,7 +98,7 @@ def one_shot(run_directory): with open(tables, newline="") as file: for row in csv.DictReader(file): loads.setdefault((row["engine"], row["configuration"]), []).append(row) - hot = {key: {r["query"]: number(r["hot_min_wall_seconds"]) for r in group if r["status"] == "ok"} + hot = {key: {r["query"]: query_seconds(r, "hot_min") for r in group if r["status"] == "ok"} for key, group in rows.items()} for (system, configuration), group in rows.items(): result = results.get((system, configuration), {}) @@ -104,14 +109,14 @@ def one_shot(run_directory): for r in group: answered = r["status"] == "ok" reference = hot.get(baseline_key, {}).get(r["query"]) if baseline_key else None - own = number(r["hot_min_wall_seconds"]) if answered else None + own = query_seconds(r, "hot_min") if answered else None queries.append({ "query": r["query"], "text": texts.get(r["query"]), "status": r["status"], - "first_run_seconds": number(r["first_run_wall_seconds"]), + "first_run_seconds": query_seconds(r, "first_run"), "hot_min_seconds": own, - "hot_median_seconds": number(r["hot_median_wall_seconds"]), + "hot_median_seconds": query_seconds(r, "hot_median"), "hot_min_engine_seconds": number(r["hot_min_engine_seconds"]), "speedup_over_baseline": reference / own if reference and own else None, "max_relative_error": number(r["max_relative_error"]), diff --git a/system-bench/src/engines_external/duckdb_command_line.rs b/system-bench/src/engines_external/duckdb_command_line.rs index de2953e3..670224a8 100644 --- a/system-bench/src/engines_external/duckdb_command_line.rs +++ b/system-bench/src/engines_external/duckdb_command_line.rs @@ -4,7 +4,7 @@ use std::process::Command; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; use aqpbm_core::harness::one_shot::{ - OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, + OneShotCpuAccounting, OneShotQueryEngine, QueryRun, QueryTime, ResultTable, }; use aqpbm_core::harness::protocol::ChildProcesses; @@ -154,6 +154,10 @@ impl OneShotQueryEngine for DuckDbEngine { SqlDialect::new(DIALECT) } + fn query_time(&self) -> QueryTime { + QueryTime::EngineReported + } + fn engine_time_covers(&self) -> Option<&'static str> { Some("the duckdb shell's .timer: running the statement and printing its result, without starting the shell or opening the database") } diff --git a/system-bench/src/engines_external/pilotdb.rs b/system-bench/src/engines_external/pilotdb.rs index 043f60b3..ea14a3c9 100644 --- a/system-bench/src/engines_external/pilotdb.rs +++ b/system-bench/src/engines_external/pilotdb.rs @@ -6,7 +6,8 @@ use std::sync::atomic::{AtomicU64, Ordering}; use super::duckdb_command_line::DuckDbDatabaseOptions; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; use aqpbm_core::harness::one_shot::{ - ErrorTarget, OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, ResultValue, + ErrorTarget, OneShotCpuAccounting, OneShotQueryEngine, QueryRun, QueryTime, ResultTable, + ResultValue, }; use aqpbm_core::harness::protocol::ChildProcesses; use serde::Deserialize; @@ -173,6 +174,10 @@ impl OneShotQueryEngine for PilotDbEngine { SqlDialect::new(super::duckdb_command_line::DIALECT) } + fn query_time(&self) -> QueryTime { + QueryTime::EngineReported + } + fn engine_time_covers(&self) -> Option<&'static str> { Some("execute_aqp in the driver: connecting to DuckDB, rewriting the query, the pilot query when there is one and the final query, without starting Python, importing PilotDB or reading the tables' columns and row counts") } diff --git a/system-bench/src/engines_external/postgresql_command_line.rs b/system-bench/src/engines_external/postgresql_command_line.rs index a25797c1..ece3854f 100644 --- a/system-bench/src/engines_external/postgresql_command_line.rs +++ b/system-bench/src/engines_external/postgresql_command_line.rs @@ -7,7 +7,7 @@ use std::time::Duration; use aqpbm_core::harness::cgroup::CgroupSource; use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; use aqpbm_core::harness::one_shot::{ - OneShotCpuAccounting, OneShotQueryEngine, QueryRun, ResultTable, + OneShotCpuAccounting, OneShotQueryEngine, QueryRun, QueryTime, ResultTable, }; use super::restart_command::restart_and_wait; @@ -204,6 +204,10 @@ impl OneShotQueryEngine for PostgreSqlEngine { SqlDialect::new(DIALECT) } + fn query_time(&self) -> QueryTime { + QueryTime::EngineReported + } + fn engine_time_covers(&self) -> Option<&'static str> { Some("psql's \\timing: from sending the query to receiving the result, without starting psql or connecting") } From d56b5aaf15ef768a36a2bcade6ed84e3db8bf211 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:24:39 +0000 Subject: [PATCH 02/11] One-shot DuckDB and PilotDB keep their process between runs Each DuckDB and PilotDB run was a new process, so every hot run started with a cold in-process buffer pool, while ClickHouse, PostgreSQL and Druid keep theirs. Both adapters now keep one process for the whole configuration: DuckDB's shell reads each query from its input, PilotDB's driver serves one JSON request per line and holds a connection so the database instance outlives each execute_aqp call. restart() starts the process again, so cold runs still start cold. The harness reads a kept process's CPU from /proc around each run and its peak memory from VmHWM, reset through clear_refs before the run; a run in which the process started or exited is not measured. Co-Authored-By: Claude Opus 5.5 --- aqpbm-core/src/harness/one_shot.rs | 57 ++++++- aqpbm-core/src/harness/protocol.rs | 26 +++- aqpbm-core/tests/harness_one_shot.rs | 135 +++++++++++++++- .../engines_external/duckdb_command_line.rs | 81 +++++++++- .../src/engines_external/kept_process.rs | 146 ++++++++++++++++++ system-bench/src/engines_external/mod.rs | 1 + system-bench/src/engines_external/pilotdb.rs | 145 +++++++++++++---- .../src/engines_external/pilotdb_duckdb.py | 58 +++++-- system-bench/tests/duckdb_command_line.rs | 69 +++++++-- system-bench/tests/pilotdb.rs | 6 +- 10 files changed, 655 insertions(+), 69 deletions(-) create mode 100644 system-bench/src/engines_external/kept_process.rs diff --git a/aqpbm-core/src/harness/one_shot.rs b/aqpbm-core/src/harness/one_shot.rs index b3d59eca..66f1d745 100644 --- a/aqpbm-core/src/harness/one_shot.rs +++ b/aqpbm-core/src/harness/one_shot.rs @@ -8,7 +8,8 @@ use crate::harness::cgroup::CgroupSource; use crate::harness::engine::{EngineDescription, EngineError, SqlDialect, WorkloadSpec}; use crate::harness::machine::MachineDescription; use crate::harness::protocol::{ - CgroupCpuClock, ChildProcesses, CpuClock, PeakMemorySampler, PeakMemorySource, ProtocolError, + process_memory_sampler, processes_cpu_ns, reset_peak_resident_bytes, CgroupCpuClock, + ChildProcesses, CpuClock, PeakMemorySampler, PeakMemorySource, ProtocolError, SessionProcess, MEMORY_SAMPLE_INTERVAL, SAMPLES_PROCESS_MEMORY, }; @@ -180,6 +181,7 @@ impl QueryTime { pub enum OneShotCpuAccounting { Cgroup(CgroupSource), ChildProcesses(ChildProcesses), + SessionProcess(SessionProcess), } pub trait OneShotQueryEngine { @@ -370,11 +372,13 @@ enum CpuAndMemory { clock: Box, }, ChildProcesses(ChildProcesses), + SessionProcess(SessionProcess), } struct RunStart { cpu_ns: u64, memory: Option, + session_pid: Option, } #[derive(Default)] @@ -400,6 +404,7 @@ impl CpuAndMemory { OneShotCpuAccounting::ChildProcesses(children) => { CpuAndMemory::ChildProcesses(children) } + OneShotCpuAccounting::SessionProcess(session) => CpuAndMemory::SessionProcess(session), }) } @@ -429,6 +434,10 @@ impl CpuAndMemory { "the processes the adapter started for each run: their user and system CPU from wait4; the run's peak memory is the larger of wait4's maximum resident set size of the process and the descendants it waited for, taken only when above the harness's own VmHWM read after wait4 (below that it can be the harness's memory, which the process shared until exec), and the largest VmHWM from /proc//status, summed over each process and its descendants, read {every} while it runs, taken only when at least one such reading got a value; empty when neither is taken; run_peak_memory_source names which" ), CpuAndMemory::ChildProcesses(_) => "the processes the adapter started for each run: their user and system CPU from wait4; memory not measured, as VmHWM is read from /proc//status, which only Linux has".into(), + CpuAndMemory::SessionProcess(_) if SAMPLES_PROCESS_MEMORY => format!( + "the engine's process, which the adapter keeps between runs and starts again only to restart the engine: its CPU from /proc//task/*/schedstat around each run; the run's peak memory is the largest VmHWM from /proc//status, summed over the process and its descendants, after resetting it through /proc//clear_refs right before the run, read {every} while it runs; empty for a run in which the process started or exited" + ), + CpuAndMemory::SessionProcess(_) => "the engine's process, which the adapter keeps between runs: CPU and memory not measured, as they are read from /proc, which only Linux has".into(), } } @@ -448,6 +457,7 @@ impl CpuAndMemory { RunStart { cpu_ns: clock.process_cpu_ns(), memory, + session_pid: None, } } CpuAndMemory::ChildProcesses(children) => { @@ -455,6 +465,30 @@ impl CpuAndMemory { RunStart { cpu_ns: 0, memory: None, + session_pid: None, + } + } + CpuAndMemory::SessionProcess(session) => { + let proc_root = Path::new("/proc"); + let started = session + .pid() + .filter(|_| SAMPLES_PROCESS_MEMORY) + .and_then(|pid| { + let cpu_ns = processes_cpu_ns(proc_root, &[pid]).ok()?; + reset_peak_resident_bytes(proc_root, pid).ok()?; + Some((pid, cpu_ns)) + }); + match started { + Some((pid, cpu_ns)) => RunStart { + cpu_ns, + memory: process_memory_sampler(pid), + session_pid: Some(pid), + }, + None => RunStart { + cpu_ns: 0, + memory: None, + session_pid: None, + }, } } } @@ -503,6 +537,27 @@ impl CpuAndMemory { }, }) } + CpuAndMemory::SessionProcess(session) => { + let memory = start.memory.map(PeakMemorySampler::finish); + let Some(pid) = start.session_pid.filter(|pid| session.pid() == Some(*pid)) else { + return Ok(RunUsage::default()); + }; + let Ok(cpu_ns) = processes_cpu_ns(Path::new("/proc"), &[pid]) else { + return Ok(RunUsage::default()); + }; + let memory = memory.unwrap_or_default(); + Ok(RunUsage { + cpu_seconds: Some(cpu_ns.saturating_sub(start.cpu_ns) as f64 / 1e9), + sampled_peak_memory_bytes: memory.peak_bytes, + memory_samples_during_run: Some(memory.samples), + memory_peak_since_group_started_bytes: None, + run_peak_memory_bytes: memory.peak_bytes, + run_peak_memory_source: Some(match memory.peak_bytes { + Some(_) => PeakMemorySource::LargestReading, + None => PeakMemorySource::NoReadingDuringRun, + }), + }) + } } } } diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index db00bea2..27190faa 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -553,15 +553,20 @@ fn process_tree_peak_resident_bytes(proc_root: &Path, pid: u32) -> Option { } #[cfg(target_os = "linux")] -fn process_memory_sampler(pid: u32) -> Option { +pub(crate) fn process_memory_sampler(pid: u32) -> Option { Some(PeakMemorySampler::start( MEMORY_SAMPLE_INTERVAL, move || process_tree_peak_resident_bytes(Path::new("/proc"), pid), )) } +#[cfg(not(unix))] +pub(crate) fn process_memory_sampler(_pid: u32) -> Option { + None +} + #[cfg(all(unix, not(target_os = "linux")))] -fn process_memory_sampler(_pid: u32) -> Option { +pub(crate) fn process_memory_sampler(_pid: u32) -> Option { None } @@ -583,6 +588,23 @@ pub struct ChildUsage { pub peak_memory_source: Option, } +#[derive(Debug, Clone, Default)] +pub struct SessionProcess(Arc>>); + +impl SessionProcess { + pub fn set(&self, pid: Option) { + *self.0.lock().unwrap_or_else(PoisonError::into_inner) = pid; + } + + pub fn pid(&self) -> Option { + *self.0.lock().unwrap_or_else(PoisonError::into_inner) + } +} + +pub fn reset_peak_resident_bytes(proc_root: &Path, pid: u32) -> std::io::Result<()> { + std::fs::write(proc_root.join(pid.to_string()).join("clear_refs"), "5\n") +} + #[derive(Debug, Clone, Default)] pub struct ChildProcesses(Arc>); diff --git a/aqpbm-core/tests/harness_one_shot.rs b/aqpbm-core/tests/harness_one_shot.rs index f47bb729..b6a688ec 100644 --- a/aqpbm-core/tests/harness_one_shot.rs +++ b/aqpbm-core/tests/harness_one_shot.rs @@ -16,7 +16,8 @@ use aqpbm_core::harness::one_shot::{ OneShotSetup, QueryRun, ResultTable, ResultValue, }; use aqpbm_core::harness::protocol::{ - ChildProcesses, PeakMemorySampler, PeakMemorySource, SampledPeak, SAMPLES_PROCESS_MEMORY, + ChildProcesses, PeakMemorySampler, PeakMemorySource, SampledPeak, SessionProcess, + SAMPLES_PROCESS_MEMORY, }; use aqpbm_core::harness::run_directory::RunDirectory; @@ -587,6 +588,138 @@ fn a_result_records_the_harness_version_and_machine_and_one_without_them_reads() assert_eq!((&read[1].harness_version, &read[1].machine), (&None, &None)); } +struct KeptShellEngine { + shell: Option<( + std::process::Child, + std::process::ChildStdin, + std::io::BufReader, + )>, + session: SessionProcess, + runs: usize, + start_again_in_run: usize, +} + +impl KeptShellEngine { + fn start(&mut self) { + if let Some((mut child, _, _)) = self.shell.take() { + let _ = child.kill(); + let _ = child.wait(); + } + let mut child = Command::new("sh") + .args([ + "-c", + "while read q; do i=0; while [ $i -lt 20000 ]; do i=$((i+1)); done; echo $i; done", + ]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()) + .spawn() + .unwrap(); + let stdin = child.stdin.take().unwrap(); + let stdout = std::io::BufReader::new(child.stdout.take().unwrap()); + self.session.set(Some(child.id())); + self.shell = Some((child, stdin, stdout)); + } +} + +impl Drop for KeptShellEngine { + fn drop(&mut self) { + if let Some((mut child, stdin, _)) = self.shell.take() { + drop(stdin); + let _ = child.wait(); + } + } +} + +impl OneShotQueryEngine for KeptShellEngine { + fn description(&self) -> EngineDescription { + EngineDescription { + id: "kept".into(), + version: "1".into(), + version_dirty: false, + build_profile: "test".into(), + } + } + fn dialect(&self) -> SqlDialect { + SqlDialect::new("DuckDb") + } + fn engine_time_covers(&self) -> Option<&'static str> { + None + } + fn table_rows(&mut self, _table: &str) -> Result, EngineError> { + Ok(Some(10)) + } + fn restart(&mut self) -> Result<(), EngineError> { + self.start(); + Ok(()) + } + fn wait_until_idle(&mut self) -> Result<(), EngineError> { + self.start(); + Ok(()) + } + fn run_query(&mut self, _sql: &str) -> Result { + use std::io::{BufRead, Write}; + self.runs += 1; + if self.runs == self.start_again_in_run { + self.start(); + } + let (_, stdin, stdout) = self.shell.as_mut().unwrap(); + stdin.write_all(b"q\n").unwrap(); + stdin.flush().unwrap(); + let mut line = String::new(); + stdout.read_line(&mut line).unwrap(); + Ok(QueryRun { + table: ResultTable::from_csv_with_header(&format!("n\n{line}"))?, + engine_reported_seconds: None, + engine_reported_cpu_seconds: None, + details: BTreeMap::new(), + }) + } + fn cpu_accounting(&self) -> Option { + Some(OneShotCpuAccounting::SessionProcess(self.session.clone())) + } +} + +#[test] +fn the_harness_reads_a_kept_process_around_each_run_and_skips_a_run_it_started_in() { + let directory = TempDirectory::new("kept"); + let drop_caches = directory.0.join("drop_caches"); + let schedule = schedule(3, false); + let mut engine = KeptShellEngine { + shell: None, + session: SessionProcess::default(), + runs: 0, + start_again_in_run: 2, + }; + let result = run_one_shot_queries( + &mut engine, + &workload(), + &setup(&schedule, None, &drop_caches), + &mut |_| {}, + ) + .unwrap(); + let source = result.cpu_and_memory_source.as_deref().unwrap(); + assert!(source.contains("keeps between runs"), "{source}"); + let runs: Vec<_> = result + .queries + .iter() + .flat_map(|query| &query.runs) + .collect(); + assert!(runs.len() >= 3); + for (index, run) in runs.iter().enumerate() { + assert_eq!( + run.result.as_ref().unwrap().rows, + vec![vec![ResultValue::Integer(20000)]] + ); + let measured = SAMPLES_PROCESS_MEMORY && index != 1; + assert_eq!( + run.harness_cpu_seconds.is_some_and(|cpu| cpu > 0.0), + measured, + "{index} {run:?}" + ); + assert_eq!(run.run_peak_memory_source.is_some(), measured, "{run:?}"); + } +} + struct ChildProcessEngine { children: ChildProcesses, } diff --git a/system-bench/src/engines_external/duckdb_command_line.rs b/system-bench/src/engines_external/duckdb_command_line.rs index 670224a8..19a4f92e 100644 --- a/system-bench/src/engines_external/duckdb_command_line.rs +++ b/system-bench/src/engines_external/duckdb_command_line.rs @@ -6,7 +6,9 @@ use aqpbm_core::harness::engine::{EngineDescription, EngineError, SqlDialect}; use aqpbm_core::harness::one_shot::{ OneShotCpuAccounting, OneShotQueryEngine, QueryRun, QueryTime, ResultTable, }; -use aqpbm_core::harness::protocol::ChildProcesses; +use aqpbm_core::harness::protocol::SessionProcess; + +use super::kept_process::KeptProcess; pub const DIALECT: &str = "DuckDb"; @@ -21,7 +23,9 @@ pub struct DuckDbCommandLine { pub struct DuckDbEngine { command_line: DuckDbCommandLine, version: String, - children: ChildProcesses, + session: Option, + session_process: SessionProcess, + queries_sent: u64, } #[derive(Debug, Clone, Copy, PartialEq)] @@ -76,10 +80,63 @@ impl DuckDbEngine { Ok(DuckDbEngine { command_line, version, - children: ChildProcesses::default(), + session: None, + session_process: SessionProcess::default(), + queries_sent: 0, }) } + fn start_session(&mut self) -> Result<(), EngineError> { + self.end_session(); + let mut command = Command::new(&self.command_line.program); + command + .args(["-readonly", "-bail", "-csv", "-nullvalue", "\\N"]) + .arg(&self.command_line.database); + let mut session = KeptProcess::start("DuckDB", &mut command)?; + let mut setup = String::new(); + if let Some(threads) = self.command_line.threads { + setup.push_str(&format!("SET threads = {threads};\n")); + } + setup.push_str(".timer on\n"); + session.send(&setup)?; + self.session_process.set(Some(session.pid())); + self.session = Some(session); + Ok(()) + } + + fn end_session(&mut self) { + self.session_process.set(None); + drop(self.session.take()); + } + + fn session_query(&mut self, sql: &str) -> Result { + if self.session.is_none() { + self.start_session()?; + } + self.queries_sent += 1; + let marker = format!("approxbench-end-of-answer-{}", self.queries_sent); + let sql = sql.trim(); + let terminator = if sql.ends_with(';') { "" } else { "\n;" }; + let session = self.session.as_mut().expect("just started"); + let reply = match session.send(&format!("{sql}{terminator}\n.print {marker}\n")) { + Ok(()) => session.lines_until(|line| line == marker), + Err(_) => Err(session.end()), + }; + match reply { + Ok(mut lines) => { + lines.pop(); + Ok(lines.into_iter().map(|line| line + "\n").collect()) + } + Err(ended) => { + self.session_process.set(None); + self.session = None; + let error = EngineError(ended.describe("DuckDB")); + let _ = self.start_session(); + Err(error) + } + } + } + fn run(&self, read_only: bool, statements: &[&str]) -> Result { let mut command = Command::new(&self.command_line.program); if read_only { @@ -97,7 +154,7 @@ impl DuckDbEngine { for statement in statements { command.arg("-c").arg(statement); } - let output = self.children.output(&mut command).map_err(|error| { + let output = command.output().map_err(|error| { EngineError(format!("{}: {error}", self.command_line.program.display())) })?; let stdout = String::from_utf8_lossy(&output.stdout).to_string(); @@ -186,6 +243,7 @@ impl OneShotQueryEngine for DuckDbEngine { } fn load_table(&mut self, statements: &[String]) -> Result<(), EngineError> { + self.end_session(); let statements: Vec<&str> = statements.iter().map(String::as_str).collect(); self.run(false, &statements).map(|_| ()) } @@ -198,11 +256,18 @@ impl OneShotQueryEngine for DuckDbEngine { } fn restart(&mut self) -> Result<(), EngineError> { - Ok(()) + self.start_session() + } + + fn wait_until_idle(&mut self) -> Result<(), EngineError> { + match self.session { + Some(_) => Ok(()), + None => self.start_session(), + } } fn run_query(&mut self, sql: &str) -> Result { - let (text, timer) = split_timer_lines(&self.run(true, &[sql])?); + let (text, timer) = split_timer_lines(&self.session_query(sql)?); Ok(QueryRun { table: ResultTable::from_csv_with_header(&text)?, engine_reported_seconds: timer.map(|timer| timer.real_seconds), @@ -212,7 +277,9 @@ impl OneShotQueryEngine for DuckDbEngine { } fn cpu_accounting(&self) -> Option { - Some(OneShotCpuAccounting::ChildProcesses(self.children.clone())) + Some(OneShotCpuAccounting::SessionProcess( + self.session_process.clone(), + )) } } diff --git a/system-bench/src/engines_external/kept_process.rs b/system-bench/src/engines_external/kept_process.rs new file mode 100644 index 00000000..5748d4a1 --- /dev/null +++ b/system-bench/src/engines_external/kept_process.rs @@ -0,0 +1,146 @@ +use std::io::{BufRead, BufReader, Read, Write}; +use std::process::{Child, ChildStdin, ChildStdout, Command, ExitStatus, Stdio}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::thread::JoinHandle; + +use aqpbm_core::harness::engine::EngineError; + +const KEPT_STDERR_BYTES: usize = 64 * 1024; + +pub struct KeptProcess { + name: String, + child: Child, + stdin: Option, + stdout: BufReader, + stderr: Arc>>, + stderr_reader: Option>, +} + +pub struct ProcessEnded { + pub status: Option, + pub stderr: String, +} + +impl ProcessEnded { + pub fn describe(&self, name: &str) -> String { + let status = self.status.map_or_else( + || "an unknown status".to_string(), + |status| status.to_string(), + ); + format!("{name} exited with {status}: {}", self.stderr.trim()) + } +} + +impl KeptProcess { + pub fn start(name: &str, command: &mut Command) -> Result { + let mut child = command + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|error| EngineError(format!("starting {name}: {error}")))?; + let stdin = child.stdin.take(); + let stdout = BufReader::new(child.stdout.take().expect("stdout is piped")); + let mut stderr_pipe = child.stderr.take().expect("stderr is piped"); + let stderr = Arc::new(Mutex::new(Vec::new())); + let stderr_reader = { + let stderr = Arc::clone(&stderr); + std::thread::spawn(move || { + let mut buffer = [0u8; 8192]; + while let Ok(read) = stderr_pipe.read(&mut buffer) { + if read == 0 { + break; + } + let mut kept = stderr.lock().unwrap_or_else(PoisonError::into_inner); + kept.extend_from_slice(&buffer[..read]); + if kept.len() > KEPT_STDERR_BYTES { + let excess = kept.len() - KEPT_STDERR_BYTES; + kept.drain(..excess); + } + } + }) + }; + Ok(KeptProcess { + name: name.to_string(), + child, + stdin, + stdout, + stderr, + stderr_reader: Some(stderr_reader), + }) + } + + pub fn pid(&self) -> u32 { + self.child.id() + } + + pub fn send(&mut self, text: &str) -> Result<(), EngineError> { + let name = &self.name; + let stdin = self + .stdin + .as_mut() + .ok_or_else(|| EngineError(format!("{name}'s input is closed")))?; + stdin + .write_all(text.as_bytes()) + .and_then(|()| stdin.flush()) + .map_err(|error| EngineError(format!("writing to {name}: {error}"))) + } + + pub fn lines_until( + &mut self, + last: impl Fn(&str) -> bool, + ) -> Result, ProcessEnded> { + let mut lines = Vec::new(); + loop { + let mut line = String::new(); + match self.stdout.read_line(&mut line) { + Ok(0) | Err(_) => return Err(self.end()), + Ok(_) => { + let line = line.trim_end_matches(['\n', '\r']).to_string(); + if last(&line) { + lines.push(line); + return Ok(lines); + } + lines.push(line); + } + } + } + } + + pub fn end(&mut self) -> ProcessEnded { + drop(self.stdin.take()); + let status = match self.child.try_wait() { + Ok(Some(status)) => Some(status), + _ => { + let waited = std::time::Instant::now(); + loop { + match self.child.try_wait() { + Ok(Some(status)) => break Some(status), + Ok(None) if waited.elapsed() < std::time::Duration::from_secs(5) => { + std::thread::sleep(std::time::Duration::from_millis(10)); + } + _ => { + let _ = self.child.kill(); + break self.child.wait().ok(); + } + } + } + } + }; + if let Some(reader) = self.stderr_reader.take() { + let _ = reader.join(); + } + let stderr = + String::from_utf8_lossy(&self.stderr.lock().unwrap_or_else(PoisonError::into_inner)) + .to_string(); + ProcessEnded { status, stderr } + } +} + +impl Drop for KeptProcess { + fn drop(&mut self) { + if self.stderr_reader.is_some() { + self.end(); + } + } +} diff --git a/system-bench/src/engines_external/mod.rs b/system-bench/src/engines_external/mod.rs index 0445db15..6bf0b9b2 100644 --- a/system-bench/src/engines_external/mod.rs +++ b/system-bench/src/engines_external/mod.rs @@ -21,6 +21,7 @@ pub mod clickhouse_query_text; pub mod clickhouse_server; pub mod druid_sql; pub mod duckdb_command_line; +mod kept_process; pub mod pilotdb; pub mod plan_file; pub mod postgresql_command_line; diff --git a/system-bench/src/engines_external/pilotdb.rs b/system-bench/src/engines_external/pilotdb.rs index ea14a3c9..e16307b5 100644 --- a/system-bench/src/engines_external/pilotdb.rs +++ b/system-bench/src/engines_external/pilotdb.rs @@ -9,9 +9,11 @@ use aqpbm_core::harness::one_shot::{ ErrorTarget, OneShotCpuAccounting, OneShotQueryEngine, QueryRun, QueryTime, ResultTable, ResultValue, }; -use aqpbm_core::harness::protocol::ChildProcesses; +use aqpbm_core::harness::protocol::SessionProcess; use serde::Deserialize; +use super::kept_process::KeptProcess; + const DRIVER: &str = include_str!("pilotdb_duckdb.py"); const VERSION: &str = "import importlib.metadata as m, os, subprocess, pilotdb, duckdb @@ -32,9 +34,13 @@ pub struct PilotDbOnDuckDb { pub struct PilotDbEngine { setup: PilotDbOnDuckDb, version: String, - children: ChildProcesses, + session: Option<(KeptProcess, ScratchDirectory)>, + session_process: SessionProcess, } +const ANSWER: &str = "approxbench-answer "; +const FAILURE: &str = "approxbench-error "; + #[derive(Debug, Deserialize)] pub struct DriverAnswer { pub columns: Vec, @@ -112,11 +118,12 @@ impl PilotDbEngine { Ok(PilotDbEngine { setup, version, - children: ChildProcesses::default(), + session: None, + session_process: SessionProcess::default(), }) } - fn driver(&self, arguments: &[&str]) -> Result { + fn scratch_directory(&self) -> Result { let scratch = ScratchDirectory(self.setup.scratch_directory.join(format!( "pilotdb-{}-{}", std::process::id(), @@ -124,15 +131,97 @@ impl PilotDbEngine { ))); std::fs::create_dir_all(&scratch.0) .map_err(|error| EngineError(format!("{}: {error}", scratch.0.display())))?; - let output = self - .children - .output( - Command::new(&self.setup.python) - .arg("-c") - .arg(DRIVER) - .args(arguments) - .current_dir(&scratch.0), - ) + Ok(scratch) + } + + fn start_session(&mut self) -> Result<(), EngineError> { + self.end_session(); + let scratch = self.scratch_directory()?; + let relative_error = self.setup.relative_error.to_string(); + let failure_probability = self.setup.failure_probability.to_string(); + let threads = self + .setup + .threads + .map_or_else(String::new, |threads| threads.to_string()); + let process = KeptProcess::start( + "PilotDB", + Command::new(&self.setup.python) + .arg("-c") + .arg(DRIVER) + .args([ + "serve", + self.database(), + &relative_error, + &failure_probability, + &threads, + ]) + .arg(&scratch.0) + .current_dir(&scratch.0), + )?; + self.session_process.set(Some(process.pid())); + self.session = Some((process, scratch)); + Ok(()) + } + + fn end_session(&mut self) { + self.session_process.set(None); + drop(self.session.take()); + } + + fn session_query(&mut self, sql: &str) -> Result { + if self.session.is_none() { + self.start_session()?; + } + let request = serde_json::json!({ "sql": sql }).to_string(); + let (process, _) = self.session.as_mut().expect("just started"); + let reply = match process.send(&format!("{request}\n")) { + Ok(()) => { + process.lines_until(|line| line.starts_with(ANSWER) || line.starts_with(FAILURE)) + } + Err(_) => Err(process.end()), + }; + match reply { + Ok(lines) => { + let last = lines.last().expect("the reply line"); + match last.strip_prefix(ANSWER) { + Some(answer) => parse_driver_answer(answer), + None => { + let failure = &last[FAILURE.len()..]; + let text = serde_json::from_str::(failure) + .unwrap_or_else(|_| failure.to_string()); + let tail: Vec<&str> = text.lines().rev().take(5).collect(); + Err(EngineError(format!( + "PilotDB failed: {}", + tail.into_iter().rev().collect::>().join(" | ") + ))) + } + } + } + Err(ended) => { + self.session_process.set(None); + self.session = None; + let tail: Vec<&str> = ended.stderr.lines().rev().take(5).collect(); + let error = EngineError(format!( + "PilotDB exited with {}: {}", + ended + .status + .map_or_else(|| "an unknown status".to_string(), |s| s.to_string()), + tail.into_iter().rev().collect::>().join(" | ") + )); + let _ = self.start_session(); + Err(error) + } + } + } + + fn driver(&self, arguments: &[&str]) -> Result { + let scratch = self.scratch_directory()?; + let output = Command::new(&self.setup.python) + .arg("-c") + .arg(DRIVER) + .args(arguments) + .current_dir(&scratch.0) + .output() .map_err(|error| EngineError(format!("{}: {error}", self.setup.python.display())))?; if !output.status.success() { let stderr = String::from_utf8_lossy(&output.stderr); @@ -199,6 +288,7 @@ impl OneShotQueryEngine for PilotDbEngine { } fn table_rows(&mut self, table: &str) -> Result, EngineError> { + self.end_session(); if !Path::new(&self.setup.database).exists() { return Ok(None); } @@ -213,29 +303,24 @@ impl OneShotQueryEngine for PilotDbEngine { } fn restart(&mut self) -> Result<(), EngineError> { - Ok(()) + self.start_session() + } + + fn wait_until_idle(&mut self) -> Result<(), EngineError> { + match self.session { + Some(_) => Ok(()), + None => self.start_session(), + } } fn run_query(&mut self, sql: &str) -> Result { - let relative_error = self.setup.relative_error.to_string(); - let failure_probability = self.setup.failure_probability.to_string(); - let threads = self - .setup - .threads - .map_or_else(String::new, |threads| threads.to_string()); - let line = self.driver(&[ - "answer", - self.database(), - sql, - &relative_error, - &failure_probability, - &threads, - ])?; - parse_driver_answer(&line) + self.session_query(sql) } fn cpu_accounting(&self) -> Option { - Some(OneShotCpuAccounting::ChildProcesses(self.children.clone())) + Some(OneShotCpuAccounting::SessionProcess( + self.session_process.clone(), + )) } } diff --git a/system-bench/src/engines_external/pilotdb_duckdb.py b/system-bench/src/engines_external/pilotdb_duckdb.py index 1da50e89..6c8a6ad1 100644 --- a/system-bench/src/engines_external/pilotdb_duckdb.py +++ b/system-bench/src/engines_external/pilotdb_duckdb.py @@ -1,8 +1,12 @@ import json +import logging import os import resource +import shutil import sys +import tempfile import time +import traceback import duckdb import pandas @@ -48,17 +52,20 @@ def read_text(path): return file.read() -def answer(database, sql, relative_error, failure_probability, threads): - with duckdb.connect(database, read_only=True) as connection: - columns, rows = table_metadata(connection) +def use_threads(threads): from pilotdb.db_driver import duckdb_utils - from pilotdb.execute import execute_aqp - from pilotdb.query import Query if threads: duckdb_utils.connect_to_db = lambda path: duckdb.connect( database=path, read_only=False, config={"threads": threads} ) + return duckdb_utils + + +def answer_with(database, columns, rows, sql, relative_error, failure_probability): + from pilotdb.execute import execute_aqp + from pilotdb.query import Query + query = Query( query=sql, table_cols=columns, @@ -98,19 +105,46 @@ def answer(database, sql, relative_error, failure_probability, threads): } +def serve(database, relative_error, failure_probability, threads, scratch_root): + import pilotdb.execute + import pilotdb.query + + duckdb_utils = use_threads(threads) + held = duckdb_utils.connect_to_db(database) + columns, rows = table_metadata(held) + root = logging.getLogger() + for line in sys.stdin: + if not line.strip(): + continue + scratch = tempfile.mkdtemp(prefix="pilotdb-", dir=scratch_root) + for handler in list(root.handlers): + root.removeHandler(handler) + handler.close() + os.chdir(scratch) + try: + found = answer_with(database, columns, rows, json.loads(line)["sql"], relative_error, + failure_probability) + reply = "approxbench-answer " + json.dumps(found, default=str) + except Exception: + reply = "approxbench-error " + json.dumps(traceback.format_exc()[-4000:]) + finally: + os.chdir(scratch_root) + shutil.rmtree(scratch, ignore_errors=True) + print(reply, flush=True) + held.close() + + def main(): mode, database = sys.argv[1], sys.argv[2] + if mode == "serve": + threads = int(sys.argv[5]) if sys.argv[5] else None + serve(database, float(sys.argv[3]), float(sys.argv[4]), threads, sys.argv[6]) + return if mode == "table-rows": with duckdb.connect(database, read_only=True) as connection: print(json.dumps({"rows": table_rows(connection, sys.argv[3])})) return - threads = int(sys.argv[6]) if sys.argv[6] else None - print( - json.dumps( - answer(database, sys.argv[3], float(sys.argv[4]), float(sys.argv[5]), threads), - default=str, - ) - ) + sys.exit(f"unknown mode {mode}") main() diff --git a/system-bench/tests/duckdb_command_line.rs b/system-bench/tests/duckdb_command_line.rs index b11205e5..9ac1fb25 100644 --- a/system-bench/tests/duckdb_command_line.rs +++ b/system-bench/tests/duckdb_command_line.rs @@ -40,10 +40,12 @@ fn timer_lines_are_summed_and_taken_out_of_the_result() { #[cfg(unix)] #[test] -fn the_command_line_is_read_only_csv_with_threads_then_the_timer() { +fn one_kept_read_only_csv_session_gets_threads_the_timer_and_each_query() { use std::io::Write; let directory = TempDirectory::new("stub"); let arguments = directory.0.join("arguments"); + let input = directory.0.join("input"); + let starts = directory.0.join("starts"); let program = directory.0.join("duckdb"); let mut writer = std::process::Command::new("sh") .arg("-c") @@ -59,9 +61,18 @@ fn the_command_line_is_read_only_csv_with_threads_then_the_timer() { .write_all( format!( "#!/bin/sh\nif [ \"$1\" = --version ]; then echo 'v9.9.9 stub'; exit 0; fi\n\ - for a in \"$@\"; do printf '%s\\n' \"$a\"; done > {}\n\ - printf 'k,count_star()\\n7,3\\n\\\\N,1\\nRun Time (s): real 0.125 user 0.250000 sys 0.000000\\n'\n", - arguments.display() + echo start >> {starts}\n\ + for a in \"$@\"; do printf '%s\\n' \"$a\"; done > {arguments}\n\ + while IFS= read -r line; do\n\ + printf '%s\\n' \"$line\" >> {input}\n\ + case \"$line\" in\n\ + *fail*) echo 'Binder Error: fail' >&2; exit 1;;\n\ + .print*) printf 'k,count_star()\\n7,3\\n\\\\N,1\\nRun Time (s): real 0.125 user 0.250000 sys 0.000000\\n'; printf '%s\\n' \"${{line#.print }}\";;\n\ + esac\n\ + done\n", + starts = starts.display(), + arguments = arguments.display(), + input = input.display(), ) .as_bytes(), ) @@ -75,30 +86,58 @@ fn the_command_line_is_read_only_csv_with_threads_then_the_timer() { }) .unwrap(); assert_eq!(engine.description().version, "v9.9.9 stub"); - let run = engine - .run_query("SELECT k, COUNT(*) FROM t GROUP BY k") - .unwrap(); - assert_eq!(run.table.columns, vec!["k", "count_star()"]); - assert_eq!(run.table.rows[1][0], ResultValue::Null); - assert_eq!(run.engine_reported_seconds, Some(0.125)); - assert_eq!(run.engine_reported_cpu_seconds, Some(0.25)); + for _ in 0..2 { + let run = engine + .run_query("SELECT k, COUNT(*) FROM t GROUP BY k") + .unwrap(); + assert_eq!(run.table.columns, vec!["k", "count_star()"]); + assert_eq!(run.table.rows[1][0], ResultValue::Null); + assert_eq!(run.engine_reported_seconds, Some(0.125)); + assert_eq!(run.engine_reported_cpu_seconds, Some(0.25)); + } let recorded = std::fs::read_to_string(&arguments).unwrap(); assert_eq!( recorded.lines().collect::>(), vec![ "-readonly", + "-bail", "-csv", "-nullvalue", "\\N", directory.0.join("hits.db").to_str().unwrap(), - "-c", - "SET threads = 16", - "-c", + ] + ); + let sent = std::fs::read_to_string(&input).unwrap(); + assert_eq!( + sent.lines().collect::>(), + vec![ + "SET threads = 16;", ".timer on", - "-c", "SELECT k, COUNT(*) FROM t GROUP BY k", + ";", + ".print approxbench-end-of-answer-1", + "SELECT k, COUNT(*) FROM t GROUP BY k", + ";", + ".print approxbench-end-of-answer-2", ] ); + assert_eq!(std::fs::read_to_string(&starts).unwrap().lines().count(), 1); + let error = engine.run_query("SELECT fail").unwrap_err(); + assert!(error.0.contains("Binder Error: fail"), "{error}"); + engine.run_query("SELECT 1").unwrap(); + assert_eq!(std::fs::read_to_string(&starts).unwrap().lines().count(), 2); + engine.restart().unwrap(); + engine.run_query("SELECT 1").unwrap(); + assert_eq!(std::fs::read_to_string(&starts).unwrap().lines().count(), 3); + let pids = std::process::Command::new("pkill") + .args(["-f", program.to_str().unwrap()]) + .status() + .unwrap(); + assert!(pids.success()); + std::thread::sleep(std::time::Duration::from_millis(100)); + assert!(engine.run_query("SELECT 1").is_err()); + engine.run_query("SELECT 1").unwrap(); + assert_eq!(std::fs::read_to_string(&starts).unwrap().lines().count(), 4); assert_eq!(engine.table_rows("t").unwrap(), None); } diff --git a/system-bench/tests/pilotdb.rs b/system-bench/tests/pilotdb.rs index 6bd721f2..472cce4a 100644 --- a/system-bench/tests/pilotdb.rs +++ b/system-bench/tests/pilotdb.rs @@ -95,11 +95,15 @@ fn a_real_pilotdb_answers_over_a_large_table_and_cleans_up() { .unwrap(); assert_eq!(dates.table.rows.len(), 7); assert_eq!(dates.table.rows[0][0].key_text(), "2013-07-15"); + let error = engine.run_query("SELECT * FROM missing").unwrap_err(); + assert!(error.0.contains("missing"), "{error}"); + let after_error = engine.run_query("SELECT COUNT(*) FROM big").unwrap(); + assert_eq!(after_error.table.rows.len(), 1); + drop(engine); let leftovers: Vec<_> = std::fs::read_dir(&directory.0) .unwrap() .filter_map(|entry| entry.ok()) .filter(|entry| entry.file_name().to_string_lossy().starts_with("pilotdb-")) .collect(); assert!(leftovers.is_empty()); - assert!(engine.run_query("SELECT * FROM missing").is_err()); } From 944fa011e6760d932cb18370d823fb5aba8f3fad Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:27:34 +0000 Subject: [PATCH 03/11] One-shot accuracy: rows without group columns match in value order A query without GROUP BY or DISTINCT was compared row by row by position, so a tie in its ORDER BY counted as an error: on ClickBench query 25 (ORDER BY EventTime LIMIT 10) the truth's own runs disagreed and every exact engine had 6 to 8 differing cells. Such rows now match in value order, and a query whose truth runs disagree gets no accuracy, as the query does not fix its answer. Co-Authored-By: Claude Opus 5.5 --- aqpbm-core/src/harness/one_shot_report.rs | 54 ++++++++++++++++----- aqpbm-core/tests/harness_one_shot_report.rs | 19 +++++++- 2 files changed, 59 insertions(+), 14 deletions(-) diff --git a/aqpbm-core/src/harness/one_shot_report.rs b/aqpbm-core/src/harness/one_shot_report.rs index b6033780..0e9d74f9 100644 --- a/aqpbm-core/src/harness/one_shot_report.rs +++ b/aqpbm-core/src/harness/one_shot_report.rs @@ -1,7 +1,9 @@ use std::collections::BTreeMap; use crate::harness::benchmark_external::{median_of, relative_error}; -use crate::harness::one_shot::{OneShotResult, QueryRecord, QueryTime, ResultTable, RunRecord}; +use crate::harness::one_shot::{ + OneShotResult, QueryRecord, QueryTime, ResultTable, ResultValue, RunRecord, +}; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct ConfigurationName { @@ -45,6 +47,28 @@ pub struct TableComparison { pub extra_groups: usize, } +fn compare_values(left: &ResultValue, right: &ResultValue) -> std::cmp::Ordering { + match (left.as_number(), right.as_number()) { + (Some(left), Some(right)) => left.total_cmp(&right), + (Some(_), None) => std::cmp::Ordering::Less, + (None, Some(_)) => std::cmp::Ordering::Greater, + (None, None) => left.key_text().cmp(&right.key_text()), + } +} + +fn rows_in_value_order(table: &ResultTable) -> Vec { + let mut order: Vec = (0..table.rows.len()).collect(); + order.sort_by(|&left, &right| { + table.rows[left] + .iter() + .zip(&table.rows[right]) + .map(|(left, right)| compare_values(left, right)) + .find(|ordering| ordering.is_ne()) + .unwrap_or(std::cmp::Ordering::Equal) + }); + order +} + pub fn compare_tables( answer: &ResultTable, truth: &ResultTable, @@ -69,19 +93,22 @@ pub fn compare_tables( )); } let keyed = |table: &ResultTable| -> BTreeMap, usize> { + if group_by_column_positions.is_empty() { + return rows_in_value_order(table) + .into_iter() + .enumerate() + .map(|(rank, index)| (vec![rank.to_string()], index)) + .collect(); + } table .rows .iter() .enumerate() .map(|(index, row)| { - let key = if group_by_column_positions.is_empty() { - vec![index.to_string()] - } else { - group_by_column_positions - .iter() - .map(|position| row[*position].key_text()) - .collect() - }; + let key = group_by_column_positions + .iter() + .map(|position| row[*position].key_text()) + .collect(); (key, index) }) .collect() @@ -388,8 +415,11 @@ pub fn one_shot_report( let truth_table = truth_query .and_then(|other| other.runs.iter().find_map(|run| run.result.as_ref())); if let (Some(truth_query), Some(truth_table)) = (truth_query, truth_table) { - row.truth_runs_agree = Some(runs_agree(truth_query, truth_table)); - accuracy(&mut row, query, truth_table, result); + let agree = runs_agree(truth_query, truth_table); + row.truth_runs_agree = Some(agree); + if agree { + accuracy(&mut row, query, truth_table, result); + } } } rows.push(row); @@ -654,7 +684,7 @@ impl OneShotReport { pub fn summary_markdown(&self) -> String { let mut text = String::new(); if let Some(truth) = &self.truth { - text.push_str(&format!("Accuracy against {truth}.\n\n")); + text.push_str(&format!("Accuracy against {truth}. The rows of a query without group columns are matched in value order, not by position; a query whose truth runs disagree with each other gets no accuracy, as the query does not fix its answer.\n\n")); } text.push_str( "Wall time is measured by the harness around each run, from handing the query to the adapter to getting the parsed answer back, so it includes starting a process or connecting when the adapter does that for each run. Query time is what speedups divide, hot median by hot median; it leaves out starting a process, as ClickBench does.\n\n", diff --git a/aqpbm-core/tests/harness_one_shot_report.rs b/aqpbm-core/tests/harness_one_shot_report.rs index a19ffb2f..18e01ef4 100644 --- a/aqpbm-core/tests/harness_one_shot_report.rs +++ b/aqpbm-core/tests/harness_one_shot_report.rs @@ -42,7 +42,7 @@ fn missing_and_extra_groups_are_counted() { } #[test] -fn without_group_columns_rows_are_matched_by_position() { +fn without_group_columns_rows_are_matched_in_value_order() { let truth = table(vec![vec![n(10.0), t("x"), n(4.0)]]); let answer = table(vec![vec![n(9.0), t("y"), n(4.0)]]); let comparison = compare_tables(&answer, &truth, &[]).unwrap(); @@ -50,6 +50,19 @@ fn without_group_columns_rows_are_matched_by_position() { assert_eq!(comparison.differing_text_cells, 1); assert!(compare_tables(&table(vec![vec![n(1.0)]]), &truth, &[]).is_err()); assert!(compare_tables(&answer, &truth, &[5]).is_err()); + let tied = table(vec![ + vec![t("b"), n(2.0)], + vec![t("a"), n(1.0)], + vec![t("c"), n(3.0)], + ]); + let reordered = table(vec![ + vec![t("a"), n(1.0)], + vec![t("c"), n(3.0)], + vec![t("b"), n(2.0)], + ]); + let comparison = compare_tables(&reordered, &tied, &[]).unwrap(); + assert_eq!(comparison.max_relative_error, Some(0.0)); + assert_eq!(comparison.differing_text_cells, 0); } fn run(seconds: f64, value: f64, exact: Option) -> RunRecord { @@ -253,7 +266,7 @@ fn empty_results_compare_whatever_their_header() { } #[test] -fn a_truth_whose_runs_differ_is_flagged_and_one_run_gives_no_speedup() { +fn a_truth_whose_runs_differ_is_flagged_scores_nothing_and_one_run_gives_no_speedup() { let mut differing = run(2.0, 100.0, None); differing.result = Some(table(vec![vec![n(99.0)]])); let results = vec![ @@ -269,6 +282,8 @@ fn a_truth_whose_runs_differ_is_flagged_and_one_run_gives_no_speedup() { let report = one_shot_report(&results, Some(&truth), std::slice::from_ref(&truth)).unwrap(); assert_eq!(report.rows[0].truth_runs_agree, Some(false)); assert_eq!(report.rows[1].truth_runs_agree, Some(false)); + assert_eq!(report.rows[1].max_relative_error, None); + assert_eq!(report.rows[1].differing_text_cells, None); assert_eq!(report.rows[1].hot_median_wall_seconds, None); assert_eq!(report.rows[1].speedups[0].1, None); assert!(report From 2214fe39f9cd16bcf3f6514d516ae7595333f722 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:28:18 +0000 Subject: [PATCH 04/11] Periodic systems: instance peaks add up; cost comparison names its queries When ASAPQuery-backend's queries do not plan together, each runs in an instance of its own. The benchmark runs them one after another, but a deployment runs them at the same time, so the peak resident bytes are now the sum of the instances' peaks; the largest instance's stays alongside. A query the reference system does not support is answered by the in-process exact plan and is not in that system's latency, CPU or memory, while the candidate's include it. Each report now lists the queries each system asked, the latency of both over the queries both asked, and says when their CPU and memory cover different queries. Co-Authored-By: Claude Opus 5.5 --- scripts/use_cases/run_use_case_on_systems.py | 35 ++++++++++++++++++- .../use_cases/test_run_use_case_on_systems.py | 25 +++++++++++-- 2 files changed, 57 insertions(+), 3 deletions(-) diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index 8742778f..f041f31d 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -429,6 +429,32 @@ def system_summary(asked, results, disk_bytes=None): return out +def queries_asked(document): + return sorted(q["id"] for q in document["queries"] if "unsupported" not in q) if document else [] + + +def latency_over(document, ids): + seconds = [c["query_seconds"] for q in document["queries"] if q["id"] in ids and "unsupported" not in q + for c in q.get("costs", []) if "query_seconds" in c] + return milliseconds("query", seconds) if seconds else {} + + +def cost_comparison(names, documents, summaries): + asked = [queries_asked(document) for document in documents] + both = sorted(set(asked[0]) & set(asked[1])) + for document, summary, ids in zip(documents, summaries, asked): + summary["queries asked"] = ids + if document: + summary["latency over the queries both systems asked"] = latency_over(document, set(both)) + comparable = asked[0] == asked[1] + return {"queries both systems asked": both, + "cpu and memory comparable": comparable, + "cpu and memory": "cover the same queries on both systems" if comparable else + f"not comparable: {names[0]} asked {', '.join(asked[0]) or 'no query'} and {names[1]} asked " + f"{', '.join(asked[1]) or 'no query'}; each system's CPU and memory are read over its whole run, so " + "they cover different queries"} + + def merged_exact(reference, truth, name=VICTORIAMETRICS): truth_by_id = {q["id"]: q for q in truth["queries"]} queries, sources = [], {} @@ -900,7 +926,10 @@ def merged_groups(spec, ran): summary = {"instances": len(ran), "per instance": summaries, "data writes": sum(s.get("data writes") or 0 for s in summaries), "cpu seconds": None if None in cpu else sum(cpu), - "peak resident bytes": max(peaks) if peaks else None} + "peak resident bytes": sum(peaks) if len(peaks) == len(summaries) else None, + "largest instance peak resident bytes": max(peaks) if peaks else None, + "peak resident bytes are": "the sum of every instance's peak, as a deployment runs the instances " + "at the same time; the benchmark runs them one after another"} summary.update(latency(asked)) summary["failed evaluations"] = {k: v for s in summaries for k, v in s["failed evaluations"].items()} summary["failed"] = failed_queries(asked) @@ -1082,6 +1111,8 @@ def run_spec_trial(args, spec_path, spec, name, workdir): "backend_rev": rev, **backend_pin_fields(args), "systems": {names[0]: reference_summary, names[1]: candidate_summary}, + "cost comparison": cost_comparison(names, (reference, approx), + (reference_summary, candidate_summary)), "per query": queries, } out = os.path.join(workdir, f"{arm}-summary.json") @@ -1221,6 +1252,8 @@ def run_case_trial(args, case, arms, spec_path, spec, run_prefix, workdir, truth "signals": {q["id"]: case.get("signals", case["signal"])(q["id"]) for q in spec["queries"]}, "write mode": write_mode(args), "systems": {names[0]: reference_summary, names[1]: candidate_summary}, + "cost comparison": cost_comparison(names, (reference, approx), + (reference_summary, candidate_summary)), **truth_check_fields(reference, names[0]), } if "rules" in case: diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index 7e6ed3ce..3c70a934 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -14,7 +14,7 @@ import run_use_case import run_use_case_on_systems from run_use_case_on_systems import (answered_query, backend_arms, backend_commit, backend_rev, cell_of, - describe_backend_plan, evaluation_counts, evaluation_steps, + cost_comparison, describe_backend_plan, evaluation_counts, evaluation_steps, harness_measurements, latency, merged_exact, merged_groups, pinned_backend_commit, plan_groups, run_directory, trial_name, truth_errors, workload, workload_name) @@ -277,7 +277,8 @@ def ran(ids, cpu, peak): self.assertEqual(summary["instances"], 2) self.assertEqual(summary["data writes"], 2) self.assertEqual(summary["cpu seconds"], 3.0) - self.assertEqual(summary["peak resident bytes"], 30) + self.assertEqual(summary["peak resident bytes"], 40) + self.assertEqual(summary["largest instance peak resident bytes"], 30) self.assertEqual(summary["evaluations"], 3) self.assertEqual(summary["evaluation steps"], 2) @@ -286,6 +287,26 @@ def test_one_group_is_returned_unchanged(self): self.assertIs(merged_groups(spec_of(), [only]), only) +class CostComparisonTest(unittest.TestCase): + def test_latency_over_shared_queries_and_cpu_flagged_when_the_queries_differ(self): + def document(costs): + return {"queries": [{"id": i, "costs": [{"query_seconds": s} for s in seconds]} if seconds is not None + else {"id": i, "unsupported": "no"} for i, seconds in costs.items()]} + reference = document({"a": [0.001, 0.003], "b": None}) + candidate = document({"a": [0.002], "b": [0.5]}) + summaries = ({}, {}) + out = cost_comparison(("R", "C"), (reference, candidate), summaries) + self.assertEqual(out["queries both systems asked"], ["a"]) + self.assertFalse(out["cpu and memory comparable"]) + self.assertIn("R asked a and C asked a, b", out["cpu and memory"]) + self.assertEqual(summaries[0]["queries asked"], ["a"]) + self.assertEqual(summaries[1]["queries asked"], ["a", "b"]) + self.assertAlmostEqual(summaries[1]["latency over the queries both systems asked"]["median query ms"], 2.0) + self.assertAlmostEqual(summaries[0]["latency over the queries both systems asked"]["mean query ms"], 2.0) + same = cost_comparison(("R", "C"), (candidate, candidate), ({}, {})) + self.assertTrue(same["cpu and memory comparable"]) + + class EvaluationCountsTest(unittest.TestCase): def test_empty_and_failed_evaluations(self): query = {"evaluations": 3, "failed_evaluations": 1, From 0ea5784a31889481405f955b78a0da9e84e5152b Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:34:32 +0000 Subject: [PATCH 05/11] planeval: state bytes count every stored state, each sketch once state_bytes counted only sketch summaries and charged every other stored value 0, and raw data at query time counted 16 bytes per sample with no labels. A stored state is now charged every value it holds, by type (8 bytes for a number or a timestamp, a string's length), and each sketch once however many rows share it. Each evaluation also reports the label bytes of the series it read, which run_use_case.py adds to the query memory. The executor's own Batch::memory_bytes is not used: once a query has read a stored state, the batch counts its sketches as held outside the run and charges them nothing. Co-Authored-By: Claude Opus 5.5 --- scripts/use_cases/run_use_case.py | 7 +++- system-bench/src/bin/planeval.rs | 1 + system-bench/src/planeval/run.rs | 59 ++++++++++++++++++++++++++----- usecase-study/src/output.rs | 2 ++ 4 files changed, 60 insertions(+), 9 deletions(-) diff --git a/scripts/use_cases/run_use_case.py b/scripts/use_cases/run_use_case.py index da5bd01c..ece43994 100644 --- a/scripts/use_cases/run_use_case.py +++ b/scripts/use_cases/run_use_case.py @@ -150,10 +150,14 @@ def query_costs(run_id, use_case, signal, exact_query, approx_query): rows.append(row(c["time"], "low_level", run_id, {**labels, "arm": arm}, "query_latency", c["query_seconds"], "s")) rows.append(row(c["time"], "low_level", run_id, {**labels, "arm": arm}, "query_memory", - c["state_bytes"] + c["samples_read_at_query"] * SAMPLE_BYTES, "bytes")) + c["state_bytes"] + raw_bytes_read(c), "bytes")) return rows +def raw_bytes_read(cost): + return cost["samples_read_at_query"] * SAMPLE_BYTES + cost.get("raw_label_bytes_read_at_query", 0) + + def mean(values): return sum(values) / len(values) if values else None @@ -170,6 +174,7 @@ def costs_of(query): "mean samples read at query": mean([c["samples_read_at_query"] for c in costs]), "peak raw sample bytes read at query": max((c["samples_read_at_query"] * SAMPLE_BYTES for c in costs), default=None), + "peak raw bytes read at query, labels included": max((raw_bytes_read(c) for c in costs), default=None), } diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index 804c67da..31294283 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -215,6 +215,7 @@ async fn main() -> Result<()> { query_seconds: cost.query_seconds, compile_seconds: cost.compile_seconds, samples_read_at_query: cost.samples_read_at_query, + raw_label_bytes_read_at_query: cost.raw_label_bytes_read_at_query, state_bytes: cost.state_bytes, }); answered.extend( diff --git a/system-bench/src/planeval/run.rs b/system-bench/src/planeval/run.rs index 096e07c6..10b29575 100644 --- a/system-bench/src/planeval/run.rs +++ b/system-bench/src/planeval/run.rs @@ -48,6 +48,7 @@ pub struct Cost { pub query_seconds: f64, pub compile_seconds: f64, pub samples_read_at_query: usize, + pub raw_label_bytes_read_at_query: usize, pub state_bytes: usize, } @@ -55,14 +56,55 @@ fn samples(slices: &[Slice]) -> usize { slices.iter().map(|(_, points)| points.len()).sum() } -fn state_bytes(state: &Batch) -> usize { - state - .to_rows() +fn value_bytes(value: &Value) -> usize { + match value { + Value::Null => 0, + Value::Bool(_) => 1, + Value::Date(_) => 4, + Value::Int64(_) | Value::Float64(_) | Value::Timestamp(_) => 8, + Value::Interval { .. } => 16, + Value::Utf8(text) => text.len(), + Value::List(values) | Value::Struct(values) => values.iter().map(value_bytes).sum(), + Value::Map(pairs) => pairs + .iter() + .map(|(key, value)| value_bytes(key) + value_bytes(value)) + .sum(), + Value::Summary { .. } => 0, + } +} + +fn state_bytes<'a>(states: impl Iterator) -> usize { + let mut seen = BTreeSet::new(); + let mut shared = BTreeMap::new(); + let mut bytes = 0; + for batch in states { + for cell in batch.to_rows().iter().flatten() { + match cell { + Value::Summary { state, .. } => { + if seen.insert(Arc::as_ptr(state) as *const () as usize) { + bytes += state.approx_memory_bytes(); + if let Some((id, shared_bytes)) = state.shared_state() { + shared.insert(id, shared_bytes); + } + } + } + plain => bytes += value_bytes(plain), + } + } + } + bytes + shared.values().sum::() +} + +fn label_bytes(slices: &[Slice]) -> usize { + slices .iter() - .flatten() - .map(|cell| match cell { - Value::Summary { state, .. } => state.approx_memory_bytes(), - _ => 0, + .filter(|(_, points)| !points.is_empty()) + .map(|(series, _)| { + series + .labels + .iter() + .map(|(name, value)| name.len() + value.len()) + .sum::() }) .sum() } @@ -419,7 +461,8 @@ impl Driver { query_seconds, compile_seconds: refresh_compile_seconds + compile_seconds, samples_read_at_query: samples(&raw), - state_bytes: self.store.values().map(|s| state_bytes(&s.state)).sum(), + raw_label_bytes_read_at_query: label_bytes(&raw), + state_bytes: state_bytes(self.store.values().map(|s| &s.state)), }; let reference_answers = match &self.reference { None => None, diff --git a/usecase-study/src/output.rs b/usecase-study/src/output.rs index 9f9879a8..f521338e 100644 --- a/usecase-study/src/output.rs +++ b/usecase-study/src/output.rs @@ -74,5 +74,7 @@ pub struct PlanevalCost { pub query_seconds: f64, pub compile_seconds: f64, pub samples_read_at_query: usize, + #[serde(default)] + pub raw_label_bytes_read_at_query: usize, pub state_bytes: usize, } From 38585eb5b71e4e348ee78a803a5ef5ca4c4885e0 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:35:09 +0000 Subject: [PATCH 06/11] planeval: building raw-sample batches is timed apart from the query Each evaluation turned the raw samples it reads into executor rows, serializing every series' labels to JSON, inside query_seconds. Only the plans that read raw samples paid it, so it raised the exact arm's latency and the speedups against it. That time is now raw_batch_seconds, taken out of query_seconds and refresh_seconds as compile time already was, and run_use_case.py reports it as its own mean. Co-Authored-By: Claude Opus 5.5 --- scripts/use_cases/run_use_case.py | 1 + system-bench/src/bin/planeval.rs | 1 + system-bench/src/planeval/run.rs | 41 +++++++++++++++++++++++++------ usecase-study/src/output.rs | 2 ++ 4 files changed, 37 insertions(+), 8 deletions(-) diff --git a/scripts/use_cases/run_use_case.py b/scripts/use_cases/run_use_case.py index ece43994..518c79b7 100644 --- a/scripts/use_cases/run_use_case.py +++ b/scripts/use_cases/run_use_case.py @@ -168,6 +168,7 @@ def costs_of(query): return { "mean query ms": mean([c["query_seconds"] * 1e3 for c in costs]), "mean compile ms": mean([c["compile_seconds"] * 1e3 for c in costs]), + "mean raw batch ms": mean([c.get("raw_batch_seconds", 0.0) * 1e3 for c in costs]), "planning ms": query.get("plan", {}).get("planning_ms"), "insert samples per second": sum(c["samples_ingested"] for c in costs) / refresh if refresh else None, "peak state bytes": max((c["state_bytes"] for c in costs), default=None), diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index 31294283..b0d828a0 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -214,6 +214,7 @@ async fn main() -> Result<()> { samples_ingested: cost.samples_ingested, query_seconds: cost.query_seconds, compile_seconds: cost.compile_seconds, + raw_batch_seconds: cost.raw_batch_seconds, samples_read_at_query: cost.samples_read_at_query, raw_label_bytes_read_at_query: cost.raw_label_bytes_read_at_query, state_bytes: cost.state_bytes, diff --git a/system-bench/src/planeval/run.rs b/system-bench/src/planeval/run.rs index 10b29575..885da98e 100644 --- a/system-bench/src/planeval/run.rs +++ b/system-bench/src/planeval/run.rs @@ -47,6 +47,7 @@ pub struct Cost { pub samples_ingested: usize, pub query_seconds: f64, pub compile_seconds: f64, + pub raw_batch_seconds: f64, pub samples_read_at_query: usize, pub raw_label_bytes_read_at_query: usize, pub state_bytes: usize, @@ -202,6 +203,17 @@ fn time_series_store(dag: &PhysicalASAPDAG, slices: &[Slice]) -> Result f64 { + self.compile_seconds + self.raw_batch_seconds + } +} + fn execute( dag: &PhysicalASAPDAG, views: BTreeMap, @@ -209,7 +221,7 @@ fn execute( ids: &[u64], scope: Scope, max_bytes: usize, -) -> Result<(Vec>, f64)> { +) -> Result<(Vec>, Untimed)> { let read: Vec = if views.is_empty() { Vec::new() } else { @@ -224,7 +236,9 @@ fn execute( let compile_started = Instant::now(); let compiled = compile(dag, &read, ids).map_err(|e| anyhow!("compiling: {e}"))?; let compile_seconds = compile_started.elapsed().as_secs_f64(); + let raw_batch_started = Instant::now(); let mut store = time_series_store(dag, slices)?; + let raw_batch_seconds = raw_batch_started.elapsed().as_secs_f64(); for (id, batch) in views { store = store .with_materialized_view(id as _, vec![batch]) @@ -255,7 +269,13 @@ fn execute( } Ok::<_, anyhow::Error>(all) })?; - Ok((outputs, compile_seconds)) + Ok(( + outputs, + Untimed { + compile_seconds, + raw_batch_seconds, + }, + )) } fn series_labels(schema: &Schema, row: &[Value]) -> Result> { @@ -343,6 +363,7 @@ impl Driver { let mut views_refreshed = 0; let mut samples_ingested = 0; let mut refresh_compile_seconds = 0.0; + let mut refresh_raw_batch_seconds = 0.0; let refresh_started = Instant::now(); let mut built: BTreeMap = BTreeMap::new(); for view in &self.views { @@ -386,7 +407,7 @@ impl Driver { }; let slices = self.scanned(between(series, span.0, span.1)); samples_ingested += samples(&slices); - let (mut outputs, compile_seconds) = execute( + let (mut outputs, untimed) = execute( dag, sources, &slices, @@ -394,7 +415,8 @@ impl Driver { scope, self.max_bytes, )?; - refresh_compile_seconds += compile_seconds; + refresh_compile_seconds += untimed.compile_seconds; + refresh_raw_batch_seconds += untimed.raw_batch_seconds; let batches = outputs.remove(0); let schema = batches .first() @@ -415,7 +437,9 @@ impl Driver { stored.retention_ms = stored.retention_ms.max(view.retention_ms); built.insert(view.node_id as u64, (stored.state.clone(), span)); } - let refresh_seconds = refresh_started.elapsed().as_secs_f64() - refresh_compile_seconds; + let refresh_seconds = refresh_started.elapsed().as_secs_f64() + - refresh_compile_seconds + - refresh_raw_batch_seconds; let mut inputs = BTreeMap::new(); let mut pending = Self::roots(&self.plan); let mut seen = BTreeSet::new(); @@ -443,7 +467,7 @@ impl Driver { evaluation_time_ms: evaluation_ms, }; let query_started = Instant::now(); - let (mut outputs, compile_seconds) = execute( + let (mut outputs, untimed) = execute( dag, inputs, &raw, @@ -452,14 +476,15 @@ impl Driver { self.max_bytes, )?; let answers_now = answers(&outputs.remove(0))?; - let query_seconds = query_started.elapsed().as_secs_f64() - compile_seconds; + let query_seconds = query_started.elapsed().as_secs_f64() - untimed.seconds(); self.store .retain(|_, state| state.start_ms >= evaluation_ms - state.retention_ms as i64); let cost = Cost { refresh_seconds, samples_ingested, query_seconds, - compile_seconds: refresh_compile_seconds + compile_seconds, + compile_seconds: refresh_compile_seconds + untimed.compile_seconds, + raw_batch_seconds: refresh_raw_batch_seconds + untimed.raw_batch_seconds, samples_read_at_query: samples(&raw), raw_label_bytes_read_at_query: label_bytes(&raw), state_bytes: state_bytes(self.store.values().map(|s| &s.state)), diff --git a/usecase-study/src/output.rs b/usecase-study/src/output.rs index f521338e..9e7bf31b 100644 --- a/usecase-study/src/output.rs +++ b/usecase-study/src/output.rs @@ -73,6 +73,8 @@ pub struct PlanevalCost { pub samples_ingested: usize, pub query_seconds: f64, pub compile_seconds: f64, + #[serde(default)] + pub raw_batch_seconds: f64, pub samples_read_at_query: usize, #[serde(default)] pub raw_label_bytes_read_at_query: usize, From 05350534956e3348b0ae8ed9294952a11dcc5938 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:52:22 +0000 Subject: [PATCH 07/11] planeval: each evaluation is pinned, idle-checked and its query repeated planeval timed every evaluation once, on whatever core the thread was on, with no check that the core was idle. It now takes --core, --runs (odd, default 5), --warmup-runs and --max-core-busy, as benchmark-external does: each evaluation's query runs through Protocol::run_job_after (pinned, idle-checked before and after, the median of the measured runs), and the refresh, which changes stored state, runs once under the same checks. Each cost records the core, the busy fractions and the marks. Without --core nothing is pinned or checked and the cost says so. run_use_case.py passes the four options on; the callers that only need answers (the truth in run_use_case_on_systems.py, inject_errors.py) run each evaluation once. Co-Authored-By: Claude Opus 5.5 --- aqpbm-core/src/harness/protocol.rs | 19 ++ scripts/use_cases/inject_errors.py | 3 +- scripts/use_cases/run_use_case.py | 14 ++ scripts/use_cases/run_use_case_on_systems.py | 3 +- system-bench/src/bin/planeval.rs | 38 ++++ system-bench/src/planeval/measured.rs | 200 +++++++++++++++++++ system-bench/src/planeval/mod.rs | 1 + system-bench/src/planeval/run.rs | 110 +++++++--- usecase-study/src/output.rs | 13 ++ 9 files changed, 368 insertions(+), 33 deletions(-) create mode 100644 system-bench/src/planeval/measured.rs diff --git a/aqpbm-core/src/harness/protocol.rs b/aqpbm-core/src/harness/protocol.rs index 27190faa..cb42e368 100644 --- a/aqpbm-core/src/harness/protocol.rs +++ b/aqpbm-core/src/harness/protocol.rs @@ -1372,6 +1372,25 @@ impl Protocol { self.run_next_job(core, probe, None, clock, job) } + pub fn run_job_after( + &self, + core: usize, + probe: &mut dyn LoadProbe, + previous: Option<&JobRecord>, + clock: &EngineClock, + job: &mut dyn FnMut() -> Result, + ) -> Result { + self.run_next_job( + core, + probe, + previous + .filter(|previous| previous.core == core) + .map(JobRecord::load_after), + clock, + job, + ) + } + /// [`Protocol::run_job`] after another job on the same core. /// `load_before` is the previous job's after-sample: nothing but the /// harness ran on the core between the two, so it stands in for a fresh diff --git a/scripts/use_cases/inject_errors.py b/scripts/use_cases/inject_errors.py index 2e92f1c7..5bbc4836 100644 --- a/scripts/use_cases/inject_errors.py +++ b/scripts/use_cases/inject_errors.py @@ -319,7 +319,8 @@ def main(argv=None): samples_path = os.path.join(args.raw_out, f"{prefix}-samples.jsonl") if ranked else None exact_out = os.path.join(args.raw_out, f"{prefix}-injected-exact.json") exact = in_process.run_binary(args.binary, spec_path, exact_out, case.get("planeval_flags", []) - + (["--samples-out", samples_path] if samples_path else [])) + + (["--samples-out", samples_path] if samples_path else []) + + in_process.ANSWERS_ONLY) for q in exact["queries"]: if "unsupported" in q: sys.exit(f"the exact plan of {q['id']} is unsupported: {q['unsupported']}") diff --git a/scripts/use_cases/run_use_case.py b/scripts/use_cases/run_use_case.py index 518c79b7..976b9f4f 100644 --- a/scripts/use_cases/run_use_case.py +++ b/scripts/use_cases/run_use_case.py @@ -23,6 +23,7 @@ REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) SAMPLE_BYTES = 16 +ANSWERS_ONLY = ["--runs", "1", "--warmup-runs", "0"] def arm_flags(arm): @@ -367,6 +368,15 @@ def main(argv=None): help="repeatable; how a rule treats an answer whose error bound leaves its check open: " "plain ignores the bound, bound takes no action, rerun asks the exact plan; " "default every policy the use case supports") + parser.add_argument("--core", type=int, + help="pin each evaluation to this core and check the core is idle around it; " + "default not pinned and not checked") + parser.add_argument("--runs", type=int, default=5, + help="measured runs of each evaluation's query, odd; the median is kept") + parser.add_argument("--warmup-runs", type=int, default=1, + help="runs of each evaluation's query before the measured ones") + parser.add_argument("--max-core-busy", type=float, default=0.10, + help="a core busier than this fraction before an evaluation refuses it") args = parser.parse_args(argv) case = USE_CASES[args.use_case] real = args.real is not None @@ -389,6 +399,10 @@ def main(argv=None): if table: data_root.existing(os.path.join(args.data_root, table["dataset"]), args.data_root) extra = case.get("planeval_flags", []) + (["--data-root", args.data_root] if real else []) + extra += ["--runs", str(args.runs), "--warmup-runs", str(args.warmup_runs), + "--max-core-busy", str(args.max_core_busy)] + if args.core is not None: + extra += ["--core", str(args.core)] exact = run_binary(args.binary, spec, exact_out, extra) for q in exact["queries"]: if "unsupported" in q: diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index f041f31d..4eb4094b 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -1211,7 +1211,8 @@ def main(argv=None): truth_path = os.path.join(workdir, "truth.json") truth = in_process.run_binary(args.planeval, spec_path, truth_path, - case.get("planeval_flags", []) + ["--data-root", args.data_root]) + case.get("planeval_flags", []) + ["--data-root", args.data_root] + + in_process.ANSWERS_ONLY) for trial in range(1, args.trials + 1): trial_workdir = workdir if trial == 1 else os.path.join(args.raw_out, trial_name(run_prefix, trial)) os.makedirs(trial_workdir, exist_ok=True) diff --git a/system-bench/src/bin/planeval.rs b/system-bench/src/bin/planeval.rs index b0d828a0..64557aaf 100644 --- a/system-bench/src/bin/planeval.rs +++ b/system-bench/src/bin/planeval.rs @@ -7,6 +7,8 @@ use clap::Parser; use aqpbm_core::harness::data::workload_series; use aqpbm_core::harness::engine::QueryLanguage; +use aqpbm_core::harness::protocol::Protocol; +use system_bench::planeval::measured::EvaluationProtocol; use system_bench::planeval::plan::{plan, summary, Arm}; use system_bench::planeval::run::Driver; use usecase_study::accuracy::AnswerAt; @@ -87,6 +89,33 @@ struct Args { #[arg(long)] out: PathBuf, + + #[arg( + long, + help = "Pin each evaluation to this core and check the core is idle before and after it; omitted: not pinned and not checked" + )] + core: Option, + + #[arg( + long, + default_value_t = 5, + help = "Measured runs of each evaluation's query; odd, so the median is one of them" + )] + runs: u32, + + #[arg( + long, + default_value_t = 1, + help = "Runs of each evaluation's query before the measured ones, discarded" + )] + warmup_runs: u32, + + #[arg( + long, + default_value_t = 0.10, + help = "A core busier than this fraction before an evaluation refuses it, after one marks it" + )] + max_core_busy: f64, } fn write_samples(path: &Path, series: &[Series]) -> Result<()> { @@ -108,6 +137,12 @@ fn write_samples(path: &Path, series: &[Series]) -> Result<()> { #[tokio::main(flavor = "current_thread")] async fn main() -> Result<()> { let args = Args::parse(); + let protocol = Protocol { + warmup_runs: args.warmup_runs, + measured_runs: args.runs, + max_core_busy_fraction: args.max_core_busy, + }; + protocol.check_run_count()?; let spec = read_workload(&args.spec)?; let arm = Arm { max_error: args.max_error, @@ -191,6 +226,7 @@ async fn main() -> Result<()> { if let Some(max_bytes) = args.executor_max_bytes { driver = driver.with_max_bytes(max_bytes); } + driver = driver.with_protocol(EvaluationProtocol::new(protocol.clone(), args.core)); let started = Instant::now(); let mut answered: Vec = Vec::new(); let mut costs: Vec = Vec::new(); @@ -218,6 +254,8 @@ async fn main() -> Result<()> { samples_read_at_query: cost.samples_read_at_query, raw_label_bytes_read_at_query: cost.raw_label_bytes_read_at_query, state_bytes: cost.state_bytes, + refresh_job: Some(cost.refresh_job.clone()), + query_job: Some(cost.query_job.clone()), }); answered.extend( evaluation diff --git a/system-bench/src/planeval/measured.rs b/system-bench/src/planeval/measured.rs new file mode 100644 index 00000000..2a478818 --- /dev/null +++ b/system-bench/src/planeval/measured.rs @@ -0,0 +1,200 @@ +use std::collections::BTreeMap; + +use anyhow::{anyhow, Result}; +use aqpbm_core::harness::engine::{EngineError, StepReport}; +use aqpbm_core::harness::protocol::{ + EngineClock, JobMark, JobRecord, LoadProbe, NoIdleCheck, OsCpuClock, OsLoadProbe, Protocol, +}; +use usecase_study::output::JobMeasurement; + +static CALLING_THREAD: OsCpuClock = OsCpuClock; + +const NET_SECONDS: &str = "net"; + +pub struct EvaluationProtocol { + protocol: Protocol, + core: Option, + probe: Box, + last: Option, +} + +impl EvaluationProtocol { + pub fn new(protocol: Protocol, core: Option) -> EvaluationProtocol { + let probe: Box = match core { + Some(_) => Box::new(OsLoadProbe::default()), + None => Box::new(NoIdleCheck), + }; + EvaluationProtocol { + protocol, + core, + probe, + last: None, + } + } + + pub fn single_run() -> EvaluationProtocol { + EvaluationProtocol::new( + Protocol { + warmup_runs: 0, + measured_runs: 1, + ..Protocol::default() + }, + None, + ) + } + + pub fn run( + &mut self, + repeat: bool, + job: &mut dyn FnMut() -> Result<(T, f64)>, + ) -> Result<(T, f64, JobMeasurement)> { + let protocol = if repeat { + self.protocol.clone() + } else { + Protocol { + warmup_runs: 0, + measured_runs: 1, + ..self.protocol.clone() + } + }; + let mut results: Vec<(T, f64)> = Vec::new(); + let Some(core) = self.core else { + for _ in 0..protocol.warmup_runs + protocol.measured_runs { + results.push(job()?); + } + let mut measured: Vec<(T, f64)> = results + .into_iter() + .skip(protocol.warmup_runs as usize) + .collect(); + let runs = measured.len() as u32; + let mut order: Vec = (0..measured.len()).collect(); + order.sort_by(|&a, &b| measured[a].1.total_cmp(&measured[b].1)); + let (value, seconds) = measured.swap_remove(order[order.len() / 2]); + return Ok(( + value, + seconds, + JobMeasurement { + core: None, + runs, + busy_before: None, + busy_after: None, + marks: vec!["NotPinned".into(), "IdleNotChecked".into()], + }, + )); + }; + let clock = EngineClock::CallingThread(&CALLING_THREAD); + let mut failure = None; + let record = protocol.run_job_after( + core, + self.probe.as_mut(), + self.last.as_ref(), + &clock, + &mut || match job() { + Ok((value, seconds)) => { + results.push((value, seconds)); + Ok(StepReport { + query_wall_ns: BTreeMap::from([( + NET_SECONDS.to_string(), + (seconds * 1e9) as u64, + )]), + ..StepReport::default() + }) + } + Err(error) => { + let text = format!("{error:#}"); + failure = Some(error); + Err(EngineError(text)) + } + }, + ); + if let Some(error) = failure { + return Err(error); + } + let record = record.map_err(|error| anyhow!("{error}"))?; + let index = protocol.warmup_runs as usize + record.median_run; + let (value, seconds) = results.swap_remove(index); + let measurement = JobMeasurement { + core: Some(core), + runs: protocol.measured_runs, + busy_before: Some(record.busy_before), + busy_after: Some(record.busy_after), + marks: record.marks.iter().map(mark_name).collect(), + }; + self.last = Some(record); + Ok((value, seconds, measurement)) + } +} + +fn mark_name(mark: &JobMark) -> String { + match mark { + JobMark::BusyAfter { busy_fraction } => format!("BusyAfter {busy_fraction:.3}"), + JobMark::NotPinned => "NotPinned".into(), + JobMark::IdleNotChecked => "IdleNotChecked".into(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn allowed_core() -> usize { + let status = std::fs::read_to_string("/proc/self/status").unwrap_or_default(); + status + .lines() + .find_map(|line| line.strip_prefix("Cpus_allowed_list:")) + .and_then(|list| aqpbm_core::harness::protocol::parse_cpu_list(list.trim()).ok()) + .and_then(|cores| cores.first().copied()) + .unwrap_or(0) + } + + fn protocol(core: Option) -> EvaluationProtocol { + EvaluationProtocol::new( + Protocol { + warmup_runs: 1, + measured_runs: 3, + max_core_busy_fraction: 1.0, + }, + core, + ) + } + + #[test] + fn a_repeated_job_keeps_the_median_run_and_a_single_job_runs_once() { + for core in [None, Some(allowed_core())] { + let mut measuring = protocol(core); + let mut calls = 0; + let (value, seconds, measurement) = measuring + .run(true, &mut || { + calls += 1; + Ok((calls, [9.0, 3.0, 1.0, 2.0][calls - 1])) + }) + .unwrap(); + assert_eq!(calls, 4); + if core.is_none() { + assert_eq!((value, seconds), (4, 2.0)); + assert_eq!(measurement.marks, vec!["NotPinned", "IdleNotChecked"]); + } else { + assert!(measurement.busy_before.is_some() && measurement.busy_after.is_some()); + } + assert_eq!(measurement.runs, 3); + assert_eq!(measurement.core, core); + let mut once = 0; + let (_, _, single) = measuring + .run(false, &mut || { + once += 1; + Ok(((), 0.5)) + }) + .unwrap(); + assert_eq!((once, single.runs), (1, 1)); + } + } + + #[test] + fn a_failing_job_returns_its_own_error() { + let mut measuring = protocol(Some(allowed_core())); + let error = measuring + .run::<()>(true, &mut || Err(anyhow!("the plan broke"))) + .unwrap_err(); + assert!(format!("{error:#}").contains("the plan broke")); + } +} diff --git a/system-bench/src/planeval/mod.rs b/system-bench/src/planeval/mod.rs index cbc08748..0e21d28e 100644 --- a/system-bench/src/planeval/mod.rs +++ b/system-bench/src/planeval/mod.rs @@ -1,3 +1,4 @@ +pub mod measured; pub mod plan; pub mod run; pub mod sketch_analytics; diff --git a/system-bench/src/planeval/run.rs b/system-bench/src/planeval/run.rs index 885da98e..5bda86cf 100644 --- a/system-bench/src/planeval/run.rs +++ b/system-bench/src/planeval/run.rs @@ -16,6 +16,9 @@ use asap_types::ir::NonASAPOp; use futures::{executor::block_on, StreamExt}; use usecase_study::data::{between, up_to, Series, Slice}; +use usecase_study::output::JobMeasurement; + +use super::measured::EvaluationProtocol; pub type Answer = (BTreeMap, f64); @@ -33,6 +36,7 @@ pub struct Driver { reference: Option, metrics: BTreeSet, max_bytes: usize, + measuring: Option, } pub struct Evaluation { @@ -51,6 +55,15 @@ pub struct Cost { pub samples_read_at_query: usize, pub raw_label_bytes_read_at_query: usize, pub state_bytes: usize, + pub refresh_job: JobMeasurement, + pub query_job: JobMeasurement, +} + +struct Refreshed { + built: BTreeMap, + views_refreshed: usize, + samples_ingested: usize, + untimed: Untimed, } fn samples(slices: &[Slice]) -> usize { @@ -335,9 +348,15 @@ impl Driver { reference, metrics, max_bytes: Limits::default().max_bytes, + measuring: Some(EvaluationProtocol::single_run()), }) } + pub fn with_protocol(mut self, measuring: EvaluationProtocol) -> Driver { + self.measuring = Some(measuring); + self + } + pub fn with_max_bytes(mut self, max_bytes: usize) -> Driver { self.max_bytes = max_bytes; self @@ -358,14 +377,18 @@ impl Driver { .collect() } - pub fn evaluate(&mut self, series: &[Series], evaluation_ms: i64) -> Result { - let dag = &self.plan.dag; - let mut views_refreshed = 0; - let mut samples_ingested = 0; - let mut refresh_compile_seconds = 0.0; - let mut refresh_raw_batch_seconds = 0.0; - let refresh_started = Instant::now(); - let mut built: BTreeMap = BTreeMap::new(); + fn refresh(&mut self, series: &[Series], evaluation_ms: i64) -> Result<(Refreshed, f64)> { + let started = Instant::now(); + let mut refreshed = Refreshed { + built: BTreeMap::new(), + views_refreshed: 0, + samples_ingested: 0, + untimed: Untimed { + compile_seconds: 0.0, + raw_batch_seconds: 0.0, + }, + }; + let built = &mut refreshed.built; for view in &self.views { let built_for_ms = match view.refresh { MaterializedViewRefresh::AtIngestion => view @@ -406,17 +429,17 @@ impl Driver { }, }; let slices = self.scanned(between(series, span.0, span.1)); - samples_ingested += samples(&slices); + refreshed.samples_ingested += samples(&slices); let (mut outputs, untimed) = execute( - dag, + &self.plan.dag, sources, &slices, &[view.node_id as u64], scope, self.max_bytes, )?; - refresh_compile_seconds += untimed.compile_seconds; - refresh_raw_batch_seconds += untimed.raw_batch_seconds; + refreshed.untimed.compile_seconds += untimed.compile_seconds; + refreshed.untimed.raw_batch_seconds += untimed.raw_batch_seconds; let batches = outputs.remove(0); let schema = batches .first() @@ -431,15 +454,45 @@ impl Driver { retention_ms: view.retention_ms, }, ); - views_refreshed += 1; + refreshed.views_refreshed += 1; } let stored = self.store.get_mut(&key).expect("just inserted"); stored.retention_ms = stored.retention_ms.max(view.retention_ms); built.insert(view.node_id as u64, (stored.state.clone(), span)); } - let refresh_seconds = refresh_started.elapsed().as_secs_f64() - - refresh_compile_seconds - - refresh_raw_batch_seconds; + let seconds = started.elapsed().as_secs_f64() - refreshed.untimed.seconds(); + Ok((refreshed, seconds)) + } + + fn query_once( + &self, + inputs: &BTreeMap, + raw: &[Slice], + query: &Scope, + ) -> Result<((Vec, Untimed), f64)> { + let inputs = inputs.clone(); + let started = Instant::now(); + let (mut outputs, untimed) = execute( + &self.plan.dag, + inputs, + raw, + &Self::roots(&self.plan), + query.clone(), + self.max_bytes, + )?; + let answers_now = answers(&outputs.remove(0))?; + let seconds = started.elapsed().as_secs_f64() - untimed.seconds(); + Ok(((answers_now, untimed), seconds)) + } + + pub fn evaluate(&mut self, series: &[Series], evaluation_ms: i64) -> Result { + let mut measuring = self + .measuring + .take() + .ok_or_else(|| anyhow!("an earlier evaluation failed while it was being measured"))?; + let (refreshed, refresh_seconds, refresh_job) = + measuring.run(false, &mut || self.refresh(series, evaluation_ms))?; + let dag = &self.plan.dag; let mut inputs = BTreeMap::new(); let mut pending = Self::roots(&self.plan); let mut seen = BTreeSet::new(); @@ -447,7 +500,7 @@ impl Driver { if !seen.insert(id) { continue; } - match built.get(&id) { + match refreshed.built.get(&id) { Some((state, _)) => { inputs.insert(id, state.clone()); } @@ -466,28 +519,23 @@ impl Driver { let query = Scope::Query { evaluation_time_ms: evaluation_ms, }; - let query_started = Instant::now(); - let (mut outputs, untimed) = execute( - dag, - inputs, - &raw, - &Self::roots(&self.plan), - query.clone(), - self.max_bytes, - )?; - let answers_now = answers(&outputs.remove(0))?; - let query_seconds = query_started.elapsed().as_secs_f64() - untimed.seconds(); + let ((answers_now, untimed), query_seconds, query_job) = + measuring.run(true, &mut || self.query_once(&inputs, &raw, &query))?; + self.measuring = Some(measuring); + let views_refreshed = refreshed.views_refreshed; self.store .retain(|_, state| state.start_ms >= evaluation_ms - state.retention_ms as i64); let cost = Cost { refresh_seconds, - samples_ingested, + samples_ingested: refreshed.samples_ingested, query_seconds, - compile_seconds: refresh_compile_seconds + untimed.compile_seconds, - raw_batch_seconds: refresh_raw_batch_seconds + untimed.raw_batch_seconds, + compile_seconds: refreshed.untimed.compile_seconds + untimed.compile_seconds, + raw_batch_seconds: refreshed.untimed.raw_batch_seconds + untimed.raw_batch_seconds, samples_read_at_query: samples(&raw), raw_label_bytes_read_at_query: label_bytes(&raw), state_bytes: state_bytes(self.store.values().map(|s| &s.state)), + refresh_job, + query_job, }; let reference_answers = match &self.reference { None => None, diff --git a/usecase-study/src/output.rs b/usecase-study/src/output.rs index 9e7bf31b..c5939593 100644 --- a/usecase-study/src/output.rs +++ b/usecase-study/src/output.rs @@ -79,4 +79,17 @@ pub struct PlanevalCost { #[serde(default)] pub raw_label_bytes_read_at_query: usize, pub state_bytes: usize, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub refresh_job: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub query_job: Option, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct JobMeasurement { + pub core: Option, + pub runs: u32, + pub busy_before: Option, + pub busy_after: Option, + pub marks: Vec, } From 4216404e73ae022e575c7d2e821ef70e3bf1f747 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 02:54:03 +0000 Subject: [PATCH 08/11] sketchbench: --core pins each measurement and checks the core is idle sketch-bench timed every run on whatever core the thread was on and never checked the core was idle; only run_throughput_fast.sh pinned it, from outside. sketchbench now takes --core and --max-core-busy (default 0.10): the measuring thread is pinned, the core's busy fraction is read before and after every run (one run's after-sample is the next one's before), a core busier than the limit before a run refuses it and after a run marks it. Records carry the core, the largest busy fractions and the marks; without --core, or with --workers above 1, they say NotPinned and IdleNotChecked. run_profiles.sh and run_throughput_fast.sh pass --core. Co-Authored-By: Claude Opus 5.5 --- aqpbm-cli/src/atomic_costs.rs | 3 + aqpbm-cli/src/cli.rs | 13 +++++ aqpbm-cli/src/repeat.rs | 4 ++ aqpbm-cli/src/sketchbench.rs | 4 +- aqpbm-core/schema/merged_record.schema.json | 21 +++++++ .../src/benchmark_result/bench_report.rs | 14 +++++ .../src/benchmark_result/flatten_record.rs | 22 +++++++ aqpbm-core/src/benchmark_result/schema.rs | 17 ++++++ aqpbm-core/src/lib.rs | 2 +- aqpbm-core/src/measure.rs | 57 ++++++++++++++++++- aqpbm-core/src/metrics/run.rs | 4 ++ aqpbm-core/tests/measure_smoke.rs | 55 +++++++++++++++--- scripts/sketch_runs/run_profiles.sh | 2 + scripts/sketch_runs/run_throughput_fast.sh | 1 + 14 files changed, 206 insertions(+), 13 deletions(-) diff --git a/aqpbm-cli/src/atomic_costs.rs b/aqpbm-cli/src/atomic_costs.rs index c8ce5840..6e91c319 100644 --- a/aqpbm-cli/src/atomic_costs.rs +++ b/aqpbm-cli/src/atomic_costs.rs @@ -453,6 +453,9 @@ mod tests { memory_bytes: Some(12_288), heap_bytes_net: None, heap_bytes_peak: None, + core: None, + core_busy_max: None, + marks: Vec::new(), insert: InsertMetrics { throughput_items_per_sec: Some(stats(1_000_000.0)), wall_time_ms: Some(stats(1000.0)), diff --git a/aqpbm-cli/src/cli.rs b/aqpbm-cli/src/cli.rs index b43bffdb..a8cf3064 100644 --- a/aqpbm-cli/src/cli.rs +++ b/aqpbm-cli/src/cli.rs @@ -201,6 +201,19 @@ pub struct SketchbenchArgs { /// cache measure the wrong thing. #[arg(long, default_value_t = 3, help_heading = "Repetition")] pub warmup_runs: usize, + #[arg( + long, + help_heading = "Repetition", + help = "Pin the measuring thread to this core and check the core is idle around every run; omitted, or with --workers above 1: not pinned and not checked, and each record says so" + )] + pub core: Option, + #[arg( + long, + default_value_t = aqpbm_core::DEFAULT_MAX_CORE_BUSY_FRACTION, + help_heading = "Repetition", + help = "A core busier than this fraction before a run refuses it; after a run, marks it" + )] + pub max_core_busy: f64, /// Re-execute the whole invocation in this many separate processes and /// report the 95% CI over their means. The only setting that makes `ci95` /// appear. At 1 no interval is claimed. Costs R times the wall clock. diff --git a/aqpbm-cli/src/repeat.rs b/aqpbm-cli/src/repeat.rs index 64c5db56..37870ba5 100644 --- a/aqpbm-cli/src/repeat.rs +++ b/aqpbm-cli/src/repeat.rs @@ -229,6 +229,10 @@ mod tests { merge_supported: Some(true), trial: None, trial_mode: None, + core: Some(3), + core_busy_before_max: Some(0.01), + core_busy_after_max: Some(0.02), + marks: Vec::new(), }); rec } diff --git a/aqpbm-cli/src/sketchbench.rs b/aqpbm-cli/src/sketchbench.rs index e83e915c..2089321b 100644 --- a/aqpbm-cli/src/sketchbench.rs +++ b/aqpbm-cli/src/sketchbench.rs @@ -420,8 +420,10 @@ pub fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { // Exactly this measurement's recorders, plus whatever rides along. // Arming the rest would build a histogram nothing writes to. metrics: metric.bit() | secondary, + core: args.core.filter(|_| args.workers <= 1), + max_core_busy_fraction: args.max_core_busy, }; - let runs = aqpbm_core::measure(&cfg, body); + let runs = aqpbm_core::measure(&cfg, body)?; let mut report = BenchReport::from_runs( variant.as_str(), library.as_str(), diff --git a/aqpbm-core/schema/merged_record.schema.json b/aqpbm-core/schema/merged_record.schema.json index d332c4dd..4152254d 100644 --- a/aqpbm-core/schema/merged_record.schema.json +++ b/aqpbm-core/schema/merged_record.schema.json @@ -4,6 +4,21 @@ "description": "Flattened form of the [`Record`]s that share one (sketch, impl,\nsketch_config, dataset) identity: one row per invocation, where the record\nstream writes one per measurement. Built by `aqpbm-cli`'s `flatten_record`.\nLives beside [`Record`] because it is a JSONL wire shape, not CLI logic.", "type": "object", "properties": { + "core": { + "type": [ + "integer", + "null" + ], + "format": "uint", + "minimum": 0 + }, + "core_busy_max": { + "type": [ + "number", + "null" + ], + "format": "double" + }, "heap_bytes_net": { "description": "Net bytes the tracking allocator attributes to this sketch's lifetime —\n**measured**, where [`Self::memory_bytes`] is a self-reported formula.\nIts own field, so a gap between the two stays visible. Needs `heap-track`.", "type": [ @@ -91,6 +106,12 @@ "language": { "$ref": "#/$defs/Language" }, + "marks": { + "type": "array", + "items": { + "type": "string" + } + }, "memory_bytes": { "type": [ "integer", diff --git a/aqpbm-core/src/benchmark_result/bench_report.rs b/aqpbm-core/src/benchmark_result/bench_report.rs index 9407bb1e..56868011 100644 --- a/aqpbm-core/src/benchmark_result/bench_report.rs +++ b/aqpbm-core/src/benchmark_result/bench_report.rs @@ -61,6 +61,20 @@ impl BenchReport { bench.heap_bytes_net = mem.heap_bytes_net; bench.heap_bytes_peak = mem.heap_bytes_peak; bench.memory_bytes = fold::memory_bytes(&runs); + bench.core = runs.iter().find_map(|r| r.core); + bench.core_busy_before_max = runs + .iter() + .filter_map(|r| r.core_busy_before) + .max_by(f64::total_cmp); + bench.core_busy_after_max = runs + .iter() + .filter_map(|r| r.core_busy_after) + .max_by(f64::total_cmp); + for mark in runs.iter().flat_map(|r| &r.marks) { + if !bench.marks.contains(mark) { + bench.marks.push(mark.clone()); + } + } Self { sketch: sketch.into(), diff --git a/aqpbm-core/src/benchmark_result/flatten_record.rs b/aqpbm-core/src/benchmark_result/flatten_record.rs index 58c77a97..896ac364 100644 --- a/aqpbm-core/src/benchmark_result/flatten_record.rs +++ b/aqpbm-core/src/benchmark_result/flatten_record.rs @@ -57,6 +57,9 @@ pub fn flatten_record(records: &[Record]) -> Result { memory_bytes: None, heap_bytes_net: None, heap_bytes_peak: None, + core: None, + core_busy_max: None, + marks: Vec::new(), insert: InsertMetrics::default(), query: QueryMetrics::default(), merge: MergeMetrics::default(), @@ -91,8 +94,27 @@ pub fn flatten_record(records: &[Record]) -> Result { merge_supported, trial, trial_mode, + core, + core_busy_before_max, + core_busy_after_max, + marks, } = bench; + if let Some(core) = core { + out.core.get_or_insert(*core); + } + for busy in [core_busy_before_max, core_busy_after_max] + .into_iter() + .flatten() + { + out.core_busy_max = Some(out.core_busy_max.map_or(*busy, |max| max.max(*busy))); + } + for mark in marks { + if !out.marks.contains(mark) { + out.marks.push(mark.clone()); + } + } + // A sketch has one size however many measurements took it, so the // first value wins and none is favoured. `heap_bytes_net` stays // separate from `memory_bytes`: see the field doc on diff --git a/aqpbm-core/src/benchmark_result/schema.rs b/aqpbm-core/src/benchmark_result/schema.rs index a8130b1a..0fda4bf0 100644 --- a/aqpbm-core/src/benchmark_result/schema.rs +++ b/aqpbm-core/src/benchmark_result/schema.rs @@ -240,6 +240,14 @@ pub struct BenchSection { pub trial: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub trial_mode: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub core: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub core_busy_before_max: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub core_busy_after_max: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub marks: Vec, } /// Aggregate across N samples: mean / stddev / optional 95% CI, plus the raw @@ -317,6 +325,12 @@ pub struct MergedRecord { pub heap_bytes_net: Option, /// High-water mark of the same counter across construction and insert. pub heap_bytes_peak: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub core: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub core_busy_max: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub marks: Vec, // One slot per operation, and within a slot one field per metric. A // measurement is named by both, so a flattened row that named only one of @@ -503,6 +517,9 @@ pub fn merged_record_schema_json() -> String { memory_bytes: None, heap_bytes_net: None, heap_bytes_peak: None, + core: None, + core_busy_max: None, + marks: Vec::new(), insert: InsertMetrics::default(), query: QueryMetrics::default(), merge: MergeMetrics::default(), diff --git a/aqpbm-core/src/lib.rs b/aqpbm-core/src/lib.rs index 59b36825..060f0090 100644 --- a/aqpbm-core/src/lib.rs +++ b/aqpbm-core/src/lib.rs @@ -28,6 +28,6 @@ pub use benchmark_result::{ pub use error::RunError; pub use measure::{ measure, record_calls, runs_for, MeasureConfig, Measurement, Pass, Report, RunOutcome, - MIN_MERGE_SHARDS, + DEFAULT_MAX_CORE_BUSY_FRACTION, MIN_MERGE_SHARDS, }; pub use metrics::{LatencyRecorder, LatencySnapshot, MetricsMask, RunMetrics}; diff --git a/aqpbm-core/src/measure.rs b/aqpbm-core/src/measure.rs index ccc2d07e..3e8e8208 100644 --- a/aqpbm-core/src/measure.rs +++ b/aqpbm-core/src/measure.rs @@ -6,6 +6,9 @@ use std::collections::BTreeMap; use std::sync::Once; use std::time::{Duration, Instant}; +use crate::harness::protocol::{ + pin_current_thread, LoadProbe, OsLoadProbe, ProtocolError, PINS_THREADS, +}; use crate::metrics::latency::{LatencyRecorder, LatencySnapshot}; use crate::metrics::memory::{JemallocAllocated, Rss}; use crate::metrics::time::{CpuTimeSampler, WallClock}; @@ -24,8 +27,12 @@ pub struct MeasureConfig { pub warmup_runs: usize, /// Which recorders to arm. An empty mask still runs the body. pub metrics: MetricsMask, + pub core: Option, + pub max_core_busy_fraction: f64, } +pub const DEFAULT_MAX_CORE_BUSY_FRACTION: f64 = 0.10; + /// One run of a measurement, primed: whatever it needed built is already built, /// so calling it *is* the work being timed. `FnOnce` because a filled sketch is /// not a fresh one — a second run is a second closure, not a second call. @@ -94,10 +101,32 @@ pub struct RunOutcome { /// The first `warmup_runs` passes are run and discarded, so the setup they /// paid for — a sketch built, a stream fed — is paid on those too, which is /// the point of them. -pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Vec { +pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Result, ProtocolError> { warmup_cpu_once(); + let mut probe = OsLoadProbe::default(); + if let Some(core) = cfg.core { + pin_current_thread(core)?; + } + let mut busy_after_last: Option = None; let mut out = Vec::with_capacity(cfg.runs); for (i, pass) in passes.into_iter().enumerate() { + let core_busy_before = match cfg.core { + Some(core) => Some(match busy_after_last.take() { + Some(busy) => busy, + None => probe.core_busy_fraction(core)?, + }), + None => None, + }; + if let (Some(core), Some(busy)) = (cfg.core, core_busy_before) { + if busy > cfg.max_core_busy_fraction { + return Err(ProtocolError::CoreBusy { + core, + busy_fraction: busy, + loadavg: probe.loadavg(), + limit: cfg.max_core_busy_fraction, + }); + } + } let mut cpu = cfg .metrics .contains(MetricsMask::CPU) @@ -117,6 +146,12 @@ pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Vec { #[cfg(feature = "heap-track")] let heap_after = crate::metrics::heap_track::snapshot(); + let core_busy_after = match cfg.core { + Some(core) => Some(probe.core_busy_fraction(core)?), + None => None, + }; + busy_after_last = core_busy_after; + if i < cfg.warmup_runs { continue; } @@ -147,6 +182,10 @@ pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Vec { heap_bytes_peak: None, latency_ns: outcome.latency_ns, scores: (!outcome.scores.is_empty()).then_some(outcome.scores), + core: cfg.core, + core_busy_before, + core_busy_after, + marks: run_marks(cfg, core_busy_after), }; #[cfg(feature = "heap-track")] @@ -157,7 +196,21 @@ pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Vec { out.push(m); } - out + Ok(out) +} + +fn run_marks(cfg: &MeasureConfig, core_busy_after: Option) -> Vec { + let mut marks = Vec::new(); + if cfg.core.is_none() || !PINS_THREADS { + marks.push("NotPinned".to_string()); + } + if cfg.core.is_none() { + marks.push("IdleNotChecked".to_string()); + } + if let Some(busy) = core_busy_after.filter(|busy| *busy > cfg.max_core_busy_fraction) { + marks.push(format!("BusyAfter {busy:.3}")); + } + marks } /// Ramp the CPU **once per process**, before the first measured region: two diff --git a/aqpbm-core/src/metrics/run.rs b/aqpbm-core/src/metrics/run.rs index 418f9e6a..8f53ec7c 100644 --- a/aqpbm-core/src/metrics/run.rs +++ b/aqpbm-core/src/metrics/run.rs @@ -38,4 +38,8 @@ pub struct RunMetrics { /// rather than an opaque blob so the fold covers every key across runs /// without knowing any algorithm's shape. pub scores: Option>, + pub core: Option, + pub core_busy_before: Option, + pub core_busy_after: Option, + pub marks: Vec, } diff --git a/aqpbm-core/tests/measure_smoke.rs b/aqpbm-core/tests/measure_smoke.rs index 6662feb6..2aab3283 100644 --- a/aqpbm-core/tests/measure_smoke.rs +++ b/aqpbm-core/tests/measure_smoke.rs @@ -16,6 +16,8 @@ fn cfg(runs: usize, warmup_runs: usize, metrics: MetricsMask) -> MeasureConfig { runs, warmup_runs, metrics, + core: None, + max_core_busy_fraction: aqpbm_core::DEFAULT_MAX_CORE_BUSY_FRACTION, } } @@ -48,7 +50,8 @@ fn warmups_run_but_do_not_appear() { passes(5, 7, move || { counted.fetch_add(1, Ordering::Relaxed); }), - ); + ) + .unwrap(); assert_eq!(calls.load(Ordering::Relaxed), 5, "3 measured + 2 warm-up"); assert_eq!(runs.len(), 3, "only the measured ones are returned"); assert!(runs.iter().all(|r| r.work == 7)); @@ -73,7 +76,7 @@ fn only_the_call_is_timed() { }) as _ }); - let runs = measure(&cfg(1, 0, MetricsMask::THROUGHPUT), vec![pass]); + let runs = measure(&cfg(1, 0, MetricsMask::THROUGHPUT), vec![pass]).unwrap(); let elapsed = runs[0].elapsed_ns; assert!( elapsed < 1_000_000, @@ -90,7 +93,8 @@ fn the_whole_call_is_the_region() { std::thread::sleep(std::time::Duration::from_millis(5)); std::thread::sleep(std::time::Duration::from_millis(5)); }), - ); + ) + .unwrap(); assert!(runs[0].elapsed_ns >= 9_000_000, "{}", runs[0].elapsed_ns); } @@ -112,7 +116,7 @@ fn the_pass_reports_its_own_footprint() { }) as Pass }) .collect(); - let runs = measure(&cfg(2, 0, MetricsMask::MEMORY), measurement); + let runs = measure(&cfg(2, 0, MetricsMask::MEMORY), measurement).unwrap(); assert!(runs.iter().all(|r| r.memory_bytes == Some(8192))); } @@ -134,7 +138,7 @@ fn per_call_timing_is_the_passs_choice() { }) as _ }) }; - let with = measure(&cfg(1, 0, MetricsMask::LATENCY), vec![each]); + let with = measure(&cfg(1, 0, MetricsMask::LATENCY), vec![each]).unwrap(); assert!(with[0].latency_ns.is_some(), "recorded per call"); let without = measure( @@ -144,7 +148,8 @@ fn per_call_timing_is_the_passs_choice() { std::hint::black_box(*v + 1); } }), - ); + ) + .unwrap(); assert!(without[0].latency_ns.is_none(), "one region → no histogram"); } @@ -162,10 +167,10 @@ fn scores_pass_through_and_absent_stays_absent() { } }) as _ }); - let scored = measure(&cfg(1, 0, MetricsMask::ACCURACY), vec![scored]); + let scored = measure(&cfg(1, 0, MetricsMask::ACCURACY), vec![scored]).unwrap(); assert_eq!(scored[0].scores.as_ref().unwrap()["are_all"], 0.25); - let plain = measure(&cfg(1, 0, MetricsMask::THROUGHPUT), passes(1, 1, || {})); + let plain = measure(&cfg(1, 0, MetricsMask::THROUGHPUT), passes(1, 1, || {})).unwrap(); assert!(plain[0].scores.is_none()); } @@ -181,6 +186,38 @@ fn zero_runs_yields_nothing() { counted.fetch_add(1, Ordering::Relaxed); }), ); - assert!(runs.is_empty()); + assert!(runs.unwrap().is_empty()); assert_eq!(calls.load(Ordering::Relaxed), 2); } + +#[test] +fn a_run_on_a_given_core_records_its_load_and_a_run_without_one_says_so() { + let unpinned = measure(&cfg(2, 1, MetricsMask::THROUGHPUT), passes(3, 1, || {})).unwrap(); + for run in &unpinned { + assert_eq!(run.core, None); + assert_eq!(run.core_busy_before, None); + assert_eq!(run.marks, vec!["NotPinned", "IdleNotChecked"]); + } + if !aqpbm_core::harness::protocol::PINS_THREADS { + return; + } + let status = std::fs::read_to_string("/proc/self/status").unwrap(); + let allowed = status + .lines() + .find_map(|line| line.strip_prefix("Cpus_allowed_list:")) + .unwrap(); + let core = aqpbm_core::harness::protocol::parse_cpu_list(allowed.trim()).unwrap()[0]; + let pinned = MeasureConfig { + core: Some(core), + max_core_busy_fraction: 1.0, + ..cfg(2, 1, MetricsMask::THROUGHPUT) + }; + let runs = measure(&pinned, passes(3, 1, || {})).unwrap(); + assert_eq!(runs.len(), 2); + for run in &runs { + assert_eq!(run.core, Some(core)); + assert!(run.core_busy_before.is_some() && run.core_busy_after.is_some()); + assert!(run.marks.is_empty(), "{:?}", run.marks); + } + assert_eq!(runs[0].core_busy_after, runs[1].core_busy_before); +} diff --git a/scripts/sketch_runs/run_profiles.sh b/scripts/sketch_runs/run_profiles.sh index 55eae831..8c06616f 100755 --- a/scripts/sketch_runs/run_profiles.sh +++ b/scripts/sketch_runs/run_profiles.sh @@ -79,6 +79,7 @@ ALGORITHMS="${ALGORITHMS:-$ALGORITHMS_DEFAULT}" # ── Tune these ────────────────────────────────────────────────── RUNS=5 WARMUP=2 +PIN_CORE="${PIN_CORE:-2}" SIZE=1000000 CARDINALITY=100000 ZIPF_S=1.1 @@ -121,6 +122,7 @@ bench() { --variant "$variant" --library asap_sketchlib --config "$config" \ --runs "$RUNS" \ --warmup-runs "$WARMUP" \ + --core "$PIN_CORE" \ --operations insert --metrics throughput,cpu,memory \ --report "$OUT_DIR/${algorithm}_${label}.jsonl" \ "$@" diff --git a/scripts/sketch_runs/run_throughput_fast.sh b/scripts/sketch_runs/run_throughput_fast.sh index 9415236c..f8d92908 100755 --- a/scripts/sketch_runs/run_throughput_fast.sh +++ b/scripts/sketch_runs/run_throughput_fast.sh @@ -116,6 +116,7 @@ run_one() { end=\$((SECONDS+${WARMUP_SECONDS})) while [ \$SECONDS -lt \$end ]; do :; done exec '${BIN_PATH}' sketchbench \ + --core '${PIN_CORE}' \ --variant '${variant}' \ --library '${impl}' \ --operations insert \ From 83d923006530e93a93809de119776fcd4beca8a7 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 03:00:12 +0000 Subject: [PATCH 09/11] sketchbench measures each sketch's heap, from its construction on memory_bytes is each wrapper's own formula (sketch_oxide's HLL is 1 << lg_k, Apache DataSketches' is its register count). heap-track was off by default, and when on it measured only what the timed run allocated, so a sketch built before the clock started measured 0. heap-track is now a default feature of approxbench, and every pass is built on its own with the heap read before and after, so each run's heap_bytes_peak is the heap its pass held once built plus the most the run added on top. Over 1M zipf items: HyperLogLog lg_k=14 (sketchlib) 16408 measured against 16400 declared, Count-Min 5x2048 (sketch_oxide) 81992 against 81920, Polars' exact baseline 8388656 against 8388608, KLL k=200 (sketchlib) 13968 against 9864. A merge pass holds every shard and a query pass its answers, so theirs are larger than one sketch's memory_bytes. The counters are process-wide, so a run with --workers above 1 leaves them out. heap_track_leak now runs with the workspace's default features; its deltas allow 1 KiB of other threads' allocations, which made it fail about one run in eight. Co-Authored-By: Claude Opus 5.5 --- aqpbm-cli/Cargo.toml | 2 +- aqpbm-cli/src/sketchbench.rs | 8 +++- aqpbm-cli/tests/measured_heap.rs | 55 ++++++++++++++++++++++++++++ aqpbm-core/src/measure.rs | 11 +++++- aqpbm-core/tests/heap_track_leak.rs | 10 +++-- sketch-bench/src/rows/measurement.rs | 47 +++++++++++++++++++++--- sketch-bench/src/rows/statistic.rs | 52 ++++++++++++++++---------- 7 files changed, 152 insertions(+), 33 deletions(-) create mode 100644 aqpbm-cli/tests/measured_heap.rs diff --git a/aqpbm-cli/Cargo.toml b/aqpbm-cli/Cargo.toml index 4064b287..894c59ee 100644 --- a/aqpbm-cli/Cargo.toml +++ b/aqpbm-cli/Cargo.toml @@ -11,7 +11,7 @@ name = "approxbench" path = "src/main.rs" [features] -default = ["heap-jemalloc"] +default = ["heap-jemalloc", "heap-track"] # When on, approxbench links jemalloc as its global allocator and # sketch-bench samples `tikv-jemalloc-ctl::stats::allocated` into # `bench.heap_allocated_kb`. Turn off with `--no-default-features` diff --git a/aqpbm-cli/src/sketchbench.rs b/aqpbm-cli/src/sketchbench.rs index 2089321b..97c6589c 100644 --- a/aqpbm-cli/src/sketchbench.rs +++ b/aqpbm-cli/src/sketchbench.rs @@ -423,7 +423,13 @@ pub fn run_sketchbench(args: SketchbenchArgs) -> Result<()> { core: args.core.filter(|_| args.workers <= 1), max_core_busy_fraction: args.max_core_busy, }; - let runs = aqpbm_core::measure(&cfg, body)?; + let mut runs = aqpbm_core::measure(&cfg, body)?; + if args.workers > 1 { + for run in &mut runs { + run.heap_bytes_net = None; + run.heap_bytes_peak = None; + } + } let mut report = BenchReport::from_runs( variant.as_str(), library.as_str(), diff --git a/aqpbm-cli/tests/measured_heap.rs b/aqpbm-cli/tests/measured_heap.rs new file mode 100644 index 00000000..7f16fc1a --- /dev/null +++ b/aqpbm-cli/tests/measured_heap.rs @@ -0,0 +1,55 @@ +use std::process::Command; + +fn insert_record(variant: &str, library: &str, config: &str) -> serde_json::Value { + let out = Command::new(env!("CARGO_BIN_EXE_approxbench")) + .args(["sketchbench", "--variant", variant, "--library", library]) + .args(["--config", config]) + .args(["--operations", "insert", "--metrics", "throughput,memory"]) + .args(["--runs", "3", "--warmup-runs", "1"]) + .args([ + "--dataset", + "zipf", + "--zipf-s", + "1.1", + "--cardinality", + "10000", + ]) + .args(["--dtype", "i64", "--size", "100000", "--seed", "7"]) + .env("BENCH_WARMUP_SECS", "0") + .output() + .expect("approxbench runs"); + assert!( + out.status.success(), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let stdout = String::from_utf8(out.stdout).expect("utf-8"); + let last = stdout.lines().last().expect("one record"); + serde_json::from_str(last).expect("a JSON record") +} + +#[cfg(feature = "heap-track")] +#[test] +fn a_sketch_built_before_the_clock_starts_is_in_the_measured_heap() { + let record = insert_record("hyperloglog", "asap_sketchlib", "lg_k=14"); + let bench = &record["bench"]; + let declared = bench["memory_bytes"].as_u64().expect("memory_bytes"); + let measured = bench["heap_bytes_peak"].as_u64().expect("heap_bytes_peak"); + assert!( + measured >= declared && measured < declared + 1024, + "declared {declared}, measured {measured}" + ); +} + +#[cfg(feature = "heap-track")] +#[test] +fn a_row_that_allocates_while_it_inserts_is_in_the_measured_heap_once() { + let record = insert_record("hyperloglog", "polars", "lg_k=14"); + let bench = &record["bench"]; + let declared = bench["memory_bytes"].as_u64().expect("memory_bytes"); + let measured = bench["heap_bytes_peak"].as_u64().expect("heap_bytes_peak"); + assert!( + measured >= declared && measured < declared + 1024, + "declared {declared}, measured {measured}" + ); +} diff --git a/aqpbm-core/src/measure.rs b/aqpbm-core/src/measure.rs index 3e8e8208..9163e9aa 100644 --- a/aqpbm-core/src/measure.rs +++ b/aqpbm-core/src/measure.rs @@ -94,6 +94,7 @@ pub struct RunOutcome { /// The per-call distribution, for the passes that timed themselves per /// item. `None` for a pass timed as one region. pub latency_ns: Option, + pub heap_bytes_at_construction: Option, } /// Run each pass with the clock around it; return the measured runs' metrics. @@ -141,11 +142,14 @@ pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Result Some(probe.core_busy_fraction(core)?), None => None, @@ -191,7 +195,10 @@ pub fn measure(cfg: &MeasureConfig, passes: Measurement) -> Result = TrackingAllocator(std::alloc::System); +const OTHER_THREADS_SLACK: i64 = 1024; + #[test] fn alloc_then_drop_releases_bytes() { reset_peak(); @@ -19,7 +21,7 @@ fn alloc_then_drop_releases_bytes() { let v: Vec = vec![0u8; 1 << 16]; let after_alloc = snapshot(); assert!( - after_alloc.in_use - before.in_use >= (1 << 16), + after_alloc.in_use - before.in_use >= (1 << 16) - OTHER_THREADS_SLACK, "expected at least 64 KiB tracked; got delta={}", after_alloc.in_use - before.in_use, ); @@ -28,7 +30,7 @@ fn alloc_then_drop_releases_bytes() { drop(v); let after_drop = snapshot(); assert!( - after_alloc.in_use - after_drop.in_use >= (1 << 16), + after_alloc.in_use - after_drop.in_use >= (1 << 16) - OTHER_THREADS_SLACK, "drop did not release the buffer: pre-drop={} post-drop={}", after_alloc.in_use, after_drop.in_use, @@ -48,7 +50,7 @@ fn realloc_grow_accounts_delta() { let big = snapshot(); assert!( - big.in_use - small.in_use >= (4096 * 8 - 64), + big.in_use - small.in_use >= 4096 * 8 - OTHER_THREADS_SLACK, "growth not tracked: small={} big={}", small.in_use, big.in_use, @@ -58,7 +60,7 @@ fn realloc_grow_accounts_delta() { drop(v); let after_drop = snapshot(); assert!( - big.in_use - after_drop.in_use >= (4096 * 8 - 64), + big.in_use - after_drop.in_use >= 4096 * 8 - OTHER_THREADS_SLACK, "drop did not release the buffer", ); let _ = small_start; diff --git a/sketch-bench/src/rows/measurement.rs b/sketch-bench/src/rows/measurement.rs index 61ba6855..7a28f5b8 100644 --- a/sketch-bench/src/rows/measurement.rs +++ b/sketch-bench/src/rows/measurement.rs @@ -1,21 +1,54 @@ use super::*; // ---------- the row's closures, in the framework's terms ---------- + +pub(super) type Built

= Vec<(P, Option)>; + +pub(super) fn one_at_a_time

( + passes: usize, + mut build: impl FnMut(usize) -> Result, BuildError>, +) -> Result, BuildError> { + let mut out = Vec::with_capacity(passes); + for _ in 0..passes { + let before = heap_in_use(); + let mut one = build(1)?; + let pass = one + .pop() + .ok_or_else(|| BuildError("asked for one pass, the row built none".into()))?; + drop(one); + let bytes = before + .zip(heap_in_use()) + .map(|(before, after)| (after - before).max(0) as u64); + out.push((pass, bytes)); + } + Ok(out) +} + +#[cfg(feature = "heap-track")] +fn heap_in_use() -> Option { + Some(aqpbm_core::metrics::heap_track::snapshot().in_use) +} + +#[cfg(not(feature = "heap-track"))] +fn heap_in_use() -> Option { + None +} // // A wrapper hands back closures over a sketch and nothing else: how many units // of work one pass covers, and what it answered, are read here. /// A pass that only does work: its unit count is the work it covers, which the /// row knows because it handed the stream over. -pub(super) fn timed(passes: Vec, work: u64) -> Measurement { +pub(super) fn timed(passes: Built, work: u64) -> Measurement { passes .into_iter() - .map(|pass| { + .map(|(pass, heap_bytes_at_construction)| { Box::new(move || { let footprint = pass(); Box::new(move || RunOutcome { work, memory_bytes: Some(footprint as u64), + heap_bytes_at_construction, ..Default::default() }) as Report }) as CorePass @@ -24,10 +57,10 @@ pub(super) fn timed(passes: Vec, work: u64) -> Measuremen } /// A pass driven one unit at a time, so the clock can be read per call. -pub(super) fn stepped(passes: Vec) -> Measurement { +pub(super) fn stepped(passes: Built) -> Measurement { passes .into_iter() - .map(|pass| { + .map(|(pass, heap_bytes_at_construction)| { let StepPass { steps, step, @@ -39,6 +72,7 @@ pub(super) fn stepped(passes: Vec) -> Measurement { work: steps as u64, memory_bytes: Some(footprint() as u64), latency_ns, + heap_bytes_at_construction, ..Default::default() }) as Report }) as CorePass @@ -49,19 +83,20 @@ pub(super) fn stepped(passes: Vec) -> Measurement { /// A pass that answers: the comparator scores what it said, here, once the /// clock has stopped. pub(super) fn answered( - passes: Vec>, + passes: Built>, score: Score, metric: Metric, ) -> Measurement { passes .into_iter() - .map(|pass| { + .map(|(pass, heap_bytes_at_construction)| { let score = score.clone(); Box::new(move || { let (answers, footprint) = pass(); Box::new(move || RunOutcome { work: answers.len() as u64, memory_bytes: Some(footprint as u64), + heap_bytes_at_construction, scores: if metric == Metric::Accuracy { score(&answers) } else { diff --git a/sketch-bench/src/rows/statistic.rs b/sketch-bench/src/rows/statistic.rs index 4a460001..0093071a 100644 --- a/sketch-bench/src/rows/statistic.rs +++ b/sketch-bench/src/rows/statistic.rs @@ -459,43 +459,55 @@ where for &(operation, metric) in want { let n = passes(req, metric); let body = match (operation, metric) { - (Operation::Insert, Metric::Latency) => { - stepped(insert_step(&req.params, items.clone(), n).map_err(cannot_build)?) - } + (Operation::Insert, Metric::Latency) => stepped( + one_at_a_time(n, |k| insert_step(&req.params, items.clone(), k)) + .map_err(cannot_build)?, + ), (Operation::Insert, _) => timed( - insert(&req.params, items.clone(), n).map_err(cannot_build)?, + one_at_a_time(n, |k| insert(&req.params, items.clone(), k)) + .map_err(cannot_build)?, items.len() as u64, ), (Operation::Query, _) => answered( - query(&req.params, items.clone(), probes.clone(), n).map_err(cannot_build)?, + one_at_a_time(n, |k| query(&req.params, items.clone(), probes.clone(), k)) + .map_err(cannot_build)?, score.clone(), metric, ), // Scored exactly as the query is: same probes, same comparator, and // the truth is still the whole stream, split across the shards. (Operation::Merge, Metric::Accuracy) => answered( - merge.expect(SUPPORTED).2( - &req.params, - merged.clone(), - probes.clone(), - shards(req), - n, - ) + one_at_a_time(n, |k| { + merge.expect(SUPPORTED).2( + &req.params, + merged.clone(), + probes.clone(), + shards(req), + k, + ) + }) .map_err(cannot_build)?, score.clone(), metric, ), (Operation::Merge, Metric::Latency) => stepped( - merge.expect(SUPPORTED).1(&req.params, merged.clone(), shards(req), n) - .map_err(cannot_build)?, + one_at_a_time(n, |k| { + merge.expect(SUPPORTED).1(&req.params, merged.clone(), shards(req), k) + }) + .map_err(cannot_build)?, ), (Operation::Merge, _) => timed( - merge.expect(SUPPORTED).0(&req.params, merged.clone(), shards(req), n) - .map_err(cannot_build)?, + one_at_a_time(n, |k| { + merge.expect(SUPPORTED).0(&req.params, merged.clone(), shards(req), k) + }) + .map_err(cannot_build)?, (shards(req) - 1) as u64, ), (Operation::Prepare, _) => timed( - prepare.expect(SUPPORTED)(&req.params, items.clone(), n).map_err(cannot_build)?, + one_at_a_time(n, |k| { + prepare.expect(SUPPORTED)(&req.params, items.clone(), k) + }) + .map_err(cannot_build)?, items.len() as u64, ), }; @@ -575,8 +587,10 @@ pub(super) fn timed_row( let body = match operation { Operation::Insert => timed( - insert(&req.params, workers, items.clone(), passes(req, metric)) - .map_err(cannot_build)?, + one_at_a_time(passes(req, metric), |k| { + insert(&req.params, workers, items.clone(), k) + }) + .map_err(cannot_build)?, items.len() as u64, ), _ => return Err(RunError::Sketch( From b90537cbe38294a38a4e06facd7338e147971a39 Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 04:31:50 +0000 Subject: [PATCH 10/11] Periodic systems: ingest CPU and query CPU are recorded apart A system's "cpu seconds" is its server's CPU over the whole arm, ingest and queries together. When ASAPQuery-backend's queries plan apart, every instance ingests the whole data, so the sum of the instances charged the data's ingest once per instance. On use case 3 (5 instances) the backend summed to 25.6 s against VictoriaMetrics' 23.4 s, of which 19.5 s was ingest repeated five times; its queries took 5.7 s against 10.1 s. Each summary now also records ingest cpu seconds and query cpu seconds, summed from the server CPU the harness reads around every ingest and every evaluation step. A run in several instances adds the largest instance's ingest, which is one ingest of the data, and says how many times the data was ingested. Co-Authored-By: Claude Opus 5.5 --- scripts/use_cases/run_use_case_on_systems.py | 17 +++++++++++++ .../use_cases/test_run_use_case_on_systems.py | 25 +++++++++++++------ 2 files changed, 34 insertions(+), 8 deletions(-) diff --git a/scripts/use_cases/run_use_case_on_systems.py b/scripts/use_cases/run_use_case_on_systems.py index 4eb4094b..f0d04490 100644 --- a/scripts/use_cases/run_use_case_on_systems.py +++ b/scripts/use_cases/run_use_case_on_systems.py @@ -406,8 +406,11 @@ def harness_measurements(results): cpu = [r.get("server_cpu_ns_whole_arm") for r in ran] after = [r.get("server_memory_after") for r in ran] peaks = [m["lifetime_peak_bytes"] for m in after if m and m.get("lifetime_peak_bytes") is not None] + step_cpu = lambda kind: sum(job["median"]["process_cpu_ns"] for r in ran for job in r[kind]) / 1e9 return {"cpu and memory": ", ".join(sources) if ran else None, "cpu seconds": sum(cpu) / 1e9 if measured and None not in cpu else None, + "ingest cpu seconds": step_cpu("ingest") if measured else None, + "query cpu seconds": step_cpu("evaluate") if measured else None, "peak resident bytes": max(peaks) if measured and peaks else None, "resident bytes at end": after[-1]["current_bytes"] if measured and after and after[-1] else None, "harness thread pinned": not any("NotPinned" in job["marks"] for r in ran @@ -922,10 +925,24 @@ def merged_groups(spec, ran): "run_seconds": a["run_seconds"]} for a, _ in ran]} summaries = [s for _, s in ran] cpu = [s["cpu seconds"] for s in summaries] + + def total(key): + values = [s.get(key) for s in summaries] + return None if None in values else sum(values) + + def largest(key): + values = [s.get(key) for s in summaries if s.get(key) is not None] + return max(values) if values else None + peaks = [s["peak resident bytes"] for s in summaries if s["peak resident bytes"] is not None] summary = {"instances": len(ran), "per instance": summaries, "data writes": sum(s.get("data writes") or 0 for s in summaries), "cpu seconds": None if None in cpu else sum(cpu), + "ingest cpu seconds": total("ingest cpu seconds"), + "largest instance ingest cpu seconds": largest("ingest cpu seconds"), + "query cpu seconds": total("query cpu seconds"), + "ingest cpu seconds are": f"every instance ingests the whole data, so the data was ingested " + f"{len(ran)} times; the largest instance's is one ingest", "peak resident bytes": sum(peaks) if len(peaks) == len(summaries) else None, "largest instance peak resident bytes": max(peaks) if peaks else None, "peak resident bytes are": "the sum of every instance's peak, as a deployment runs the instances " diff --git a/scripts/use_cases/test_run_use_case_on_systems.py b/scripts/use_cases/test_run_use_case_on_systems.py index 3c70a934..f2d6638a 100644 --- a/scripts/use_cases/test_run_use_case_on_systems.py +++ b/scripts/use_cases/test_run_use_case_on_systems.py @@ -112,26 +112,31 @@ def test_the_arm_records_its_raw_store(self): self.assertIsNone(run_use_case_on_systems.arm_details(args, "noraw-eps0.01")["raw_store"]) -def arm_result(cpu_source, cpu_ns, memory, marks=()): - job = {"marks": list(marks)} +def arm_result(cpu_source, cpu_ns, memory, marks=(), ingest_ns=(0,), evaluate_ns=(0,)): + def jobs(steps): + return [{"marks": list(marks), "median": {"process_cpu_ns": ns}} for ns in steps] return {"cpu_source": cpu_source, "server_cpu_ns_whole_arm": cpu_ns, "server_memory_after": memory, - "ingest": [job], "evaluate": [job]} + "ingest": jobs(ingest_ns), "evaluate": jobs(evaluate_ns)} class HarnessMeasurementsTest(unittest.TestCase): def test_a_cgroup_server_adds_up_its_cells(self): memory = {"current_bytes": 100, "anon_bytes": 0, "file_bytes": 0, "lifetime_peak_bytes": 300} - out = harness_measurements([arm_result("cgroup /g/cpu.stat", 2_000_000_000, memory), + out = harness_measurements([arm_result("cgroup /g/cpu.stat", 2_000_000_000, memory, + ingest_ns=(1_000_000_000, 500_000_000), evaluate_ns=(250_000_000,)), None, arm_result("cgroup /g/cpu.stat", 500_000_000, - {**memory, "current_bytes": 150, "lifetime_peak_bytes": 400})]) + {**memory, "current_bytes": 150, "lifetime_peak_bytes": 400}, + ingest_ns=(250_000_000,), evaluate_ns=(125_000_000,))]) self.assertEqual(out, {"cpu and memory": "cgroup /g/cpu.stat", "cpu seconds": 2.5, + "ingest cpu seconds": 1.75, "query cpu seconds": 0.375, "peak resident bytes": 400, "resident bytes at end": 150, "harness thread pinned": True}) def test_a_server_without_a_group_is_not_measured(self): out = harness_measurements([arm_result("not measured", None, None, ["NotPinned", "IdleNotChecked"])]) - self.assertEqual(out, {"cpu and memory": "not measured", "cpu seconds": None, "peak resident bytes": None, + self.assertEqual(out, {"cpu and memory": "not measured", "cpu seconds": None, "ingest cpu seconds": None, + "query cpu seconds": None, "peak resident bytes": None, "resident bytes at end": None, "harness thread pinned": False}) def test_a_kernel_without_memory_peak_has_no_peak(self): @@ -269,8 +274,8 @@ def ran(ids, cpu, peak): "queries": [{"id": i, "costs": [{"query_seconds": 0.002}], "failed_evaluations": 0} for i in ids], "evaluation steps": [{"time": 60000, "step seconds": 0.002, "queries": ids}]} - return asked, {"cpu seconds": cpu, "peak resident bytes": peak, "failed evaluations": {}, - "data writes": 1} + return asked, {"cpu seconds": cpu, "ingest cpu seconds": cpu * 0.75, "query cpu seconds": cpu * 0.25, + "peak resident bytes": peak, "failed evaluations": {}, "data writes": 1} asked, summary = merged_groups(spec_of("a", "b", "c"), [ran(["c"], 1.0, 10), ran(["a", "b"], 2.0, 30)]) self.assertEqual([q["id"] for q in asked["queries"]], ["a", "b", "c"]) self.assertEqual([g["queries"] for g in asked["groups"]], [["c"], ["a", "b"]]) @@ -279,6 +284,10 @@ def ran(ids, cpu, peak): self.assertEqual(summary["cpu seconds"], 3.0) self.assertEqual(summary["peak resident bytes"], 40) self.assertEqual(summary["largest instance peak resident bytes"], 30) + self.assertEqual(summary["ingest cpu seconds"], 2.25) + self.assertEqual(summary["largest instance ingest cpu seconds"], 1.5) + self.assertEqual(summary["query cpu seconds"], 0.75) + self.assertIn("ingested 2 times", summary["ingest cpu seconds are"]) self.assertEqual(summary["evaluations"], 3) self.assertEqual(summary["evaluation steps"], 2) From 431ff62172ddd61b6cfc92b8eb34fdbabe0e993b Mon Sep 17 00:00:00 2001 From: GordonYuanyc Date: Thu, 3 Dec 2026 04:32:57 +0000 Subject: [PATCH 11/11] Leaderboard data and use-case runs carry what the fairness fixes record The fixes record more than the leaderboard and Grafana read. Each leaderboard record now also has: - query_time (one-shot): whether its speedups divide the engine's own time or the harness's wall time; results written before it existed divided wall time, so they say harness_wall. - query_cpu_seconds, ingest_cpu_seconds and ingest_cpu_seconds_one_instance (periodic): the server CPU of the queries and of the ingest, the ingest summed over the instances and of the largest one. - cpu_and_memory_comparable (periodic): whether both systems asked the same queries, so their whole-run CPU and memory compare. schema.json knows the new keys, so the page does not warn about them, and benchmarkRecord.js holds each to its benchmark. A use-case run of run_use_case.py records how planeval measured each arm: the cores, the query runs, the busiest core reading and the marks. Co-Authored-By: Claude Opus 5.5 --- scripts/system-leaderboard-data.py | 17 +++++++++++++++++ scripts/use_cases/run_use_case.py | 13 +++++++++++++ scripts/use_cases/test_run_use_case.py | 14 +++++++++++++- system-leaderboard/src/utils/benchmarkRecord.js | 5 +++++ system-leaderboard/src/utils/schema.json | 5 +++++ 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/scripts/system-leaderboard-data.py b/scripts/system-leaderboard-data.py index 93d1bb63..48ab836b 100755 --- a/scripts/system-leaderboard-data.py +++ b/scripts/system-leaderboard-data.py @@ -165,6 +165,11 @@ def one_shot(run_directory): "median_query_ms": None, "p99_query_ms": None, "cpu_seconds": None, + "query_cpu_seconds": None, + "ingest_cpu_seconds": None, + "ingest_cpu_seconds_one_instance": None, + "cpu_and_memory_comparable": None, + "query_time": group[0].get("query_time") or "harness_wall", "disk_bytes": None, "decision_agreement": {}, "queries": queries, @@ -184,6 +189,11 @@ def instance_totals(measured): } +def comparable(trials): + flags = [(d.get("cost comparison") or {}).get("cpu and memory comparable") for _, d, _, _ in trials] + return None if None in flags else all(flags) + + def names(value): return sorted(value) if isinstance(value, dict) else list(value or []) @@ -256,6 +266,13 @@ def periodic(index_path): "median_query_ms": median([m.get("median query ms") for _, _, m, _ in trials]), "p99_query_ms": median([m.get("p99 query ms") for _, _, m, _ in trials]), "cpu_seconds": median([m.get("cpu seconds") for _, _, m, _ in trials]), + "query_cpu_seconds": median([m.get("query cpu seconds") for _, _, m, _ in trials]), + "ingest_cpu_seconds": median([m.get("ingest cpu seconds") for _, _, m, _ in trials]), + "ingest_cpu_seconds_one_instance": median([m.get("largest instance ingest cpu seconds", + m.get("ingest cpu seconds")) + for _, _, m, _ in trials]), + "cpu_and_memory_comparable": comparable(trials), + "query_time": None, "disk_bytes": median([t["disk_bytes"] for t in totals]), "decision_agreement": {rule: median(values) for rule, values in agreement.items()}, "queries": queries, diff --git a/scripts/use_cases/run_use_case.py b/scripts/use_cases/run_use_case.py index 976b9f4f..42eee759 100644 --- a/scripts/use_cases/run_use_case.py +++ b/scripts/use_cases/run_use_case.py @@ -159,6 +159,18 @@ def raw_bytes_read(cost): return cost["samples_read_at_query"] * SAMPLE_BYTES + cost.get("raw_label_bytes_read_at_query", 0) +def measurement_of(document): + jobs = [c[kind] for q in document.get("queries", []) for c in q.get("costs", []) + for kind in ("refresh_job", "query_job") if c.get(kind)] + if not jobs: + return None + busy = [b for job in jobs for b in (job.get("busy_before"), job.get("busy_after")) if b is not None] + return {"cores": sorted({job["core"] for job in jobs if job.get("core") is not None}), + "query runs": max(job["runs"] for job in jobs), + "largest core busy fraction": max(busy) if busy else None, + "marks": sorted({mark for job in jobs for mark in job.get("marks", [])})} + + def mean(values): return sum(values) / len(values) if values else None @@ -319,6 +331,7 @@ def write_arm(data, case, prefix, arm, exact, approx, trial=1, policy=bounds.PLA "harness_version": approx.get("harness_version"), "machine": approx.get("machine"), "process": {"exact": exact.get("process"), "approx": approx.get("process")}, + "measurement": {"exact": measurement_of(exact), "approx": measurement_of(approx)}, "dashboard": case["dashboard"], "signals": {q["id"]: case.get("signals", case["signal"])(q["id"]) for q in exact["queries"]}, } diff --git a/scripts/use_cases/test_run_use_case.py b/scripts/use_cases/test_run_use_case.py index c9d7f64b..e1b480ff 100644 --- a/scripts/use_cases/test_run_use_case.py +++ b/scripts/use_cases/test_run_use_case.py @@ -5,7 +5,7 @@ from approx_rows import row from cases.uc4_canary_release import stage2 as uc4_stage2 from rollout import rollout_errors -from run_use_case import rank_errors, relative_errors, stage1 +from run_use_case import measurement_of, rank_errors, relative_errors, stage1 def query(id_, answers, costs=(), planning_ms=None): @@ -90,3 +90,15 @@ def test_success_rate_uses_its_relative_error(self): if __name__ == "__main__": unittest.main() + + +class MeasurementOfTest(unittest.TestCase): + def test_the_jobs_of_every_evaluation_are_summed_up(self): + job = {"core": 7, "runs": 5, "busy_before": 0.01, "busy_after": 0.08, "marks": []} + single = {"core": 7, "runs": 1, "busy_before": 0.02, "busy_after": 0.03, "marks": ["BusyAfter 0.300"]} + document = {"queries": [{"costs": [{"refresh_job": single, "query_job": job}]}, + {"costs": [{"query_job": job}]}]} + self.assertEqual(measurement_of(document), + {"cores": [7], "query runs": 5, "largest core busy fraction": 0.08, + "marks": ["BusyAfter 0.300"]}) + self.assertIsNone(measurement_of({"queries": [{"costs": [{}]}]})) diff --git a/system-leaderboard/src/utils/benchmarkRecord.js b/system-leaderboard/src/utils/benchmarkRecord.js index f1b7dca0..32ef201d 100644 --- a/system-leaderboard/src/utils/benchmarkRecord.js +++ b/system-leaderboard/src/utils/benchmarkRecord.js @@ -13,6 +13,7 @@ const ONE_SHOT_ONLY = [ "geomean_hot_seconds", "load_seconds", "data_size_bytes", + "query_time", ]; const PERIODIC_ONLY = [ @@ -20,6 +21,10 @@ const PERIODIC_ONLY = [ "median_query_ms", "p99_query_ms", "cpu_seconds", + "query_cpu_seconds", + "ingest_cpu_seconds", + "ingest_cpu_seconds_one_instance", + "cpu_and_memory_comparable", "disk_bytes", ]; diff --git a/system-leaderboard/src/utils/schema.json b/system-leaderboard/src/utils/schema.json index b875aec7..fa7abdb0 100644 --- a/system-leaderboard/src/utils/schema.json +++ b/system-leaderboard/src/utils/schema.json @@ -33,6 +33,11 @@ "median_query_ms": { "$ref": "#/$defs/Measurement" }, "p99_query_ms": { "$ref": "#/$defs/Measurement" }, "cpu_seconds": { "$ref": "#/$defs/Measurement" }, + "query_cpu_seconds": { "$ref": "#/$defs/Measurement" }, + "ingest_cpu_seconds": { "$ref": "#/$defs/Measurement" }, + "ingest_cpu_seconds_one_instance": { "$ref": "#/$defs/Measurement" }, + "cpu_and_memory_comparable": { "type": ["boolean", "null"] }, + "query_time": { "enum": ["engine_reported", "harness_wall", null] }, "disk_bytes": { "$ref": "#/$defs/Measurement" }, "speedup_over_baseline": { "$ref": "#/$defs/Measurement" }, "max_relative_error": { "$ref": "#/$defs/Error" },