Your browser sucks, JavaScript disabled! Gunnar's console needs JavaScript and WebAssembly. Git over SSH on port 2222 does not.

nordisk/kleene

crates/kleene-ballista/src/stats.rs

//! Where a job's time went, from the scheduler's REST view of it (`GET /api/jobs`,
//! `GET /api/job/{id}/stages?plan_format=metrics`): the rounds, the tasks and their spans, the
//! core's step time and the shuffle's fetch time and bytes, as the stage plans' merged
//! metrics print them.
//!
//! Read only for the measured runs; the queries never need it.

use std::io::{Read, Write};
use std::net::TcpStream;
use std::time::Duration;

use datafusion::error::{DataFusionError, Result};
use serde_json::Value;

fn ext(e: impl std::fmt::Display) -> DataFusionError {
    DataFusionError::Execution(e.to_string())
}

/// A plain HTTP/1.0 GET of `path` at `url` (`http://host:port`), the body as JSON.
pub fn get_json(url: &str, path: &str) -> Result<Value> {
    let host = url
        .strip_prefix("http://")
        .ok_or_else(|| ext(format!("not an http:// URL: {url}")))?
        .trim_end_matches('/');
    let mut s = TcpStream::connect(host).map_err(ext)?;
    s.set_read_timeout(Some(Duration::from_secs(30)))
        .map_err(ext)?;
    write!(
        s,
        "GET {path} HTTP/1.0\r\nHost: {host}\r\nAccept: application/json\r\n\r\n"
    )
    .map_err(ext)?;
    let mut body = Vec::new();
    s.read_to_end(&mut body).map_err(ext)?;
    let text = String::from_utf8_lossy(&body);
    let (head, json) = text
        .split_once("\r\n\r\n")
        .ok_or_else(|| ext(format!("no HTTP body from {url}{path}")))?;
    if !head.starts_with("HTTP/1.") || !head.split_whitespace().nth(1).is_some_and(|c| c == "200") {
        return Err(ext(format!(
            "{url}{path}: {}",
            head.lines().next().unwrap_or("")
        )));
    }
    serde_json::from_str(json).map_err(ext)
}

/// The id of the job that started last.
pub fn last_job(url: &str) -> Result<String> {
    let jobs = get_json(url, "/api/jobs")?;
    jobs.as_array()
        .and_then(|a| {
            a.iter()
                .max_by_key(|j| j["start_time"].as_u64().unwrap_or(0))
                .and_then(|j| j["job_id"].as_str())
        })
        .map(str::to_string)
        .ok_or_else(|| ext("the scheduler lists no job"))
}

/// A metric's value as DataFusion prints it, in its base unit: a count (`1234`, `1.23 K`,
/// `4.5 M`, `3.22 B` for thousand millions, `1.5 T`), a time in ns (`12ns`, `3.2µs`,
/// `4.5ms`, `1.2s`) or a size with a byte unit (`1.5 KB`, `2.0 MB`). A bare `B` is the
/// count's thousand millions, as in `decoded_bytes`, which DataFusion keeps as a count; the
/// sizes this module reads have a value of their own only from `KB` up.
pub fn metric_value(text: &str) -> Option<f64> {
    let t = text.trim();
    let split = t
        .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))
        .unwrap_or(t.len());
    let (num, unit) = t.split_at(split);
    let n: f64 = num.parse().ok()?;
    let m = match unit.trim() {
        "" | "ns" => 1.0,
        "K" | "KB" => 1e3,
        "M" | "MB" => 1e6,
        "B" | "G" | "GB" => 1e9,
        "T" | "TB" => 1e12,
        "KiB" => 1024.0,
        "MiB" => 1024.0 * 1024.0,
        "GiB" => 1024.0 * 1024.0 * 1024.0,
        "µs" | "us" => 1e3,
        "ms" => 1e6,
        "s" => 1e9,
        _ => return None,
    };
    Some(n * m)
}

/// The sum of metric `name` over the lines of a stage plan whose operator starts with `op`.
pub fn metric_in(plan: &str, op: &str, name: &str) -> f64 {
    plan.lines()
        .filter(|l| l.trim_start().starts_with(op))
        .filter_map(|l| {
            let m = l.split("metrics=[").nth(1)?;
            let m = m.rsplit_once(']').map_or(m, |(a, _)| a);
            m.split(", ").find_map(|kv| {
                kv.strip_prefix(name)?
                    .strip_prefix('=')
                    .and_then(metric_value)
            })
        })
        .sum()
}

/// One job as the scheduler saw it.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct JobStats {
    /// The rounds: stages that ran [`crate::StepExec`].
    pub rounds: usize,
    /// Stages in all.
    pub stages: usize,
    /// Tasks in all, and of them the round tasks.
    pub tasks: usize,
    /// Tasks of the round stages.
    pub round_tasks: usize,
    /// Wall time from the job's start to its end, in ms.
    pub job_ms: f64,
    /// Over the stages, the first task's launch to the last one's finish, summed, in ms.
    pub stage_ms: f64,
    /// Over the stages, the longest task's run on its executor, summed (the critical path
    /// of the tasks), in ms.
    pub task_ms: f64,
    /// The core's step over all round tasks (`step_time`), in ms.
    pub step_ms: f64,
    /// The shuffle readers' fetch time over all tasks, in ms.
    pub fetch_ms: f64,
    /// The bytes the shuffle readers decoded (local and remote).
    pub bytes: f64,
    /// Shuffle partitions read from another executor.
    pub remote_reads: f64,
    /// Rows the round stages' steps took in (`arrived`).
    pub arrived: f64,
    /// The whole-graph answers' own time (many searches, the components), summed over tasks.
    pub answer_ms: f64,
}

impl JobStats {
    /// The job's stats from its stages' JSON.
    pub fn from_json(job: &Value, stages: &Value) -> Result<Self> {
        let mut s = JobStats::default();
        let (start, end) = (job["start_time"].as_u64(), job["end_time"].as_u64());
        if let (Some(a), Some(b)) = (start, end) {
            s.job_ms = b.saturating_sub(a) as f64;
        }
        let list = stages["stages"]
            .as_array()
            .ok_or_else(|| ext("no stages in the job's JSON"))?;
        for st in list {
            let plan = st["stage_plan"].as_str().unwrap_or("");
            let tasks: Vec<&Value> = st["tasks"]
                .as_array()
                .map(|t| t.iter().filter(|t| !t.is_null()).collect())
                .unwrap_or_default();
            s.stages += 1;
            s.tasks += tasks.len();
            // A round: a part's step, or a machine's level of a sliced search.
            let is_round = plan.lines().any(|l| {
                let l = l.trim_start();
                l.starts_with("StepExec") || l.starts_with("SliceExec")
            });
            if is_round {
                s.rounds += 1;
                s.round_tasks += tasks.len();
                s.step_ms += (metric_in(plan, "StepExec", "step_time")
                    + metric_in(plan, "SliceExec", "step_time"))
                    / 1e6;
                s.arrived += metric_in(plan, "StepExec", "arrived");
            }
            s.answer_ms += metric_in(plan, "AnswerExec", "step_time") / 1e6;
            s.fetch_ms += metric_in(plan, "ShuffleReaderExec", "fetch_time") / 1e6;
            s.bytes += metric_in(plan, "ShuffleReaderExec", "decoded_bytes");
            s.remote_reads += metric_in(plan, "ShuffleReaderExec", "remote_partitions");
            let launch = tasks.iter().filter_map(|t| t["launch_time"].as_u64()).min();
            let finish = tasks.iter().filter_map(|t| t["finish_time"].as_u64()).max();
            if let (Some(a), Some(b)) = (launch, finish) {
                s.stage_ms += b.saturating_sub(a) as f64;
            }
            s.task_ms += tasks
                .iter()
                .filter_map(|t| t["exec_duration"].as_u64())
                .max()
                .unwrap_or(0) as f64;
        }
        Ok(s)
    }

    /// The last job's stats from the scheduler at `url`.
    pub fn of_last_job(url: &str) -> Result<(String, Self)> {
        let id = last_job(url)?;
        let job = get_json(url, &format!("/api/job/{id}"))?;
        let stages = get_json(url, &format!("/api/job/{id}/stages?plan_format=metrics"))?;
        Ok((id, Self::from_json(&job, &stages)?))
    }

    /// One line: where the time went.
    pub fn line(&self) -> String {
        format!(
            "job {:.0} ms: {} rounds ({} round tasks, {} tasks, {} stages); stages {:.0} ms, longest tasks {:.0} ms, scheduler between stages {:.0} ms; core step {:.1} ms; shuffle fetch {:.1} ms, {:.0} bytes decoded, {:.0} remote reads; {:.0} rows arrived; answers {:.1} ms",
            self.job_ms,
            self.rounds,
            self.round_tasks,
            self.tasks,
            self.stages,
            self.stage_ms,
            self.task_ms,
            (self.job_ms - self.stage_ms).max(0.0),
            self.step_ms,
            self.fetch_ms,
            self.bytes,
            self.remote_reads,
            self.arrived,
            self.answer_ms
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn metric_values_read_as_datafusion_prints_them() {
        assert_eq!(metric_value("1234"), Some(1234.0));
        assert_eq!(metric_value("1.5 K"), Some(1500.0));
        assert_eq!(metric_value("2.5ms"), Some(2.5e6));
        assert_eq!(metric_value("3µs"), Some(3e3));
        assert_eq!(metric_value("1.0 MB"), Some(1e6));
        // A count past a thousand million: DataFusion's `B`, as in `decoded_bytes=3.22 B`.
        assert_eq!(metric_value("3.22 B"), Some(3.22e9));
        assert_eq!(metric_value("1.5 T"), Some(1.5e12));
        assert_eq!(metric_value("nonsense"), None);
    }

    #[test]
    fn a_jobs_rounds_and_times_come_from_its_stage_plans() {
        let job = serde_json::json!({"start_time": 1000, "end_time": 1100});
        let stages = serde_json::json!({"stages": [
            {"stage_plan": "ShuffleWriterExec\n  StepExec: reach, metrics=[arrived=3, sent=5, step_time=2ms]\n    ShuffleReaderExec: metrics=[decoded_bytes=1.0 KB, fetch_time=1ms, remote_partitions=2]",
             "tasks": [{"launch_time": 1010, "finish_time": 1030, "exec_duration": 15},
                       {"launch_time": 1012, "finish_time": 1040, "exec_duration": 25}]},
            {"stage_plan": "ShuffleWriterExec\n  CollectExec: reach",
             "tasks": [{"launch_time": 1050, "finish_time": 1060, "exec_duration": 8}, null]}
        ]});
        let s = JobStats::from_json(&job, &stages).unwrap();
        assert_eq!((s.rounds, s.stages, s.tasks, s.round_tasks), (1, 2, 3, 2));
        assert_eq!((s.job_ms, s.stage_ms, s.task_ms), (100.0, 40.0, 33.0));
        assert_eq!(
            (s.step_ms, s.fetch_ms, s.bytes, s.remote_reads, s.arrived),
            (2.0, 1.0, 1000.0, 2.0, 3.0)
        );
        assert!(s.line().contains("1 rounds"));
    }
}