about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-22 09:36:44 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-22 09:36:44 +0000
commit58de629953a75daad50daca795465784d37c7359 (patch)
treedaaac66e88dcbc2e9aa655d485a6bc1039d929c3 /src
parent4f7c1adc527defc54a6ea1aee77e205067a49120 (diff)
downloadgenenetwork4-58de629953a75daad50daca795465784d37c7359.tar.gz
compute: name the genotype phase, and list every step including cached kinship
Two gaps, both found by measuring a request that dwarfs the mapping itself.

**The genotypes phase.** `resolve_inputs` opens the panel, works out which
individuals have genotypes and writes the prepared subset; on
HSNIH-Palmer_true (134,918 markers, 6,147 individuals) that is 20.5 s of a
29.5 s request -- 70 % of it, and until now reported nowhere. The phases now
start with it, and on that panel they sum to 97 % of `took_ms` (genotypes
20,522 ms, artifacts reused 3 ms, workflow 8,013 ms, parse 152 ms, of 29,529).

**Cached kinship steps.** `steps` listed only GWA entries: `kinship_log` is not
a workflow output (ccwl's `pipe` publishes the last step's outputs only), and a
cached step submits no job to trace it by. But GEMMA prints the command line it
ran, and the GWA job's `-k` names the K file ravanan staged from the kinship
step's own store directory -- so the path carries both the step key
("<key>-kinship") and the chromosome ("<chr>-kin.cXX.txt"). Reading the log
beside it gives the cached figure: 40 steps on both panels now, kinship
included (HSNIH chr1 1,769,670 ms, chr10 1,315,176 ms).

**And a parsing bug that fix exposed:** GEMMA's `## total computation time` is
0 for `-gk` while its breakdown says `time on calculating relatedness matrix =
0.0783561 min`. The parts are summed as well and the larger of the two wins; a
figure of exactly zero becomes absent rather than a false "instant".

Worth reading off the result: on this panel the engine reports ~19 h of step
time (68.8 M ms across 20 kinship + 20 GWA), while Slurm's records show the 20
GWA jobs overlapping into a 21-minute wall -- job time and wall time differ by
more than an order of magnitude here, which is why both are labelled.
Diffstat (limited to 'src')
-rw-r--r--src/gemma.rs108
-rw-r--r--src/routes/gemma.rs20
2 files changed, 116 insertions, 12 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 5730d83..2188530 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -807,21 +807,45 @@ pub struct GemmaOutput {
 /// 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> {
+    let minutes_of = |text: &str| -> Option<f64> {
+        text.split('=')
+            .nth(1)?
+            .trim()
+            .trim_end_matches("min")
+            .trim()
+            .parse()
+            .ok()
+    };
+    let mut total: Option<f64> = None;
+    let mut breakdown = 0.0f64;
+    let mut saw_breakdown = false;
     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);
+            total = minutes_of(rest);
+        } else if line.starts_with("##") && line.ends_with("min") && line.contains('=') {
+            // "##      time on calculating relatedness matrix = 0.0783561 min".
+            // GEMMA's *total* is unreliable for -gk (it prints 0 while the
+            // breakdown says 0.078 min), so the parts are summed as well and
+            // the larger of the two wins.
+            if let Some(minutes) = minutes_of(line) {
+                breakdown += minutes;
+                saw_breakdown = true;
+            }
         }
     }
-    None
+    let minutes = match (total, saw_breakdown) {
+        (Some(total), true) => total.max(breakdown),
+        (Some(total), false) => total,
+        (None, true) => breakdown,
+        (None, false) => return None,
+    };
+    // A real computation never takes exactly nothing; an engine that reports
+    // neither figure is unknown, not instant.
+    if minutes <= 0.0 {
+        return None;
+    }
+    Some((minutes * 60_000.0).round() as u64)
 }
 
 /// The chromosome a step's log file was written for: the workflow names each
@@ -843,6 +867,45 @@ fn step_chromosome(path: &str, step: &str, suffix: &str) -> Option<String> {
     Some(stem)
 }
 
+/// The kinship step behind one GWA log: its store key and the chromosome.
+///
+/// GEMMA prints the command line it ran, and the wrapper's `-k` names the K
+/// file it was given -- ravanan stages that from the kinship step's own store
+/// directory, so the path carries both the step's key ("<key>-kinship") and the
+/// chromosome ("<chr>-kin.cXX.txt"). That is how a *cached* kinship step can be
+/// reported: its log is not a workflow output (ccwl's `pipe` publishes only the
+/// last step's), and a cached step submitted no job to trace it by.
+fn kinship_of_gwa_log(path: &str) -> Option<(String, String)> {
+    let log = std::fs::read_to_string(path).ok()?;
+    let line = log
+        .lines()
+        .find(|line| line.contains("Command Line Input"))?;
+    let mut words = line.split_whitespace();
+    while let Some(word) = words.next() {
+        if word != "-k" {
+            continue;
+        }
+        let kpath = Path::new(words.next()?);
+        let chr = kpath
+            .file_name()?
+            .to_string_lossy()
+            .split("-kin")
+            .next()?
+            .to_string();
+        let key = kpath
+            .parent()?
+            .file_name()?
+            .to_string_lossy()
+            .strip_suffix("-kinship")?
+            .to_string();
+        if chr.is_empty() || key.is_empty() {
+            return None;
+        }
+        return Some((key, chr));
+    }
+    None
+}
+
 /// [`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.
@@ -1997,6 +2060,31 @@ pub async fn compute_ravanan(
         ".log.txt",
         request_started,
     ));
+    // The kinship step's log is not a workflow output, so its figure is taken
+    // from the store directory its own GWA job pointed at.
+    for gwa_log in &gwa_log_paths {
+        let Some((key, chr)) = kinship_of_gwa_log(gwa_log) else {
+            continue;
+        };
+        let kin_log = Path::new(cache_dir)
+            .join("ravanan-store")
+            .join("files")
+            .join(format!("{key}-kinship"))
+            .join(format!("{chr}-kin.log.txt"));
+        let Ok(log) = std::fs::read_to_string(&kin_log) else {
+            continue;
+        };
+        let ran_now = std::fs::metadata(&kin_log)
+            .and_then(|metadata| metadata.modified())
+            .map(|modified| modified >= request_started)
+            .unwrap_or(false);
+        steps.push(StepTiming {
+            step: "kinship".to_string(),
+            chr: Some(chr),
+            compute_ms: step_compute_ms(&log),
+            state: if ran_now { "ran" } else { "cached" }.to_string(),
+        });
+    }
     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("")))
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index e97eea8..548c464 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -1820,6 +1820,7 @@ pub(crate) async fn gemma_via_ravanan(
     endpoint: &'static str,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    let mut genotypes_ms: u64 = 0;
     // 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.
@@ -1884,7 +1885,17 @@ pub(crate) async fn gemma_via_ravanan(
         names: resolved_names,
         group: resolved_group,
         notes: input_notes,
-    } = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?;
+    } = {
+        // Reading the panel is a phase of its own: `resolve_inputs` opens the
+        // genotype file (a 134,918-marker BIMBAM is a multi-GB read), works out
+        // which individuals have genotypes, and writes the prepared subset. On
+        // HSNIH-Palmer_true that is ~29 s of a 46 s request -- the largest
+        // single cost, and invisible until it is named.
+        let started = std::time::Instant::now();
+        let resolved = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?;
+        genotypes_ms = started.elapsed().as_millis() as u64;
+        resolved
+    };
     if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() {
         return Err(ApiError::new(
             StatusCode::UNPROCESSABLE_ENTITY,
@@ -2093,10 +2104,15 @@ pub(crate) async fn gemma_via_ravanan(
         // 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: "genotypes".to_string(),
+            state: None,
+            ms: genotypes_ms,
+        }];
+        phases.push(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,