about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/gemma.rs241
-rw-r--r--src/response.rs108
-rw-r--r--src/routes/gemma.rs114
3 files changed, 458 insertions, 5 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 4805b84..5730d83 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -18,6 +18,7 @@ use std::process::Output;
 
 use serde_json::Value;
 
+use crate::response::StepTiming;
 use crate::streaming::{self, RunLogError};
 
 /// One phenotype value per strain (genotype-file order), or `None` for
@@ -790,6 +791,216 @@ pub struct GemmaOutput {
     pub columns: Vec<String>,
     pub rows: Value,
     pub notes: Vec<String>,
+    /// Per-step compute times read out of the steps' own logs.
+    pub steps: Vec<StepTiming>,
+    /// How long the ravanan invocation took, in ms.
+    pub workflow_ms: u64,
+    /// How long reading the engine's outputs took, in ms.
+    pub parse_ms: u64,
+}
+
+/// The compute time a step's own log reports, in ms.
+///
+/// GEMMA and pangemma both write "## total computation time = <n> min" into the
+/// per-chromosome log, so this is the engine's own figure for that step -- not
+/// a wall-clock estimate that includes staging, dispatch or archive handling.
+/// A cached step's log is still in ravanan's store, with the figure from when
+/// it ran, which is why the caller labels the step `cached`.
+fn step_compute_ms(log: &str) -> Option<u64> {
+    for line in log.lines() {
+        let line = line.trim();
+        if let Some(rest) = line.strip_prefix("## total computation time") {
+            let minutes: f64 = rest
+                .split('=')
+                .nth(1)?
+                .trim()
+                .trim_end_matches("min")
+                .trim()
+                .parse()
+                .ok()?;
+            return Some((minutes * 60_000.0).round() as u64);
+        }
+    }
+    None
+}
+
+/// The chromosome a step's log file was written for: the workflow names each
+/// one `<chr>-<step>.log.txt` (`9-gwa.log.txt`, `X-kin.log.txt`).
+fn step_chromosome(path: &str, step: &str, suffix: &str) -> Option<String> {
+    let name = Path::new(path).file_name()?.to_string_lossy();
+    // "<chr>-<step>.log.txt": strip the step as well, or every scattered log
+    // looks as if its chromosome were "9-gwa" (and is rejected for the hyphen).
+    let marker = format!("-{step}{suffix}");
+    let stem = name
+        .strip_suffix(&marker)
+        .map(str::to_string)
+        .or_else(|| name.strip_suffix(suffix).map(str::to_string))?;
+    if stem.is_empty() || stem.contains('-') {
+        // "kin"/"gwa" are the only hyphen-free steps we name this way; a
+        // chromosome never contains '-' but a key can, so be strict.
+        return None;
+    }
+    Some(stem)
+}
+
+/// [`step_timings`], with each step's state taken from its log's mtime: a log
+/// older than the request was not written by it, so ravanan answered that step
+/// from its store.
+fn step_timings_stateful(
+    paths: &[&str],
+    step: &str,
+    suffix: &str,
+    request_started: std::time::SystemTime,
+) -> Vec<StepTiming> {
+    paths
+        .iter()
+        .filter_map(|path| {
+            let log = std::fs::read_to_string(path).ok()?;
+            let ran_now = std::fs::metadata(path)
+                .and_then(|metadata| metadata.modified())
+                .map(|modified| modified >= request_started)
+                .unwrap_or(false);
+            Some(StepTiming {
+                step: step.to_string(),
+                chr: step_chromosome(path, step, suffix),
+                compute_ms: step_compute_ms(&log),
+                state: if ran_now { "ran" } else { "cached" }.to_string(),
+            })
+        })
+        .collect()
+}
+
+/// One [`StepTiming`] per log file handed in, in the order given.
+fn step_timings(paths: &[&str], step: &str, suffix: &str, state: &str) -> Vec<StepTiming> {
+    paths
+        .iter()
+        .filter_map(|path| {
+            let log = std::fs::read_to_string(path).ok()?;
+            Some(StepTiming {
+                step: step.to_string(),
+                chr: step_chromosome(path, step, suffix),
+                compute_ms: step_compute_ms(&log),
+                state: state.to_string(),
+            })
+        })
+        .collect()
+}
+
+/// What Slurm did for this request: the jobs it accepted since `since`
+/// (epoch seconds), and their queue and run times.
+///
+/// Ravanan's store records no job ids and Slurm's job record carries neither a
+/// stdout path nor the scattered input, so the only join available without
+/// ravanan's help is the job *name* -- which this deployment's patched ravanan
+/// sets to the step's store basename.  Only the aggregate is reported here;
+/// the per-step figures come from the engines' own logs.
+pub async fn cluster_timing(
+    batch: &crate::config::RavananBatch,
+    since_epoch: u64,
+    store: &str,
+) -> (Option<crate::response::ClusterTiming>, Vec<StepTiming>) {
+    let crate::config::RavananBatch::SlurmApi {
+        endpoint, jwt_file, ..
+    } = batch
+    else {
+        return (None, Vec::new());
+    };
+    let Some(jwt) = std::fs::read_to_string(jwt_file)
+        .ok()
+        .map(|jwt| jwt.trim().to_string())
+    else {
+        return (None, Vec::new());
+    };
+    let store = store.to_string();
+    let url = format!(
+        "{}/slurm/v0.0.41/jobs",
+        endpoint.trim_end_matches('/')
+    );
+    let mut request = reqwest::Client::new()
+        .get(&url)
+        .header("X-SLURM-USER-TOKEN", jwt)
+        .header(
+            "X-SLURM-USER-NAME",
+            std::env::var("SLURM_USER").unwrap_or_else(|_| "testuser".to_string()),
+        )
+        .header("Accept", "application/json");
+    if let Ok(timeout) = std::env::var("SLURM_TIMEOUT_SECS") {
+        if let Ok(seconds) = timeout.parse::<u64>() {
+            request = request.timeout(std::time::Duration::from_secs(seconds));
+        }
+    }
+    let Ok(response) = request.timeout(std::time::Duration::from_secs(10)).send().await else {
+        return (None, Vec::new());
+    };
+    let Ok(body) = response.text().await else {
+        return (None, Vec::new());
+    };
+    let Ok(json) = serde_json::from_str::<Value>(&body) else {
+        return (None, Vec::new());
+    };
+    let number = |value: &Value, key: &str| -> Option<u64> {
+        value
+            .get(key)
+            .and_then(|v| v.get("number").and_then(Value::as_u64))
+    };
+    let mut timing = crate::response::ClusterTiming::default();
+    let (mut run_sum, mut run_max, mut queue_sum) = (0u64, 0u64, 0u64);
+    let Some(jobs) = json.get("jobs").and_then(Value::as_array) else {
+        return (None, Vec::new());
+    };
+    let mut steps = Vec::new();
+    for job in jobs {
+        let Some(submit) = number(job, "submit_time") else {
+            continue;
+        };
+        if submit < since_epoch {
+            continue;
+        }
+        timing.jobs_submitted += 1;
+        // The job's name is the step's store basename ("<key>-<step>"), so its
+        // outputs -- and the log with the engine's own compute time -- are one
+        // directory away.  This is the only way to a *scattered* step's figures
+        // when its log is not a workflow output (kinship's is not).
+        if let Some(name) = job.get("name").and_then(Value::as_str) {
+            let dir = Path::new(&store).join("files").join(name);
+            if let Ok(entries) = std::fs::read_dir(&dir) {
+                for entry in entries.flatten() {
+                    let path = entry.path();
+                    let file = path.to_string_lossy().into_owned();
+                    if !file.ends_with(".log.txt") {
+                        continue;
+                    }
+                    let step = if name.ends_with("-kinship") {
+                        "kinship"
+                    } else if name.ends_with("-gwa") {
+                        "gwa"
+                    } else {
+                        continue;
+                    };
+                    if let Ok(log) = std::fs::read_to_string(&path) {
+                        steps.push(StepTiming {
+                            step: step.to_string(),
+                            chr: step_chromosome(&file, step, ".log.txt"),
+                            compute_ms: step_compute_ms(&log),
+                            state: "ran".to_string(),
+                        });
+                    }
+                }
+            }
+        }
+        if let Some(start) = number(job, "start_time") {
+            queue_sum += start.saturating_sub(submit) * 1000;
+            if let Some(end) = number(job, "end_time") {
+                let run = end.saturating_sub(start) * 1000;
+                run_sum += run;
+                run_max = run_max.max(run);
+            }
+        }
+    }
+    timing.run_ms_sum = Some(run_sum);
+    timing.run_ms_max = Some(run_max);
+    timing.queue_ms_sum = Some(queue_sum);
+    (Some(timing), steps)
 }
 
 /// The gemma-wrapper arguments for the kinship step, shared between the
@@ -1016,6 +1227,12 @@ pub async fn compute(
             columns,
             rows: Value::Array(rows),
             notes: output_notes,
+            // The wrapper path reports its own timings in its JSON record and
+            // the route times the call as a whole; the per-step figures are a
+            // ravanan-path thing (one process ran everything here).
+            steps: Vec::new(),
+            workflow_ms: 0,
+            parse_ms: 0,
         })
     }
     .await;
@@ -1556,6 +1773,9 @@ pub async fn compute_ravanan(
     workflow: &RavananWorkflow<'_>,
     // pangemma only: the lmdb store built by the store workflow.
     store: Option<&str>,
+    // When the request started, so a step whose log predates it can be
+    // reported as cached rather than as work this request did.
+    request_started: std::time::SystemTime,
     cache_dir: &str,
     scratch_dir: &str,
     genotype_file: &str,
@@ -1728,12 +1948,14 @@ pub async fn compute_ravanan(
         (None, GemmaEngine::Gemma) => None,
     };
 
+    let workflow_started = std::time::Instant::now();
     let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref())
         .await
         .map_err(|error| GemmaError::Spawn {
             command: ravanan_cmd.to_string(),
             error,
         })?;
+    let workflow_ms = workflow_started.elapsed().as_millis() as u64;
     if !output.status.success() {
         return Err(GemmaError::RavananFailed(
             String::from_utf8_lossy(&output.stderr).into_owned(),
@@ -1743,6 +1965,7 @@ pub async fn compute_ravanan(
         .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?;
     let assoc_paths = ravanan_output_paths(&outputs, "assoc")?;
     let gwa_log_paths = ravanan_output_paths(&outputs, "gwa_log")?;
+    let kinship_log_paths = ravanan_output_paths(&outputs, "kinship_log").unwrap_or_default();
     if assoc_paths.is_empty() {
         return Err(GemmaError::NoAssocFiles);
     }
@@ -1750,6 +1973,7 @@ pub async fn compute_ravanan(
     // One .assoc.txt and one .log.txt per chromosome, straight from the
     // workflow's own outputs: gemma writes named files (`-o <chr>-gwa`), so
     // there is no wrapper JSON record to parse and no archive to unpack.
+    let parse_started = std::time::Instant::now();
     let mut columns = Vec::new();
     let mut rows = Vec::new();
     for assoc_path in &assoc_paths {
@@ -1760,9 +1984,23 @@ pub async fn compute_ravanan(
         }
         rows.extend(file_rows.into_iter().map(Value::Array));
     }
+    let parse_ms = parse_started.elapsed().as_millis() as u64;
     // `-pve` puts the variance components in each job's .log.txt, which the
     // workflow returns as a first-class output.
     let components = read_variance_components_from_log_files(&gwa_log_paths);
+    // Per-step figures from the engines' own logs, with the state taken from
+    // each log's mtime: a log older than the request is a step ravanan reused.
+    let mut steps = step_timings_stateful(&gwa_log_paths, "gwa", ".log.txt", request_started);
+    steps.extend(step_timings_stateful(
+        &kinship_log_paths,
+        "kinship",
+        ".log.txt",
+        request_started,
+    ));
+    steps.sort_by(|a, b| {
+        (a.step.as_str(), a.chr.as_deref().unwrap_or(""))
+            .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or("")))
+    });
 
     streaming::mark_complete(&log_path);
 
@@ -1800,6 +2038,9 @@ pub async fn compute_ravanan(
         columns,
         rows: Value::Array(rows),
         notes,
+        steps,
+        workflow_ms,
+        parse_ms,
     })
 }
 
diff --git a/src/response.rs b/src/response.rs
index f830054..46db64a 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -29,6 +29,102 @@ pub enum State {
     Partial,
 }
 
+/// How a compute request spent its time, beside `took_ms` rather than instead
+/// of it.
+///
+/// `took_ms` alone cannot say the two things a caller most needs: which engine
+/// answered, and whether the work in it was done *now* or reused from a cache.
+/// A warm answer and a cold one differ by an order of magnitude on real
+/// panels (BXD.8: 3.9 s against 21 min on HET3), and a cached run reports the
+/// cache's speed, not the engine's -- so the counts and the states are here
+/// next to the durations.
+#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)]
+pub struct Timing {
+    /// Which engine produced `data`: `gemma` (gemma-wrapper, in process),
+    /// `pangemma` (ravanan + slurm), or `gemma` over ravanan.
+    pub engine: String,
+    /// The request's own phases, in the order they ran. Their sum is at most
+    /// `meta.took_ms`.
+    pub phases: Vec<PhaseTiming>,
+    /// What the cluster did, when the engine used one. Absent for the
+    /// in-process runner and when no Slurm endpoint is configured -- the
+    /// distinction matters more than a made-up zero.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub cluster: Option<ClusterTiming>,
+    /// Per-step figures, one per CWL step instance that has a log. On a warm
+    /// request these are the times recorded when the step *ran*, which is why
+    /// each carries its `state`.
+    #[serde(skip_serializing_if = "Vec::is_empty")]
+    pub steps: Vec<StepTiming>,
+    /// Totals over `steps`, so a caller need not sum them.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub steps_summary: Option<StepsSummary>,
+}
+
+/// One phase of a request.
+#[derive(Serialize, utoipa::ToSchema, Clone, Debug)]
+pub struct PhaseTiming {
+    /// `artifacts` (genotype treatment and/or lmdb store), `workflow` (the
+    /// ravanan invocation), `parse` (reading the engine's outputs), or
+    /// `wrapper` (the in-process gemma-wrapper run).
+    pub name: String,
+    /// `reused` when an artifact was already built for these inputs, `built`
+    /// when this request built it, `ran` for work done now, and `cached` when
+    /// the whole phase was a cache hit.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub state: Option<String>,
+    pub ms: u64,
+}
+
+/// What the cluster did for this request.
+#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)]
+pub struct ClusterTiming {
+    /// Jobs Slurm accepted between the request starting and finishing. **Zero
+    /// is the warm claim**: no job ran, so every step came from ravanan's
+    /// store.
+    pub jobs_submitted: u64,
+    /// Sum of those jobs' run times, in ms. This is job time, not wall time:
+    /// it exceeds the wall clock when jobs overlap on several nodes.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub run_ms_sum: Option<u64>,
+    /// The longest single job, in ms -- the floor a scatter cannot beat.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub run_ms_max: Option<u64>,
+    /// Sum of queue delays (start minus submit), in ms: dispatch cost as
+    /// opposed to compute.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub queue_ms_sum: Option<u64>,
+}
+
+/// One CWL step instance that has a log.
+#[derive(Serialize, utoipa::ToSchema, Clone, Debug)]
+pub struct StepTiming {
+    /// `kinship`, `gwa`, `prepare` or `store`.
+    pub step: String,
+    /// The chromosome a scattered step ran for, when the log names it (the
+    /// workflow writes "<chr>-gwa.log.txt").
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub chr: Option<String>,
+    /// What the engine itself reported (`## total computation time`), in ms.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub compute_ms: Option<u64>,
+    /// `ran` when this request ran the step, `cached` when the figure comes
+    /// from ravanan's store.
+    pub state: String,
+}
+
+/// Totals over [`StepTiming`].
+#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)]
+pub struct StepsSummary {
+    pub n: usize,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub compute_ms_sum: Option<u64>,
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub compute_ms_max: Option<u64>,
+    /// How many of `n` were answered from ravanan's store.
+    pub cached: usize,
+}
+
 /// Facts about this response, as opposed to its data.
 #[derive(Serialize, utoipa::ToSchema)]
 pub struct Meta {
@@ -60,6 +156,11 @@ pub struct Meta {
     #[serde(flatten, skip_serializing_if = "Option::is_none")]
     #[schema(inline)]
     pub extra: Option<serde_json::Map<String, serde_json::Value>>,
+    /// Where a compute request's time went (see [`Timing`]). Present only on
+    /// the compute endpoints, which are the ones whose cost is worth
+    /// reporting; a read endpoint's `took_ms` says everything.
+    #[serde(skip_serializing_if = "Option::is_none")]
+    pub timing: Option<Timing>,
 }
 
 /// A success response: the payload, facts about the response, notes on
@@ -162,6 +263,12 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> {
         self
     }
 
+    /// Attaches [`Timing`] to `meta`.
+    pub fn with_timing(mut self, timing: Timing) -> Self {
+        self.meta.timing = Some(timing);
+        self
+    }
+
     pub fn with_note(mut self, note: &str) -> Self {
         self.notes.push(note.to_string());
         self
@@ -273,6 +380,7 @@ impl Ctx {
                 num_rows: None,
                 num_cols: None,
                 extra: None,
+                timing: None,
             },
             notes: Vec::new(),
             next: Vec::new(),
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 38b5b0c..2716bfc 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -281,6 +281,8 @@ async fn ravanan_artifacts(
     rid: RequestInfo,
 ) -> Result<Artifacts, ApiError> {
     let cache_dir = &config.ravanan_cache_dir;
+    let artifacts_started = std::time::Instant::now();
+    let mut built = false;
     let mut notes = Vec::new();
     std::fs::create_dir_all(cache_dir).map_err(|error| {
         ApiError::new(
@@ -576,6 +578,7 @@ async fn ravanan_artifacts(
                 .unwrap_or_default()
         };
         artifact_memo_save(&memo, &outputs);
+        built = true;
         notes.push(format!(
             "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \
              cluster), cached by ravanan on (script, inputs)"
@@ -640,6 +643,7 @@ async fn ravanan_artifacts(
             .find(|(name, _)| name == "store")
             .and_then(|(_, paths)| paths.first().cloned());
         artifact_memo_save(&memo, &outputs);
+        built = true;
         notes.push(
             "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \
              cluster), cached by ravanan on (script, inputs)"
@@ -651,11 +655,20 @@ async fn ravanan_artifacts(
         None
     };
 
+    let needed = mode != "none" || engine == gemma::GemmaEngine::Pangemma;
     Ok(Artifacts {
         genotype_file,
         snps_file,
         store,
         individuals_file,
+        ms: artifacts_started.elapsed().as_millis() as u64,
+        state: if !needed {
+            "none".to_string()
+        } else if built {
+            "built".to_string()
+        } else {
+            "reused".to_string()
+        },
         notes,
     })
 }
@@ -665,6 +678,11 @@ struct Artifacts {
     genotype_file: String,
     snps_file: String,
     store: Option<String>,
+    /// Milliseconds spent producing the artifacts, and whether any of them was
+    /// built by this request (`built`), all came from ravanan's store
+    /// (`reused`), or the request needed none (`none`).
+    ms: u64,
+    state: String,
     /// The individual order of the prepared genotypes, when the treatment
     /// changed it (`hmm` takes its order from the cross).
     individuals_file: Option<String>,
@@ -1332,6 +1350,9 @@ pub async fn compute_gemma(
     let rid_for_job = rid.clone();
     let trait_values_for_job = trait_values.clone();
     let covariates_for_job = covariate_list.clone();
+    // The in-process run: one phase, because one process did the whole thing
+    // (the wrapper's own JSON record carries its internal figures).
+    let wrapper_started = std::time::Instant::now();
     compute_gate::gemma()
         .run(__gn4_claim, async move {
             gemma::compute(
@@ -1493,7 +1514,18 @@ pub async fn compute_gemma(
                 body: Some(serde_json::Value::Object(body)),
             });
         }
-        Json(envelope)
+        let timing = crate::response::Timing {
+            engine: "gemma".to_string(),
+            phases: vec![crate::response::PhaseTiming {
+                name: "wrapper".to_string(),
+                state: None,
+                ms: wrapper_started.elapsed().as_millis() as u64,
+            }],
+            cluster: None,
+            steps: Vec::new(),
+            steps_summary: None,
+        };
+        Json(envelope.with_timing(timing))
     })
 }
 
@@ -1580,6 +1612,10 @@ pub(crate) async fn gemma_via_ravanan(
     endpoint: &'static str,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    // Before anything else runs, for two reasons: the cluster query has to know
+    // which jobs belong to *this* request, and each step log's mtime is
+    // compared against it to tell a step that ran from one ravanan reused.
+    let request_started = std::time::SystemTime::now();
     let engine = match request.engine.as_deref() {
         None => crate::gemma::GemmaEngine::Gemma,
         Some(value) => match crate::gemma::GemmaEngine::parse(value) {
@@ -1722,6 +1758,7 @@ pub(crate) async fn gemma_via_ravanan(
     )
     .await?;
     let mut impute_notes = artifacts.notes;
+    let (artifacts_ms, artifacts_state) = (artifacts.ms, artifacts.state.clone());
     let (genotype_file, snps_file) = (artifacts.genotype_file, artifacts.snps_file);
     if impute == "hmm" {
         if let (Some(individuals), Some(names)) =
@@ -1761,6 +1798,10 @@ pub(crate) async fn gemma_via_ravanan(
 
     let run_id = params.id.clone();
     let job_rid = rid.clone();
+    let since_epoch = request_started
+        .duration_since(std::time::UNIX_EPOCH)
+        .map(|since| since.as_secs())
+        .unwrap_or(0);
     compute_gate::ravanan()
         .run(__gn4_claim, async move {
             // The workflow pair follows the engine: gemma-gn2 on BIMBAM, or
@@ -1782,12 +1823,13 @@ pub(crate) async fn gemma_via_ravanan(
                 source: workflow_source,
                 manifest: manifest_source,
             };
-            gemma::compute_ravanan(
+            let output = gemma::compute_ravanan(
                 &config.ravanan_cmd,
                 &config.ravanan_batch,
                 &config.ccwl_cmd,
                 &ravanan_workflow,
                 store.as_deref(),
+                request_started,
                 &config.ravanan_cache_dir,
                 &config.ravanan_scratch,
                 &genotype_file,
@@ -1807,10 +1849,20 @@ pub(crate) async fn gemma_via_ravanan(
                 )
                 .with_request_id(job_rid.clone()),
                 other => gemma_error_to_api_error(other, job_rid.clone()),
-            })
+            })?;
+            // Asked here, inside the async block: the reply closure below is a
+            // plain `map`, and this is the last moment the jobs of *this*
+            // request can be told from every other request's.
+            let (cluster, ran_steps) = gemma::cluster_timing(
+                &config.ravanan_batch,
+                since_epoch,
+                &format!("{}/ravanan-store", config.ravanan_cache_dir),
+            )
+            .await;
+            Ok::<_, ApiError>((output, cluster, ran_steps))
         })
         .await
-    .map(|output| {
+    .map(|(output, cluster, ran_steps)| {
         let num_rows = output.rows.as_array().map(Vec::len).unwrap_or(0);
         let mut envelope = ctx
             .envelope(output.rows)
@@ -1830,7 +1882,59 @@ pub(crate) async fn gemma_via_ravanan(
         for note in &output.notes {
             envelope = envelope.with_note(note);
         }
-        Json(envelope)
+        // Where the time went, beside `took_ms`: the phases this request paid
+        // for, what the cluster did, and each step's own figure with its state.
+        let mut phases = vec![crate::response::PhaseTiming {
+            name: "artifacts".to_string(),
+            state: Some(artifacts_state.clone()),
+            ms: artifacts_ms,
+        }];
+        phases.push(crate::response::PhaseTiming {
+            name: "workflow".to_string(),
+            state: None,
+            ms: output.workflow_ms,
+        });
+        phases.push(crate::response::PhaseTiming {
+            name: "parse".to_string(),
+            state: None,
+            ms: output.parse_ms,
+        });
+        // Steps located through the jobs of this request (kinship's logs are
+        // not a workflow output) join the ones read from the returned logs;
+        // a step present in both keeps the "ran" entry.
+        let mut steps = output.steps.clone();
+        for step in ran_steps {
+            let duplicate = steps.iter().any(|existing| {
+                existing.step == step.step && existing.chr == step.chr && existing.state == "ran"
+            });
+            if !duplicate {
+                steps.push(step);
+            }
+        }
+        steps.sort_by(|a, b| {
+            (a.step.as_str(), a.chr.as_deref().unwrap_or(""))
+                .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or("")))
+        });
+        let cached = steps.iter().filter(|s| s.state == "cached").count();
+        let compute: Vec<u64> = steps.iter().filter_map(|s| s.compute_ms).collect();
+        let summary = crate::response::StepsSummary {
+            n: steps.len(),
+            compute_ms_sum: if compute.is_empty() {
+                None
+            } else {
+                Some(compute.iter().sum())
+            },
+            compute_ms_max: compute.iter().copied().max(),
+            cached,
+        };
+        let timing = crate::response::Timing {
+            engine: engine.as_str().to_string(),
+            phases,
+            cluster,
+            steps,
+            steps_summary: Some(summary),
+        };
+        Json(envelope.with_timing(timing))
     })
 }