about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr Prins <pjotr.public01@thebird.nl>2026-11-20 14:39:17 +0000
committerPjotr Prins <pjotr.public01@thebird.nl>2026-11-20 14:39:17 +0000
commit7863db3ff8b124c43211572987359e2d69d0951f (patch)
tree262415e83264fb4b70be6c19ac326f4b3d57e8fb /src
parenta621bb36303ad6c45fee88e9d3700abd36799a26 (diff)
downloadgenenetwork4-7863db3ff8b124c43211572987359e2d69d0951f.tar.gz
gemma: "engine": "pangemma" runs the same workflow on an lmdb store
The pangemma workflow (cwl/gemma/gemma-loco-mdb.scm, committed but until now
unreachable: nothing pointed at it) is now selected per request.  It differs
from its gemma twin in the genotype input only -- pangemma reads the
chromosome from the store's key, so it needs neither `-g` BIMBAM nor the `-a`
annotation -- so the two run the same kinship-then-GWA scatter and answer the
same question:

  gemma    21,055 rows in 4.1 s    af and l_mle identical to pangemma
  pangemma 21,055 rows in 3.9 s    beta/se/p_lrt median |d| 2.6e-4/3.6e-5/1.3e-4,
                                   max 1.2e-3/5.4e-4/6.2e-4

(trait 10001, BXD.8, lmm 9, warm; pangemma builds its GRM in float32, which is
where that third decimal goes -- verified against the store itself: Gf,
198 samples, 21,056 markers, 21,056 geno records.)  At BXD.8 size there is
nothing to win; on HLC the same 23 chromosomes cost 141 s of cluster job time
against 958 s for gemma on BIMBAM, which is the point of the engine.

Selection is a request field, defaulting to gemma, so no existing caller
changes:

- GemmaEngine::{Gemma,Pangemma} carries the workflow's input list and the
  compiled-CWL suffix as well as the parse aliases (gemma-gn2, pangemma-lmdb);
  an unknown value is 422 invalid_engine, not a silent gemma.
- check_workflow_inputs now takes the engine's own list, so a stale workflow
  is still refused by name -- the mdb workflow declares `store` where the
  gemma one declares `genotype_file` and `snps_file`, and handing it the
  wrong one fails deep inside cwltool as "expected File but got null".
- The store is built once per genotype file, not per trait, by geno2mdb.py
  (GENO2MDB_CMD) into GEMMA_LMDB_CACHE_DIR, keyed on the genotype file's
  path, size and mtime plus the annotation's contents.  Gf always: exact for
  a mean-genotype panel, where Gb is exact only for integer calls.  Written
  aside and renamed, so a concurrent identical request sees no store or a
  complete one; two first-runs both build it, which the rename makes
  harmless rather than wrong.  Measured: 22.3 s cold (store built), 3.9 s
  warm, and a second trait on the same panel reuses the store.
- There is no fallback for this engine.  The in-process runner is
  gemma-wrapper on BIMBAM, so falling back would answer a different question
  under the requested engine's name: pangemma forces the ravanan route even
  when GEMMA_ENGINE=local, and its failures are returned as they are.

Also fixed on the way: GemmaError::CommandFailed said "gemma-wrapper (<step>)
failed" for every step, which blamed the wrapper for geno2mdb and ccwl
compile; the step now names its own tool ("gemma-wrapper gwa failed",
"geno2mdb failed").

Deployment knobs (README and docs/ravanan-slurm.md updated):
GEMMA_RAVANAN_WORKFLOW_MDB, GEMMA_RAVANAN_MANIFEST_MDB (a manifest naming
pangemma-git -- a manifest change needs a cold run, since ravanan keys a step
on (script, inputs)), GENO2MDB_CMD and GEMMA_LMDB_CACHE_DIR.

Deployed and verified on the production instance: both engines answer 200 on
the same request through ravanan on Slurm, and bin/monitor-gn4 --tier all is
50 ok / 0 failed.  One deployment detail worth recording: geno2mdb.py needs
numpy and python-lmdb, which the store script's own shebang interpreter does
not have, so the server now runs with PYTHONPATH pointing at the profile's
site-packages -- without it the engine answers 502 "No module named 'numpy'".
Diffstat (limited to 'src')
-rw-r--r--src/config.rs60
-rw-r--r--src/gemma.rs436
-rw-r--r--src/routes/gemma.rs61
3 files changed, 508 insertions, 49 deletions
diff --git a/src/config.rs b/src/config.rs
index 7e4fa2c..849b30a 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -107,6 +107,28 @@ pub struct Config {
     /// the working directory the server is started from, same
     /// convention as `gemma_ravanan_workflow`.
     pub gemma_ravanan_manifest: String,
+    /// The pangemma twin of `gemma_ravanan_workflow`:
+    /// cwl/gemma/gemma-loco-mdb.scm, which reads genotypes from an lmdb
+    /// store instead of parsing BIMBAM, so its inputs are a single
+    /// `store` file where the gemma workflow takes `genotype_file` plus
+    /// `snps_file`.  Selected per request by `"engine": "pangemma"`
+    /// (see src/gemma.rs's `GemmaEngine`).  Set via
+    /// GEMMA_RAVANAN_WORKFLOW_MDB.
+    pub gemma_ravanan_workflow_mdb: String,
+    /// The manifest that workflow's steps resolve against, i.e. one
+    /// naming `pangemma-git` rather than `gemma-gn2`
+    /// (GEMMA_RAVANAN_MANIFEST_MDB).
+    pub gemma_ravanan_manifest_mdb: String,
+    /// The lmdb store builder `geno2mdb.py` (in gemma-wrapper's bin/,
+    /// which is not on PATH in every deployment): turns a BIMBAM
+    /// genotype file plus its annotation into the store pangemma reads.
+    /// Set via GENO2MDB_CMD.
+    pub geno2mdb_cmd: String,
+    /// Where those stores are kept, one file per genotype file
+    /// (`GEMMA_LMDB_CACHE_DIR`).  They are the expensive part of a
+    /// pangemma run -- built once, reused by every trait over the same
+    /// panel -- so a deployment must point this somewhere durable.
+    pub gemma_lmdb_cache_dir: String,
     /// Directory POST /compute/gemma/ravanan uses for phenotype files,
     /// run logs, and ravanan's own --store and --output-directory.
     /// Separate from `gemma_cache_dir` so the two runners don't share
@@ -327,6 +349,22 @@ impl Config {
             "cwl/gemma/manifest.scm".to_string(),
         );
         values.insert(
+            "GEMMA_RAVANAN_WORKFLOW_MDB".to_string(),
+            "cwl/gemma/gemma-loco-mdb.scm".to_string(),
+        );
+        values.insert(
+            "GEMMA_RAVANAN_MANIFEST_MDB".to_string(),
+            "cwl/gemma/manifest-mdb.scm".to_string(),
+        );
+        values.insert("GENO2MDB_CMD".to_string(), "geno2mdb.py".to_string());
+        values.insert(
+            "GEMMA_LMDB_CACHE_DIR".to_string(),
+            std::env::temp_dir()
+                .join("gn4-gemma-lmdb")
+                .to_string_lossy()
+                .into_owned(),
+        );
+        values.insert(
             "RAVANAN_CACHE_DIR".to_string(),
             std::env::temp_dir()
                 .join("gn4-gemma-ravanan")
@@ -506,6 +544,10 @@ impl Config {
             "RAVANAN_CMD",
             "CCWL_CMD",
             "GEMMA_RAVANAN_WORKFLOW",
+            "GEMMA_RAVANAN_WORKFLOW_MDB",
+            "GEMMA_RAVANAN_MANIFEST_MDB",
+            "GENO2MDB_CMD",
+            "GEMMA_LMDB_CACHE_DIR",
             "GEMMA_RAVANAN_MANIFEST",
             "RAVANAN_CACHE_DIR",
             "RAVANAN_BATCH_SYSTEM",
@@ -576,6 +618,10 @@ impl Config {
             ccwl_cmd: values["CCWL_CMD"].clone(),
             gemma_ravanan_workflow: values["GEMMA_RAVANAN_WORKFLOW"].clone(),
             gemma_ravanan_manifest: values["GEMMA_RAVANAN_MANIFEST"].clone(),
+            gemma_ravanan_workflow_mdb: values["GEMMA_RAVANAN_WORKFLOW_MDB"].clone(),
+            gemma_ravanan_manifest_mdb: values["GEMMA_RAVANAN_MANIFEST_MDB"].clone(),
+            geno2mdb_cmd: values["GENO2MDB_CMD"].clone(),
+            gemma_lmdb_cache_dir: values["GEMMA_LMDB_CACHE_DIR"].clone(),
             ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(),
             ravanan_batch: parse_ravanan_batch(&values),
             gemma_engine: values["GEMMA_ENGINE"].clone(),
@@ -862,6 +908,10 @@ mod tests {
             "RAVANAN_CMD",
             "CCWL_CMD",
             "GEMMA_RAVANAN_WORKFLOW",
+            "GEMMA_RAVANAN_WORKFLOW_MDB",
+            "GEMMA_RAVANAN_MANIFEST_MDB",
+            "GENO2MDB_CMD",
+            "GEMMA_LMDB_CACHE_DIR",
             "GEMMA_RAVANAN_MANIFEST",
             "RAVANAN_CACHE_DIR",
             "RAVANAN_BATCH_SYSTEM",
@@ -905,6 +955,16 @@ mod tests {
         assert_eq!(config.ccwl_cmd, "ccwl");
         assert_eq!(config.gemma_ravanan_workflow, "cwl/gemma/gemma-loco.scm");
         assert_eq!(config.gemma_ravanan_manifest, "cwl/gemma/manifest.scm");
+        assert_eq!(
+            config.gemma_ravanan_workflow_mdb,
+            "cwl/gemma/gemma-loco-mdb.scm"
+        );
+        assert_eq!(
+            config.gemma_ravanan_manifest_mdb,
+            "cwl/gemma/manifest-mdb.scm"
+        );
+        assert_eq!(config.geno2mdb_cmd, "geno2mdb.py");
+        assert!(config.gemma_lmdb_cache_dir.ends_with("gn4-gemma-lmdb"));
         assert!(config.ravanan_cache_dir.ends_with("gn4-gemma-ravanan"));
         assert_eq!(config.rqtl_wrapper_path, "scripts/rqtl_wrapper.R");
         assert!(config.rqtl_cache_dir.ends_with("gn4-rqtl"));
diff --git a/src/gemma.rs b/src/gemma.rs
index c502903..e9f6a60 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -13,7 +13,7 @@
 //! shared infrastructure; see `crate::streaming`.
 
 use std::io;
-use std::path::Path;
+use std::path::{Path, PathBuf};
 use std::process::Output;
 
 use serde_json::Value;
@@ -73,8 +73,12 @@ impl std::fmt::Display for GemmaError {
             GemmaError::Spawn { command, error } => {
                 write!(f, "failed to run {command}: {error}")
             }
+            // The step already names its tool: gemma-wrapper's own steps are
+            // prefixed, and the ones that are not its (geno2mdb, ccwl compile)
+            // would otherwise be blamed on the wrapper -- which is what a
+            // missing numpy in the store builder once looked like.
             GemmaError::CommandFailed { step, stderr } => {
-                write!(f, "gemma-wrapper ({step}) failed: {stderr}")
+                write!(f, "{step} failed: {stderr}")
             }
             GemmaError::WrapperError { step, detail } => {
                 write!(f, "gemma-wrapper ({step}) reported an error: {detail}")
@@ -744,7 +748,7 @@ async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Resu
     .map_err(GemmaError::Io)?;
     if !output.status.success() {
         return Err(GemmaError::CommandFailed {
-            step: "extract-archive",
+            step: "gemma-wrapper extract-archive",
             stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
         });
     }
@@ -991,7 +995,7 @@ pub async fn compute(
             .get("archive")
             .and_then(Value::as_str)
             .ok_or_else(|| GemmaError::WrapperError {
-                step: "gwa",
+                step: "gemma-wrapper gwa",
                 detail: "gemma-wrapper's response did not list an output archive".to_string(),
             })?;
         let extract_dir = Path::new(cache_dir).join(format!("{unique}-gwa-extract"));
@@ -1275,24 +1279,252 @@ fn chromosomes_from(contents: &str) -> Vec<String> {
     chromosomes
 }
 
+/// Which mapping engine the per-chromosome workflow runs.
+///
+/// The two are the same computation through the same CWL shape (kinship per
+/// chromosome, then GWA per chromosome) and differ only in what reads the
+/// genotypes: `gemma` parses BIMBAM text every invocation and needs the
+/// `-a` annotation to know which markers to leave out, while `pangemma`
+/// reads an lmdb store whose keys carry the chromosome, so it needs neither.
+/// The store is built once per panel (see [`lmdb_store`]) and is what makes
+/// pangemma cheaper at scale -- measured on HLC (358,454 markers): 141 s of
+/// cluster job time against 958 s for gemma on BIMBAM.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum GemmaEngine {
+    /// gemma-gn2 on BIMBAM: `-g` plus the `-a` annotation.
+    Gemma,
+    /// pangemma on an lmdb store: one `store` input, no BIMBAM parse, no `-a`.
+    Pangemma,
+}
+
+impl GemmaEngine {
+    /// Parse the request's `engine` value; `None` for anything unknown.
+    pub fn parse(value: &str) -> Option<GemmaEngine> {
+        match value.trim().to_ascii_lowercase().as_str() {
+            "gemma" | "gemma-gn2" => Some(GemmaEngine::Gemma),
+            "pangemma" | "pangemma-lmdb" => Some(GemmaEngine::Pangemma),
+            _ => None,
+        }
+    }
+
+    pub const fn as_str(self) -> &'static str {
+        match self {
+            GemmaEngine::Gemma => "gemma",
+            GemmaEngine::Pangemma => "pangemma",
+        }
+    }
+
+    /// The compiled-CWL suffix, so the two engines never share one artifact.
+    const fn cwl_suffix(self) -> &'static str {
+        match self {
+            GemmaEngine::Gemma => "gemma-loco",
+            GemmaEngine::Pangemma => "gemma-loco-mdb",
+        }
+    }
+
+    /// The inputs this engine's ccwl workflow declares, which is what the
+    /// pre-flight check in `check_workflow_inputs` compares against.
+    pub const fn workflow_inputs(self) -> &'static [&'static str] {
+        match self {
+            GemmaEngine::Gemma => &[
+                "genotype_file",
+                "pheno_file",
+                "kinship_pheno_file",
+                "snps_file",
+                "lmm",
+                "chromosomes",
+            ],
+            GemmaEngine::Pangemma => &[
+                "store",
+                "pheno_file",
+                "kinship_pheno_file",
+                "lmm",
+                "chromosomes",
+            ],
+        }
+    }
+}
+
+/// The per-chromosome workflow to run and the engine behind it: what a
+/// deployment pins in `GEMMA_RAVANAN_WORKFLOW`/`_MANIFEST` (gemma) and their
+/// `_MDB` twins (pangemma), plus what pangemma needs to build its store.
+pub struct RavananWorkflow<'a> {
+    pub engine: GemmaEngine,
+    /// The ccwl source compiled to CWL before every run.
+    pub source: &'a str,
+    /// The Guix manifest ravanan resolves the steps' commands against.
+    pub manifest: &'a str,
+    /// `geno2mdb.py`, used only by the pangemma engine.
+    pub geno2mdb: &'a str,
+    /// Where built lmdb stores live, one per genotype file.
+    pub lmdb_cache_dir: &'a str,
+}
+
+/// A key for one genotype file's lmdb store: path, size and mtime plus the
+/// annotation's contents and the store format.
+///
+/// Not the genotype *contents*: a 200 MB BIMBAM file is not hashed on every
+/// request (the same reason `kinship_input_key` uses path and size).  The
+/// mtime is what catches an in-place rewrite, which size alone would miss
+/// when a prepared file is regenerated with the same byte count.
+fn lmdb_store_key(genotype_file: &str, snps_file: &str) -> String {
+    let mut material = Vec::new();
+    material.extend_from_slice(genotype_file.as_bytes());
+    material.push(0);
+    if let Ok(metadata) = std::fs::metadata(genotype_file) {
+        material.extend_from_slice(&metadata.len().to_le_bytes());
+        if let Ok(modified) = metadata.modified() {
+            if let Ok(since) = modified.duration_since(std::time::UNIX_EPOCH) {
+                material.extend_from_slice(&since.as_nanos().to_le_bytes());
+            }
+        }
+    }
+    material.push(0);
+    if let Ok(snps) = std::fs::read(snps_file) {
+        material.extend_from_slice(&snps);
+    }
+    material.push(0);
+    // Gf: one float32 per sample, exact for a mean-genotype panel (0, 0.5, 1
+    // all fit).  Gb is 4x smaller but exact only for integer calls, where it
+    // would move p-values in the third decimal.
+    material.extend_from_slice(b"Gf");
+    sha16(&material)
+}
+
+/// Build (or reuse) the lmdb genotype store pangemma reads with `-g`.
+///
+/// One store per genotype file, not per trait: the store holds the panel's
+/// markers and samples, and pangemma does GEMMA's own per-marker
+/// mean-substitution at run time, so every trait over the panel shares it and
+/// a repeat request costs one `stat`.
+///
+/// Written aside and renamed, so a concurrent identical request sees either no
+/// store or a complete one; two simultaneous first-runs both build it, which
+/// the rename makes harmless rather than wrong.
+async fn lmdb_store(
+    cmd: &str,
+    cache_dir: &str,
+    genotype_file: &str,
+    snps_file: &str,
+) -> Result<(PathBuf, String), GemmaError> {
+    std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?;
+    let key = lmdb_store_key(genotype_file, snps_file);
+    let stem = Path::new(genotype_file)
+        .file_name()
+        .map(|name| name.to_string_lossy().into_owned())
+        .unwrap_or_else(|| "genotypes".to_string());
+    let store_path = Path::new(cache_dir).join(format!("{stem}-{key}.mdb"));
+    if store_path.is_file() {
+        return Ok((
+            store_path.clone(),
+            format!(
+                "pangemma's lmdb genotype store was already built ({})",
+                store_path.display()
+            ),
+        ));
+    }
+
+    let tmp_path = Path::new(cache_dir).join(format!(
+        "{stem}-{key}.tmp-{}.mdb",
+        std::process::id()
+    ));
+    let _ = std::fs::remove_file(&tmp_path);
+    let tmp_arg = tmp_path.to_string_lossy().into_owned();
+    let args = [
+        genotype_file,
+        "--snps",
+        snps_file,
+        "--format",
+        "Gf",
+        "--out",
+        tmp_arg.as_str(),
+    ];
+    let output = streaming::run_streaming(cmd, &args, None)
+        .await
+        .map_err(|error| GemmaError::Spawn {
+            command: cmd.to_string(),
+            error,
+        })?;
+    if !output.status.success() {
+        let _ = std::fs::remove_file(&tmp_path);
+        return Err(GemmaError::CommandFailed {
+            step: "geno2mdb",
+            stderr: format!(
+                "{}\n{}",
+                String::from_utf8_lossy(&output.stdout),
+                String::from_utf8_lossy(&output.stderr)
+            ),
+        });
+    }
+    std::fs::rename(&tmp_path, &store_path).map_err(GemmaError::Io)?;
+    // lmdb leaves a `<file>-lock` companion beside the temporary name.
+    let _ = std::fs::remove_file(tmp_path.with_extension("mdb-lock"));
+    Ok((
+        store_path.clone(),
+        format!(
+            "pangemma's lmdb genotype store was built from {genotype_file} ({})",
+            store_path.display()
+        ),
+    ))
+}
+
+/// The ravanan inputs YAML for one engine: same fields the workflow declares,
+/// and the store stands exactly where `genotype_file`/`snps_file` would.
+fn ravanan_inputs_yaml(
+    engine: GemmaEngine,
+    genotype_file: &str,
+    snps_file: &str,
+    store_path: Option<&Path>,
+    pheno_path: &Path,
+    kinship_pheno_path: &Path,
+    lmm: u8,
+    chromosomes_yaml: &str,
+) -> String {
+    match engine {
+        GemmaEngine::Gemma => format!(
+            "genotype_file: {{class: File, path: {genotype_file}}}\n\
+             pheno_file: {{class: File, path: {}}}\n\
+             kinship_pheno_file: {{class: File, path: {}}}\n\
+             snps_file: {{class: File, path: {snps_file}}}\n\
+             lmm: \"{lmm}\"\n\
+             chromosomes: [{chromosomes_yaml}]\n",
+            pheno_path.display(),
+            kinship_pheno_path.display(),
+        ),
+        GemmaEngine::Pangemma => format!(
+            "store: {{class: File, path: {}}}\n\
+             pheno_file: {{class: File, path: {}}}\n\
+             kinship_pheno_file: {{class: File, path: {}}}\n\
+             lmm: \"{lmm}\"\n\
+             chromosomes: [{chromosomes_yaml}]\n",
+            store_path
+                .map(|path| path.display().to_string())
+                .unwrap_or_default(),
+            pheno_path.display(),
+            kinship_pheno_path.display(),
+        ),
+    }
+}
+
 /// The same GEMMA `--loco` kinship-then-GWA computation as `compute`,
 /// but run via `ravanan` (https://github.com/vepiteski/ravanan) driving
 /// a CWL workflow compiled from the ccwl (https://ccwl.systemreboot.net/)
-/// source at `workflow_scm_path` (see `cwl/gemma/gemma-loco.scm`).
+/// source at `workflow.source` (see `cwl/gemma/gemma-loco.scm` and its
+/// pangemma twin `cwl/gemma/gemma-loco-mdb.scm`).
 ///
-/// This runner invokes **gemma itself**, one invocation per
-/// chromosome, relying on `-loco <chr>` being native to 0.98.6 for both
-/// `-gk` and `-lmm` -- where `compute` still drives gemma-wrapper. That
+/// This runner invokes **gemma itself** (or pangemma), one invocation per
+/// chromosome, relying on `-loco <chr>` being native to both for `-gk`
+/// and `-lmm` -- where `compute` still drives gemma-wrapper. That
 /// is deliberate: it is what makes the two endpoints comparable, the
 /// same computation through two stacks, and the day the numbers stop
 /// agreeing the difference is visible rather than assumed away.
-/// Backs `POST /compute/gemma/ravanan`.
+/// Backs `POST /compute/gemma/ravanan`, and is the engine behind
+/// `/compute/gemma` unless `GEMMA_ENGINE=local`.
 pub async fn compute_ravanan(
     ravanan_cmd: &str,
     batch: &crate::config::RavananBatch,
     ccwl_cmd: &str,
-    workflow_scm_path: &str,
-    manifest_path: &str,
+    workflow: &RavananWorkflow<'_>,
     cache_dir: &str,
     scratch_dir: &str,
     genotype_file: &str,
@@ -1312,9 +1544,12 @@ pub async fn compute_ravanan(
     // Two keys, not one: the kinship step is keyed on the *individual set*
     // only (see `kinship_input_key`), so a second trait over the same animals
     // reuses all twenty K matrices, and only the GWA step's inputs change.
+    let engine = workflow.engine;
+    let workflow_scm_path = workflow.source;
+    let manifest_path = workflow.manifest;
     let kinship_key = kinship_input_key(genotype_file, snps_file, trait_values, lmm);
     let trait_key = trait_input_key(&kinship_key, trait_values);
-    let workflow = workflow_key(workflow_scm_path);
+    let workflow_hash = workflow_key(workflow_scm_path);
 
     // A constant-valued phenotype file with the trait's missing-data pattern:
     // what the kinship step gets, so its files are the same for every trait
@@ -1340,13 +1575,14 @@ pub async fn compute_ravanan(
     // call (cheap: ccwl compile is pure macro expansion, no Guix build
     // involved) and never checked into the repo -- see the doc comment
     // on Config::gemma_ravanan_workflow.
+    let cwl_suffix = engine.cwl_suffix();
     let compiled_workflow_path =
-        Path::new(cache_dir).join(format!("{workflow}-gemma-loco.cwl"));
+        Path::new(cache_dir).join(format!("{workflow_hash}-{cwl_suffix}.cwl"));
     // Compile to a per-process path and rename: the compiled CWL is
     // deterministic, so two concurrent identical requests would otherwise
     // race on the same file.
-    let compiled_tmp =
-        Path::new(cache_dir).join(format!("{workflow}-gemma-loco.tmp-{}.cwl", std::process::id()));
+    let compiled_tmp = Path::new(cache_dir)
+        .join(format!("{workflow_hash}-{cwl_suffix}.tmp-{}.cwl", std::process::id()));
     let ccwl_output_arg = format!("--output={}", compiled_tmp.display());
     let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), workflow_scm_path];
     let ccwl_output = streaming::run_streaming(ccwl_cmd, &ccwl_args, None)
@@ -1364,17 +1600,7 @@ pub async fn compute_ravanan(
     std::fs::rename(&compiled_tmp, &compiled_workflow_path).map_err(GemmaError::Io)?;
     // Before anything is staged for ravanan: does the workflow in this
     // deployment's checkout take what this build is about to send it?
-    check_workflow_inputs(
-        &compiled_workflow_path,
-        &[
-            "genotype_file",
-            "pheno_file",
-            "kinship_pheno_file",
-            "snps_file",
-            "lmm",
-            "chromosomes",
-        ],
-    )?;
+    check_workflow_inputs(&compiled_workflow_path, engine.workflow_inputs())?;
     let compiled_workflow_arg = compiled_workflow_path.to_string_lossy().into_owned();
 
     let store_dir = Path::new(cache_dir).join("ravanan-store");
@@ -1395,23 +1621,37 @@ pub async fn compute_ravanan(
         .collect::<Vec<_>>()
         .join(", ");
 
+    // pangemma reads an lmdb store instead of BIMBAM plus its annotation, so
+    // that store has to exist before anything is staged -- and it is the one
+    // expensive input, built once per genotype file rather than per trait.
+    let (store_path, store_note) = match engine {
+        GemmaEngine::Gemma => (None, None),
+        GemmaEngine::Pangemma => {
+            let (path, note) = lmdb_store(
+                workflow.geno2mdb,
+                workflow.lmdb_cache_dir,
+                genotype_file,
+                snps_file,
+            )
+            .await?;
+            (Some(path), Some(note))
+        }
+    };
+
     let inputs_yaml_path = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.yaml"));
     let inputs_tmp =
         Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.tmp-{}.yaml", std::process::id()));
-    std::fs::write(
-        &inputs_tmp,
-        format!(
-            "genotype_file: {{class: File, path: {genotype_file}}}\n\
-             pheno_file: {{class: File, path: {}}}\n\
-             kinship_pheno_file: {{class: File, path: {}}}\n\
-             snps_file: {{class: File, path: {snps_file}}}\n\
-             lmm: \"{lmm}\"\n\
-             chromosomes: [{chromosomes_yaml}]\n",
-            pheno_path.display(),
-            kinship_pheno_path.display(),
-        ),
-    )
-    .map_err(GemmaError::Io)?;
+    let inputs_yaml = ravanan_inputs_yaml(
+        engine,
+        genotype_file,
+        snps_file,
+        store_path.as_deref(),
+        &pheno_path,
+        &kinship_pheno_path,
+        lmm,
+        &chromosomes_yaml,
+    );
+    std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?;
     std::fs::rename(&inputs_tmp, &inputs_yaml_path).map_err(GemmaError::Io)?;
 
     let store_arg = format!("--store={}", store_dir.display());
@@ -1448,11 +1688,25 @@ pub async fn compute_ravanan(
         args.join(" ")
     );
     let chromosomes_note = format!(
-        "Scattered gemma itself over {} chromosome(s) via CWL scatter, one \
+        "Scattered {} itself over {} chromosome(s) via CWL scatter, one \
          invocation per chromosome: {}",
+        engine.as_str(),
         chromosomes.len(),
         chromosomes.join(", "),
     );
+    // Which engine ran, and for pangemma where its genotypes came from: the
+    // two produce identical rows on the same input, so without this a reply
+    // cannot say which cost its caller what.
+    let engine_note = match (&store_note, engine) {
+        (Some(note), _) => Some(format!(
+            "Engine: {} (lmdb genotypes rather than BIMBAM): {note}",
+            engine.as_str()
+        )),
+        (None, GemmaEngine::Gemma) => None,
+        (None, GemmaEngine::Pangemma) => {
+            Some(format!("Engine: {}", engine.as_str()))
+        }
+    };
 
     let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref())
         .await
@@ -1513,6 +1767,9 @@ pub async fn compute_ravanan(
         chromosomes_note,
         format!("workflow: {workflow_scm_path} (compiled to {compiled_workflow_arg})"),
     ];
+    if let Some(note) = engine_note {
+        notes.push(note);
+    }
     notes.extend(ephemeral_note);
     if let Some(note) = variance_components_note(&components) {
         notes.push(note);
@@ -1867,10 +2124,7 @@ mod tests {
         let err = parse_wrapper_output("kinship", output).unwrap_err();
         assert!(matches!(
             err,
-            GemmaError::WrapperError {
-                step: "kinship",
-                ..
-            }
+            GemmaError::WrapperError { step: "kinship", .. }
         ));
         assert_eq!(
             err.to_string(),
@@ -2040,3 +2294,95 @@ FATAL ERROR: gemma-wrapper bailed out with pid 42 exit 130
         assert!(got.contains("bailed out"), "{got}");
     }
 }
+
+#[cfg(test)]
+mod engine_tests {
+    use super::*;
+
+    // ---- the two engines ----------------------------------------------------
+
+    #[test]
+    fn the_engines_parse_and_declare_their_own_inputs() {
+        assert_eq!(GemmaEngine::parse("pangemma"), Some(GemmaEngine::Pangemma));
+        assert_eq!(GemmaEngine::parse(" GEMMA "), Some(GemmaEngine::Gemma));
+        // Not an engine, and not silently gemma either.
+        assert_eq!(GemmaEngine::parse("gemma-wrapper"), None);
+        assert_eq!(GemmaEngine::parse(""), None);
+
+        let gemma = GemmaEngine::Gemma.workflow_inputs();
+        assert!(gemma.contains(&"genotype_file"));
+        assert!(gemma.contains(&"snps_file"));
+        let pangemma = GemmaEngine::Pangemma.workflow_inputs();
+        assert!(pangemma.contains(&"store"));
+        // The store replaces both BIMBAM inputs; a workflow declaring `store`
+        // cannot be handed them, which is what the pre-flight check enforces.
+        assert!(!pangemma.contains(&"genotype_file"));
+        assert!(!pangemma.contains(&"snps_file"));
+        assert_ne!(GemmaEngine::Gemma.cwl_suffix(), GemmaEngine::Pangemma.cwl_suffix());
+    }
+
+    /// The staged inputs file must name exactly what the compiled workflow
+    /// declares -- a workflow that wants `store` and is handed
+    /// `genotype_file` fails inside cwltool as "expected File but got null",
+    /// long after the request looked fine.
+    #[test]
+    fn the_inputs_yaml_names_the_workflows_own_fields() {
+        let pheno = Path::new("/c/1-pheno.txt");
+        let kin = Path::new("/c/1-kin-pheno.txt");
+        let gemma = ravanan_inputs_yaml(
+            GemmaEngine::Gemma,
+            "/g/BXD_geno.txt.gz",
+            "/g/BXD_snps.txt",
+            None,
+            pheno,
+            kin,
+            9,
+            "\"1\", \"2\"",
+        );
+        let pangemma = ravanan_inputs_yaml(
+            GemmaEngine::Pangemma,
+            "/g/BXD_geno.txt.gz",
+            "/g/BXD_snps.txt",
+            Some(Path::new("/s/BXD_geno.txt.gz-ab.mdb")),
+            pheno,
+            kin,
+            9,
+            "\"1\", \"2\"",
+        );
+        for field in GemmaEngine::Gemma.workflow_inputs() {
+            assert!(gemma.contains(&format!("{field}:")), "gemma lacks {field}");
+        }
+        for field in GemmaEngine::Pangemma.workflow_inputs() {
+            assert!(
+                pangemma.contains(&format!("{field}:")),
+                "pangemma lacks {field}"
+            );
+        }
+        assert!(gemma.contains("path: /g/BXD_geno.txt.gz"));
+        assert!(pangemma.contains("path: /s/BXD_geno.txt.gz-ab.mdb"));
+        assert!(!pangemma.contains("genotype_file"));
+        assert!(!pangemma.contains("snps_file"));
+    }
+
+    /// A store belongs to a genotype file, not to a trait: every trait over
+    /// the panel must reuse it, or the expensive half of a pangemma run is
+    /// paid again per request.  The annotation is part of the key because it
+    /// decides which markers and chromosomes the store holds.
+    #[test]
+    fn the_store_key_follows_the_genotype_file_and_annotation_only() {
+        let dir = std::env::temp_dir().join(format!("gn4-lmdbkey-{}", std::process::id()));
+        std::fs::create_dir_all(&dir).unwrap();
+        let geno = dir.join("G.txt");
+        let snps = dir.join("S.txt");
+        std::fs::write(&geno, "s1\ts2\nm1\t1\t1\t0\t2\n").unwrap();
+        std::fs::write(&snps, "m1 150 1\n").unwrap();
+        let geno_s = geno.to_string_lossy().into_owned();
+        let snps_s = snps.to_string_lossy().into_owned();
+
+        let first = lmdb_store_key(&geno_s, &snps_s);
+        assert_eq!(first, lmdb_store_key(&geno_s, &snps_s), "must be stable");
+        std::fs::write(&snps, "m1 150 2\n").unwrap();
+        assert_ne!(first, lmdb_store_key(&geno_s, &snps_s), "annotation counts");
+        let _ = std::fs::remove_dir_all(&dir);
+    }
+}
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index e0dc411..c36c1c2 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -133,6 +133,13 @@ pub struct GemmaRequest {
     /// `hmm` needs a group-scoped request, since the cross it predicts from is
     /// the group's.
     pub impute: Option<String>,
+    /// Which engine the per-chromosome workflow runs: `gemma` (default,
+    /// gemma-gn2 on BIMBAM) or `pangemma` (the GeneNetwork fork reading an
+    /// lmdb genotype store, built once per genotype file and reused by every
+    /// trait over that panel).  pangemma needs the ravanan/Slurm route and
+    /// has no in-process fallback, so a request for it fails rather than
+    /// silently mapping with gemma.
+    pub engine: Option<String>,
 }
 
 /// One trait value, by individual name.
@@ -584,8 +591,16 @@ pub async fn compute_gemma(
     // reason to fall back: that would hide a regression behind an answer from
     // the other engine.
     let engine_config = Config::load();
+    // pangemma has no in-process counterpart: the wrapper runs gemma on
+    // BIMBAM, so falling back would answer a different question under the
+    // requested engine's name.  It therefore forces the Slurm route even when
+    // GEMMA_ENGINE=local, and its failures are returned as they are.
+    let pangemma = matches!(
+        request.engine.as_deref(),
+        Some(value) if crate::gemma::GemmaEngine::parse(value) == Some(crate::gemma::GemmaEngine::Pangemma)
+    );
     let mut fallback_note: Option<String> = None;
-    if !engine_config.gemma_engine.eq_ignore_ascii_case("local") {
+    if pangemma || !engine_config.gemma_engine.eq_ignore_ascii_case("local") {
         match gemma_via_ravanan(
             ctx.clone(),
             token.clone(),
@@ -597,7 +612,7 @@ pub async fn compute_gemma(
         .await
         {
             Ok(answer) => return Ok(answer),
-            Err(error) if error.status >= 500 => {
+            Err(error) if error.status >= 500 && !pangemma => {
                 eprintln!(
                     "compute_gemma: slurm route failed ({} {}); falling back to the local gemma-wrapper run",
                     error.status, error.code
@@ -1308,6 +1323,24 @@ pub(crate) async fn gemma_via_ravanan(
     endpoint: &'static str,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
+    let engine = match request.engine.as_deref() {
+        None => crate::gemma::GemmaEngine::Gemma,
+        Some(value) => match crate::gemma::GemmaEngine::parse(value) {
+            Some(engine) => engine,
+            None => {
+                return Err(ApiError::new(
+                    StatusCode::UNPROCESSABLE_ENTITY,
+                    "invalid_engine",
+                    "Invalid engine",
+                    format!(
+                        "'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)."
+                    ),
+                    endpoint,
+                )
+                .with_request_id(rid))
+            }
+        },
+    };
     let lmm = request.lmm.unwrap_or(9);
     if !matches!(lmm, 1 | 2 | 3 | 4 | 9) {
         return Err(ApiError::new(
@@ -1475,12 +1508,32 @@ pub(crate) async fn gemma_via_ravanan(
     let job_rid = rid.clone();
     compute_gate::ravanan()
         .run(__gn4_claim, async move {
+            // The workflow pair follows the engine: gemma-gn2 on BIMBAM, or
+            // pangemma on an lmdb store, each with the manifest that resolves
+            // its own step commands.  Both are pinned by the deployment, so a
+            // checkout that lacks one fails here by name rather than producing
+            // a workflow that cannot find its binary.
+            let (workflow_source, manifest_source) = match engine {
+                gemma::GemmaEngine::Gemma => {
+                    (&config.gemma_ravanan_workflow, &config.gemma_ravanan_manifest)
+                }
+                gemma::GemmaEngine::Pangemma => (
+                    &config.gemma_ravanan_workflow_mdb,
+                    &config.gemma_ravanan_manifest_mdb,
+                ),
+            };
+            let ravanan_workflow = gemma::RavananWorkflow {
+                engine,
+                source: workflow_source,
+                manifest: manifest_source,
+                geno2mdb: &config.geno2mdb_cmd,
+                lmdb_cache_dir: &config.gemma_lmdb_cache_dir,
+            };
             gemma::compute_ravanan(
                 &config.ravanan_cmd,
                 &config.ravanan_batch,
                 &config.ccwl_cmd,
-                &config.gemma_ravanan_workflow,
-                &config.gemma_ravanan_manifest,
+                &ravanan_workflow,
                 &config.ravanan_cache_dir,
                 &config.ravanan_scratch,
                 &genotype_file,