diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/baskets.rs | 19 | ||||
| -rw-r--r-- | src/config.rs | 162 | ||||
| -rw-r--r-- | src/gemma.rs | 876 | ||||
| -rw-r--r-- | src/genotypes.rs | 112 | ||||
| -rw-r--r-- | src/json_errors.rs | 118 | ||||
| -rw-r--r-- | src/lib.rs | 100 | ||||
| -rw-r--r-- | src/listing.rs | 268 | ||||
| -rw-r--r-- | src/pca.rs | 90 | ||||
| -rw-r--r-- | src/qtl2.rs | 335 | ||||
| -rw-r--r-- | src/response.rs | 172 | ||||
| -rw-r--r-- | src/routes/baskets.rs | 19 | ||||
| -rw-r--r-- | src/routes/bnw.rs | 18 | ||||
| -rw-r--r-- | src/routes/bulklmm.rs | 18 | ||||
| -rw-r--r-- | src/routes/compare.rs | 290 | ||||
| -rw-r--r-- | src/routes/correlation.rs | 2 | ||||
| -rw-r--r-- | src/routes/correlation_matrix.rs | 80 | ||||
| -rw-r--r-- | src/routes/datasets.rs | 39 | ||||
| -rw-r--r-- | src/routes/fitqtl.rs | 20 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 1197 | ||||
| -rw-r--r-- | src/routes/genoupload.rs | 8 | ||||
| -rw-r--r-- | src/routes/groups.rs | 204 | ||||
| -rw-r--r-- | src/routes/matrices.rs | 8 | ||||
| -rw-r--r-- | src/routes/mod.rs | 1 | ||||
| -rw-r--r-- | src/routes/plot.rs | 15 | ||||
| -rw-r--r-- | src/routes/qtl2.rs | 31 | ||||
| -rw-r--r-- | src/routes/rqtl.rs | 40 | ||||
| -rw-r--r-- | src/routes/search.rs | 13 | ||||
| -rw-r--r-- | src/rqtl.rs | 65 | ||||
| -rw-r--r-- | src/runs.rs | 126 | ||||
| -rw-r--r-- | src/usage.rs | 333 |
30 files changed, 4366 insertions, 413 deletions
diff --git a/src/baskets.rs b/src/baskets.rs index c6410bf..54e2ce2 100644 --- a/src/baskets.rs +++ b/src/baskets.rs @@ -97,6 +97,10 @@ pub struct Version { /// Why a basket operation failed. #[derive(Debug)] pub enum BasketError { + /// The caller picked a name that is taken. Its own variant because it is a + /// conflict (409), not a malformed request (422): the body is fine, the + /// name is not free. + NameInUse(String), /// No basket with that name for this user. NotFound(String), /// The request could not be stored as asked (a bad name, a bad value). @@ -108,7 +112,10 @@ pub enum BasketError { impl std::fmt::Display for BasketError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - BasketError::NotFound(what) | BasketError::Invalid(what) | BasketError::Store(what) => { + BasketError::NotFound(what) + | BasketError::Invalid(what) + | BasketError::NameInUse(what) + | BasketError::Store(what) => { write!(f, "{what}") } } @@ -432,7 +439,7 @@ pub fn create( .optional() .map_err(|error| BasketError::Store(error.to_string()))?; if exists.is_some() { - return Err(BasketError::Invalid(format!( + return Err(BasketError::NameInUse(format!( "a basket named '{name}' already exists; PATCH it, or pick another name" ))); } @@ -582,9 +589,13 @@ pub fn get( }; let counts: (i64, i64) = connection .query_row( + // The current revision only: `cell` is keyed on (basket_id, + // revision, sample), so a PATCH leaves the previous revision's + // rows in place. Without this the reply counted every revision + // ever written -- 93 values reported as 186 after one PATCH. "SELECT COALESCE(SUM(status = 'ok'), 0), COALESCE(SUM(status = 'missing'), 0) \ - FROM cell WHERE basket_id = ?1", - params![id], + FROM cell WHERE basket_id = ?1 AND revision = ?2", + params![id, revision], |row| Ok((row.get(0)?, row.get(1)?)), ) .map_err(|error| BasketError::Store(error.to_string()))?; diff --git a/src/config.rs b/src/config.rs index c6a1553..e029969 100644 --- a/src/config.rs +++ b/src/config.rs @@ -107,6 +107,42 @@ 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 R script the `hmm` treatment runs (`IMPUTE_SCRIPT`, + /// scripts/qtl2-impute-bimbam.R), passed to the prepare workflow as a + /// staged input so a compute node needs nothing from the checkout. + pub impute_script: 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, + /// The workflow that applies the missing-genotype treatment + /// (`GEMMA_PREPARE_WORKFLOW`, cwl/gemma/prepare.scm): one cluster job + /// that writes the prepared BIMBAM pair, cached by ravanan on + /// (script, inputs) so the treatment runs once per (panel, mode). + pub gemma_prepare_workflow: String, + /// The workflow that builds pangemma's lmdb store + /// (`GEMMA_STORE_WORKFLOW`, cwl/gemma/store.scm), cached the same way + /// -- the store is the expensive artifact of a pangemma run (22 MB for + /// BXD.8, minutes for HLC), so it is built once per panel. + pub gemma_store_workflow: String, + /// The manifest those two workflows' jobs resolve their commands + /// against (`GEMMA_ARTIFACTS_MANIFEST`): bash, awk, R/qtl2, python, + /// numpy and lmdb -- a different toolchain from the mapping steps', + /// and ravanan builds one profile per workflow. + pub gemma_artifacts_manifest: 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 @@ -120,12 +156,28 @@ pub struct Config { /// through slurmrestd's REST API). Set via RAVANAN_BATCH_SYSTEM; /// see `RavananBatch` and docs/ravanan-slurm.md. pub ravanan_batch: RavananBatch, + /// Which engine POST /compute/gemma uses: `slurm` (the default) runs the + /// same per-chromosome workflow /compute/gemma/ravanan does, one job per + /// chromosome on the cluster, and falls back to the in-process + /// gemma-wrapper run when that path answers 5xx -- Slurm or ravanan + /// unreachable, or the engine exiting non-zero. `local` always uses the + /// wrapper. Set via GEMMA_ENGINE. + /// + /// Slurm is the default because the workflow's results are keyed on + /// (script, inputs) -- the K matrix is one of the inputs -- while the + /// wrapper's GWA cache is keyed on the phenotype alone, so a rebuilt K + /// could leave stale association rows behind (measured: 2,060 of 21,055 + /// rows differed until that cache entry was cleared). + pub gemma_engine: String, /// Directory ravanan stages job scratch space in (its own --scratch /// switch). Only meaningful for the slurm backend, where it must be /// a path every compute node can write; defaults to /// `ravanan_cache_dir` when the backend is slurm. Empty means "do /// not pass --scratch" (single-machine's own default). pub ravanan_scratch: String, + /// The script that materialises a genotype file for a given + /// missing-data treatment (`PREPARE_GENOTYPES`). + pub prepare_genotypes: String, /// Path to scripts/rqtl_wrapper.R (copied here from GeneNetwork3) /// for POST /compute/rqtl. Defaults to that path relative to the /// working directory the server is started from. @@ -136,6 +188,9 @@ pub struct Config { pub fitqtl_script_path: String, /// Path to scripts/qtl2_scan.R, which POST /compute/qtl2 runs. pub qtl2_script_path: String, + /// The `.geno` -> qtl2-cross conversion, an R script (`Qt l2` owns its + /// own file format; see `src/qtl2.rs`). + pub qtl2_convert_script: String, /// Directory POST /compute/qtl2 keeps converted crosses and scan /// output in. Defaults to a "gn4-qtl2" directory under the temp dir. pub qtl2_cache_dir: String, @@ -175,6 +230,8 @@ pub struct Config { pub pca_plotter: String, /// Script that draws the clustered heatmap of a correlation matrix (HEATMAP_PLOTTER). pub heatmap_plotter: String, + /// Script that draws the scatter plot of a two-trait comparison (COMPARE_PLOTTER). + pub compare_plotter: String, /// Directory holding BNW's worked example datasets (`BNW_EXAMPLES_DIR`), /// served by `/compute/bnw/examples`. Empty means the endpoint reports /// that no examples are configured. @@ -285,6 +342,9 @@ impl Config { values.insert("SEARCH_ENGINE".to_string(), "forward".to_string()); values.insert("GN4_API_TOKENS_DB".to_string(), "tokens.sqlite".to_string()); values.insert("GEMMA_WRAPPER_CMD".to_string(), "gemma-wrapper".to_string()); + // Slurm by default: the per-chromosome workflow is the one whose + // results cannot go stale, and the local wrapper is the fallback. + values.insert("GEMMA_ENGINE".to_string(), "slurm".to_string()); values.insert( "GEMMA_CACHE_DIR".to_string(), std::env::temp_dir() @@ -303,6 +363,31 @@ 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( + "IMPUTE_SCRIPT".to_string(), + "scripts/qtl2-impute-bimbam.R".to_string(), + ); + values.insert("GENO2MDB_CMD".to_string(), "geno2mdb.py".to_string()); + values.insert( + "GEMMA_PREPARE_WORKFLOW".to_string(), + "cwl/gemma/prepare.scm".to_string(), + ); + values.insert( + "GEMMA_STORE_WORKFLOW".to_string(), + "cwl/gemma/store.scm".to_string(), + ); + values.insert( + "GEMMA_ARTIFACTS_MANIFEST".to_string(), + "cwl/gemma/manifest-artifacts.scm".to_string(), + ); + values.insert( "RAVANAN_CACHE_DIR".to_string(), std::env::temp_dir() .join("gn4-gemma-ravanan") @@ -313,6 +398,12 @@ impl Config { "RAVANAN_BATCH_SYSTEM".to_string(), "single-machine".to_string(), ); + // The one place where "how is a missing genotype treated?" is decided + // (`scripts/prepare-genotypes.sh`): mode none, mean or hmm. + values.insert( + "PREPARE_GENOTYPES".to_string(), + "scripts/prepare-genotypes.sh".to_string(), + ); // Only read when RAVANAN_BATCH_SYSTEM=slurm-api; left blank so // the single-machine default stays a zero-configuration path. values.insert("RAVANAN_SLURM_API_ENDPOINT".to_string(), String::new()); @@ -333,6 +424,10 @@ impl Config { "scripts/qtl2_scan.R".to_string(), ); values.insert( + "QTL2_CONVERT_SCRIPT".to_string(), + "scripts/qtl2-convert-geno.R".to_string(), + ); + values.insert( "QTL2_CACHE_DIR".to_string(), std::env::temp_dir() .join("gn4-qtl2") @@ -419,6 +514,10 @@ impl Config { "HEATMAP_PLOTTER".to_string(), "scripts/plot-heatmap.py".to_string(), ); + values.insert( + "COMPARE_PLOTTER".to_string(), + "scripts/plot-compare.py".to_string(), + ); // Per-user baskets: one SQLite file each (src/baskets.rs). Never // MariaDB -- a user's edited column is theirs. values.insert( @@ -464,9 +563,17 @@ impl Config { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", + "GENO2MDB_CMD", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -478,6 +585,7 @@ impl Config { "RQTL_WRAPPER_PATH", "FITQTL_SCRIPT_PATH", "QTL2_SCRIPT_PATH", + "QTL2_CONVERT_SCRIPT", "QTL2_CACHE_DIR", "RQTL_CACHE_DIR", "WIKIDATA_CACHE_DIR", @@ -487,6 +595,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -535,12 +644,40 @@ 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(), + impute_script: values["IMPUTE_SCRIPT"].clone(), + geno2mdb_cmd: values["GENO2MDB_CMD"].clone(), + gemma_prepare_workflow: values["GEMMA_PREPARE_WORKFLOW"].clone(), + gemma_store_workflow: values["GEMMA_STORE_WORKFLOW"].clone(), + gemma_artifacts_manifest: values["GEMMA_ARTIFACTS_MANIFEST"].clone(), ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), + gemma_engine: values["GEMMA_ENGINE"].clone(), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), + prepare_genotypes: { + // A relative default is fine when the server runs from its + // checkout, and silently fatal when it does not (measured: an + // instance started elsewhere answered "could not run + // scripts/prepare-genotypes.sh"). The workflow path already + // points into that checkout, so it is used to locate the + // scripts directory when the relative name does not resolve. + let configured = values["PREPARE_GENOTYPES"].clone(); + let path = std::path::Path::new(&configured); + if path.is_absolute() || path.exists() { + configured + } else { + let workflow = std::path::Path::new(&values["GEMMA_RAVANAN_WORKFLOW"]); + match workflow.parent().and_then(|cwl| cwl.parent()).and_then(|repo| repo.parent()) { + Some(repo) => repo.join(&configured).to_string_lossy().into_owned(), + None => configured, + } + } + }, rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(), + qtl2_convert_script: values["QTL2_CONVERT_SCRIPT"].clone(), qtl2_cache_dir: values["QTL2_CACHE_DIR"].clone(), rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), wikidata_cache_dir: values["WIKIDATA_CACHE_DIR"].clone(), @@ -554,6 +691,7 @@ impl Config { bnw_plotter: values["BNW_PLOTTER"].clone(), pca_plotter: values["PCA_PLOTTER"].clone(), heatmap_plotter: values["HEATMAP_PLOTTER"].clone(), + compare_plotter: values["COMPARE_PLOTTER"].clone(), bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(), bulklmm_cmd: values["BULKLMM_CMD"].clone(), bulklmm_env: values["BULKLMM_ENV"].clone(), @@ -795,9 +933,17 @@ mod tests { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", + "GENO2MDB_CMD", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -841,6 +987,22 @@ 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.impute_script, "scripts/qtl2-impute-bimbam.R"); + assert_eq!(config.geno2mdb_cmd, "geno2mdb.py"); + assert_eq!(config.gemma_prepare_workflow, "cwl/gemma/prepare.scm"); + assert_eq!(config.gemma_store_workflow, "cwl/gemma/store.scm"); + assert_eq!( + config.gemma_artifacts_manifest, + "cwl/gemma/manifest-artifacts.scm" + ); 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 02a2456..c49446f 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 @@ -73,8 +74,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 +749,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(), }); } @@ -786,6 +791,279 @@ 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> { + 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") { + 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; + } + } + } + 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 +/// 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) +} + +/// 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. +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 @@ -991,7 +1269,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")); @@ -1012,6 +1290,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; @@ -1033,10 +1317,23 @@ pub async fn compute( /// `{"<output id>": [{"class": "File", "path": ..., ...}, ...], ...}`, /// one entry per `cwl/gemma/gemma-loco.scm` chromosome). fn ravanan_output_paths<'a>(outputs: &'a Value, id: &str) -> Result<Vec<&'a str>, GemmaError> { - let files = outputs - .get(id) - .and_then(Value::as_array) - .ok_or_else(|| GemmaError::RavananOutput(format!("no \"{id}\" array in ravanan's output")))?; + let Some(value) = outputs.get(id) else { + return Err(GemmaError::RavananOutput(format!( + "no \"{id}\" in ravanan's output" + ))); + }; + // A scattered step's output is an array of Files; a single-step workflow's + // is one File object. Both are outputs here -- the mapping workflows + // scatter over chromosomes, the artifact ones (prepare, store) do not. + let files: Vec<&Value> = match value { + Value::Array(items) => items.iter().collect(), + Value::Object(_) => vec![value], + _ => { + return Err(GemmaError::RavananOutput(format!( + "\"{id}\" in ravanan's output is neither a File nor an array of them" + ))) + } + }; files .iter() .map(|file| { @@ -1181,7 +1478,7 @@ fn check_workflow_inputs(compiled_path: &Path, supplied: &[&str]) -> Result<(), /// file, interned verbatim into ravanan's store). The SNP file is hashed, /// because the chromosome list -- and therefore the whole scatter -- comes /// from it. -fn sha16(material: &[u8]) -> String { +pub fn sha16(material: &[u8]) -> String { crate::indexer::sha256::hex_digest(material)[..16].to_string() } @@ -1255,8 +1552,18 @@ fn trait_input_key(kinship_key: &str, trait_values: &TraitValues) -> String { fn chromosomes_from(contents: &str) -> Vec<String> { let mut seen = std::collections::HashSet::new(); let mut chromosomes = Vec::new(); + // The SNP map is `marker, pos, chr` in the panel's own files (spaces after + // the commas) and `marker,pos,chr` in the ones scripts/qtl2-impute-bimbam.R + // writes. Splitting on whitespace alone read the second form as one token + // and returned no chromosomes at all, which reaches ravanan as an empty + // scatter and comes back as "no association output files" -- a genotype + // problem that was really a delimiter problem. for line in contents.lines() { - if let Some(chr) = line.split_whitespace().nth(2) { + let fields: Vec<&str> = line + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|field| !field.is_empty()) + .collect(); + if let Some(chr) = fields.get(2) { if seen.insert(chr.to_string()) { chromosomes.push(chr.to_string()); } @@ -1265,24 +1572,307 @@ 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 cwl/gemma/store.scm) 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). +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, +} + +/// A note's worth of text with absolute paths reduced to their file names. +/// +/// A reply is read in chats and pasted into repositories; the server's own +/// `/gnu/store/...` and `/home/wrk/...` paths are implementation detail, and +/// they were reaching callers through the ravanan command line. The name is +/// kept -- which ravanan, which workflow, which store -- and only the +/// directory is dropped. +pub fn redact_paths(text: &str) -> String { + /// The file name of an absolute path, so "which tool, which file" survives + /// the redaction and only the directory goes. + fn short(path: &str) -> String { + Path::new(path) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.to_string()) + } + text.split_whitespace() + .map(|token| { + // A wrapper around a path: "ravanan (/gnu/store/...-ravanan", + // "(/home/wrk/...)", "--store=/home/wrk/...". + let is_edge = |c: char| matches!(c, ',' | ';' | ')' | '(' | '[' | ']' | '"' | '\''); + let inner = token.trim_matches(is_edge); + if let Some((flag, value)) = inner.split_once('=') { + if value.starts_with('/') { + return token.replace(inner, &format!("{flag}={}", short(value))); + } + } + if inner.starts_with('/') { + return token.replace(inner, &short(inner)); + } + token.to_string() + }) + .collect::<Vec<_>>() + .join(" ") +} + +/// What running an artifact workflow needs: the ccwl source, the manifest its +/// jobs resolve against, ravanan's own switches, and the outputs wanted. +/// +/// The two artifacts -- the missing-genotype treatment (`prepare.scm`) and +/// pangemma's lmdb store (`store.scm`) -- are workflows of their own rather +/// than steps inside the mapping workflows, because ccwl's `pipe` is linear: +/// the GWA step needs the prepared genotypes *and* the kinship matrix, and a +/// step sees only the immediately preceding step's outputs. Chaining +/// workflows is what that diamond becomes; ravanan caches each of them on +/// (script, inputs), so each artifact is still built once. +pub struct ArtifactWorkflow<'a> { + /// "prepare" or "store", for the compiled artifact's name and for errors. + pub label: &'a str, + pub ccwl_cmd: &'a str, + pub ravanan_cmd: &'a str, + pub batch: &'a crate::config::RavananBatch, + pub source: &'a str, + pub manifest: &'a str, + pub cache_dir: &'a str, + pub scratch_dir: &'a str, +} + +/// Run one artifact workflow and return its outputs by id. +/// +/// The inputs YAML's own hash names the staged file, so two concurrent +/// identical requests share one and different ones cannot collide -- the same +/// convention the mapping workflow uses for its phenotype files. +pub async fn run_artifact( + run: &ArtifactWorkflow<'_>, + supplied: &[&str], + inputs_yaml: &str, + output_ids: &[&str], +) -> Result<Vec<(String, Vec<String>)>, GemmaError> { + std::fs::create_dir_all(run.cache_dir).map_err(GemmaError::Io)?; + let workflow = workflow_key(run.source); + let compiled_path = Path::new(run.cache_dir).join(format!("{workflow}-{}.cwl", run.label)); + let compiled_tmp = Path::new(run.cache_dir) + .join(format!("{workflow}-{}.tmp-{}.cwl", run.label, std::process::id())); + let ccwl_output_arg = format!("--output={}", compiled_tmp.display()); + let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), run.source]; + let ccwl_output = streaming::run_streaming(run.ccwl_cmd, &ccwl_args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ccwl_cmd.to_string(), + error, + })?; + if !ccwl_output.status.success() { + return Err(GemmaError::CommandFailed { + step: "ccwl compile", + stderr: String::from_utf8_lossy(&ccwl_output.stderr).into_owned(), + }); + } + std::fs::rename(&compiled_tmp, &compiled_path).map_err(GemmaError::Io)?; + check_workflow_inputs(&compiled_path, supplied)?; + + let key = sha16(inputs_yaml.as_bytes()); + let inputs_path = + Path::new(run.cache_dir).join(format!("{key}-{}-inputs.yaml", run.label)); + if !inputs_path.is_file() { + let inputs_tmp = Path::new(run.cache_dir).join(format!( + "{key}-{}-inputs.tmp-{}.yaml", + run.label, + std::process::id() + )); + std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?; + std::fs::rename(&inputs_tmp, &inputs_path).map_err(GemmaError::Io)?; + } + + let store_dir = Path::new(run.cache_dir).join("ravanan-store"); + for subdir in ["files", "logs", "data"] { + std::fs::create_dir_all(store_dir.join(subdir)).map_err(GemmaError::Io)?; + } + let scratch = if run.scratch_dir.is_empty() { + run.cache_dir + } else { + run.scratch_dir + }; + let store_arg = format!("--store={}", store_dir.display()); + let manifest_arg = format!("--guix-manifest={}", run.manifest); + let compiled_arg = compiled_path.to_string_lossy().into_owned(); + let inputs_arg = inputs_path.to_string_lossy().into_owned(); + let mut args = vec![ + store_arg.as_str(), + manifest_arg.as_str(), + compiled_arg.as_str(), + inputs_arg.as_str(), + ]; + let batch_args = run.batch.ravanan_args(scratch); + args.extend(batch_args.iter().map(String::as_str)); + // GUIX_PACKAGE_PATH stays set. Clearing it saves ~4 s of Guile per + // artifact call (guix autoloads guix-bioinformatics' module tree, one ABI + // mismatch warning per module) -- but a manifest may name a package that + // only exists in the channel, which is exactly what happened when the store + // step moved to gemma-wrapper's geno2mdb: with the variable cleared the + // job died with "gemma-wrapper: unknown package" before a single marker was + // read. Correctness over four seconds, and the artifact memo means most + // requests never pay it at all. + let output = streaming::run_streaming(run.ravanan_cmd, &args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ravanan_cmd.to_string(), + error, + })?; + if !output.status.success() { + return Err(GemmaError::RavananFailed(format!( + "{} ({})", + run.label, + String::from_utf8_lossy(&output.stderr) + ))); + } + let outputs: Value = serde_json::from_str(&String::from_utf8_lossy(&output.stdout)) + .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?; + let mut found = Vec::new(); + for id in output_ids { + let paths = ravanan_output_paths(&outputs, id)?; + if paths.is_empty() { + return Err(GemmaError::WrapperError { + step: "artifact workflow", + detail: format!("{} produced no '{id}'", run.label), + }); + } + found.push((id.to_string(), paths.into_iter().map(str::to_string).collect())); + } + Ok(found) +} + +/// 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<'_>, + // 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, @@ -1302,9 +1892,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 @@ -1330,13 +1923,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) @@ -1354,17 +1948,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"); @@ -1385,23 +1969,28 @@ pub async fn compute_ravanan( .collect::<Vec<_>>() .join(", "); + // pangemma reads an lmdb store instead of BIMBAM plus its annotation; the + // caller has already had it built (cwl/gemma/store.scm), and ravanan's + // store holds it, so this is just the path. + let store_path = store.map(Path::new); + let store_note = store_path.map(|path| { + redact_paths(&format!("pangemma's lmdb genotype store: {}", path.display())) + }); + 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, + &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()); @@ -1429,27 +2018,41 @@ pub async fn compute_ravanan( ]; let batch_args = batch.ravanan_args(scratch); args.extend(batch_args.iter().map(String::as_str)); - let ravanan_note = format!( + let ravanan_note = redact_paths(&format!( "ravanan ({ravanan_cmd}, {} backend): {}", match batch { crate::config::RavananBatch::SingleMachine => "single-machine", crate::config::RavananBatch::SlurmApi { .. } => "slurm-api", }, 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: {} reads its genotypes from an lmdb store rather than BIMBAM ({note})", + engine.as_str() + )), + (None, GemmaEngine::Pangemma) => None, + (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(), @@ -1459,6 +2062,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); } @@ -1466,6 +2070,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 { @@ -1476,9 +2081,48 @@ 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, + )); + // 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(""))) + }); streaming::mark_complete(&log_path); @@ -1501,8 +2145,13 @@ pub async fn compute_ravanan( let mut notes = vec![ ravanan_note, chromosomes_note, - format!("workflow: {workflow_scm_path} (compiled to {compiled_workflow_arg})"), + redact_paths(&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); @@ -1513,6 +2162,9 @@ pub async fn compute_ravanan( columns, rows: Value::Array(rows), notes, + steps, + workflow_ms, + parse_ms, }) } @@ -1857,10 +2509,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(), @@ -2030,3 +2679,124 @@ 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")); + } + + /// ravanan reports a scattered step's output as an array of Files and a + /// single-step workflow's as one File. Both arrive here: the mapping + /// workflows scatter, the artifact ones (prepare, store) do not, and a + /// single-output workflow answering "no store array" is how this was found. + #[test] + fn ravanan_outputs_may_be_one_file_or_an_array() { + let one: Value = serde_json::from_str( + r#"{"store":{"class":"File","path":"/s/genotypes.mdb"}}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&one, "store").unwrap(), + vec!["/s/genotypes.mdb"] + ); + + let many: Value = serde_json::from_str( + r#"{"assoc":[{"class":"File","path":"/s/1-gwa.assoc.txt"}, + {"class":"File","path":"/s/2-gwa.assoc.txt"}]}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&many, "assoc").unwrap(), + vec!["/s/1-gwa.assoc.txt", "/s/2-gwa.assoc.txt"] + ); + assert!(ravanan_output_paths(&many, "store").is_err()); + } +} + +#[cfg(test)] +mod redact_tests { + use super::redact_paths; + + /// A reply is pasted into chats and repositories; no note may carry the + /// server's own paths (measured on the release service: the ravanan command + /// line, with `/gnu/store/...-ravanan` and `/home/wrk/...`, reached + /// callers). + #[test] + fn redact_paths_leaves_no_absolute_path() { + let note = redact_paths( + "ravanan (/gnu/store/8b2iq-ravanan-0.2.0/bin/ravanan, slurm-api backend): \ + --store=/home/wrk/tmp/ai-root/slurm-share/gn4-ravanan-cache/ravanan-store \ + --guix-manifest=/home/wrk/x/manifest.scm cwl/gemma/store.cwl", + ); + assert!(!note.contains("/gnu/store"), "{note}"); + assert!(!note.contains("/home/"), "{note}"); + // The names stay: which ravanan, which manifest, which workflow. + assert!(note.contains("ravanan"), "{note}"); + assert!(note.contains("manifest.scm"), "{note}"); + assert!(note.contains("store.cwl"), "{note}"); + } +} diff --git a/src/genotypes.rs b/src/genotypes.rs index 0d6c1c2..2948b28 100644 --- a/src/genotypes.rs +++ b/src/genotypes.rs @@ -159,13 +159,28 @@ pub fn resolve_named(root: &Path, requested: &str) -> Result<PathBuf, GenotypeEr ))) } +/// File contents as text, tolerating bytes that are not UTF-8. +/// +/// Real GeneNetwork exports carry latin-1 in their header comments (At-Serin's +/// says "Bay-0 \xd7 Shahdara"), and `read_to_string` failing on one byte hides +/// the whole panel with "stream did not contain valid UTF-8". Nothing here +/// parses the comments; the data lines are ASCII. +pub fn read_text_lossy(path: &Path) -> std::io::Result<String> { + Ok(String::from_utf8_lossy(&std::fs::read(path)?).into_owned()) +} + +fn read_text(path: &Path) -> Result<String, GenotypeError> { + let bytes = std::fs::read(path).map_err(|e| io_err(path, e))?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + fn io_err(path: &Path, error: std::io::Error) -> GenotypeError { GenotypeError::Io(format!("{}: {error}", path.display())) } /// The `.geno` header's sample names, in column order (GN3's rule). pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; for line in text.lines() { let line = line.trim_end_matches(['\r', '\n']); if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { @@ -191,7 +206,7 @@ pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> { /// Number of marker rows in a `.geno` (every non-comment line but the /// header). pub fn marker_count(geno: &Path) -> Result<usize, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut seen_header = false; let mut markers = 0; for line in text.lines() { @@ -267,7 +282,7 @@ fn json_versions( if !path.is_file() { return Ok(None); } - let text = std::fs::read_to_string(&path).map_err(|e| io_err(&path, e))?; + let text = read_text(&path)?; let document: serde_json::Value = serde_json::from_str(&text) .map_err(|e| GenotypeError::Io(format!("{}: {e}", path.display())))?; let Some(entries) = document.get("genofile").and_then(|v| v.as_array()) else { @@ -519,7 +534,7 @@ pub struct ParentalDesign { /// The roles a group's metadata declares, or `None` when the group is unlisted. fn design_roles(dir: &Path, group: &str) -> Option<(Vec<DesignRole>, Option<DesignRole>, Option<DesignRole>)> { let path = dir.join("parents_and_f1s.json"); - let text = std::fs::read_to_string(&path).ok()?; + let text = read_text(&path).ok()?; let document: serde_json::Value = serde_json::from_str(&text).ok()?; let entry = document.get(group)?; let role = |key: &str| { @@ -667,7 +682,7 @@ pub struct FileMeta { /// Read a `.geno`'s metadata: labels, individuals, marker positions. The /// genotype calls themselves are read and discarded, never returned. pub fn file_meta(geno: &Path) -> Result<FileMeta, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut labels = Vec::new(); let mut individuals = Vec::new(); let mut markers = Vec::new(); @@ -763,7 +778,7 @@ pub fn prepare( markers_dropped: 0, }); } - let path = subset_path(cache_dir, &resolved.version, keep, "geno")?; + let path = subset_path(cache_dir, &resolved.version, keep, "geno", &resolved.geno)?; if !path.is_file() { write_subset_geno(&resolved.geno, keep, &path)?; } @@ -792,16 +807,16 @@ pub fn prepare( let (panel_file, individuals) = if all_kept { (geno.clone(), resolved.panel.len()) } else { - let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt")?; + let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt", &geno)?; if !path.is_file() { write_subset_bimbam(&geno, keep, &path)?; } (path, keep.len()) }; let filtered_geno = - subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt")?; + subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt", &snps)?; let filtered_snps = - subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt")?; + subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt", &snps)?; if !filtered_geno.is_file() || !filtered_snps.is_file() { let written = drop_degenerate_chromosomes(&panel_file, &snps, &filtered_geno, &filtered_snps)?; @@ -861,7 +876,7 @@ fn drop_degenerate_chromosomes( out_geno: &Path, out_snps: &Path, ) -> Result<usize, GenotypeError> { - let snps_text = std::fs::read_to_string(snps).map_err(|e| io_err(snps, e))?; + let snps_text = read_text(snps)?; let mut keep_row: Vec<bool> = Vec::new(); let mut kept_snps = String::with_capacity(snps_text.len()); for line in snps_text.lines() { @@ -886,7 +901,7 @@ fn drop_degenerate_chromosomes( if dropped == 0 { return Ok(0); } - let geno_text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let geno_text = read_text(geno)?; let mut kept_geno = String::with_capacity(geno_text.len()); for (index, line) in geno_text.lines().enumerate() { if line.trim().is_empty() { @@ -904,18 +919,42 @@ fn drop_degenerate_chromosomes( /// Non-empty lines in a file (the marker count of a snps annotation). fn count_lines(path: &Path) -> Result<usize, GenotypeError> { - Ok(std::fs::read_to_string(path) - .map_err(|e| io_err(path, e))? + Ok(read_text(path)? .lines() .filter(|line| !line.trim().is_empty()) .count()) } +/// `size-mtime` of a panel file: the part of a cache key that notices a file +/// being replaced in place. +/// +/// The subset/noY pair is derived from the genotypes, so its key has to cover +/// them. It did not -- it hashed the kept *indices* only -- which meant an +/// updated `<stem>.geno` (or BIMBAM) kept serving the previous prepared pair +/// for as long as the individual set was unchanged. `prepare_cross` has always +/// keyed on this stamp; now the subset does too. +fn source_stamp(path: &Path) -> String { + match std::fs::metadata(path) { + Ok(metadata) => format!( + "{}-{}", + metadata.len(), + metadata + .modified() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|since| since.as_secs()) + .unwrap_or(0) + ), + Err(_) => "unknown".to_string(), + } +} + fn subset_path( cache_dir: &Path, version: &str, keep: &[usize], suffix: &str, + source: &Path, ) -> Result<PathBuf, GenotypeError> { let dir = cache_dir.join("prepared"); std::fs::create_dir_all(&dir).map_err(|e| io_err(&dir, e))?; @@ -923,11 +962,14 @@ fn subset_path( for index in keep { hash = (hash ^ *index as u64).wrapping_mul(1099511628211); } + for byte in source_stamp(source).bytes() { + hash = (hash ^ byte as u64).wrapping_mul(1099511628211); + } Ok(dir.join(format!("{version}-{hash:016x}-{suffix}"))) } fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut result = String::with_capacity(text.len()); let mut seen_header = false; for line in text.lines() { @@ -964,7 +1006,7 @@ fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), Geno } fn write_subset_bimbam(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut result = String::with_capacity(text.len()); for line in text.lines() { let trimmed = line.trim_end_matches('\r'); @@ -1351,7 +1393,7 @@ mod tests { /// the file cannot be read (the caller then proceeds as before rather than /// refusing the run). pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> { - let text = std::fs::read_to_string(geno).ok()?; + let text = read_text(geno).ok()?; let mut mask: Option<Vec<bool>> = None; for line in text.lines() { let line = line.trim(); @@ -1379,6 +1421,44 @@ pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> { mask } +/// The `.geno` that carries the individual names for a BIMBAM file. +/// +/// BIMBAM has no names: its columns are positional. A request that names its +/// values ("samples", or a basket) therefore cannot be aligned against the +/// BIMBAM it asks to map -- and until this, the file branch tried anyway, read +/// the BIMBAM as if it were a `.geno`, found no header, and answered 422 +/// "no mapping inputs" with every value dropped (measured on At-Serin). +/// +/// The deployment keeps the two side by side under a shared stem +/// (`genotype/<stem>.geno` and `genotype/bimbam/<stem>_geno.txt`), and the +/// BIMBAM is generated from the `.geno`, so its column order is the header's +/// order. That makes the sibling the name source. +pub fn names_for_bimbam(bimbam: &Path) -> Option<PathBuf> { + let file = bimbam.file_name()?.to_string_lossy().into_owned(); + let stem = file + .strip_suffix("_geno.txt") + .or_else(|| file.strip_suffix(".txt"))?; + let genotype_dir = bimbam.parent()?.parent()?; + let candidate = genotype_dir.join(format!("{stem}.geno")); + candidate.is_file().then_some(candidate) +} + +/// `align_to_file`, but for a file that carries no names: the names come from +/// `names_source` (see [`names_for_bimbam`]), and the values are placed in the +/// file's own column order. +pub fn align_to_columns_of( + names_source: &Path, + values: &[(String, Option<f64>)], +) -> Result<Vec<Option<f64>>, GenotypeError> { + let names = panel_of(names_source)?; + let by_name: std::collections::HashMap<&str, Option<f64>> = + values.iter().map(|(name, value)| (name.as_str(), *value)).collect(); + Ok(names + .iter() + .map(|name| by_name.get(name.as_str()).copied().flatten()) + .collect()) +} + /// One value per individual of a `.geno`, in the file's own order, from values /// given by name. Used when a request names a file rather than a group -- an /// uploaded population, typically -- because the caller has a trait's values diff --git a/src/json_errors.rs b/src/json_errors.rs new file mode 100644 index 0000000..458eea9 --- /dev/null +++ b/src/json_errors.rs @@ -0,0 +1,118 @@ +//! Make every client error answer in the API's own envelope. +//! +//! Extractor failures never reach a handler, so they never see `ApiError`: axum +//! answers a body it cannot deserialize with `text/plain`, e.g. +//! +//! ```text +//! Failed to deserialize the JSON body into the target type: +//! missing field `trait_name` at line 1 column 1387 +//! ``` +//! +//! That is the one error class a client cannot parse -- everything else carries +//! `code`, `detail` and `request_id`. Measured on the release service: a +//! `/compute/rqtl` call without `trait_name` answered 422 `text/plain`. +//! +//! A middleware fixes it in one place instead of adding a custom extractor to +//! every handler: if the response is a 4xx that is not already JSON, its body +//! becomes `{"type": "/errors/invalid_request", "title": ..., "status": ..., +//! "code": "invalid_request", "detail": <the original text>, "error": null, +//! "operation_id": <the matched route>}`. +use axum::body::Body; +use axum::extract::MatchedPath; +use axum::http::{header, Request, StatusCode}; +use axum::middleware::Next; +use axum::response::Response; + +pub async fn jsonify_client_errors(request: Request<Body>, next: Next) -> Response { + // The matched route pattern is the closest thing to an operation id + // available this early; it names /compute/rqtl rather than the path asked. + let operation = request + .extensions() + .get::<MatchedPath>() + .map(|matched: &MatchedPath| matched.as_str().to_string()); + let mut response = next.run(request).await; + let status = response.status(); + if !status.is_client_error() { + return response; + } + let is_json = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(|value| value.starts_with("application/json")) + .unwrap_or(false); + if is_json { + return response; + } + // Take the body apart and rebuild it: the original text is the detail. + let (mut parts, body) = response.into_parts(); + let bytes = axum::body::to_bytes(body, 64 * 1024) + .await + .unwrap_or_default(); + let detail = String::from_utf8_lossy(&bytes).trim().to_string(); + let body = serde_json::json!({ + "type": "/errors/invalid_request", + "title": "Invalid request", + "status": status.as_u16(), + "code": match status { + StatusCode::UNSUPPORTED_MEDIA_TYPE => "unsupported_media_type", + StatusCode::PAYLOAD_TOO_LARGE => "payload_too_large", + _ => "invalid_request", + }, + "detail": if detail.is_empty() { "the request could not be read".to_string() } else { detail }, + "error": null, + "operation_id": operation, + "spec_url": "/openapi.json", + "next": null, + }); + let text = body.to_string(); + parts.headers.insert( + header::CONTENT_TYPE, + header::HeaderValue::from_static("application/json"), + ); + parts.headers.remove(header::CONTENT_LENGTH); + Response::from_parts(parts, Body::from(text)) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::Router; + use axum::routing::post; + + async fn boom() -> StatusCode { + StatusCode::BAD_REQUEST + } + + /// A 4xx that is not JSON comes back as the envelope; a JSON one is left + /// alone. + #[tokio::test] + async fn a_plain_text_client_error_becomes_the_envelope() { + use tower::ServiceExt; + let app = Router::new() + .route("/boom", post(boom)) + .layer(axum::middleware::from_fn(jsonify_client_errors)); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/boom") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + Some("application/json") + ); + let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["code"], "invalid_request"); + assert!(body["operation_id"].is_string()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..bf1047b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod frequencies; pub mod genoupload; pub mod genotypes; pub mod heatmap; +pub mod listing; pub mod normalize; mod plot; mod error; @@ -30,12 +31,15 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod json_errors; +pub mod runs; mod routes; mod rqtl; pub mod search; mod streaming; pub mod suggest; pub mod tokens; +pub mod usage; pub mod wikidata; use error::ApiError; @@ -87,6 +91,11 @@ async fn tag_caller( ) -> axum::response::Response { let slot = crate::auth::CallerSlot::default(); request.extensions_mut().insert(slot.clone()); + // What the *work* was (dataset, engine, cached, …): the handler knows + // it (it parses the body) and this middleware does not, so it opens a + // slot the same way, and reads it back below. See `crate::usage`. + let usage = crate::usage::UsageSlot::default(); + request.extensions_mut().insert(usage.clone()); let started = std::time::Instant::now(); let method = request.method().clone(); // The path only: a query string can carry a credential (`?token=`) and has @@ -122,6 +131,7 @@ async fn tag_caller( started.elapsed().as_millis(), request_id.as_deref(), caller.as_ref(), + &usage.entries(), ) ); } @@ -138,6 +148,12 @@ async fn tag_caller( /// lets `scripts/gn4-log.py` resolve the handle against the registry -- the /// subject as it is *now*, the token's status and its note -- without the log /// ever holding a secret or a hash. +/// +/// `usage` is what the handler added about the work itself (dataset, group, +/// engine, cached, run, `q`), and it is empty for every route that does not +/// call [`crate::usage`]'s macro. Those keys go after the request's own +/// fields, and [`crate::usage::RESERVED`] keeps a handler from overwriting +/// one of them. fn request_log_line( method: &str, path: &str, @@ -145,6 +161,7 @@ fn request_log_line( took_ms: u128, request_id: Option<&str>, caller: Option<&crate::auth::Caller>, + usage: &[(&'static str, serde_json::Value)], ) -> String { let mut line = serde_json::json!({ "event": "request", @@ -166,6 +183,11 @@ fn request_log_line( object.insert("token".to_string(), serde_json::json!(id)); } } + if let Some(object) = line.as_object_mut() { + for (key, value) in usage { + object.insert((*key).to_string(), value.clone()); + } + } line.to_string() } @@ -231,6 +253,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) @@ -283,6 +307,8 @@ pub fn app() -> Router { .routes(routes!(routes::gemma::compute_gemma)) .routes(routes!(routes::gemma::compute_gemma_ravanan)) .routes(routes!(routes::gemma::gemma_status)) + .routes(routes!(routes::gemma::compute_gemma_async)) + .routes(routes!(routes::gemma::gemma_result)) .routes(routes!(routes::fitqtl::compute_fitqtl)) .routes(routes!(routes::qtl2::compute_qtl2)) .routes(routes!(routes::rqtl::compute_rqtl)) @@ -329,6 +355,10 @@ pub fn app() -> Router { // Outermost, so the slot exists before the handler's extractors // run: see `tag_caller`. .layer(axum::middleware::from_fn(tag_caller)) + // Outside everything, so an extractor's rejection (which never + // reaches a handler) still answers in the API's envelope instead of + // axum's text/plain. + .layer(axum::middleware::from_fn(json_errors::jsonify_client_errors)) } /// The largest request body the API accepts: 64 MiB, comfortably above a @@ -450,6 +480,7 @@ mod access_log_tests { 17, Some("abc"), Some(&caller(Scheme::Jwt, None, "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["event"], "request"); @@ -479,6 +510,7 @@ mod access_log_tests { 900, None, Some(&caller(Scheme::Opaque, Some("agent-ravanan-3"), "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["user"], "zachs"); @@ -491,9 +523,75 @@ mod access_log_tests { /// reader could mistake for a user name. #[test] fn no_user_field_when_nobody_was_identified() { - let line = request_log_line("GET", "/groups", 401, 0, None, None); + let line = request_log_line("GET", "/groups", 401, 0, None, None, &[]); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert!(parsed.get("user").is_none(), "{line}"); assert!(parsed.get("request_id").is_none(), "{line}"); } + + /// The wiring the whole feature rests on: the slot `tag_caller` puts in + /// the request extensions is the slot the handler's `Ctx` writes into and + /// the same one the line is built from. If these ever became two slots, + /// nothing would fail -- the lines would just lose their fields. + #[tokio::test] + async fn a_handler_writes_into_the_slot_the_logging_middleware_reads() { + use axum::extract::FromRequestParts; + + let slot = crate::usage::UsageSlot::default(); + let mut parts = axum::http::Request::builder() + .uri("/compute/gemma") + .body(()) + .unwrap() + .into_parts() + .0; + parts.extensions.insert(slot.clone()); + + let ctx = crate::response::Ctx::from_request_parts(&mut parts, &()) + .await + .unwrap(); + crate::usage!(ctx, dataset = "HSNIH-Palmer", engine = "gemma"); + // A clone of the handler's ctx (the fallback path) lands in the same + // place, and a second note replaces rather than duplicates. + crate::usage!(ctx.clone(), engine = "pangemma"); + + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")) + ], + "one slot, and the later answer wins" + ); + } + + /// What the handler recorded about the work lands beside the request's + /// own fields, and a route that records nothing grows nothing: five + /// sixths of the traffic (every read route) must stay as it was. + #[test] + fn usage_fields_are_added_after_the_lines_own_fields() { + let usage = vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")), + ("cached", serde_json::json!(true)), + ]; + let line = request_log_line( + "POST", + "/compute/gemma", + 200, + 900, + None, + Some(&caller(Scheme::Jwt, None, "JoM")), + &usage, + ); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(parsed["dataset"], "HSNIH-Palmer"); + assert_eq!(parsed["engine"], "pangemma"); + assert_eq!(parsed["cached"], true); + assert_eq!(parsed["user"], "JoM", "the line's own fields survive"); + assert_eq!(parsed["path"], "/compute/gemma"); + + let quiet = request_log_line("GET", "/groups/BXD", 200, 1, None, None, &[]); + let parsed: serde_json::Value = serde_json::from_str(&quiet).unwrap(); + assert_eq!(parsed.as_object().unwrap().len(), 6, "{quiet}"); + } } diff --git a/src/listing.rs b/src/listing.rs new file mode 100644 index 0000000..584429f --- /dev/null +++ b/src/listing.rs @@ -0,0 +1,268 @@ +//! The shape of a listing: `limit_to`, `ids_only`, `names_only`. +//! +//! GN2 offers all three on its listings, and a client that has to enumerate a +//! group's 20 000 traits wants them for the same reason: a 2 MB answer of +//! objects to build a dropdown is a waste of everyone's connection. The three +//! are one concept, so they live in one type rather than being copied into each +//! handler's query struct: +//! +//! * `limit_to=a,b,c` keeps only the rows whose id, name, full name or trait +//! name matches one of the listed values (case-insensitive). A value that +//! matches nothing is named in the reply's note rather than silently ignored, +//! because "my trait's missing" is the failure mode this exists to prevent. +//! * `ids_only=true` answers `["BXD", "BXH", ...]` instead of objects. +//! * `names_only=true` answers `["BXD", ...]` too, but from the *name* field; +//! asking for both is a contradiction and is refused rather than guessed. +//! +//! Rows keep their order, so a caller can zip the slim answer against what it +//! asked for. +//! +//! **Status: the type and its tests are in, the handlers are not wired yet.** +//! Wiring one is small but not mechanical: a listing handler returns typed rows +//! (`Envelope<Vec<db::Group>>`), so answering with `["BXD", ...]` changes its +//! return type to `Envelope<serde_json::Value>` *and* the `body =` type in its +//! `utoipa::path` block, which utoipa checks at compile time (a mismatch fails +//! with "could not find `__path_<handler>`", which reads like a macro problem +//! and is not one). Doing that for six handlers is a pass of its own; doing it +//! for two would leave the API inconsistent, which is worse than not having it. + +use serde::Deserialize; + +/// What a listing answers with. +/// +/// `Objects` is the shape the API has always had, and it stays the default: a +/// caller who sends no listing parameters gets exactly what it got before, so +/// adding this cannot break an existing client. `Plain` is the opt-in slim form +/// (`ids_only` / `names_only`), one value per row. +/// +/// Untagged because the wire shapes are a plain JSON array either way -- the +/// difference is what is *in* the array, not how it is wrapped, and a wrapper +/// would have been a breaking change dressed as a feature. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +#[serde(untagged)] +pub enum Rows { + /// One serialised row per entry, the shape every listing has always had. + Objects(Vec<serde_json::Value>), + /// One identifier per entry, from `ids_only` or `names_only`. + Plain(Vec<String>), +} + +/// Query parameters every listing shares, for handlers with no other parameters. +#[derive(Debug, Clone, Default, Deserialize, utoipa::IntoParams)] +pub struct ListingParams { + /// Keep only these ids or names, comma-separated. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with ids only. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with names only. + #[serde(default)] + pub names_only: Option<bool>, +} + +/// What a listing should answer with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Listing { + /// The rows as they are. + Full, + /// One identifier per row, from this field. + Only(&'static str), +} + +/// The fields a `limit_to` value may match, in the order they are tried. +const MATCH_FIELDS: [&str; 5] = ["id", "name", "trait_name", "display_name", "full_name"]; +/// Where an `ids_only` answer takes its value from. +const ID_FIELDS: [&str; 4] = ["id", "name", "trait_name", "abbreviation"]; +/// Where a `names_only` answer takes its value from. +const NAME_FIELDS: [&str; 4] = ["name", "trait_name", "display_name", "id"]; + +impl Listing { + /// Read the parameters, refusing the contradiction. + pub fn parse(params: &ListingParams) -> Result<Self, String> { + let ids = params.ids_only.unwrap_or(false); + let names = params.names_only.unwrap_or(false); + match (ids, names) { + (true, true) => Err( + "ask for ids_only or names_only, not both: a row has one identifier and one name, \ + and which one you get should not depend on parse order" + .to_string(), + ), + (true, false) => Ok(Listing::Only("id")), + (false, true) => Ok(Listing::Only("name")), + (false, false) => Ok(Listing::Full), + } + } + + /// Shape already-serialised rows into a [`Rows`] body. + /// + /// `rows` is the full form; `Listing::Full` hands it back untouched, so the + /// default answer is the old answer. + pub fn shape( + &self, + rows: Vec<serde_json::Value>, + limit_to: Option<&str>, + ) -> (Rows, Vec<String>) { + let as_value = serde_json::Value::Array(rows); + let (shaped, missing) = self.apply(&as_value, limit_to); + let entries = shaped.as_array().cloned().unwrap_or_default(); + let body = match self { + Listing::Full => Rows::Objects(entries), + Listing::Only(_) => Rows::Plain( + entries + .into_iter() + .filter_map(|value| match value { + serde_json::Value::String(text) => Some(text), + serde_json::Value::Number(number) => Some(number.to_string()), + _ => None, + }) + .collect(), + ), + }; + (body, missing) + } + + /// Shape `rows` (already serialised) according to the parameters. + /// + /// Returns the shaped array and, for a `limit_to` that matched nothing, the + /// values that were not found -- so the caller can say so. + pub fn apply( + &self, + rows: &serde_json::Value, + limit_to: Option<&str>, + ) -> (serde_json::Value, Vec<String>) { + let Some(array) = rows.as_array() else { + return (rows.clone(), Vec::new()); + }; + let wanted: Option<Vec<String>> = limit_to + .map(|text| { + text.split(',') + .map(|value| value.trim().to_lowercase()) + .filter(|value| !value.is_empty()) + .collect() + }) + .filter(|values: &Vec<String>| !values.is_empty()); + + let mut kept: Vec<serde_json::Value> = Vec::with_capacity(array.len()); + let mut found: Vec<String> = Vec::new(); + for row in array { + if let Some(wanted) = &wanted { + let mut matched = false; + for field in MATCH_FIELDS { + if let Some(value) = row.get(field).and_then(|value| { + value + .as_str() + .map(str::to_string) + .or_else(|| value.as_i64().map(|n| n.to_string())) + }) { + let lowered = value.to_lowercase(); + if wanted.contains(&lowered) { + matched = true; + found.push(lowered); + break; + } + } + } + if !matched { + continue; + } + } + match self { + Listing::Full => kept.push(row.clone()), + Listing::Only(field) => { + let fields: &[&str] = if *field == "id" { &ID_FIELDS } else { &NAME_FIELDS }; + let value = fields + .iter() + .find_map(|candidate| row.get(*candidate)) + .cloned() + .unwrap_or(serde_json::Value::Null); + kept.push(value); + } + } + } + let missing = match &wanted { + Some(wanted) => wanted + .iter() + .filter(|value| !found.contains(value)) + .cloned() + .collect(), + None => Vec::new(), + }; + (serde_json::Value::Array(kept), missing) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rows() -> serde_json::Value { + json!([ + {"id": 1, "name": "BXD", "full_name": "BXD recombinant inbreds"}, + {"id": 2, "name": "BXH", "full_name": "BXH recombinant inbreds"}, + {"id": 3, "name": "HET3-ITP", "full_name": "UM-HET3"} + ]) + } + + #[test] + fn full_leaves_the_rows_alone() { + let listing = Listing::parse(&ListingParams::default()).expect("default"); + assert_eq!(listing, Listing::Full); + let (shaped, missing) = listing.apply(&rows(), None); + assert_eq!(shaped, rows()); + assert!(missing.is_empty()); + } + + #[test] + fn ids_and_names_are_one_value_per_row() { + let ids = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = ids.apply(&rows(), None); + assert_eq!(shaped, json!([1, 2, 3])); + + let names = Listing::parse(&ListingParams { + names_only: Some(true), + ..Default::default() + }) + .expect("names"); + let (shaped, _) = names.apply(&rows(), None); + assert_eq!(shaped, json!(["BXD", "BXH", "HET3-ITP"])); + } + + #[test] + fn limit_to_matches_any_of_the_matching_fields_case_insensitively() { + let listing = Listing::Full; + let (shaped, missing) = listing.apply(&rows(), Some("bxd,UM-HET3")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(2)); + assert!(missing.is_empty(), "both were found: {missing:?}"); + + let (shaped, missing) = listing.apply(&rows(), Some("bxd,nope")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(1)); + assert_eq!(missing, vec!["nope".to_string()], "the miss is reported, not dropped"); + } + + #[test] + fn limit_to_composes_with_ids_only() { + let listing = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = listing.apply(&rows(), Some("BXH")); + assert_eq!(shaped, json!([2])); + } + + #[test] + fn asking_for_both_shapes_is_refused() { + let error = Listing::parse(&ListingParams { + ids_only: Some(true), + names_only: Some(true), + ..Default::default() + }); + assert!(error.is_err(), "ids_only + names_only must not be guessed"); + } +} diff --git a/src/pca.rs b/src/pca.rs index 23e3105..e924882 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -55,6 +55,29 @@ pub struct Pca { /// Eigenvalues should sum to the number of traits; reported so a caller can /// check that the decomposition is sane rather than trust it. pub trace: f64, + /// The components *as traits*: one value per individual per component, so + /// they can be used the way GN2's "PCA traits" are -- correlated, mapped, + /// plotted, saved in a basket. Empty when the caller did not ask, or when + /// the values were not available to project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub traits: Vec<PcTrait>, +} + +/// One principal component as a trait: a value per individual. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcTrait { + /// `PC1`, `PC2`, ... in eigenvalue order. + pub name: String, + /// Score per individual, in the same order as `individuals`. + pub values: Vec<PcValue>, + /// Share of total variance this component explains. + pub explained_variance_ratio: f64, +} + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcValue { + pub name: String, + pub value: f64, } #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] @@ -189,6 +212,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; } let small: Vec<Vec<f64>> = kept @@ -201,6 +225,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; }; let trace: f64 = eigenvalues.iter().sum(); @@ -221,7 +246,72 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: eigenvalues, dropped, trace, + traits: Vec::new(), + } +} + +/// Project standardised trait values onto the components, giving PC scores. +/// +/// `values` is traits x individuals for the traits the PCA kept, in the kept +/// order and already aligned to `individuals`; a trait is standardised with the +/// **sample** standard deviation (n-1), because that is what the correlation +/// matrix was built from -- using the population one would rescale every score +/// by a constant and quietly disagree with `r`. +/// +/// Returns one [`PcTrait`] per component. `None` when the shapes disagree or a +/// value is missing, rather than filling a zero into a score. +pub fn scores( + pca: &Pca, + values: &[Vec<f64>], + individuals: &[String], +) -> Option<Vec<PcTrait>> { + let n_traits = values.len(); + if n_traits == 0 || individuals.len() != values[0].len() || values.iter().any(|v| v.len() != individuals.len()) { + return None; + } + if pca.components.len() < n_traits || pca.components[0].loadings.len() != n_traits { + return None; + } + let n = individuals.len(); + if n < 2 { + return None; + } + // z-scores per trait + let mut standardised: Vec<Vec<f64>> = Vec::with_capacity(n_traits); + for trait_values in values { + if trait_values.iter().any(|v| !v.is_finite()) { + return None; + } + let mean = trait_values.iter().sum::<f64>() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64; + let sd = variance.sqrt(); + // A constant trait has no z-score; it also has no correlation with + // anything, so it should have been dropped before we get here. + if !(sd > 0.0) { + return None; + } + standardised.push(trait_values.iter().map(|v| (v - mean) / sd).collect()); + } + let mut out = Vec::with_capacity(pca.components.len()); + for (index, component) in pca.components.iter().enumerate() { + let mut scores = vec![0.0; n]; + for (trait_index, loading) in component.loadings.iter().enumerate() { + for (individual, z) in standardised[trait_index].iter().enumerate() { + scores[individual] += loading * z; + } + } + out.push(PcTrait { + name: format!("PC{}", index + 1), + values: individuals + .iter() + .cloned() + .zip(scores) + .map(|(name, value)| PcValue { name, value }) + .collect(), + explained_variance_ratio: component.explained_variance_ratio, + }); } + Some(out) } #[cfg(test)] diff --git a/src/qtl2.rs b/src/qtl2.rs index 2bb11f7..99f2370 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -155,47 +155,22 @@ pub struct Qtl2Output { pub permutation_note: Option<String>, } -/// How many genotype cells carry one code -- the count a cached conversion -/// needs to say what it dropped, without re-converting. -fn count_calls(text: &str, code: &str) -> usize { - let mut seen_header = false; - let mut start = 3usize; - let mut count = 0usize; - for line in text.lines() { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { - continue; - } - let columns: Vec<&str> = line.split('\t').collect(); - if !seen_header { - seen_header = true; - start = if columns.len() > 3 && columns[3] == "Mb" { 4 } else { 3 }; - continue; - } - count += columns.iter().skip(start).filter(|cell| cell.trim() == code).count(); - } - count -} - -/// The header's `@het` code, if it declares one. -fn metadata_het(text: &str) -> Option<String> { - text.lines() - .find_map(|line| line.strip_prefix("@het:")) - .map(|value| value.trim().to_string()) -} - -fn io_error(path: &Path, error: io::Error) -> Qtl2Error { - Qtl2Error::Io(io::Error::new( - error.kind(), - format!("{}: {error}", path.display()), - )) -} +/// The conversion, as an R script. +pub const CONVERT_SCRIPT: &str = "scripts/qtl2-convert-geno.R"; /// Convert `resolved`'s `.geno` into a cached qtl2 cross. +/// +/// The conversion itself is [`CONVERT_SCRIPT`], an R script: the output is an +/// R/qtl2 cross, and qtl2's own `write_control_file` describes it. Doing that +/// here meant a second implementation of the format in Rust, and one of its +/// conventions -- the genotype codes -- was wrong in a way that silently +/// destroyed the scan (see the script's own comment). Reading the report the +/// script leaves beside the cross is all this side needs to do. pub fn prepare_cross( resolved: &Resolved, cache_dir: &Path, het: Het, + convert_script: &Path, ) -> Result<PreparedCross, Qtl2Error> { let geno = &resolved.geno; let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?; @@ -209,37 +184,22 @@ pub fn prepare_cross( .map(|since| since.as_secs()) .unwrap_or(0) ); - // The version tag is part of the key: a change to this conversion (the - // heterozygous calls dropped for a riself panel, say) must not silently - // reuse the previous cross's probabilities and kinship. - // v3 keyed the heterozygous policy in as well: a cross converted with the - // calls kept is a different cross from one with them dropped. - const CONVERSION_VERSION: &str = "v3"; - let directory = cache_dir.join("crosses").join(format!( - "{CONVERSION_VERSION}-{}-{}-{stamp}", - het.as_str(), - resolved.version.replace(['/', '.'], "_") - )); - let control = directory.join("control.json"); - let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?; - - // Metadata: the genotype codes, and the cross type. - let mut codes: BTreeMap<String, String> = BTreeMap::new(); - let mut cross_type = String::new(); + // Lossy, like the genotype readers: a latin-1 byte in a header comment must + // not hide the panel (measured on At-Serin.geno). + let text = crate::genotypes::read_text_lossy(geno).map_err(|e| io_error(geno, e))?; + + // The cross type is checked here rather than in R: this is the endpoint's + // own limit (a `.geno` panel carries no founder genotypes, so it cannot be + // a multiparent cross), and the answer is a 422 with a reason, not a + // script failure. + let mut declared = String::new(); for line in text.lines() { - if let Some(rest) = line.strip_prefix('@') { - let Some((key, value)) = rest.split_once(':') else { continue }; - let value = value.trim().to_string(); - match key.trim() { - "mat" => { codes.insert(value, "A".to_string()); } - "het" => { codes.insert(value, "H".to_string()); } - "pat" => { codes.insert(value, "B".to_string()); } - "type" => cross_type = value, - _ => {} - } + if let Some(rest) = line.strip_prefix("@type:") { + declared = rest.trim().to_string(); + break; } } - let crosstype = match cross_type.as_str() { + let crosstype = match declared.as_str() { // A riset panel read as `f2` is a riset panel whose H calls are kept: // qtl2 needs a cross type that has a heterozygous state for that. "riset" if het == Het::Keep => "f2", @@ -253,192 +213,106 @@ pub fn prepare_cross( ))) } }; - // A riself panel is inbred lines: a heterozygous call is an error in the - // genotyping, not a third allele. R/qtl's `convert2riself` omits those - // genotypes, and qtl2 needs the same treatment -- left in, it reads the - // cross as multiparent and its scan1 takes a path this panel cannot - // satisfy ("scan1_pg ..."). - let mut het_kept: Option<String> = None; - if crosstype == "riself" { - let het_code = metadata_het(&text); - if let Some(het_code) = het_code { - codes.remove(&het_code); - het_kept = Some(het_code); - } - } - if codes.len() < 2 { - return Err(Qtl2Error::Unsupported( - "the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded" - .to_string(), - )); - } - // Header row: Chr, Locus, cM, Mb?, then the individuals. - let mut lines = text.lines(); - let Some(header) = lines.find(|line| line.to_lowercase().starts_with("chr\t")) else { - return Err(Qtl2Error::Unsupported( - "the .geno file has no 'Chr' header row".to_string(), - )); - }; - let fields: Vec<&str> = header.split('\t').collect(); - let first_individual = if fields.get(3).copied() == Some("Mb") { 4 } else { 3 }; - let individuals: Vec<String> = fields[first_individual..] - .iter() - .map(|name| name.trim().to_string()) - .collect(); - if individuals.is_empty() { - return Err(Qtl2Error::Unsupported( - "the .geno header names no individuals".to_string(), - )); - } + // The version tag is part of the key: a change to the conversion must not + // silently reuse the previous cross's probabilities and kinship. v3 keyed + // the heterozygous policy in; v4/v5 were the allele codes; v6 is the + // conversion itself moving to R, which changes the files it writes (qtl2's + // own genotype layout, individuals in rows). + const CONVERSION_VERSION: &str = "v6"; + let directory = cache_dir.join("crosses").join(format!( + "{CONVERSION_VERSION}-{}-{}-{stamp}", + het.as_str(), + resolved.version.replace(['/', '.'], "_") + )); + let control = directory.join("control.json"); if !control.is_file() { std::fs::create_dir_all(&directory).map_err(|e| io_error(&directory, e))?; - let mut geno_csv = String::new(); - let mut gmap_csv = String::from("marker,chr,pos\n"); - let mut pmap_csv = String::from("marker,chr,pos\n"); - geno_csv.push_str("marker,"); - geno_csv.push_str(&individuals.join(",")); - geno_csv.push('\n'); - let mut markers = 0usize; - let mut non_autosomal = 0usize; - let mut het_dropped = 0usize; - for line in lines { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') { - continue; - } - let row: Vec<&str> = line.split('\t').collect(); - if row.len() < first_individual { - continue; - } - let (chromosome, marker, centimorgans, megabases) = - (row[0].trim(), row[1].trim(), row[2].trim(), row.get(3).copied().unwrap_or("")); - // Autosomes only: see the module comment. - if !chromosome.chars().all(|c| c.is_ascii_digit()) { - non_autosomal += 1; - continue; - } - markers += 1; - geno_csv.push_str(marker); - for value in &row[first_individual..] { - let call = codes.get(value.trim()).map(String::as_str).unwrap_or(""); - if call.is_empty() && het_kept.as_deref() == Some(value.trim()) { - het_dropped += 1; + let het_arg = het.as_str(); + let output = std::process::Command::new("Rscript") + .arg(convert_script) + .arg("--geno") + .arg(geno) + .arg("--out") + .arg(&directory) + .arg("--het") + .arg(het_arg) + .arg("--crosstype") + .arg(crosstype) + .output() + .map_err(Qtl2Error::Io)?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let interesting = |line: &&str| { + let line = line.trim(); + !line.is_empty() + && !line.starts_with("Warning") + && !line.starts_with("In ") + && line != "Execution halted" + }; + let complaint: Vec<&str> = stderr.lines().filter(interesting).collect(); + return Err(Qtl2Error::CommandFailed(format!( + "converting {} failed: {}", + geno.display(), + if complaint.is_empty() { + "R/qtl2 gave no reason".to_string() + } else { + complaint.join(" ") } - geno_csv.push(','); - geno_csv.push_str(call); - } - geno_csv.push('\n'); - gmap_csv.push_str(&format!("{marker},{chromosome},{centimorgans}\n")); - let base_pairs = megabases.parse::<f64>().map(|mb| (mb * 1e6).round() as i64).unwrap_or(0); - pmap_csv.push_str(&format!("{marker},{chromosome},{base_pairs}\n")); - } - if markers == 0 { - return Err(Qtl2Error::Unsupported( - "the panel has no autosomal markers to scan".to_string(), - )); - } - // The cross needs a phenotype file of its own to be readable; the - // trait comes from the request, through the script's --pheno. - let mut pheno_csv = String::from("id,trait\n"); - for name in &individuals { - pheno_csv.push_str(&format!("{name},1\n")); + ))); } - for (path, contents) in [ - (directory.join("geno.csv"), &geno_csv), - (directory.join("gmap.csv"), &gmap_csv), - (directory.join("pmap.csv"), &pmap_csv), - (directory.join("pheno.csv"), &pheno_csv), - ] { - std::fs::write(&path, contents).map_err(|e| io_error(&path, e))?; - } - let control_json = serde_json::json!({ - // Paths are relative to the control file: qtl2 joins its own - // directory onto whatever it finds here. - "crosstype": crosstype, - "geno": "geno.csv", - "gmap": "gmap.csv", - "pmap": "pmap.csv", - "pheno": "pheno.csv", - "sep": ",", - "na.strings": [""], - "genotypes": {"A": 1, "H": 2, "B": 3}, - // Our own CSVs are markers-in-rows, individuals-in-columns. - "geno_transposed": true, - }); - std::fs::write(&control, control_json.to_string()).map_err(|e| io_error(&control, e))?; - // What the conversion discarded, kept beside the cross: a cached cross - // must be able to say how many calls it dropped. - let report = serde_json::json!({ - "het_dropped": het_dropped, - "cells": individuals.len() * markers, - }); - let report_path = directory.join("conversion.json"); - let _ = std::fs::write(&report_path, report.to_string()); - return Ok(PreparedCross { - control, - individuals: individuals.clone(), - markers, - non_autosomal, - crosstype: crosstype.to_string(), - het_dropped, - cells: individuals.len() * markers, - founders: 0, - multiparent: false, - }); } - // Cached: count what the conversion produced, without re-reading the - // panel. The marker counts come from the maps it wrote. - let markers = std::fs::read_to_string(directory.join("pmap.csv")) - .map_err(|e| io_error(&directory.join("pmap.csv"), e))? - .lines() - .filter(|line| !line.trim().is_empty()) - .count() - .saturating_sub(1); + // The script's report is the cross's own account of itself: what it + // dropped, and which individuals it holds. A cross converted before the + // report existed is measured once from the panel. let report_path = directory.join("conversion.json"); - let mut report: Value = std::fs::read_to_string(&report_path) + let report: Value = std::fs::read_to_string(&report_path) .ok() .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_else(|| serde_json::json!({})); - if report.get("het_dropped").is_none() { - // A cross converted before the count was kept: measure it once from the - // panel and record it beside the cross, so later replies are free. - let het_code = if crosstype == "riself" { - metadata_het(&text) - } else { - None - }; - let dropped = het_code - .as_deref() - .map(|code| count_calls(&text, code)) - .unwrap_or(0); - report = serde_json::json!({ - "het_dropped": dropped, - "cells": individuals.len() * markers, - }); - let _ = std::fs::write(&report_path, report.to_string()); + .ok_or_else(|| { + Qtl2Error::CommandFailed(format!( + "{} wrote no conversion report; can this convert {}?", + convert_script.display(), + geno.display() + )) + })?; + let want = |key: &str| report.get(key).and_then(Value::as_u64).unwrap_or(0) as usize; + let individuals: Vec<String> = report + .get("individuals") + .and_then(Value::as_array) + .map(|names| { + names + .iter() + .filter_map(|name| name.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + if individuals.is_empty() { + return Err(Qtl2Error::Unsupported( + "the .geno header names no individuals".to_string(), + )); + } + let markers = want("markers"); + if markers == 0 { + return Err(Qtl2Error::Unsupported( + "the panel has no autosomal markers to scan".to_string(), + )); } - let het_dropped = report - .get("het_dropped") - .and_then(Value::as_u64) - .unwrap_or(0) as usize; - let cells = report.get("cells").and_then(Value::as_u64).unwrap_or(0) as usize; Ok(PreparedCross { control, individuals, markers, - non_autosomal: 0, + non_autosomal: want("non_autosomal"), crosstype: crosstype.to_string(), - het_dropped, - cells, + het_dropped: want("het_dropped"), + cells: want("cells"), founders: 0, multiparent: false, }) } -/// Find the control file of a cross named in a request. pub fn resolve_control_file(root: &Path, requested: &str) -> Result<PathBuf, Qtl2Error> { let name = requested.trim(); if name.is_empty() { @@ -488,6 +362,13 @@ fn control_path(control: &Path, json: &Value, key: &str) -> Option<PathBuf> { .map(|name| directory.join(name)) } +fn io_error(path: &Path, error: io::Error) -> Qtl2Error { + Qtl2Error::Io(io::Error::new( + error.kind(), + format!("{}: {error}", path.display()), + )) +} + /// The data lines of a CSV: comments and blank lines skipped, header dropped. fn data_lines(path: &Path, comment: &str) -> Result<Vec<String>, Qtl2Error> { let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?; diff --git a/src/response.rs b/src/response.rs index 5e6fcff..8ebcdcd 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 @@ -85,10 +186,24 @@ pub struct Envelope<T: Serialize + utoipa::ToSchema> { pub struct NextAction { /// Endpoint to call, relative to the API root, e.g. "/species/mouse". pub href: String, + /// True when `href` is a *shape* rather than an address: it still contains + /// a `{placeholder}` the caller substitutes (a trait id the scan does not + /// know, a genotype file name no group lists). Every other link is a `GET` + /// that answers 200 as it stands -- that is the promise `next` makes, and + /// a caller has to be able to tell the two apart without pattern-matching + /// on braces, or it follows a template and gets a 404 (measured: a scan + /// reply carried "/groups/BXD/genotypes/%7Bversion%7D/markers/..."). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub template: bool, /// What this call gives you, e.g. "Drill down into one species". pub description: String, } +/// Whether a `next` href still holds a placeholder. +fn is_template(href: &str) -> bool { + href.contains('{') || href.contains("%7B") +} + /// A suggested call that is not a plain `GET`, so it cannot live in /// `next`: following a `next` link is a `GET` that returns 200, which is /// what makes those links safe to follow blindly (and what the test @@ -114,6 +229,7 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { pub fn with_next(mut self, href: &str, description: &str) -> Self { self.next.push(NextAction { href: href.to_string(), + template: is_template(href), description: description.to_string(), }); self @@ -155,6 +271,7 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { continue; } self.next.push(NextAction { + template: is_template(&href), href, description: description.to_string(), }); @@ -162,6 +279,21 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { self } + /// Puts one endpoint-specific value into `meta.extra` (qualified data that + /// belongs beside the rows rather than around them -- the permutation null + /// of a scan, say). + pub fn with_extra(mut self, key: &str, value: serde_json::Value) -> Self { + let extra = self.meta.extra.get_or_insert_with(serde_json::Map::new); + extra.insert(key.to_string(), value); + 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 @@ -241,11 +373,36 @@ impl RequestInfo { /// What a handler needs to build its envelope and its errors. Take it /// as the first extractor, so the clock covers authentication too (and /// the token extractor's 401 reports the same request id and time). +/// +/// It also carries the request's usage slot (see [`crate::usage`]): a +/// handler that knows what data the request ran on says so with +/// `usage!(ctx, dataset = …, engine = …)` and the access line grows those +/// fields. Reading routes say nothing -- their dataset is already in the +/// path. pub struct Ctx { info: RequestInfo, + usage: crate::usage::UsageSlot, +} + +// `Ctx` is a request id, a start instant and a handle on the usage slot, so a +// clone is another handle on the same request: /compute/gemma needs it twice +// when the slurm engine runs and the local fallback has to answer, and both +// must write into the one log line. +impl Clone for Ctx { + fn clone(&self) -> Self { + Ctx { + info: self.info.clone(), + usage: self.usage.clone(), + } + } } impl Ctx { + /// Record what this request ran on, for the access log: the same call + /// the `usage!` macro makes, spelled out. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + self.usage.note(pairs); + } /// For `ApiError::with_request_id`: stamps an error with the /// request id and the time taken so far. pub fn request_info(&self) -> RequestInfo { @@ -264,6 +421,7 @@ impl Ctx { num_rows: None, num_cols: None, extra: None, + timing: None, }, notes: Vec::new(), next: Vec::new(), @@ -278,7 +436,18 @@ impl<S: Send + Sync> FromRequestParts<S> for Ctx { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { let info = RequestInfo::from_parts(parts); parts.extensions.insert(info.clone()); - Ok(Ctx { info }) + // `tag_caller` opened this before routing; a `Ctx` built outside a + // request (a test, an internal call) gets its own, empty, slot. + let usage = parts + .extensions + .get::<crate::usage::UsageSlot>() + .cloned() + .unwrap_or_else(|| { + let slot = crate::usage::UsageSlot::default(); + parts.extensions.insert(slot.clone()); + slot + }); + Ok(Ctx { info, usage }) } } @@ -308,6 +477,7 @@ mod tests { id: Some("req-1".to_string()), started: Instant::now(), }, + usage: crate::usage::UsageSlot::default(), } } diff --git a/src/routes/baskets.rs b/src/routes/baskets.rs index a542620..533a155 100644 --- a/src/routes/baskets.rs +++ b/src/routes/baskets.rs @@ -111,6 +111,16 @@ fn map_error(error: BasketError, rid: RequestInfo) -> ApiError { "baskets", ) .with_request_id(rid), + // A taken name is a conflict, not a malformed request: the body is + // fine, the name is not free. Say so, and point at PATCH. + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Basket name already in use", + format!("{message}"), + "baskets", + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_basket", @@ -159,7 +169,7 @@ pub async fn list_baskets( .envelope(baskets) .with_note("Baskets are yours: they live in your own SQLite file, not in GeneNetwork's \ database.") - .with_note("A mapping can name one instead of posting values: POST /compute/qtl2 with \ + .with_note("A mapping can name one instead of posting values: POST /compute/rqtl, \ \"basket\": \"<name>\"."); envelope = envelope.with_links(crate::suggest::root_links()); Ok(Json(envelope)) @@ -212,7 +222,7 @@ pub async fn create_basket( .map_err(|error| map_error(error, rid.clone()))?; let mut envelope = ctx.envelope(stored).with_note( "Stored. Edit it with PATCH (a new revision, a new digest) and map it with \ - POST /compute/qtl2 {\"basket\": \"<name>\"}.", + POST /compute/rqtl, /compute/qtl2, /compute/gemma or /compute/gemma/ravanan \n {\"basket\": \"<name>\"}.", ); envelope = envelope.with_links(crate::suggest::root_links()); Ok((StatusCode::CREATED, Json(envelope))) @@ -253,7 +263,10 @@ pub async fn get_basket( .envelope(stored) .with_note("`revision` and `digest` identify these exact values: a mapping reply records \ them, so an edit cannot make two runs look alike.") - .with_note("Map it: POST /compute/qtl2 with \"basket\": \"<name>\" in place of `samples`."); + .with_note( + "Map it: POST /compute/rqtl, /compute/qtl2, /compute/gemma or \ + /compute/gemma/ravanan with \"basket\": \"<name>\" in place of `samples`.", + ); envelope = envelope.with_links(links); Ok(Json(envelope)) } diff --git a/src/routes/bnw.rs b/src/routes/bnw.rs index 02cb591..3904ba6 100644 --- a/src/routes/bnw.rs +++ b/src/routes/bnw.rs @@ -102,6 +102,15 @@ pub async fn compute_bnw( Json(request): Json<BnwRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // Which panel and how many traits the structure search was asked for: the + // request body's, not the path's (see crate::usage). + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + crate::usage!(ctx, dataset = group); + } + crate::usage!(ctx, traits = request.traits.len()); + crate::usage!(ctx, engine = "bnw"); let config = Config::load(); let parameters = Parameters { @@ -402,6 +411,15 @@ pub async fn compute_bnw_features( Json(request): Json<BnwFeaturesRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // Which panel and how many traits the structure search was asked for: the + // request body's, not the path's (see crate::usage). + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + crate::usage!(ctx, dataset = group); + } + crate::usage!(ctx, traits = request.traits.len()); + crate::usage!(ctx, engine = "bnw"); let config = Config::load(); let parameters = Parameters { maxparents: request.maxparents.unwrap_or(bnw::DEFAULT_MAXPARENTS), diff --git a/src/routes/bulklmm.rs b/src/routes/bulklmm.rs index d549f07..94d5524 100644 --- a/src/routes/bulklmm.rs +++ b/src/routes/bulklmm.rs @@ -114,6 +114,24 @@ pub async fn compute_bulklmm( Json(mut request): Json<BulklmmRequest>, ) -> Result<Json<Envelope<Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage): the body names the panel and + // the trait, the trait count is what makes a bulklmm request large. + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + None, + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "bulklmm"); let config = Config::load(); let trait_label = request .trait_name diff --git a/src/routes/compare.rs b/src/routes/compare.rs new file mode 100644 index 0000000..9879b8a --- /dev/null +++ b/src/routes/compare.rs @@ -0,0 +1,290 @@ +//! Compare two traits: their shared individuals, the correlation, and a +//! scatter plot of one against the other. +//! +//! GN1's "compare traits" and GN2's trait page both show this, and every piece +//! of it already existed here -- `values_of` for the values, the engine for r +//! and p, the plot family for the figure. What was missing was one endpoint +//! that says "these two, over the individuals they share", with the individual +//! names in the reply so a reader can see which points they are looking at. +//! +//! Deliberate choices: +//! +//! * **The minimum overlap is the correlation floor** (6), not 2: two points +//! always fit a line, and a scatter of two points would look like a result. +//! * **The individuals travel with the numbers**, because a scatter plot is +//! read by looking at outliers, and "which animal is that" is the first +//! question. GN2's page answers it with a hover label; here it is in the +//! reply and in the plot's tooltips. +//! * **Nothing is regressed.** The line in the plot is drawn from r and the two +//! means (an ordinary least-squares line through standardised values), which +//! is the only slope implied by the numbers; no fitted model is invented. + +use axum::Json; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::correlation::{self, Method, Reference}; +use crate::error::ApiError; +use crate::error::Unauthorized; +use crate::response::{Ctx, Envelope}; + +use super::correlation::{db_failure, values_of, TraitRef}; +use crate::plot; +use gnauth_macros::gnauth; + +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct CompareRequest { + /// The first trait. + pub a: TraitRef, + /// The second trait. + pub b: TraitRef, + /// "pearson" (default) or "spearman". + #[serde(default)] + pub method: Option<String>, +} + +#[utoipa::path(post, path = "/compute/compare", + summary = "Compare two traits: their shared individuals, r, p and n", + description = "Fetches both traits, keeps the individuals that have a value for both, and \ +returns the correlation over them together with the paired values -- so the reply is both the \ +statistic and the data a scatter plot is drawn from. Needs the same six paired observations the \ +rest of the correlation surface needs: two points always fit a line. `spearman` ranks the pairs \ +first, as everywhere else.", + request_body = CompareRequest, + responses( + (status = 200, description = "The comparison", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 422, description = "Unknown method, a trait with no values, or fewer than six shared individuals", body = ApiError), + (status = 500, description = "Internal error", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn compare( + ctx: Ctx, + _token: AuthToken, + Json(request): Json<CompareRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let fail = |code: &str, title: &str, detail: String| { + ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + code, + title, + detail, + "compare_traits", + ) + .with_request_id(rid.clone()) + }; + let method = Method::parse(request.method.as_deref().unwrap_or("pearson")) + .map_err(|detail| fail("invalid_method", "Invalid correlation method", detail))?; + + let wanted = request.clone(); + let computed = tokio::task::spawn_blocking(move || align(&request)) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compare_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|failure| failure.into_api(rid.clone()))?; + + let aligned = computed; + let n = aligned.pairs.len(); + if n < correlation::MIN_OVERLAP { + return Err(fail( + "too_few_shared", + "Too few shared individuals", + format!( + "these two traits share {n} individual(s) with values; a comparison needs at \ + least {}", + correlation::MIN_OVERLAP + ), + )); + } + let x: Vec<f64> = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec<f64> = aligned.pairs.iter().map(|(_, _, b)| *b).collect(); + let (r, p) = correlation::correlate_named_value(&x, &y, n, method).ok_or_else(|| { + fail( + "no_correlation", + "No correlation", + "the coefficient is not a number over these individuals \ + (a constant trait has no correlation with anything)" + .to_string(), + ) + })?; + + let rows = serde_json::Value::Array( + aligned + .pairs + .iter() + .map(|(individual, a, b)| serde_json::json!([individual, a, b])) + .collect(), + ); + let mut body = serde_json::json!({ + "a": {"dataset": wanted.a.dataset, "trait_name": wanted.a.trait_name}, + "b": {"dataset": wanted.b.dataset, "trait_name": wanted.b.trait_name}, + "method": method.as_str(), + "r": r, + "p": if p.is_finite() { serde_json::Value::from(p) } else { serde_json::Value::Null }, + "n": n, + "pairs": rows, + }); + if let Some(extra) = aligned.only_one_side { + body["only_one_side"] = serde_json::Value::from(extra); + } + Ok(Json( + ctx.envelope(body) + .with_columns( + vec!["individual".to_string(), "a".to_string(), "b".to_string()], + n, + ) + .with_note(&format!( + "{} ({}) against {} ({}), {} over the {n} individual(s) with a value for both.", + wanted.a.trait_name, wanted.a.dataset, wanted.b.trait_name, wanted.b.dataset, + method.as_str() + )) + .with_note( + "`pairs` is positional: individual, first trait's value, second trait's value. \ + The individuals that had a value for only one side are counted in \ + `only_one_side`.", + ) + .with_next("/plot/compare", "The same numbers as a scatter plot"), + )) +} + +#[utoipa::path(post, path = "/plot/compare", + summary = "Draw the scatter plot of two compared traits, as an SVG", + description = "Post the response of POST /compute/compare back (as-is) and get the figure \ +scripts/plot-compare.py draws from it: one point per individual that has both values, the \ +individual's name in each point's tooltip, and the least-squares line implied by r and the two \ +means. Nothing is refitted and nothing is recomputed. image/svg+xml, not the JSON envelope; \ +`x-plot-summary` carries the plotter's one-line summary.", + params(super::plot::PlotParams), + request_body = serde_json::Value, + responses( + (status = 200, description = "The SVG", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The posted body is not a comparison", body = ApiError), + (status = 502, description = "The plotter failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_compare( + ctx: Ctx, + _token: AuthToken, + axum::extract::Query(plot_params): axum::extract::Query<super::plot::PlotParams>, + Json(posted): Json<serde_json::Value>, +) -> Result<axum::response::Response, ApiError> { + let rid = ctx.request_info(); + let data = posted.get("data").unwrap_or(&posted); + let pairs = data.get("pairs").and_then(|pairs| pairs.as_array()); + if pairs.map(|rows| rows.len()).unwrap_or(0) < 2 { + return Err(ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "not_a_comparison", + "Not a comparison", + "the posted body has fewer than two `pairs`: post a /compute/compare reply".to_string(), + "plot_compare", + ) + .with_request_id(rid)); + } + let config = crate::config::Config::load(); + let mut extra: Vec<String> = Vec::new(); + if let Some(title) = plot_params.title.as_deref() { + extra.push("--title".to_string()); + extra.push(title.to_string()); + } + let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect(); + let rendered = plot::render( + &config.plot_python, + &config.compare_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &posted, + plot_params.trait_label.as_deref().unwrap_or(""), + &borrowed, + ) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::BAD_GATEWAY, + "plot_failed", + "The plotter failed", + error.to_string(), + "plot_compare", + ) + .with_request_id(rid) + })?; + Ok(super::plot::svg_response(rendered)) +} + +/// The aligned pairs, plus a count of individuals only one side had. +struct Aligned { + pairs: Vec<(String, f64, f64)>, + only_one_side: Option<usize>, +} + +fn align(request: &CompareRequest) -> Result<Aligned, super::correlation::Failure> { + let a = values_of(&request.a.dataset, &request.a.trait_name)?; + let b = values_of(&request.b.dataset, &request.b.trait_name)?; + let mut pairs = Vec::new(); + let mut only_one_side = 0usize; + for (index, name) in a.names.iter().enumerate() { + match b.names.iter().position(|candidate| candidate == name) { + Some(position) => pairs.push((name.clone(), a.values[index], b.values[position])), + None => only_one_side += 1, + } + } + // Individuals only in B are not visited by the loop above. + for name in &b.names { + if !a.names.contains(name) { + only_one_side += 1; + } + } + Ok(Aligned { + pairs, + only_one_side: if only_one_side > 0 { + Some(only_one_side) + } else { + None + }, + }) +} + +/// Keep `Reference` in scope for readers of `align`. +#[allow(dead_code)] +fn _reference_is_used(_: &Reference) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pairs_are_the_shared_individuals() { + let a = Reference::from_pairs(vec![ + ("s1".to_string(), Some(1.0)), + ("s2".to_string(), Some(2.0)), + ("s3".to_string(), Some(3.0)), + ]); + let b = Reference::from_pairs(vec![ + ("s2".to_string(), Some(20.0)), + ("s3".to_string(), Some(30.0)), + ("s4".to_string(), Some(40.0)), + ]); + let mut pairs = Vec::new(); + for (index, name) in a.names.iter().enumerate() { + if let Some(position) = b.names.iter().position(|candidate| candidate == name) { + pairs.push((name.clone(), a.values[index], b.values[position])); + } + } + assert_eq!(pairs, vec![ + ("s2".to_string(), 2.0, 20.0), + ("s3".to_string(), 3.0, 30.0), + ]); + } +} diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index 2a7f8a2..a3620f6 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -702,7 +702,7 @@ fn resolve_reference(request: &CorrelationRequest) -> Result<correlation::Refere /// One trait's values, from whichever kind of dataset holds it: a probeset by /// name, a phenotype trait by numeric id. -fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { let request = CorrelationRequest { dataset: dataset.to_string(), trait_name: trait_name.to_string(), diff --git a/src/routes/correlation_matrix.rs b/src/routes/correlation_matrix.rs index 9a433b6..9676cd4 100644 --- a/src/routes/correlation_matrix.rs +++ b/src/routes/correlation_matrix.rs @@ -167,7 +167,7 @@ pub async fn correlation_matrix( } let wanted = request.clone(); - let matrix = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) + let (matrix, references) = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) .await .map_err(|error| { ApiError::new( @@ -192,11 +192,22 @@ pub async fn correlation_matrix( } } let measured = measured / 2; - let pca = if wanted.pca.unwrap_or(false) { + let mut pca = if wanted.pca.unwrap_or(false) { Some(crate::pca::analyse(&matrix)) } else { None }; + // The components as *traits*: a PC is only usable (correlated, mapped, + // plotted, saved in a basket) if it has a value per individual, and that + // needs the values the matrix was built from -- which is why it happens + // here and not in pca::analyse. + if let Some(pca) = pca.as_mut() { + if let Some((values, individuals)) = kept_values_in_order(&references, pca) { + if let Some(traits) = crate::pca::scores(pca, &values, &individuals) { + pca.traits = traits; + } + } + } let mut body = serde_json::json!({ "traits": matrix.traits, "r": matrix.r, @@ -278,6 +289,64 @@ pub async fn correlation_matrix( )) } +/// The aligned values of the traits the PCA kept, over the individuals that +/// have a value for **every** kept trait. +/// +/// PCA of standardised traits is only defined on a complete rectangle, which is +/// the same rule that already dropped traits with a gap: a different individual +/// set per trait would make the scores incomparable across individuals. +fn kept_values_in_order( + references: &[Reference], + pca: &crate::pca::Pca, +) -> Option<(Vec<Vec<f64>>, Vec<String>)> { + let components = pca.components.first()?; + let n_kept = components.loadings.len(); + if n_kept == 0 || n_kept > references.len() { + return None; + } + // The kept traits are the first n_kept that have values; the PCA was built + // from the matrix's own kept order, so take that same order. + let kept: Vec<&Reference> = references + .iter() + .filter(|reference| !reference.is_empty()) + .take(n_kept) + .collect(); + if kept.len() != n_kept { + return None; + } + let individuals: Vec<String> = kept[0] + .names + .iter() + .filter(|name| { + kept.iter().all(|reference| { + reference + .names + .iter() + .position(|candidate| candidate == *name) + .map(|position| true) + .unwrap_or(false) + }) + }) + .cloned() + .collect(); + if individuals.len() < 3 { + return None; + } + let mut values: Vec<Vec<f64>> = Vec::with_capacity(n_kept); + for reference in &kept { + let mut row = Vec::with_capacity(individuals.len()); + for name in &individuals { + let position = reference + .names + .iter() + .position(|candidate| candidate == name)?; + row.push(reference.values[position]); + } + values.push(row); + } + Some((values, individuals)) +} + /// How many traits the request asked for. fn matrix_trait_count(matrix: &Matrix) -> usize { matrix.traits.len() @@ -299,9 +368,10 @@ fn build( request: &MatrixRequest, method: Method, min_overlap: usize, -) -> Result<Matrix, Failure> { +) -> Result<(Matrix, Vec<Reference>), Failure> { let axis = matrix_axis(request)?; let references = resolve_traits(request, axis.as_deref())?; + let references_out = references.clone(); let count = references.len(); let mut r = vec![vec![None; count]; count]; @@ -343,7 +413,7 @@ fn build( } } - Ok(Matrix { + Ok((Matrix { traits: request .traits .iter() @@ -355,7 +425,7 @@ fn build( r, p, n, - }) + }, references_out)) } /// The individuals every trait is measured over: the first trait's group. diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs index 1835b4c..eed7d1c 100644 --- a/src/routes/datasets.rs +++ b/src/routes/datasets.rs @@ -107,7 +107,8 @@ fn get_dataset_probesets_result( #[utoipa::path(get, path = "/datasets/{dataset}/probesets", summary = "List the expression (ProbeSet) traits belonging to a dataset", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( - (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata", body = Envelope<Vec<db::ProbeSetInfo>>), + (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata; \ +`ids_only`/`names_only` answer one value per probeset instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset", body = ApiError), @@ -118,8 +119,20 @@ pub async fn dataset_probesets( ctx: Ctx, Path(dataset): Path<String>, token: AuthToken, -) -> Result<Json<Envelope<Vec<db::ProbeSetInfo>>>, ApiError> { + axum::extract::Query(params): axum::extract::Query<crate::listing::ListingParams>, +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(¶ms).map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "dataset_probesets", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = dataset.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { @@ -150,8 +163,14 @@ pub async fn dataset_probesets( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json( - ctx.envelope(probesets) + DatasetProbesetsLookup::Found(_authorized, probesets) => { + let rows: Vec<serde_json::Value> = probesets + .iter() + .map(|probeset| serde_json::to_value(probeset).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) .with_note(db::LOD_NOTE) .with_next( &format!("/datasets/{}", path_segment(¬_found_name)), @@ -161,8 +180,16 @@ pub async fn dataset_probesets( &format!("/datasets/{}/probesets/{{probeset}}/values", path_segment(¬_found_name)), "One probeset's value per strain, with the mapping suggestions", ) - .with_links(crate::suggest::root_links()), - )), + .with_links(crate::suggest::root_links()); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no probeset: {}", + missing.len(), + missing.join(", ") + )); + } + Ok(Json(envelope)) + } DatasetProbesetsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs index ee2e259..60b4af3 100644 --- a/src/routes/fitqtl.rs +++ b/src/routes/fitqtl.rs @@ -123,6 +123,26 @@ pub async fn compute_fitqtl( Json(mut request): Json<FitqtlRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "fitqtl"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } if let Some(upload) = request.genotype_upload.clone() { if request.genotype_file.is_some() || request.group.is_some() { return Err(ApiError::new( diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index a17010b..fc5c06e 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -22,22 +22,53 @@ use crate::compute_gate; use crate::covariates; use crate::error::{ApiError, Unauthorized}; use crate::genotypes; +use crate::qtl2; use crate::gemma::{self, GemmaError}; use crate::response::{Ctx, Envelope, RequestInfo, path_segment}; use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; +/// Tell the access log what this GEMMA request ran on: the body names the +/// panel (or the upload, file or basket), the path cannot. Called before +/// any validation, so a 4xx still records what was asked for -- a failed +/// compute is as interesting as a successful one. `engine` is the route +/// that will answer: `gemma` (the in-process wrapper), `ravanan` (the +/// per-chromosome workflow) or `pangemma` (the lmdb store); see +/// [`crate::usage`]. +fn record_usage(ctx: Ctx, request: &GemmaRequest, run: Option<&str>, engine: &str) { + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + None, + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + // An explicit `engine` in the body wins over the route's own label, so + // the field says what answered rather than where it was posted. + crate::usage!(ctx, engine = crate::usage::engine(request.engine.as_deref(), engine)); + if let Some(run) = run.map(str::trim).filter(|run| !run.is_empty()) { + crate::usage!(ctx, run = run); + } +} + /// `?id=` on `POST /compute/gemma`: an optional, caller-chosen run id /// to log this run's progress under and poll back via `GET /// /compute/gemma/status/{id}`. Omitted entirely, no log is written. /// Must be unique: a collision with an existing log (another run still /// in progress, or one finished and never polled/cleaned up) errors out /// rather than overwriting it -- see `gemma::GemmaError::RunIdInUse`. -#[derive(Deserialize, utoipa::IntoParams)] +// Clone so that the slurm engine (the default) and the local fallback can +// both be handed the same request: /compute/gemma passes it to the slurm path +// first, and keeps it for the wrapper run when that fails. +#[derive(Clone, Deserialize, utoipa::IntoParams)] pub struct ComputeGemmaParams { pub id: Option<String>, } -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaRequest { /// Path to a BIMBAM genotype file (plain text or gzipped), passed /// as GEMMA's `-g`. Give this and `snps_file`, or `group` -- not @@ -119,10 +150,36 @@ pub struct GemmaRequest { pub permutations: Option<u32>, /// Refused unless 0, as `nperm`. pub permutate: Option<u32>, + + /// How a missing genotype is treated, for the ravanan path: `none` + /// (default -- the file is used as it stands, so GEMMA does complete-case + /// per marker and reports `n_miss`), `mean` (each gap takes that marker's + /// mean) or `hmm` (R/qtl2's HMM predicts it from flanking markers). The + /// last two produce a complete genotype file, which is what a comparison + /// between engines needs: a complete file maps one marker more than + /// complete-case treatment does (21,056 against 21,055 on BXD.8), so the + /// two modes are not interchangeable. `hmm` needs a group-scoped request, + /// since the cross it predicts from is the group's. + /// + /// Neither engine needs it: GEMMA does complete-case per marker, and + /// pangemma's store keeps the gaps (NaN for Gf, 255 for Gb) and + /// mean-substitutes them per marker as GEMMA does -- measured: `none` + /// answers 21,055 rows through pangemma with `af` identical to GEMMA's. + /// The mode is applied before the store is built, so each one gets its own + /// store (they are different genotype files) and an already-imputed panel + /// pays the store build once per mode. + 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. -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaSample { pub name: String, pub value: Option<f64>, @@ -155,6 +212,512 @@ 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`). +/// +/// Both are workflows rather than steps inside the mapping workflow because +/// ccwl's `pipe` is linear -- the GWA step needs the prepared genotypes *and* +/// the kinship matrix, which is a diamond. Ravanan caches each of them on +/// (script, inputs), so the treatment runs once per (panel, mode) and the store +/// once per panel, however many traits follow. +/// +/// Failure here is the caller's error only when it is the *request's* (an +/// unknown mode, `hmm` without a group); a cluster or script failure is a 502 +/// like any other engine failure. +#[allow(clippy::too_many_arguments)] +async fn ravanan_artifacts( + config: &Config, + engine: crate::gemma::GemmaEngine, + mode: &str, + genotype_file: &str, + snps_file: &str, + group: &Option<String>, + version: Option<&str>, + names: Option<&Vec<String>>, + endpoint: &'static str, + 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( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cache directory", + format!("creating {cache_dir} failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + + // The cross `hmm' predicts from, and the individuals this request serves. + // Both are inputs of the prepare workflow even when it ignores them: a CWL + // step input cannot be optional here, and an empty directory and file are + // cheaper than building a cross nobody asked for. + let (cross_dir, cross_note) = if mode == "hmm" { + let Some(group_name) = group.clone() else { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_group", + "hmm imputation needs a group", + "the HMM predicts a missing call from flanking markers in a converted \ + cross, and a cross is built from a group; send `group` (with \ + `genotype_version` if you want a particular version), or use \ + impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + }; + let (directory, cache, convert) = ( + config.genotype_files_dir.clone(), + config.qtl2_cache_dir.clone(), + config.qtl2_convert_script.clone(), + ); + let version = version.map(|v| v.to_string()); + let prepared = tokio::task::spawn_blocking(move || { + let resolved = + genotypes::resolve(std::path::Path::new(&directory), &group_name, version.as_deref()) + .map_err(|error| error.to_string())?; + // Drop is the default genotype model: the heterozygous calls a + // riset panel carries are exactly the ones the HMM is asked to + // re-predict, so predicting from the kept calls would be circular. + qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache), + qtl2::Het::Drop, + std::path::Path::new(&convert), + ) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cross", + format!("preparing the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "cross_preparation_failed", + "Could not prepare the cross", + format!("{error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + let dir = prepared + .control + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)); + // Copy it under the cache directory, which is on the filesystem the + // compute nodes see: ravanan's slurm backend does not stage a Directory + // input (measured: the staged path reached the job and the HMM's setwd + // failed, while the same workflow ran under single-machine), so the job + // reads the cross where it lies instead. The cross's own name carries + // its version and a panel fingerprint, so copying once is enough. + let staged = std::path::Path::new(&config.ravanan_cache_dir) + .join("crosses") + .join(dir.file_name().unwrap_or_default()); + if !staged.is_dir() { + let (from, to) = (dir.clone(), staged.clone()); + tokio::task::spawn_blocking(move || { + std::fs::create_dir_all(to.parent().unwrap_or(&to))?; + let status = std::process::Command::new("cp") + .arg("-r") + .arg(&from) + .arg(&to) + .status()?; + if !status.success() { + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + "cp -r failed", + )); + } + Ok::<(), std::io::Error>(()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("staging the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("copying {} to {} failed: {error}", dir.display(), staged.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + } + ( + staged.to_string_lossy().into_owned(), + Some( + "genotypes: the group's R/qtl2 cross, so a missing call is predicted by the \ + HMM (maxmarg on the same genotype probabilities /compute/qtl2 maps on)" + .to_string(), + ), + ) + } else { + let empty = std::path::Path::new(cache_dir).join("no-cross"); + std::fs::create_dir_all(&empty).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not create the artifact staging directory", + format!("creating {} failed: {error}", empty.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + (empty.to_string_lossy().into_owned(), None) + }; + if let Some(note) = cross_note { + notes.push(note); + } + + // The served individuals, one per line: an input of the workflow, and for + // `hmm' also the list the R script restricts its calls to. + let served = match names { + Some(names) if !names.is_empty() => { + let path = std::path::Path::new(cache_dir).join(format!( + "served-individuals-{}.txt", + crate::gemma::sha16(names.join(",").as_bytes()) + )); + let body: String = names.iter().map(|n| format!("{n}\n")).collect(); + std::fs::write(&path, body).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + _ => { + if mode == "hmm" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_names", + "hmm imputation needs named individuals", + "the HMM is asked for a specific set of individuals, so the request has to \ + name them: send `samples` or a group-scoped request (not positional \ + `trait_values`), or use impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + } + let path = std::path::Path::new(cache_dir).join("no-individuals.txt"); + std::fs::write(&path, "").map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the empty individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + }; + + // Ravanan resolves an input path relative to the inputs YAML, which lives + // in the cache directory -- so a configured script path has to be absolute + // here, not merely valid from the server's working directory (measured: a + // relative prepare-genotypes.sh died inside ravanan as + // "canonicalize-path: No such file or directory"). + let absolute = |path: &str| -> String { + std::fs::canonicalize(path) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| path.to_string()) + }; + let prepare_script = absolute(&config.prepare_genotypes); + let impute_script = absolute(&config.impute_script); + + let (genotype_file, snps_file, individuals_file) = if mode == "none" { + (genotype_file.to_string(), snps_file.to_string(), None) + } else { + let inputs = format!( + "mode: \"{mode}\"\n\ + prepare_script: {{class: File, path: {}}}\n\ + impute_script: {{class: File, path: {}}}\n\ + genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n\ + cross: \"{cross_dir}\"\n\ + 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, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_prepare_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &[ + "mode", + "prepare_script", + "impute_script", + "genotype_file", + "snps_file", + "cross", + "individuals_file", + ], + &inputs, + &["genotype_file", "snps_file", "individuals_file"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let pick = |id: &str| { + outputs + .iter() + .find(|(name, _)| name == id) + .and_then(|(_, paths)| paths.first().cloned()) + .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)" + )); + (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 { + // No converter script: geno2mdb comes from the job's profile + // (gemma-wrapper's bin/geno2mdb, an Odin binary), and ccwl appends + // every declared input to the command line -- a staged copy of the + // binary arrived as argv[1] and was read as the BIMBAM file. + let inputs = format!( + "genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n" + ); + let run = gemma::ArtifactWorkflow { + label: "store", + ccwl_cmd: &config.ccwl_cmd, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_store_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &["genotype_file", "snps_file"], + &inputs, + &["store"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let path = outputs + .iter() + .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)" + .to_string(), + ); + path + } + } else { + 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, + }) +} + +/// What [`ravanan_artifacts`] produced. +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>, + notes: Vec<String>, +} + /// Resolve a request's genotype input and trait values. /// /// `endpoint` names this endpoint in errors ("compute_gemma" or @@ -301,6 +864,9 @@ pub(crate) async fn resolve_inputs( }) .unwrap_or_default(); let supplied_values = request.trait_values.clone(); + // Whether the caller named its values: `named` moves into the alignment + // closure below, and the note after it still has to say which it was. + let had_named_values = !named.is_empty(); match (request.genotype_file.clone(), request.snps_file.clone(), group) { (Some(genotype_file), Some(snps_file), None) => { @@ -320,7 +886,15 @@ pub(crate) async fn resolve_inputs( } else { let path = std::path::PathBuf::from(&genotype_file); let aligned = tokio::task::spawn_blocking(move || { - genotypes::align_to_file(&path, &named) + // A `.geno` names its individuals in the header; a BIMBAM + // does not, so its names come from the `.geno` beside it + // (see `names_for_bimbam`). Without that, named values on + // a file request aligned against nothing and every value + // was dropped. + match genotypes::names_for_bimbam(&path) { + Some(names_source) => genotypes::align_to_columns_of(&names_source, &named), + None => genotypes::align_to_file(&path, &named), + } }) .await .map_err(|error| { @@ -337,8 +911,15 @@ pub(crate) async fn resolve_inputs( aligned }; notes.push(format!( - "Genotype: given file and SNP map; {} values used.", - trait_values.iter().filter(|value| value.is_some()).count() + // Name the order the values ended up in, so a caller can check + // it without knowing the file by heart. + "Genotype: given file and SNP map; {} values used{}.", + trait_values.iter().filter(|value| value.is_some()).count(), + if had_named_values { + ", aligned by name onto the genotype file's individuals" + } else { + "" + } )); Ok(ResolvedInputs { individuals: trait_values.len(), @@ -392,7 +973,21 @@ pub(crate) async fn resolve_inputs( None => keep, }; let dropped_empty = (resolved.panel.len() - parents_f1s) - keep.len(); - let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &named); + // Pad the phenotype over *the genotype file's* individuals + // instead of narrowing the genotypes to the ones that have + // values. Both files must describe the same animals in the + // same order, and padding is the side that cannot drift: an + // excluded animal is a row of NA, which GEMMA drops from the + // fit (and from -gk, where `-p` only names who is analysed), + // while a narrowed genotype file has to be written correctly + // for every delimiter a panel might use -- which is how this + // went wrong: write_subset_bimbam splits on ',' and HSNIH's + // BIMBAM is whitespace-separated, so the "subset" was a byte + // copy of all 6147 columns against a 6111-row phenotype, and + // GEMMA failed every marker (6147 != 6111). + let all_individuals: Vec<usize> = (0..resolved.panel.len()).collect(); + let (aligned, matched) = + genotypes::align(&resolved.panel, &all_individuals, &named); let kept_names: Vec<String> = keep .iter() .filter_map(|index| resolved.panel.get(*index).cloned()) @@ -401,7 +996,7 @@ pub(crate) async fn resolve_inputs( &directory, &resolved, genotypes::Engine::Gemma, - &keep, + &all_individuals, &cache_dir, )?; Ok::<_, genotypes::GenotypeError>(( @@ -560,6 +1155,79 @@ pub async fn compute_gemma( Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this request ran on, for the access log (see crate::usage). + record_usage(ctx.clone(), &request, params.id.as_deref(), "gemma"); + + // Which engine answers: Slurm by default (GEMMA_ENGINE=slurm), the same + // per-chromosome workflow /compute/gemma/ravanan runs; the in-process + // gemma-wrapper run below is then only a fallback, and only for an + // infrastructure failure -- Slurm or ravanan unreachable, the engine + // exiting non-zero, i.e. a 5xx from that path. A 4xx is the caller's + // error and is returned as such, and a numerical disagreement is never a + // 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) + ); + // A treatment the request asked for and the wrapper cannot apply: the + // in-process run reads the panel's genotypes as they stand, so falling back + // to it on `impute: hmm` answered 21,055 rows where the request meant the + // HMM's 20,453 -- a wrong answer wearing a "degraded" note. Treated + // requests therefore fail rather than fall back. + let treated = pangemma + || !request + .impute + .as_deref() + .unwrap_or("none") + .eq_ignore_ascii_case("none"); + let mut fallback_note: Option<String> = None; + if treated || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { + match gemma_via_ravanan( + ctx.clone(), + token.clone(), + params.clone(), + request.clone(), + __gn4_claim, + "compute_gemma", + ) + .await + { + Ok(answer) => return Ok(answer), + Err(error) if error.status >= 500 && !treated => { + eprintln!( + "compute_gemma: slurm route failed ({} {}); falling back to the local gemma-wrapper run", + error.status, error.code + ); + // The claim went with the slurm attempt; a light claim is by + // design cheap and reserves nothing, so take a fresh one for + // the fallback rather than plumbing it back. + __gn4_claim = crate::compute_gate::gemma().claim_light( + &token.sub, + params.id.as_deref(), + "compute_gemma", + "compute_gemma", + "/compute/gemma/status", + ); + fallback_note = Some(format!( + concat!( + "Engine: the Slurm route was unavailable ({} {}), so this answer ", + "comes from the local gemma-wrapper run instead -- same GEMMA, ", + "per-chromosome LOCO computed in process rather than as cluster jobs." + ), + error.status, error.code + )); + } + Err(error) => return Err(error), + } + } + let lmm = request.lmm.unwrap_or(9); // Only the values actually run against this GEMMA build (see the // `lmm` field doc above) are allowed; 5-8 are stock-invalid and @@ -746,6 +1414,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( @@ -800,6 +1471,9 @@ pub async fn compute_gemma( for note in &covariate_notes { envelope = envelope.with_note(note); } + if let Some(note) = &fallback_note { + envelope = envelope.with_note(note); + } for note in &extra_notes { envelope = envelope.with_note(note); } @@ -904,10 +1578,50 @@ 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)) }) } + + +/// Re-order trait values to the individual order of a prepared genotype file. +/// +/// `hmm` genotypes come from the qtl2 cross, whose individuals are the whole +/// panel -- 235 for BXD.8 against the 198 that have trait values. Passing the +/// panel's positional values against those columns makes every individual +/// missing, which GEMMA reports as "no individuals in common" and ravanan as +/// "no association output files"; the fix is to write the phenotype by name in +/// the genotype file's order. +fn align_to_individuals( + individuals_path: &str, + names: &[String], + values: &[Option<f64>], +) -> Result<Vec<Option<f64>>, std::io::Error> { + let by_name: std::collections::HashMap<&str, Option<f64>> = names + .iter() + .map(String::as_str) + .zip(values.iter().copied()) + .collect(); + let text = std::fs::read_to_string(individuals_path)?; + Ok(text + .lines() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(|name| by_name.get(name).copied().flatten()) + .collect()) +} + #[utoipa::path(post, path = "/compute/gemma/ravanan", summary = "Map a QTL with GEMMA, run via ravanan instead of gemma-wrapper directly", description = "Same computation and request/response shape as POST \ @@ -941,7 +1655,263 @@ pub async fn compute_gemma_ravanan( Query(params): Query<ComputeGemmaParams>, Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + record_usage(ctx.clone(), &request, params.id.as_deref(), "ravanan"); + gemma_via_ravanan(ctx, token, params, request, __gn4_claim, "compute_gemma_ravanan").await +} +/// `POST /compute/gemma/async` -- start the same mapping a blocking call would, +/// and answer `202` at once with an id to poll. +/// +/// The blocking endpoints stay the default: this is for a run that cannot fit +/// in a client's patience, which on a large panel is any cold one (a cold +/// HSNIH-Palmer_true scan is ~20 minutes of wall clock; a 5-minute client +/// cutoff could never have returned an answer, and its connection closing used +/// to take the result with it). +#[utoipa::path(post, path = "/compute/gemma/async", + summary = "Start a mapping in the background and return an id to poll", + description = "Same request body as /compute/gemma. Answers 202 with the \ +run's id and the URL of /compute/gemma/result/{id}, which reports progress and \ +then the finished reply. Use it when the run may outlast the client: a cold \ +fit on a large panel takes tens of minutes, and a closed connection would \ +otherwise lose the answer.", + params(ComputeGemmaParams), + request_body = GemmaRequest, + responses( + (status = 202, description = "Run started; poll its id", + body = crate::response::Envelope<serde_json::Value>), + (status = 409, description = "id already in use", body = ApiError) + ) +)] +pub async fn compute_gemma_async( + ctx: Ctx, + token: AuthToken, + Query(params): Query<ComputeGemmaParams>, + Json(request): Json<GemmaRequest>, +) -> Result<(StatusCode, Json<Envelope<serde_json::Value>>), ApiError> { + let rid = ctx.request_info(); + let id = params + .id + .clone() + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| { + // The request id is already a uuid (tower-http's MakeRequestUuid), + // and it is the natural name for a run started by this request. + let rid = ctx.request_info(); + format!( + "run-{}", + rid.id().unwrap_or_else(|| "anonymous".to_string()) + ) + }); + if !streaming::is_valid_run_id(&id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid id", + "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + let engine = match request.engine.as_deref() { + None => crate::gemma::GemmaEngine::Gemma, + Some(value) => crate::gemma::GemmaEngine::parse(value).ok_or_else(|| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_engine", + "Invalid engine", + format!("'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)."), + "compute_gemma_async", + ) + .with_request_id(rid.clone()) + })?, + }; + // The run id is the join key a later result fetch carries in its path, + // so recording it here is what makes "computed and never fetched" + // measurable (see crate::usage). + record_usage(ctx.clone(), &request, Some(&id), engine.as_str()); + if !crate::runs::global().begin(&id, engine.as_str()) { + return Err(ApiError::new( + StatusCode::CONFLICT, + "run_id_in_use", + "Run id already in use", + format!("id '{id}' is already in use by another background run; pick a different id."), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + + let job_id = id.clone(); + // A handle for the 202 body: `ctx` itself moves into the task below. + let reply_ctx = ctx.clone(); + let job_subject = token.sub.clone(); + let mut job_params = params.clone(); + job_params.id = Some(id.clone()); + tokio::spawn(async move { + let claim = crate::compute_gate::ravanan().claim_light( + &job_subject, + Some(&job_id), + "compute_gemma_async", + "compute_gemma_async", + "/compute/gemma/result", + ); + let outcome = gemma_via_ravanan( + ctx, + token, + job_params, + request, + claim, + "compute_gemma_async", + ) + .await; + match outcome { + Ok(Json(envelope)) => { + let body = serde_json::to_value(&envelope).unwrap_or(serde_json::Value::Null); + crate::runs::global().finish(&job_id, body); + } + Err(error) => { + let status = error.status; + let body = serde_json::to_value(&error).unwrap_or(serde_json::Value::Null); + crate::runs::global().fail(&job_id, status, body); + } + } + }); + + let envelope = reply_ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": engine.as_str(), + "status": format!("/compute/gemma/result/{id}"), + })) + .with_note( + "The run is in flight. Poll `status`: it reports how long the run has been going \ + and what the cluster is doing, and returns the finished reply once it completes.", + ); + Ok((StatusCode::ACCEPTED, Json(envelope))) +} + +/// `GET /compute/gemma/result/{id}` -- progress while a background run is in +/// flight, its reply once it finishes, its error if it failed. +#[utoipa::path(get, path = "/compute/gemma/result/{id}", + summary = "Progress or the finished reply of a background mapping", + description = "While the run is in flight: its state, how long it has been \ +running and the cluster's job counts. Afterwards: exactly the body the blocking \ +endpoint would have returned (or the error it would have raised).", + params(("id" = String, Path, description = "The run id given to /compute/gemma/async")), + responses( + (status = 200, description = "Progress, or the finished reply", + body = crate::response::Envelope<serde_json::Value>), + (status = 404, description = "No such run in this process", body = ApiError) + ) +)] +pub async fn gemma_result( + ctx: Ctx, + Path(id): Path<String>, +) -> Result<axum::response::Response, ApiError> { + use axum::response::IntoResponse; let rid = ctx.request_info(); + let Some(run) = crate::runs::global().get(&id) else { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "unknown_run", + "No such run", + format!( + "no background run '{id}' in this process; it may have finished before a \ + restart, in which case re-post the request (ravanan's store answers the \ + steps it already ran)." + ), + "compute_gemma_result", + ) + .with_request_id(rid)); + }; + match run.state.as_str() { + "finished" => { + let body = run.result.unwrap_or(serde_json::Value::Null); + Ok((StatusCode::OK, Json(body)).into_response()) + } + "failed" => { + let (status, body) = run.error.unwrap_or(( + 500, + serde_json::json!({"code": "internal_error", "detail": "no error recorded"}), + )); + let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + Ok((status, Json(body)).into_response()) + } + _ => { + // Still running: what we can measure from outside the run -- the + // clock, and the cluster's view of the jobs this request submitted. + let since_epoch = run + .started_at + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs()) + .unwrap_or(0); + let config = Config::load(); + let (cluster, steps) = crate::gemma::cluster_timing( + &config.ravanan_batch, + since_epoch, + &format!("{}/ravanan-store", config.ravanan_cache_dir), + ) + .await; + let envelope = ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": run.engine, + "elapsed_ms": run.elapsed_ms(), + "cluster": cluster, + "steps_recorded": steps.len(), + })) + .with_note( + "Still running. elapsed_ms is this process's clock for the run, \ + meta.timing.cluster counts the jobs Slurm accepted for it, and \ + steps_recorded counts the step logs already in the store.", + ); + Ok((StatusCode::OK, Json(envelope)).into_response()) + } + } +} + +/// The Slurm path, callable from either GEMMA endpoint. +/// +/// `/compute/gemma/ravanan` is this and nothing else, and `/compute/gemma` +/// uses it as its *default* engine when `GEMMA_ENGINE=slurm` (the default), +/// falling back to its own in-process gemma-wrapper run when this answers +/// 5xx -- i.e. when Slurm, ravanan or the engine is unavailable. A 4xx is a +/// caller error and is returned as such; a numerical disagreement is never a +/// reason to fall back, because it would hide a regression behind an answer +/// from the other engine. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn gemma_via_ravanan( + ctx: Ctx, + token: AuthToken, + params: ComputeGemmaParams, + mut request: GemmaRequest, + mut __gn4_claim: crate::compute_gate::Claim<'static>, + 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. + 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) { + 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( @@ -951,7 +1921,7 @@ pub async fn compute_gemma_ravanan( format!( "lmm must be one of 1, 2, 3, 4, 9 (got {lmm}); 1=Wald, 2=LRT, 3=score, 4=all three, 9=GeneNetwork's convention (observed to behave like LRT)." ), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -962,7 +1932,7 @@ pub async fn compute_gemma_ravanan( "invalid_run_id", "Invalid id", "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -979,12 +1949,22 @@ pub async fn compute_gemma_ravanan( let ResolvedInputs { genotype_file, snps_file, - trait_values, + mut trait_values, individuals: panel_individuals, - names: _, - group: _, + names: resolved_names, + group: resolved_group, notes: input_notes, - } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", 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, @@ -993,7 +1973,7 @@ pub async fn compute_gemma_ravanan( "ravanan needs a genotype file and a SNP map (a group whose version has a BIMBAM \ pair, an upload, or genotype_file + snps_file) and at least one trait value." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1010,7 +1990,7 @@ pub async fn compute_gemma_ravanan( step, so `covariates` cannot be fitted on this path. Use POST /compute/gemma \ for a covariate fit, or drop the covariates." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1022,11 +2002,81 @@ pub async fn compute_gemma_ravanan( "send the values already normalized, or use POST /compute/gemma, which applies \ its normalization pipeline before the run." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } + // Genotypes as the caller asked for them: `impute` decides what happens to + // a missing call, and both non-default answers produce a complete file. + // Doing it here rather than inside the workflow keeps one implementation + // (`scripts/prepare-genotypes.sh`) for every engine, which is the point -- + // the same trait can then be mapped with `mean` and with `hmm` and the two + // answers compared. + let impute = request + .impute + .clone() + .unwrap_or_else(|| "none".to_string()) + .to_ascii_lowercase(); + if !matches!(impute.as_str(), "none" | "mean" | "hmm") { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_impute", + "Invalid impute mode", + format!("'{}' is not a mode; use none, mean or hmm.", impute), + endpoint, + ) + .with_request_id(rid)); + } + // The genotypes as the caller asked for them, built on the cluster: the + // `hmm`/`mean` treatment and pangemma's lmdb store are workflows of their + // own (see ravanan_artifacts), so what arrives here are paths in ravanan's + // store. + let artifacts = ravanan_artifacts( + &config, + engine, + &impute, + &genotype_file, + &snps_file, + &Some(resolved_group.clone()), + request.genotype_version.as_deref(), + resolved_names.as_ref(), + endpoint, + rid.clone(), + ) + .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)) = + (artifacts.individuals_file.as_deref(), resolved_names.as_deref()) + { + match align_to_individuals(individuals, names, &trait_values) { + Ok(aligned) => { + impute_notes.push(format!( + "genotypes: trait values aligned by name to the {} individuals of the \ + HMM calls ({} had a value in the panel)", + aligned.len(), + trait_values.iter().filter(|v| v.is_some()).count() + )); + trait_values = aligned; + } + Err(error) => { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not align individuals", + format!("reading {individuals} failed: {error}"), + endpoint, + ) + .with_request_id(rid)); + } + } + } + } + let store = artifacts.store; + // Gated like the direct GEMMA run and by the same size rule, now with the // real panel size: a samples-only request used to be sized 0 and took no // slot at all. @@ -1036,14 +2086,38 @@ pub async fn compute_gemma_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 { - gemma::compute_ravanan( + // 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, + }; + let output = gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, - &config.gemma_ravanan_workflow, - &config.gemma_ravanan_manifest, + &ravanan_workflow, + store.as_deref(), + request_started, &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, @@ -1059,14 +2133,24 @@ pub async fn compute_gemma_ravanan( "run_id_in_use", "Run id already in use", format!("id '{id}' is already in use; pick a different id."), - "compute_gemma_ravanan", + endpoint, ) .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) @@ -1075,14 +2159,75 @@ pub async fn compute_gemma_ravanan( "Rows come from GEMMA's own .assoc.txt output, positional (see meta.columns for names); column names depend on the lmm value used.", ); // What the request resolved to first (which genotype version, how many - // values aligned, what was dropped), then the run's own notes. + // values aligned, what was dropped), how the genotypes were treated if + // the caller asked for imputation, then the run's own notes. for note in &input_notes { envelope = envelope.with_note(note); } + for note in &impute_notes { + envelope = envelope.with_note(note); + } 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: "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, + 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)) }) } diff --git a/src/routes/genoupload.rs b/src/routes/genoupload.rs index bd12018..d6d688b 100644 --- a/src/routes/genoupload.rs +++ b/src/routes/genoupload.rs @@ -55,6 +55,14 @@ fn map_error(error: BasketError, rid: RequestInfo, operation: &'static str) -> A operation, ) .with_request_id(rid), + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Name already in use", + message, + operation, + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_genotype_upload", diff --git a/src/routes/groups.rs b/src/routes/groups.rs index dd59165..28e9c03 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -30,6 +30,16 @@ pub struct GroupsParams { /// Keep groups whose name, display name or full name contains this /// text, case-insensitively, e.g. "alzheimer". pub q: Option<String>, + /// Keep only these ids or names, comma-separated. Values that match nothing + /// are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per group instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per group instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } fn contains_ci(field: &Option<String>, needle: &str) -> bool { @@ -39,7 +49,8 @@ fn contains_ci(field: &Option<String>, needle: &str) -> bool { } #[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows), optionally filtered", params(GroupsParams), responses( - (status = 200, description = "The groups (InbredSet rows), with family and species name", body = Envelope<Vec<db::Group>>), + (status = 200, description = "The groups (InbredSet rows), with family and species name; \ +`ids_only`/`names_only` answer one value per group instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] @@ -48,8 +59,24 @@ pub async fn groups( ctx: Ctx, _token: AuthToken, Query(params): Query<GroupsParams>, -) -> Result<Json<Envelope<Vec<db::Group>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "groups", + ) + .with_request_id(rid.clone()) + })?; + let listing_rid = rid.clone(); tokio::task::spawn_blocking(db::get_all_groups) .await .map_err(|e| { @@ -86,10 +113,24 @@ pub async fn groups( }) }) .collect(); - Json(ctx.envelope(groups).with_next( + let rows: Vec<serde_json::Value> = groups + .iter() + .map(|group| serde_json::to_value(group).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let _ = &listing_rid; + let mut envelope = ctx.envelope(shaped).with_next( "/species", "The species the groups belong to (filter groups with ?species=<name>)", - )) + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no group: {}", + missing.len(), + missing.join(", ") + )); + } + Json(envelope) }) .map_err(|e| ApiError::from_db(e, "groups").with_request_id(rid)) } @@ -210,6 +251,16 @@ pub async fn group_by_name( #[derive(serde::Deserialize)] pub struct GroupStrainsParams { used_for_mapping: Option<bool>, + /// Keep only these ids or names, comma-separated. Values that match nothing + /// are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per strain instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per strain instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } #[utoipa::path(get, path = "/groups/{group}/parents-and-f1s", @@ -327,7 +378,8 @@ pub async fn group_parental_design( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping") ), responses( - (status = 200, description = "The strains/samples belonging to the group", body = Envelope<Vec<db::Strain>>), + (status = 200, description = "The strains/samples belonging to the group; \ +`ids_only`/`names_only` answer one value per strain instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -338,8 +390,24 @@ pub async fn group_strains( Path(group): Path<String>, Query(params): Query<GroupStrainsParams>, _token: AuthToken, -) -> Result<Json<Envelope<Vec<db::Strain>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_strains", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); let used_for_mapping = params.used_for_mapping; tokio::task::spawn_blocking(move || { @@ -362,18 +430,30 @@ pub async fn group_strains( .map_err(|e| ApiError::from_db(e, "group_strains").with_request_id(rid.clone()))? .map(|strains| { let group = path_segment(¬_found_name); - Json( - ctx.envelope(strains) - .with_next( - &format!("/groups/{group}"), - "The group these strains belong to", - ) - .with_links(crate::suggest::group_links(¬_found_name)) - .with_next( - &format!("/groups/{group}/case-attributes"), - "Case-attribute names and per-strain values", - ), - ) + let rows: Vec<serde_json::Value> = strains + .iter() + .map(|strain| serde_json::to_value(strain).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) + .with_next( + &format!("/groups/{group}"), + "The group these strains belong to", + ) + .with_links(crate::suggest::group_links(¬_found_name)) + .with_next( + &format!("/groups/{group}/case-attributes"), + "Case-attribute names and per-strain values", + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no strain: {}", + missing.len(), + missing.join(", ") + )); + } + Json(envelope) }) .ok_or_else(|| { ApiError::new( @@ -727,6 +807,16 @@ pub struct GroupTraitsParams { /// Only the traits with this short name (abbreviation), e.g. /// "5HT_MB_M" or "3NP_Tox". pub abbreviation: Option<String>, + /// Keep only these ids or trait names, comma-separated. Values that match + /// nothing are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per trait instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per trait instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } enum GroupTraitsLookup { @@ -764,7 +854,8 @@ fn get_group_traits_result( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), GroupTraitsParams ), responses( - (status = 200, description = "The published traits belonging to the group", body = Envelope<Vec<db::TraitInfo>>), + (status = 200, description = "The published traits belonging to the group; \ +`ids_only`/`names_only` answer one value per trait instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 403, description = "The group's published data isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group", body = ApiError), @@ -776,8 +867,24 @@ pub async fn group_traits( Path(group): Path<String>, token: AuthToken, Query(params): Query<GroupTraitsParams>, -) -> Result<Json<Envelope<Vec<db::TraitInfo>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_traits", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { @@ -813,15 +920,27 @@ pub async fn group_traits( .and_then(|lookup| match lookup { GroupTraitsLookup::Found(traits) => { let group = path_segment(¬_found_name); - Ok(Json( - ctx.envelope(traits) - .with_note(db::LOD_NOTE) - .with_links(crate::suggest::root_links()) - .with_next( + let rows: Vec<serde_json::Value> = traits + .iter() + .map(|trait_info| serde_json::to_value(trait_info).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) + .with_note(db::LOD_NOTE) + .with_links(crate::suggest::root_links()) + .with_next( &format!("/groups/{group}"), "The group these traits belong to", - ), - )) + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no trait: {}", + missing.len(), + missing.join(", ") + )); + } + Ok(Json(envelope)) } GroupTraitsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, @@ -1060,7 +1179,8 @@ pub async fn group_trait_case_attribute( #[utoipa::path(get, path = "/groups/{group}/datasets", summary = "List the expression (ProbeSet) datasets belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") ), responses( - (status = 200, description = "The expression (ProbeSet) datasets belonging to the group", body = Envelope<Vec<db::Dataset>>), + (status = 200, description = "The expression (ProbeSet) datasets belonging to the group; \ +`ids_only`/`names_only` answer one value per dataset instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -1070,8 +1190,20 @@ pub async fn group_datasets( ctx: Ctx, Path(group): Path<String>, _token: AuthToken, -) -> Result<Json<Envelope<Vec<db::Dataset>>>, ApiError> { + Query(params): Query<crate::listing::ListingParams>, +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(¶ms).map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_datasets", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); tokio::task::spawn_blocking(move || { db::get_group_by_name(&group).and_then(|group| match group { @@ -1106,13 +1238,25 @@ pub async fn group_datasets( ), ) }); + let rows: Vec<serde_json::Value> = datasets + .iter() + .map(|dataset| serde_json::to_value(dataset).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); let mut envelope = ctx - .envelope(datasets) + .envelope(shaped) .with_next( &format!("/groups/{}", path_segment(¬_found_name)), "The group these datasets belong to", ) .with_links(crate::suggest::group_links(¬_found_name)); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no dataset: {}", + missing.len(), + missing.join(", ") + )); + } if let Some((href, description)) = example { envelope = envelope.with_next(&href, &description); } diff --git a/src/routes/matrices.rs b/src/routes/matrices.rs index b8b3967..a392456 100644 --- a/src/routes/matrices.rs +++ b/src/routes/matrices.rs @@ -67,6 +67,14 @@ fn map_error(error: BasketError, rid: RequestInfo) -> ApiError { "matrices", ) .with_request_id(rid), + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Name already in use", + message, + "matrices", + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_matrix", diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0461165..0da2eaa 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod baskets; pub mod bnw; pub mod bulklmm; +pub mod compare; pub mod correlation; pub mod correlation_matrix; pub mod datasets; diff --git a/src/routes/plot.rs b/src/routes/plot.rs index 2b4c043..0f698be 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -158,11 +158,16 @@ fn check_gemma_result(posted: &serde_json::Value) -> Result<(), String> { /// What `/plot/rqtl` validates in a posted R/qtl result: `data.markers`, /// each row `[name, chr, pos, lod, ...]`. fn check_rqtl_result(result: &serde_json::Value) -> Result<(), String> { - let rows = result["data"]["markers"] - .as_array() - .ok_or("`data.markers` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; + // `data` is the marker array; a reply from a build before that change kept + // it under `data.markers`, and a caller may still be holding one. + let rows = if result["data"].is_array() { + result["data"].as_array() + } else { + result["data"]["markers"].as_array() + } + .ok_or("`data` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; if rows.is_empty() { - return Err("`data.markers` is empty: nothing to plot".to_string()); + return Err("`data` is empty: nothing to plot".to_string()); } let first = rows[0] .as_array() @@ -346,7 +351,7 @@ pub async fn plot_gemma( } /// The SVG, with the plotter's summary alongside it. -fn svg_response(rendered: plot::Plot) -> Response { +pub(crate) fn svg_response(rendered: plot::Plot) -> Response { let mut response = rendered.svg.into_response(); let headers = response.headers_mut(); headers.insert( diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index 896c0e9..46ce90d 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -174,6 +174,27 @@ pub async fn compute_qtl2( Json(mut request): Json<Qtl2Request>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on: the body names the panel or the trait, the path + // cannot (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "qtl2"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } // An uploaded genotype is just another `.geno`: materialise it and let the // path branch below do the rest. if let Some(upload) = request.genotype_upload.clone() { @@ -675,10 +696,14 @@ pub async fn compute_qtl2( let genotype_root = config.genotype_files_dir.clone(); let cache_dir_for_cross = cache_dir.clone(); let het_for_cross = het; + let convert_for_cross = config.qtl2_convert_script.clone(); let cross = tokio::task::spawn_blocking(move || match source_for_cross { - Source::Convert(resolved) => { - qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir_for_cross), het_for_cross) - } + Source::Convert(resolved) => qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache_dir_for_cross), + het_for_cross, + std::path::Path::new(&convert_for_cross), + ), Source::Control(name) => { qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name) } diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index c02adbe..1b9607e 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -137,6 +137,24 @@ pub async fn compute_rqtl( Json(mut request): Json<RqtlRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + crate::usage!(ctx, trait = request.trait_name.as_str()); + crate::usage!(ctx, engine = "rqtl"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } if let Some(upload) = request.genotype_upload.clone() { if request.genotype_file.is_some() || request.group.is_some() { return Err(ApiError::new( @@ -546,12 +564,30 @@ pub async fn compute_rqtl( // responses from the same panel apart, and `/plot/rqtl` reads it // for the title. let mut envelope = ctx - .envelope(rqtl::to_json(output)) + // `data` is the marker rows, like every other compute endpoint: + // the permutation null is qualifier information and goes to + // meta.extra, so a caller can write one script for all of them + // (measured: Rob Williams's test-drive read data.markers here and + // data itself on GEMMA, and had to special-case both). + .envelope(rqtl::marker_rows(&output)) .with_columns(rqtl::MARKER_COLUMNS.iter().map(|s| s.to_string()).collect(), num_rows) .with_note(&format!("Trait: {}", request.trait_name)) .with_note( - "markers come from R/qtl's scanone output, positional (see meta.columns for names); permutation is null unless nperm > 0 was requested.", + "markers come from R/qtl's scanone output, positional (see meta.columns for names); the permutation null, when nperm > 0 was requested, is meta.permutation.", + ) + // The conversion is not silent in the status log, but it was + // silent here: every heterozygous call is dropped and X becomes an + // autosome, while GEMMA keeps a heterozygote as 0.5. A caller + // comparing the two engines has to know that. + .with_note( + "R/qtl reads this panel as a riself cross: heterozygous calls are dropped (the \ + run log counts them) and X is treated as an autosome. GEMMA models the same \ + panel with heterozygotes at 0.5, so the two are different models, not two \ + implementations of one.", ); + if let Some(permutation) = rqtl::permutation_json(&output) { + envelope = envelope.with_extra("permutation", permutation); + } for note in ¬es { envelope = envelope.with_note(note); } diff --git a/src/routes/search.rs b/src/routes/search.rs index 20f9712..22ce169 100644 --- a/src/routes/search.rs +++ b/src/routes/search.rs @@ -216,10 +216,23 @@ pub async fn search( (limit, page) }; + // The query itself goes in the line here, and only here: the access log + // drops query strings on purpose (one can carry a credential), so `?q=` + // is otherwise invisible -- and "what people search for" is the most + // useful behavioural signal the API has. Bounded, and sanitised only by + // being text: see crate::usage. + crate::usage!(ctx, q = q); + crate::usage!(ctx, type = search_type); + crate::usage!( + ctx, + engine = crate::config::Config::load().search_engine.clone() + ); + let mut hits = search::search(q, search_type, fetch_limit, gn3_page) .await .map_err(|e| engine_error(e, rid))?; let fetched = hits.len() as u64; + crate::usage!(ctx, hits = fetched); for hit in &mut hits { hit.lod = hit.lrs.map(db::lod); } diff --git a/src/rqtl.rs b/src/rqtl.rs index 2bf6de3..7dd608d 100644 --- a/src/rqtl.rs +++ b/src/rqtl.rs @@ -495,32 +495,39 @@ pub const MARKER_COLUMNS: [&str; 4] = ["name", "chr", "pos", "lod"]; /// is what utoipa needs here. `markers` rows are positional (see /// `MARKER_COLUMNS`), the same space-saving shape `crate::gemma::compute` /// uses for its own (much larger) marker rows. -pub fn to_json(output: RqtlOutput) -> Value { - let markers: Vec<Value> = output - .markers - .into_iter() - .map(|m| { - let mut row = vec![ - Value::String(m.name), - Value::String(m.chr), - serde_json::json!(m.pos), - serde_json::json!(m.lod), - ]; - row.extend(m.extra.into_iter().map(Value::String)); - Value::Array(row) - }) - .collect(); - serde_json::json!({ - "markers": markers, - "permutation": output.permutation, - }) +pub fn marker_rows(output: &RqtlOutput) -> Value { + Value::Array( + output + .markers + .iter() + .map(|m| { + let mut row = vec![ + Value::String(m.name.clone()), + Value::String(m.chr.clone()), + serde_json::json!(m.pos), + serde_json::json!(m.lod), + ]; + row.extend(m.extra.iter().cloned().map(Value::String)); + Value::Array(row) + }) + .collect(), + ) +} + +/// The permutation null, for `meta.extra` beside the rows -- it qualifies the +/// scan rather than being one of its rows, which is why it is not in `data` +/// (that is where every other compute endpoint keeps its rows). +pub fn permutation_json(output: &RqtlOutput) -> Option<Value> { + output + .permutation + .as_ref() + .and_then(|permutation| serde_json::to_value(permutation).ok()) } /// The marker with the strongest LOD in a `to_json` result, if there is /// one: the QTL's peak, which is what a PheWAS wants to be centred on. pub fn peak_marker(data: &Value) -> Option<String> { - data.get("markers")? - .as_array()? + data.as_array()? .iter() .filter_map(|row| { let row = row.as_array()?; @@ -661,16 +668,14 @@ mod tests { #[test] fn the_peak_marker_is_the_strongest_lod() { - let data = serde_json::json!({ - "markers": [ - ["rs1", "1", 3.0, 0.5], - ["rs2", "3", 9.0, 4.2], - ["rs3", "5", 12.0, 1.1] - ], - "permutation": null - }); + // `data` is the rows themselves; the permutation null is in meta. + let data = serde_json::json!([ + ["rs1", "1", 3.0, 0.5], + ["rs2", "3", 9.0, 4.2], + ["rs3", "5", 12.0, 1.1] + ]); assert_eq!(peak_marker(&data).as_deref(), Some("rs2")); - assert_eq!(peak_marker(&serde_json::json!({"markers": []})), None); + assert_eq!(peak_marker(&serde_json::json!([])), None); assert_eq!(peak_marker(&serde_json::json!({})), None); } diff --git a/src/runs.rs b/src/runs.rs new file mode 100644 index 0000000..d62333f --- /dev/null +++ b/src/runs.rs @@ -0,0 +1,126 @@ +//! Compute runs started in the background, so a caller that cannot wait for a +//! long one -- a cold LOCO scan of a large panel is ~20 minutes here -- can +//! still collect its result. +//! +//! `POST /compute/gemma/async` registers an id, spawns the work and returns +//! `202` at once; `GET /compute/gemma/result/{id}` reports progress while it +//! runs and the finished reply afterwards. The blocking endpoints are +//! unchanged, so nothing that fits in a client's patience starts using this. +//! +//! In-process and unbounded on purpose: results live for the life of the +//! process (a finished reply, not a cache), so a restart forgets them -- the +//! same lifetime as the run itself, and the caller can always re-post, which +//! ravanan's store answers from its cache. +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Instant, SystemTime}; + +/// One background run. +#[derive(Clone)] +pub struct Run { + pub engine: String, + pub started: Instant, + pub started_at: SystemTime, + /// `running`, `finished` or `failed`. + pub state: String, + /// The finished reply's body, exactly as the blocking endpoint would have + /// answered it. + pub result: Option<serde_json::Value>, + /// The failure body, with the status code the blocking endpoint would have + /// used, so a caller can tell a 4xx from a 5xx. + pub error: Option<(u16, serde_json::Value)>, +} + +impl Run { + pub fn elapsed_ms(&self) -> u64 { + self.started.elapsed().as_millis() as u64 + } +} + +#[derive(Clone, Default)] +pub struct Registry { + runs: Arc<Mutex<HashMap<String, Run>>>, +} + +fn registry() -> &'static Registry { + static REGISTRY: OnceLock<Registry> = OnceLock::new(); + REGISTRY.get_or_init(Registry::default) +} + +/// What the handlers use. +pub fn global() -> &'static Registry { + registry() +} + +impl Registry { + /// Registers `id` as running. Returns false when it is already known, so a + /// caller cannot silently take over another run's id. + pub fn begin(&self, id: &str, engine: &str) -> bool { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if runs.contains_key(id) { + return false; + } + runs.insert( + id.to_string(), + Run { + engine: engine.to_string(), + started: Instant::now(), + started_at: SystemTime::now(), + state: "running".to_string(), + result: None, + error: None, + }, + ); + true + } + + pub fn finish(&self, id: &str, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "finished".to_string(); + run.result = Some(body); + } + } + + pub fn fail(&self, id: &str, status: u16, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "failed".to_string(); + run.error = Some((status, body)); + } + } + + pub fn get(&self, id: &str) -> Option<Run> { + let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + runs.get(id).cloned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_run_is_registered_once_and_remembers_its_outcome() { + let registry = Registry::default(); + assert!(registry.begin("r1", "pangemma")); + assert!(!registry.begin("r1", "gemma"), "ids are not taken over"); + let run = registry.get("r1").expect("registered"); + assert_eq!(run.state, "running"); + assert_eq!(run.engine, "pangemma"); + registry.finish("r1", serde_json::json!({"data": []})); + let run = registry.get("r1").expect("still there"); + assert_eq!(run.state, "finished"); + assert_eq!(run.result.unwrap()["data"], serde_json::json!([])); + } + + #[test] + fn a_failure_keeps_the_status_the_blocking_endpoint_would_have_used() { + let registry = Registry::default(); + registry.begin("r2", "gemma"); + registry.fail("r2", 422, serde_json::json!({"code": "no_samples_aligned"})); + let run = registry.get("r2").expect("registered"); + assert_eq!(run.state, "failed"); + assert_eq!(run.error.unwrap().0, 422); + } +} diff --git a/src/usage.rs b/src/usage.rs new file mode 100644 index 0000000..2f18613 --- /dev/null +++ b/src/usage.rs @@ -0,0 +1,333 @@ +//! What the *work* was, for the access log — the half a path cannot say. +//! +//! The access line (`request_log_line`, src/lib.rs) is built by middleware +//! that never sees a request body, so on its own it can say which endpoint +//! ran but not which data it ran on: `/compute/gemma` names its panel in +//! the body (`group`, `genotype_file`, `genotype_upload`), and +//! `/compute/bulklmm` names its traits there too. Measured on the week to +//! 2026-11-27, that is 706 of 2 272 requests whose dataset could only be +//! *guessed* from whatever the same user had read a minute earlier. +//! +//! So a handler that knows the answer says it, once, and the line grows +//! those fields: +//! +//! ```ignore +//! usage!(ctx, dataset = &group, engine = "pangemma", run = &run_id); +//! // {"event":"request", …, "dataset":"HSNIH-Palmer","engine":"pangemma","run":"t42"} +//! ``` +//! +//! Deliberately **not** every route: a read route already carries the +//! dataset (`/traits/{dataset}/{trait}/values`) or the group +//! (`/groups/{group}/…`) in its path, so instrumenting it would only +//! duplicate the path into the line. The tracked set is the compute +//! family, listed in [`TRACKED`], plus `/search` — whose query string the +//! line drops on purpose (a query string can carry a credential), which +//! is why `q` is recorded here instead, by the handler, sanitised. +//! +//! Two rules for a value: it is **not a secret** (never a token, a hash or +//! a file's contents), and it is **bounded** — [`MAX_VALUE`] characters, +//! truncated by `note`, because a field a caller controls must not become +//! a way to write megabytes into the log. + +use std::sync::{Arc, Mutex}; + +/// The longest value a field may carry. `q` on `/search` is caller text, +/// and a query can be long: the line stays readable and bounded. +pub const MAX_VALUE: usize = 200; + +/// Keys the line already owns. A handler must not write one of these: it +/// would overwrite the request's own record (`status`, `user`) or invent a +/// second `path`. Checked by [`tests::no_tracked_field_shadows_the_line`]. +pub const RESERVED: &[&str] = &[ + "event", + "method", + "path", + "status", + "took_ms", + "ts", + "request_id", + "user", + "scheme", + "token", +]; + +/// The handlers that must report what they ran on, and the fields each is +/// expected to add. This is documentation *and* the guard: a test walks +/// [`TRACKED`] against the source (see [`tests::every_tracked_handler_reports`]), +/// so a handler edited later without its `usage!` call fails a test rather +/// than silently going dark. +/// +/// Field meanings, shared across handlers so the log stays joinable: +/// +/// - `dataset`: a GeneNetwork dataset name (`UTHSC_BXD_Cochlea_0225`), or a +/// panel name when the request named a group. Use `group` for the second +/// case; both is best (`dataset = group` when they are the same). +/// - `group`: an `InbredSet` name (`BXD`, `HSNIH-Palmer`). +/// - `trait`: the trait id or name the request named, when it named one. +/// - `traits`: how many, for the multi-trait routes (`bulklmm`, `bnw`). +/// - `source`: where the data came from: `group`, `file`, `upload`, +/// `basket`, `values`. +/// - `engine`: `gemma` | `pangemma` | `ravanan` | `rqtl` | `qtl2` | +/// `bulklmm` | `bnw` | `native` | `gn3`. +/// - `cached`: `true` when the answer came from a cache instead of a run. +/// - `run`: the run id the caller can poll or fetch. +/// - `q`: the sanitised `/search` query. +pub const TRACKED: &[(&str, &[&str])] = &[ + ("compute_gemma", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_ravanan", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_async", &["dataset", "group", "source", "engine"]), + ("compute_qtl2", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_rqtl", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_fitqtl", &["dataset", "group", "source", "trait", "engine"]), + ("compute_bulklmm", &["group", "source", "trait", "engine"]), + ("compute_bnw", &["group", "traits", "engine"]), + ("compute_bnw_features", &["group", "traits", "engine"]), + ("search", &["q", "type", "engine", "hits"]), +]; + +/// Where a compute request's data came from: the `dataset`/`source` +/// pair every compute handler reports. +/// +/// Order matters and is the order a request may name them: a `group` is +/// the common case and names a panel (`HSNIH-Palmer`), then an upload (by +/// its handle, `Arabid.thaliana.genotypes.171126`), then a file on the +/// server -- logged by its stem, because the directory is an +/// implementation detail and `BXD.geno` says the same thing -- and last a +/// basket. `None` when the request gave only inline values, which is +/// honest: there is no dataset to name. +pub fn source<'a>( + group: Option<&'a str>, + upload: Option<&'a str>, + file: Option<&'a str>, + basket: Option<&'a str>, +) -> Option<(&'static str, String)> { + if let Some(group) = group.map(str::trim).filter(|group| !group.is_empty()) { + return Some(("group", group.to_string())); + } + if let Some(upload) = upload.map(str::trim).filter(|upload| !upload.is_empty()) { + return Some(("upload", upload.to_string())); + } + if let Some(file) = file.map(str::trim).filter(|file| !file.is_empty()) { + let stem = std::path::Path::new(file) + .file_stem() + .map(|stem| stem.to_string_lossy().to_string()) + .unwrap_or_else(|| file.to_string()); + return Some(("file", stem)); + } + if let Some(basket) = basket.map(str::trim).filter(|basket| !basket.is_empty()) { + return Some(("basket", basket.to_string())); + } + None +} + +/// The `engine` field: what the request asked for, else what the +/// deployment defaults to. Lower-cased, because the value is compared and +/// counted, not read. +pub fn engine(requested: Option<&str>, default: &str) -> String { + let engine = requested + .map(str::trim) + .filter(|engine| !engine.is_empty()) + .unwrap_or(default); + engine.to_ascii_lowercase() +} + +/// The per-request slot a handler writes its fields into. +/// +/// An `Arc` behind a mutex, exactly like [`crate::auth::CallerSlot`], for +/// the same reason: the handler is not the only holder of the request's +/// [`crate::response::Ctx`] (compute clones it for the fallback path), and +/// every handle must land in the one line. The lock is taken once per +/// note on an instrumented route and never otherwise. +#[derive(Clone, Debug, Default)] +pub struct UsageSlot(Arc<Mutex<Vec<(&'static str, serde_json::Value)>>>); + +impl UsageSlot { + /// Record fields for the line. A later note with the same key replaces + /// the earlier one, so a handler can say what was asked at the top and + /// add `cached` once it knows. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + if pairs.is_empty() { + return; + } + let mut guard = match self.0.lock() { + Ok(guard) => guard, + // A poisoned slot must not fail a request: an access-log field + // is not worth a 500, and the line is still written without it. + Err(poisoned) => poisoned.into_inner(), + }; + for (key, value) in pairs { + debug_assert!( + !RESERVED.contains(key), + "{key} is a field of the line itself, not a usage field" + ); + debug_assert!( + !matches!(value, serde_json::Value::String(text) if text.len() > MAX_VALUE), + "note() should have truncated {key}" + ); + match guard.iter_mut().find(|(name, _)| name == key) { + Some(slot) => slot.1 = value.clone(), + None => guard.push((key, value.clone())), + } + } + } + + /// The fields noted so far, in the order they were first noted. + pub fn entries(&self) -> Vec<(&'static str, serde_json::Value)> { + match self.0.lock() { + Ok(guard) => guard.clone(), + Err(poisoned) => poisoned.into_inner().clone(), + } + } + + /// A value as the line will carry it: a string is bounded to + /// [`MAX_VALUE`] characters; a number or a bool stays one, so a reader + /// can count `hits` or test `cached` without parsing text back. + pub fn json<T: Into<serde_json::Value>>(value: T) -> serde_json::Value { + match value.into() { + serde_json::Value::String(text) => serde_json::Value::String(Self::bounded(&text)), + other => other, + } + } + + /// Truncate to [`MAX_VALUE`] characters, on a character boundary (the + /// query is caller text and may be multi-byte). + pub fn bounded(value: &str) -> String { + if value.len() <= MAX_VALUE { + return value.to_string(); + } + let mut end = MAX_VALUE; + while end > 0 && !value.is_char_boundary(end) { + end -= 1; + } + let mut truncated = value[..end].to_string(); + truncated.push('…'); + truncated + } +} + +/// Record usage fields for this request; see the module docs. Values are +/// anything `ToString` (`&str`, `String`, `bool`, numbers), so a handler +/// writes what it has without converting first. +/// +/// ```ignore +/// usage!(ctx, dataset = &group, source = "group", engine = "gemma"); +/// ``` +/// The key is `stringify!`ed, so it is written bare (`group = …`) and may be +/// a keyword (`type = …` on `/search`); it ends up a `&'static str` in the +/// line, which is what keeps a field name from being built at runtime. +#[macro_export] +macro_rules! usage { + ($ctx:expr $(, $key:tt = $value:expr )* $(,)?) => {{ + $ctx.note(&[ $( (stringify!($key), $crate::usage::UsageSlot::json($value)) ),* ]) + }}; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_note_is_read_back_in_order() { + let slot = UsageSlot::default(); + slot.note(&[ + ("dataset", "BXD".into()), + ("group", "BXD".into()), + ("cached", false.into()), + ("hits", 3.into()), + ]); + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("BXD")), + ("group", serde_json::json!("BXD")), + ("cached", serde_json::json!(false)), + ("hits", serde_json::json!(3)), + ], + "a bool stays a bool and a number stays a number" + ); + } + + /// The handler may say what was asked at the top (`engine`) and add + /// what happened later (`cached`) without the line growing a duplicate. + #[test] + fn a_second_note_with_the_same_key_replaces_it() { + let slot = UsageSlot::default(); + slot.note(&[("cached", false.into())]); + slot.note(&[("cached", true.into())]); + assert_eq!(slot.entries(), vec![("cached", serde_json::json!(true))]); + } + + #[test] + fn an_empty_note_is_a_no_op() { + let slot = UsageSlot::default(); + slot.note(&[]); + assert!(slot.entries().is_empty()); + } + + /// `q` is caller text: bounded, and still valid UTF-8 after truncation. + #[test] + fn a_long_value_is_bounded_on_a_character_boundary() { + let long = "é".repeat(MAX_VALUE); + let bounded = UsageSlot::bounded(&long); + assert!(bounded.len() <= MAX_VALUE + '…'.len_utf8()); + assert!(bounded.ends_with('…')); + assert!(bounded.chars().all(|c| c == 'é' || c == '…')); + assert_eq!(UsageSlot::bounded("bxd"), "bxd"); + } + + /// A clone is another handle on the same line, not a second line: the + /// compute handlers clone `Ctx` for the fallback path. + #[test] + fn a_clone_writes_into_the_same_slot() { + let slot = UsageSlot::default(); + let clone = slot.clone(); + clone.note(&[("dataset", "HXB".into())]); + assert_eq!(slot.entries(), vec![("dataset", serde_json::json!("HXB"))]); + } + + #[test] + fn no_tracked_field_shadows_the_line() { + for (handler, fields) in TRACKED { + for field in *fields { + assert!( + !RESERVED.contains(field), + "{handler} would overwrite the line's own {field}" + ); + } + } + } + + /// The guard for a handler edited later without its `usage!` call: each + /// tracked handler's source must contain one. Crude on purpose — it + /// greps the file the handler lives in, so it costs nothing and cannot + /// pass by accident. + #[test] + fn every_tracked_handler_reports() { + let sources = [ + ("compute_gemma", include_str!("routes/gemma.rs")), + ("compute_gemma_ravanan", include_str!("routes/gemma.rs")), + ("compute_gemma_async", include_str!("routes/gemma.rs")), + ("compute_qtl2", include_str!("routes/qtl2.rs")), + ("compute_rqtl", include_str!("routes/rqtl.rs")), + ("compute_fitqtl", include_str!("routes/fitqtl.rs")), + ("compute_bulklmm", include_str!("routes/bulklmm.rs")), + ("compute_bnw", include_str!("routes/bnw.rs")), + ("compute_bnw_features", include_str!("routes/bnw.rs")), + ("search", include_str!("routes/search.rs")), + ]; + for (handler, source) in sources { + let start = source + .find(&format!("pub async fn {handler}(")) + .unwrap_or_else(|| panic!("{handler} is not in the source it should be")); + let rest = &source[start..]; + let end = rest.find("\npub async fn ").unwrap_or(rest.len()); + let body = &rest[..end]; + // `record_usage` is the shared helper the GEMMA handlers call; + // everything else writes the macro out. + assert!( + body.contains("usage!(") || body.contains("record_usage("), + "{handler} is in usage::TRACKED but records nothing" + ); + } + } +} |
