about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-21 12:04:20 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-21 12:04:20 +0000
commit3a526efb4cd3721adadf17cbf4a8dc1c5cbd8dec (patch)
tree4a7db1b91af38912b180e16435b890cdb6f1921c /src
parent64f1268be9a06462fe9685107c949dbbad84212d (diff)
downloadgenenetwork4-3a526efb4cd3721adadf17cbf4a8dc1c5cbd8dec.tar.gz
gemma: a warm request is ravanan's walk, not Slurm's scheduler
Measured where a warm request's time actually goes, because it was easy to
blame the scheduler.  It is not the scheduler: over 683 jobs slurmrestd reports
a queue delay of 0 s (median; p90 1 s, max 1 s) and run times of 1-4 s, with
the container's tuned 5 s interval already invisible to backfill.  What cost
time was ravanan's own overhead, paid once per invocation:

  - ~4 s per invocation just to evaluate a manifest: leaving GUIX_PACKAGE_PATH
    set makes guix autoload guix-bioinformatics' whole module tree (one ABI
    mismatch warning per module).  The artifact workflows' manifests name only
    `(gnu packages)` specs, so run_artifact now clears the variable for its
    child: 12.0 s -> 7.9 s for the same cached run.
  - ~7 s to walk a fully cached 40-step workflow (no jobs at all).
  - pangemma ran *two* invocations per request (store, then mapping) even when
    both were cached, so it paid all of that twice.

So the artifacts are memoized: a small pointer file under
<ravanan cache>/artifacts/ records where a workflow left its outputs, keyed on
the inputs' path, size and mtime (a regenerated panel file misses; a stale
pointer whose files are gone is ignored and rebuilt).  Ravanan's store remains
the data cache and the mapping workflow's own key is unchanged -- this only
avoids asking ravanan to tell us something we already know.

Warm BXD.8 trait 10001, before -> after:

  gemma     8.3 s -> 4.2 s
  pangemma 21.1 s -> 4.1 s

and a request for a new trait is now the same for both engines (9.5 s: the 20
GWA jobs, cached K), where gemma's was 13.5 s.

Still on the table, not done here: merging the kinship and GWA steps into one
job per chromosome (20 steps instead of 40, halving the walk) at the cost of
the K-sharing across traits, a Slurm sched_interval of 1 s in the container,
and pruning ravanan's store -- 87 GB now, of which 72 GB is per-step logs.
Diffstat (limited to 'src')
-rw-r--r--src/gemma.rs22
-rw-r--r--src/routes/gemma.rs132
2 files changed, 148 insertions, 6 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 5d2d173..4805b84 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -1458,12 +1458,22 @@ pub async fn run_artifact(
     ];
     let batch_args = run.batch.ravanan_args(scratch);
     args.extend(batch_args.iter().map(String::as_str));
-    let output = streaming::run_streaming(run.ravanan_cmd, &args, None)
-        .await
-        .map_err(|error| GemmaError::Spawn {
-            command: run.ravanan_cmd.to_string(),
-            error,
-        })?;
+    // With GUIX_PACKAGE_PATH cleared: these manifests name only `(gnu
+    // packages)` specs (bash, gawk, R/qtl2, python), and leaving the channel
+    // path set makes guix autoload guix-bioinformatics' module tree for every
+    // invocation -- an ABI mismatch warning per module and about four seconds
+    // of Guile per ravanan call (measured: 12.0 s with, 7.9 s without).
+    let output = streaming::run_streaming_with_env(
+        run.ravanan_cmd,
+        &args,
+        None,
+        &[("GUIX_PACKAGE_PATH", "")],
+    )
+    .await
+    .map_err(|error| GemmaError::Spawn {
+        command: run.ravanan_cmd.to_string(),
+        error,
+    })?;
     if !output.status.success() {
         return Err(GemmaError::RavananFailed(format!(
             "{} ({})",
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 6cb8d0b..38b5b0c 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -185,6 +185,75 @@ pub(crate) struct ResolvedInputs {
     pub notes: Vec<String>,
 }
 
+/// A memo of where an artifact workflow left its outputs.
+///
+/// Not a data cache -- ravanan's store is that, and it is keyed on
+/// (script, inputs) -- but a pointer cache, so a request whose artifact is
+/// already built does not pay for a whole ravanan invocation to be told so.
+/// Measured: a cached 40-step run still costs ~7 s of ravanan's own walk, and
+/// a warm pangemma request runs two workflows (store, then mapping), so the
+/// pointer is worth keeping.
+///
+/// The key covers the inputs' size and mtime, so a regenerated panel file or a
+/// rewritten prepared file misses.  A stale entry whose paths have gone (a
+/// pruned store) is ignored and rebuilt.
+fn artifact_memo_key(label: &str, parts: &[String]) -> String {
+    let mut material = Vec::new();
+    material.extend_from_slice(label.as_bytes());
+    for part in parts {
+        material.push(0);
+        material.extend_from_slice(part.as_bytes());
+    }
+    gemma::sha16(&material)
+}
+
+fn artifact_memo_load(path: &std::path::Path) -> Option<Vec<(String, String)>> {
+    let contents = std::fs::read_to_string(path).ok()?;
+    let entries: Vec<(String, String)> = contents
+        .lines()
+        .filter_map(|line| line.split_once('\t'))
+        .map(|(id, file)| (id.to_string(), file.to_string()))
+        .collect();
+    if entries.is_empty()
+        || entries
+            .iter()
+            .any(|(_, file)| !std::path::Path::new(file).is_file())
+    {
+        return None;
+    }
+    Some(entries)
+}
+
+fn artifact_memo_save(path: &std::path::Path, outputs: &[(String, Vec<String>)]) {
+    if let Some(parent) = path.parent() {
+        let _ = std::fs::create_dir_all(parent);
+    }
+    let body: String = outputs
+        .iter()
+        .filter_map(|(id, paths)| paths.first().map(|file| format!("{id}\t{file}\n")))
+        .collect();
+    let tmp = path.with_extension(format!("tmp-{}", std::process::id()));
+    if std::fs::write(&tmp, body).is_ok() {
+        let _ = std::fs::rename(&tmp, path);
+    }
+}
+
+/// `path:size:mtime` for a file, so a rewritten input misses the memo.
+fn artifact_input_stamp(path: &str) -> String {
+    match std::fs::metadata(path) {
+        Ok(metadata) => {
+            let mtime = metadata
+                .modified()
+                .ok()
+                .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
+                .map(|since| since.as_nanos())
+                .unwrap_or(0);
+            format!("{path}:{}:{mtime}", metadata.len())
+        }
+        Err(_) => path.to_string(),
+    }
+}
+
 /// The two cluster-side artifacts a ravanan request needs before anything is
 /// mapped: the missing-genotype treatment (`cwl/gemma/prepare.scm`) and, for
 /// pangemma, its lmdb store (`cwl/gemma/store.scm`).
@@ -440,6 +509,39 @@ async fn ravanan_artifacts(
              individuals_file: {{class: File, path: {served}}}\n",
             prepare_script, impute_script,
         );
+        let memo = std::path::Path::new(cache_dir)
+            .join("artifacts")
+            .join(format!(
+                "{}.txt",
+                artifact_memo_key(
+                    "prepare",
+                    &[
+                        mode.to_string(),
+                        artifact_input_stamp(genotype_file),
+                        artifact_input_stamp(snps_file),
+                        cross_dir.clone(),
+                        artifact_input_stamp(&served),
+                    ],
+                )
+            ));
+        let from_memo = artifact_memo_load(&memo).map(|entries| {
+            let pick = |id: &str| {
+                entries
+                    .iter()
+                    .find(|(name, _)| name == id)
+                    .map(|(_, file)| file.clone())
+                    .unwrap_or_default()
+            };
+            (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file")))
+        });
+        if let Some(found) = from_memo {
+            notes.push(format!(
+                "genotypes: '{mode}' treatment reused (ravanan built it for this panel and \
+                 mode earlier; the mapping workflow takes the same paths, so its own cache \
+                 still applies)"
+            ));
+            found
+        } else {
         let run = gemma::ArtifactWorkflow {
             label: "prepare",
             ccwl_cmd: &config.ccwl_cmd,
@@ -473,14 +575,42 @@ async fn ravanan_artifacts(
                 .and_then(|(_, paths)| paths.first().cloned())
                 .unwrap_or_default()
         };
+        artifact_memo_save(&memo, &outputs);
         notes.push(format!(
             "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \
              cluster), cached by ravanan on (script, inputs)"
         ));
         (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file")))
+        }
     };
 
     let store = if engine == gemma::GemmaEngine::Pangemma {
+        let memo = std::path::Path::new(cache_dir)
+            .join("artifacts")
+            .join(format!(
+                "{}.txt",
+                artifact_memo_key(
+                    "store",
+                    &[
+                        artifact_input_stamp(&genotype_file),
+                        artifact_input_stamp(&snps_file),
+                    ],
+                )
+            ));
+        if let Some(entries) = artifact_memo_load(&memo) {
+            notes.push(
+                "genotypes: pangemma's lmdb store reused (ravanan built it for these genotypes \
+                 earlier)"
+                    .to_string(),
+            );
+            Some(
+                entries
+                    .iter()
+                    .find(|(name, _)| name == "store")
+                    .map(|(_, file)| file.clone())
+                    .unwrap_or_default(),
+            )
+        } else {
         let inputs = format!(
             "store_script: {{class: File, path: {}}}\n\
              genotype_file: {{class: File, path: {genotype_file}}}\n\
@@ -509,12 +639,14 @@ async fn ravanan_artifacts(
             .iter()
             .find(|(name, _)| name == "store")
             .and_then(|(_, paths)| paths.first().cloned());
+        artifact_memo_save(&memo, &outputs);
         notes.push(
             "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \
              cluster), cached by ravanan on (script, inputs)"
                 .to_string(),
         );
         path
+        }
     } else {
         None
     };