From 304b92e310df9570a67ef3cdd3bbcc714569bc83 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:14:29 +0000 Subject: correlation: PC traits as basket columns, and compare-two-traits **PC traits.** `pca.traits` carries each component *as a trait*: PC1, PC2, ... with a score per individual, so a component can be used the way GN2's "PCA traits" are -- correlated, mapped, plotted, saved. Scores are the standardised values projected onto the loadings, standardised with the sample standard deviation because that is what the correlation matrix was built from; a constant trait has no z-score and refuses rather than filling a zero. They live on the complete cases of the kept traits (31 of 34 in the fixture), which is the honest reading of "a PCA is defined on a rectangle". The module story is a basket: POST /baskets with a PC's values gives a per-user, versioned, digest-recorded column (verified: 201, revision 1, values read back), which the mapping and plotting endpoints already accept. No new store, no new dataset concept. **Compare traits.** POST /compute/compare takes two trait references, keeps the individuals with a value for both, and returns r, p, n *and* the pairs -- the statistic and the data behind it. It agrees with the matrix: the same pair is r = 0.6756270426459695 in both. POST /plot/compare draws the scatter (6 303 bytes) with the individual's name in each tooltip and the OLS line implied by r and the two means; nothing is refitted. Monitor gained compute-compare and plot-compare; full run 49 ok, 0 failed, 1 skipped. Not done, deliberately: limit_to/ids_only/names_only. The listing handlers return typed rows (Envelope>), so "names only" is a shape change in every one of them -- a pass of its own rather than a query parameter. --- src/config.rs | 8 ++ src/lib.rs | 2 + src/pca.rs | 90 ++++++++++++ src/routes/compare.rs | 290 +++++++++++++++++++++++++++++++++++++++ src/routes/correlation.rs | 2 +- src/routes/correlation_matrix.rs | 80 ++++++++++- src/routes/mod.rs | 1 + src/routes/plot.rs | 2 +- 8 files changed, 468 insertions(+), 7 deletions(-) create mode 100644 src/routes/compare.rs (limited to 'src') diff --git a/src/config.rs b/src/config.rs index c6a1553..0061070 100644 --- a/src/config.rs +++ b/src/config.rs @@ -175,6 +175,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. @@ -419,6 +421,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( @@ -487,6 +493,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -554,6 +561,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(), diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..c025c46 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -231,6 +231,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)) 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, +} + +/// 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, + /// 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> = 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], + individuals: &[String], +) -> Option> { + 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::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::() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::() / (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/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, +} + +#[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), + 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, +) -> Result>, 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 = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec = 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, + Json(posted): Json, +) -> Result { + 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 = 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, +} + +fn align(request: &CompareRequest) -> Result { + 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 Result { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result { 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)> { + 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 = 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::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 { +) -> Result<(Matrix, Vec), 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/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..d33f5d7 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -346,7 +346,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( -- cgit 1.4.1 From d4c7a85a2565997b3878f565af5e5198a4312907 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Mon, 16 Nov 2026 18:55:43 +0000 Subject: listing: the limit_to / ids_only / names_only model, with its tests The shared type for the three parameters GN2 has and we do not: one value per row (`ids_only`, `names_only`), a case-insensitive `limit_to` over id / name / trait_name / display_name / full_name, the contradiction (both shapes at once) refused rather than resolved by parse order, and a `limit_to` value that matches nothing *reported* instead of silently dropped -- "my trait is missing" is the failure this parameter exists to prevent. Five tests: identity, ids/names shaping, limit_to matching any field and being case-insensitive, its composition with ids_only, and the refusal. Status, recorded in the module docs because it is the interesting part: the handlers are NOT wired yet. A listing handler returns typed rows (`Envelope>`), so answering `["BXD", ...]` changes its return type to `Envelope` and the `body =` type in its utoipa block, which utoipa checks at compile time -- a mismatch fails as "could not find `__path_groups`", which looks like a macro bug and is not one. Six handlers or none: two would leave the API inconsistent, which is worse than not having the parameter at all. Build green with the module and its tests; nothing deployed, since until a handler uses it the binary is unchanged. --- src/lib.rs | 1 + src/listing.rs | 221 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 222 insertions(+) create mode 100644 src/listing.rs (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index c025c46..1d60f9d 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; diff --git a/src/listing.rs b/src/listing.rs new file mode 100644 index 0000000..fa42cb5 --- /dev/null +++ b/src/listing.rs @@ -0,0 +1,221 @@ +//! 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>`), so answering with `["BXD", ...]` changes its +//! return type to `Envelope` *and* the `body =` type in its +//! `utoipa::path` block, which utoipa checks at compile time (a mismatch fails +//! with "could not find `__path_`", 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; + +/// Query parameters three listings share. +#[derive(Debug, Clone, Default, Deserialize)] +pub struct ListingParams { + /// Keep only these ids or names, comma-separated. + #[serde(default)] + pub limit_to: Option, + /// Answer with ids only. + #[serde(default)] + pub ids_only: Option, + /// Answer with names only. + #[serde(default)] + pub names_only: Option, +} + +/// 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 { + 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 `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) { + let Some(array) = rows.as_array() else { + return (rows.clone(), Vec::new()); + }; + let wanted: Option> = limit_to + .map(|text| { + text.split(',') + .map(|value| value.trim().to_lowercase()) + .filter(|value| !value.is_empty()) + .collect() + }) + .filter(|values: &Vec| !values.is_empty()); + + let mut kept: Vec = Vec::with_capacity(array.len()); + let mut found: Vec = 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"); + } +} -- cgit 1.4.1 From 7f6d92b546892ea5dba5a3f5df541c77c229f1e4 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 20:20:20 +0000 Subject: impute: one switch for how a missing genotype is treated, on the ravanan path "How do we treat a missing genotype?" now has one answer shared by every engine, so the same trait can be mapped both ways and the results compared: none the file as it stands -- GEMMA does complete-case per marker and reports n_miss (235 individuals for some markers, 234 for others) mean every gap takes that marker's mean (complete file, all individuals) hmm R/qtl2's HMM predicts the gap from flanking markers (maxmarg on the genotype probabilities, the calls /compute/qtl2 itself maps on) scripts/prepare-genotypes.sh is that one place. It writes .bimbam.txt and .snps.txt and nothing else, so the two engines consume the same files: /compute/gemma/ravanan takes `impute`, and the pangemma store builder (the next endpoint) takes the same script with --mode mean|hmm into the LMDB makers. On the ravanan path the files are cached under RAVANAN_CACHE_DIR/imputed/ -, so a second request for the same panel and treatment costs nothing: mean is a single pass (1.7 s for BXD.8), hmm is the qtl2 HMM (10 s including computing the probabilities the first time, then cached beside the cross). The reply says which treatment ran, and `hmm` refuses without a group (422 impute_needs_group) since the cross it predicts from is the group's. Measured, BXD.8 (20 453 markers, 235 individuals), missing calls in the prepared panel: 1 465 of 4.8M as NA. Both modes produce complete files of 9.2 and 10.0 MB, and a request with impute=mean or impute=hmm writes them and then proceeds to ravanan. What this box could not finish is the run itself: ravanan in the scratch instance failed on its own manifest cache ("manifest.scm newer than compiled ... warning") and, for hmm, answered "no association output files" -- environment, not the preparation, and the next thing to settle. Why not keep it in the workflow: the treatment has to be the same for both engines, and pangemma's store builder needs the file *before* the workflow exists (it builds an LMDB store from it). One script, two consumers. --- scripts/prepare-genotypes.sh | 77 +++++++++++++ scripts/qtl2-impute-bimbam.R | 19 +++- src/config.rs | 10 ++ src/routes/gemma.rs | 252 ++++++++++++++++++++++++++++++++++++++++++- 4 files changed, 355 insertions(+), 3 deletions(-) create mode 100755 scripts/prepare-genotypes.sh (limited to 'src') diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh new file mode 100755 index 0000000..36a959b --- /dev/null +++ b/scripts/prepare-genotypes.sh @@ -0,0 +1,77 @@ +#!/bin/sh +# prepare-genotypes.sh -- one place where "how do we treat a missing genotype?" +# is decided, so the same question can be asked of every engine and the answers +# compared. +# +# --mode none leave the file as it is (GEMMA then does complete-case per +# marker and reports n_miss; pangemma cannot represent a gap at +# all, so its store builder refuses this mode) +# --mode mean replace each missing call by that marker's mean over the +# individuals that have one (cheap, but it invents a datum and +# deflates the variance) +# --mode hmm predict the missing calls from flanking markers with R/qtl2's +# HMM (maxmarg on genotype probabilities) -- the genotype set +# /compute/qtl2 maps on, and the one that does not invent a value +# +# scripts/prepare-genotypes.sh --mode mean|hmm|none \ +# --geno --snps --out \ +# [--cross ] [--probs ] [--minprob N] +# +# Writes .bimbam.txt and .snps.txt and prints the prefix. +# Exits 2 on bad arguments, 1 when a step fails. +set -eu + +mode= geno= snps= out= cross_dir= probs= minprob=0 +while [ $# -gt 0 ]; do + case $1 in + --mode) mode=$2; shift 2 ;; + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs=$2; shift 2 ;; + --minprob) minprob=$2; shift 2 ;; + -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; + esac +done + +case $mode in none|mean|hmm) ;; *) echo "prepare-genotypes.sh: --mode must be none, mean or hmm" >&2; exit 2 ;; esac +[ -n "$out" ] || { echo "prepare-genotypes.sh: --out is required" >&2; exit 2; } +mkdir -p "$(dirname "$out")" + +case $mode in +none) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + cp "$geno" "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +mean) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +hmm) + [ -n "$cross_dir" ] || { echo "prepare-genotypes.sh: --mode hmm needs --cross DIR" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + # R's own complaint last, so a caller that reports the final stderr line + # reports the cause rather than our wrapper sentence. + if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + "$cross_dir" "${probs:--}" "$out" "$minprob" 2>&1); then + echo "prepare-genotypes.sh: HMM imputation failed:" >&2 + printf '%s\n' "$r_output" | tail -6 >&2 + exit 1 + fi + ;; +esac + +printf '%s\n' "$out" diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 1a9cd1b..4003f4e 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -29,7 +29,24 @@ minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 setwd(cross_dir) cross <- read_cross2("control.json") -probs <- readRDS(probs_path) + +# Passing "-" as the probabilities means "compute them": a caller that only has +# the converted cross (the GEMMA path has no qtl2 scan to borrow a cache entry +# from) should not have to run /compute/qtl2 first just to get genotypes. The +# result is cached in the cross directory, which is itself content-keyed, so a +# second call is free. +probs <- if (identical(probs_path, "-")) { + cached <- "probs-imputed.rds" + if (file.exists(cached)) { + readRDS(cached) + } else { + p <- calc_genoprob(cross, error_prob = 0.002, cores = 1, quiet = TRUE) + saveRDS(p, cached) + p + } +} else { + readRDS(probs_path) +} # maxmarg returns one call per marker and individual, at the highest # probability above MINPROB -- or NA when the HMM is less sure than that. At diff --git a/src/config.rs b/src/config.rs index 0061070..b937ce5 100644 --- a/src/config.rs +++ b/src/config.rs @@ -126,6 +126,9 @@ pub struct Config { /// `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. @@ -315,6 +318,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()); @@ -545,6 +554,7 @@ impl Config { ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), + prepare_genotypes: values["PREPARE_GENOTYPES"].clone(), rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(), diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index a17010b..8c2c543 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -22,6 +22,7 @@ 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}; @@ -119,6 +120,16 @@ pub struct GemmaRequest { pub permutations: Option, /// Refused unless 0, as `nperm`. pub permutate: Option, + + /// 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: pangemma's LMDB store cannot hold a gap at all. + /// `hmm` needs a group-scoped request, since the cross it predicts from is + /// the group's. + pub impute: Option, } /// One trait value, by individual name. @@ -908,6 +919,200 @@ pub async fn compute_gemma( }) } + +/// A genotype file materialised for one missing-data treatment. +struct PreparedGenotypes { + genotype_file: String, + snps_file: String, + notes: Vec, +} + +/// Run `scripts/prepare-genotypes.sh` to turn the resolved genotype file into +/// the one the caller asked for (`mean` or `hmm`). +/// +/// Both modes write a *complete* file beside the ravanan cache, keyed by the +/// panel and the mode, so a second request for the same panel and treatment +/// reuses it: `mean` costs a pass over the file, `hmm` costs the qtl2 HMM +/// (about ten seconds for BXD.8 on one core, then cached). +async fn prepare_genotypes( + config: &Config, + mode: &str, + genotype_file: &str, + snps_file: &str, + group: &Option, + version: Option<&str>, + rid: RequestInfo, +) -> Result { + let stem = std::path::Path::new(genotype_file) + .file_stem() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "panel".to_string()); + let prefix = std::path::Path::new(&config.ravanan_cache_dir) + .join("imputed") + .join(format!("{stem}-{mode}")); + let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); + let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); + + let mut notes = Vec::new(); + if std::path::Path::new(&prepared_geno).is_file() + && std::path::Path::new(&prepared_snps).is_file() + { + notes.push(format!( + "genotypes: '{mode}' treatment reused from the cache ({})", + prepared_geno + )); + return Ok(PreparedGenotypes { + genotype_file: prepared_geno, + snps_file: prepared_snps, + notes, + }); + } + + // hmm predicts from the group's qtl2 cross: the same conversion and the + // same cache /compute/qtl2 uses, so the calls are the ones that endpoint + // maps on, and the probabilities are computed once and kept beside the + // cross. + let cross_dir = if mode == "hmm" { + let Some(group) = 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(), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + }; + let directory = config.genotype_files_dir.clone(); + let cache = config.qtl2_cache_dir.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, + 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) + .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}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "cross_preparation_failed", + "Could not prepare the cross", + format!("{error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })?; + prepared + .control + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)) + } else { + std::path::PathBuf::new() + }; + + let script = config.prepare_genotypes.clone(); + let script_for_job = script.clone(); + let geno = genotype_file.to_string(); + let snps = snps_file.to_string(); + let out = prefix.to_string_lossy().into_owned(); + let mode_owned = mode.to_string(); + let status = tokio::task::spawn_blocking(move || { + let mut args: Vec = vec![ + "--mode".to_string(), + mode_owned, + "--out".to_string(), + out, + ]; + if !geno.is_empty() { + args.push("--geno".to_string()); + args.push(geno); + args.push("--snps".to_string()); + args.push(snps); + } + if !cross_dir.as_os_str().is_empty() { + args.push("--cross".to_string()); + args.push(cross_dir.to_string_lossy().into_owned()); + args.push("--probs".to_string()); + args.push("-".to_string()); + } + std::process::Command::new(&script_for_job).args(&args).output() + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare genotypes", + format!("running {script} failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::BAD_GATEWAY, + "prepare_genotypes_failed", + "Could not prepare genotypes", + format!("could not run {}: {error}", config.prepare_genotypes), + "compute_gemma_ravanan", + ) + .with_request_id(rid.clone()) + })?; + if !status.status.success() { + return Err(ApiError::new( + StatusCode::BAD_GATEWAY, + "prepare_genotypes_failed", + "Could not prepare genotypes", + format!( + "{} --mode {mode} failed: {}", + config.prepare_genotypes, + String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("no message") + ), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + + notes.push(match mode { + "mean" => "genotypes: missing calls replaced by each marker's mean (a complete \ + file, so every individual is analysed; GEMMA's own treatment is \ + complete-case per marker, which this replaces)" + .to_string(), + _ => "genotypes: missing calls predicted by R/qtl2's HMM (maxmarg on the \ + group's cached genotype probabilities, the same calls /compute/qtl2 \ + maps on)" + .to_string(), + }); + Ok(PreparedGenotypes { + genotype_file: prepared_geno, + snps_file: prepared_snps, + notes, + }) +} + #[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 \ @@ -982,7 +1187,7 @@ pub async fn compute_gemma_ravanan( trait_values, individuals: panel_individuals, names: _, - group: _, + group: resolved_group, notes: input_notes, } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() { @@ -1027,6 +1232,45 @@ pub async fn compute_gemma_ravanan( .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), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + let mut impute_notes: Vec = Vec::new(); + let (genotype_file, snps_file) = if impute == "none" { + (genotype_file, snps_file) + } else { + let prepared = prepare_genotypes( + &config, + &impute, + &genotype_file, + &snps_file, + &Some(resolved_group.clone()), + request.genotype_version.as_deref(), + rid.clone(), + ) + .await?; + impute_notes = prepared.notes; + (prepared.genotype_file, prepared.snps_file) + }; + // 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. @@ -1075,10 +1319,14 @@ 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); } -- cgit 1.4.1 From bce93d3deedfc4f0a00a931b1b06ee1c9e8520d1 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Mon, 16 Nov 2026 21:23:45 +0000 Subject: impute: make the hmm path able to run at all -- three bugs impute=none and impute=mean already worked; impute=hmm died every time with "gemma-wrapper's response listed no association output files", which named neither the cause nor the place. Three separate faults, each measured: 1. chromosomes_from split the SNP map on whitespace only. The panel's own file reads "marker, 3001490, 1" (spaces after the commas) and the HMM file scripts/qtl2-impute-bimbam.R writes reads "marker,3001490,1" -- one token -- so the chromosome list came back empty and ravanan was handed an empty scatter. It now splits on commas and whitespace both. 2. The HMM calls come from the qtl2 cross, whose individuals are the whole panel: 235 for BXD.8 against the 198 animals that carry trait values. Passing the panel's positional values against those columns makes every individual missing -- GEMMA says "no individuals in common", ravanan says "no association output files". The R script now also writes .individuals.txt and the ravanan path re-aligns the trait values to it by name; the reply says how many individuals the HMM calls carry. 3. A relative PREPARE_GENOTYPES ("scripts/prepare-genotypes.sh") is only found when the server runs from its checkout. An instance started elsewhere answered "could not run scripts/prepare-genotypes.sh: No such file or directory". A relative default is now resolved against the checkout that GEMMA_RAVANAN_WORKFLOW points into. State after these: none 200 (21 055 rows), mean 200 (21 056 rows, with its note), hmm now runs the whole workflow (the run took 32 minutes single-machine before failing) and stops on ravanan's own manifest cache -- "source file .../manifest.scm newer than compiled .../ccache" -- which is the next thing to fix and is not about genotypes. Same-genotype agreement, measured separately (gemma on the HMM BIMBAM versus pangemma on an LMDB store built from that same file): identical top marker (rsm10000010578, p 1.04e-05), Spearman rho 0.999971, top-50 overlap 50/50, median |difference in -log10 p| 0.00000. The engines agree; what was left was plumbing. --- scripts/qtl2-impute-bimbam.R | 6 +++++ src/config.rs | 20 +++++++++++++- src/gemma.rs | 12 ++++++++- src/routes/gemma.rs | 62 ++++++++++++++++++++++++++++++++++++++++++-- 4 files changed, 96 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 4003f4e..df5f6d6 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -82,6 +82,12 @@ for (chr_name in names(imputed)) { writeLines(vapply(rows, paste, character(1), collapse = ","), paste0(out_prefix, ".bimbam.txt")) +# The individual order of the calls, because it is the *cross's* order and not +# necessarily the panel's: a caller that writes a phenotype file positionally +# has to align to this, or the two disagree by name and every individual is +# missing (measured: gemma answered "no individuals in common" and ravanan +# reported no association files at all). +writeLines(colnames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/config.rs b/src/config.rs index b937ce5..118b12b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -554,7 +554,25 @@ impl Config { ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), - prepare_genotypes: values["PREPARE_GENOTYPES"].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(), diff --git a/src/gemma.rs b/src/gemma.rs index 02a2456..c502903 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -1255,8 +1255,18 @@ fn trait_input_key(kinship_key: &str, trait_values: &TraitValues) -> String { fn chromosomes_from(contents: &str) -> Vec { 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()); } diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 8c2c543..329158a 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1113,6 +1113,33 @@ async fn prepare_genotypes( }) } +/// 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], +) -> Result>, std::io::Error> { + let by_name: std::collections::HashMap<&str, Option> = 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 \ @@ -1184,9 +1211,9 @@ pub async fn compute_gemma_ravanan( let ResolvedInputs { genotype_file, snps_file, - trait_values, + mut trait_values, individuals: panel_individuals, - names: _, + names: resolved_names, group: resolved_group, notes: input_notes, } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; @@ -1268,6 +1295,37 @@ pub async fn compute_gemma_ravanan( ) .await?; impute_notes = prepared.notes; + if impute == "hmm" { + let individuals = format!( + "{}.individuals.txt", + prepared + .genotype_file + .trim_end_matches(".bimbam.txt") + ); + if let Some(names) = 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}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + } + } (prepared.genotype_file, prepared.snps_file) }; -- cgit 1.4.1 From 2df90559ca597c0d35daf68e8648f8a46c823787 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 10:25:14 +0000 Subject: impute=hmm runs now: individuals from rownames, and a versioned cache Two more faults, both measured, both in the plumbing rather than the statistics. maxmarg returns individuals x markers, so colnames are *markers*: the individuals file I added last commit listed 1 452 marker names, every trait value aligned to nothing, and the workflow answered "number of analyzed individuals equals 0". It writes rownames now -- 235 names for BXD.8 -- and impute=hmm completes: 200, 11 657 rows, 26 s, single machine, with both notes ("missing calls predicted by R/qtl2's HMM", "trait values aligned by name to the 235 individuals"). The second fault was the cache: the prepared files are keyed on (panel, mode) and not on the code that writes them, so the corrected individuals file was ignored and the run kept failing on the stale one. The key now carries IMPUTE_CACHE_VERSION, bumped when either script changes what it writes. Three modes through the workflow, same trait, same machine: none 200, 21 055 rows mean 200, 21 056 rows hmm 200, 11 657 rows none and mean agree as they should: identical top marker (rs32133186), Spearman rho 1.00000, top-50 50/50, median |d(-log10 p)| 0.00004. hmm disagrees, and that is a real finding rather than a rounding matter: rho -0.07 against both, different top marker, and only 11 657 of the 20 453 markers reported. A rank correlation near zero means the genotypes and the markers are not being paired the way the other two modes pair them, so the next thing to check is the annotation file this path feeds GEMMA (it comes from the cross's physical map, while the genotype rows come from the HMM's marker order) -- not the imputation itself, which the same-genotype comparison already showed to be sound (rho 0.999971 against pangemma on the identical calls). --- scripts/qtl2-impute-bimbam.R | 9 ++++++--- src/routes/gemma.rs | 8 +++++++- 2 files changed, 13 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index df5f6d6..2e11a40 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -82,12 +82,15 @@ for (chr_name in names(imputed)) { writeLines(vapply(rows, paste, character(1), collapse = ","), paste0(out_prefix, ".bimbam.txt")) -# The individual order of the calls, because it is the *cross's* order and not -# necessarily the panel's: a caller that writes a phenotype file positionally +# The individual order of the calls -- rownames, because maxmarg returns +# individuals x markers and colnames are therefore markers (measured: writing +# colnames put 1452 marker names in a file of individuals, every value aligned +# to nothing, and the run reported "number of analyzed individuals equals 0") -- +# because it is the *cross's* order and not necessarily the panel's: a caller that writes a phenotype file positionally # has to align to this, or the two disagree by name and every individual is # missing (measured: gemma answered "no individuals in common" and ravanan # reported no association files at all). -writeLines(colnames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) +writeLines(rownames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 329158a..e94ca72 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -947,9 +947,15 @@ async fn prepare_genotypes( .file_stem() .map(|name| name.to_string_lossy().into_owned()) .unwrap_or_else(|| "panel".to_string()); + // The cache key carries a version, because it is keyed on the panel and the + // mode and NOT on the code that produces them: a fixed bug in the imputation + // script would otherwise be masked by its own old output (measured: a + // corrected individuals file was ignored and the run kept failing on the + // stale one). Bump this when either script changes what it writes. + const IMPUTE_CACHE_VERSION: &str = "v2"; let prefix = std::path::Path::new(&config.ravanan_cache_dir) .join("imputed") - .join(format!("{stem}-{mode}")); + .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); -- cgit 1.4.1 From ab710df0a1502b851292b61a1052585374c40ea3 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 11:25:20 +0000 Subject: groups: limit_to / ids_only / names_only, with the old shape as the default The first of the six listings, and the pattern for the other five: the answer type becomes `Rows` (untagged -- `Objects` or `Plain`), and *no listing parameters means the old answer*, so this cannot break a client that already exists. Untagged matters: the wire shape is a plain array either way, so a wrapper object would have been a breaking change dressed as a feature. Verified on the deployed build: GET /groups?species=mouse 59 objects, keys as before GET /groups?species=mouse&names_only=true 59 strings, first "AKXD" GET /groups?ids_only=true&limit_to=BXD,NOPE ["1"], note names "nope" GET /groups?ids_only=true&names_only=true 422 invalid_listing The note for a limit_to value that matched nothing is the point of that parameter's error path: "my group is missing" is what a silent empty answer makes impossible to diagnose. `listing.shape` keeps the full rows as objects for the default path, so no client sees a serialisation round-trip; `Rows::Plain` takes the field that was matched. The other five handlers get the same three edits plus their utoipa body type, which is the mechanical part that needs care. --- src/listing.rs | 47 +++++++++++++++++++++++++++++++++++++++++++++++ src/routes/groups.rs | 49 +++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 92 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/listing.rs b/src/listing.rs index fa42cb5..1e659ab 100644 --- a/src/listing.rs +++ b/src/listing.rs @@ -28,6 +28,25 @@ 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), + /// One identifier per entry, from `ids_only` or `names_only`. + Plain(Vec), +} + /// Query parameters three listings share. #[derive(Debug, Clone, Default, Deserialize)] pub struct ListingParams { @@ -75,6 +94,34 @@ impl Listing { } } + /// 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, + limit_to: Option<&str>, + ) -> (Rows, Vec) { + 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 diff --git a/src/routes/groups.rs b/src/routes/groups.rs index dd59165..eca9574 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, + /// 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, + /// Answer with one id per group instead of objects. + #[serde(default)] + pub ids_only: Option, + /// Answer with one name per group instead of objects. + #[serde(default)] + pub names_only: Option, } fn contains_ci(field: &Option, needle: &str) -> bool { @@ -39,7 +49,8 @@ fn contains_ci(field: &Option, 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>), + (status = 200, description = "The groups (InbredSet rows), with family and species name; \ +`ids_only`/`names_only` answer one value per group instead", body = Envelope), Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] @@ -48,8 +59,24 @@ pub async fn groups( ctx: Ctx, _token: AuthToken, Query(params): Query, -) -> Result>>, ApiError> { +) -> Result>, 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 = 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=)", - )) + ); + 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)) } -- cgit 1.4.1 From a3d67c72dfa78840eb846f5d93f6f6326ac32b32 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 11:31:10 +0000 Subject: impute: a monotone genetic map for the HMM, and say hmm is not yet sound The HMM smooths along a genetic map, and ours is degenerate: the .geno files carry no cM, so the converted cross has 19 markers "with missing genetic map position; using 0". With no distance between markers the HMM has nothing to smooth with, and the probabilities show it: P(BB) never rises above 0.5 and every individual is called AA. When the map has gaps it is now replaced by physical position at 1 cM per Mb -- crude, monotone, and better than zeros. That fixed part of it (the spread of calls at a marker went from sd 0.21 to 0.34 where the panel has 0.46) but not the collapse: at rsm10000005700, where the panel has 125 BB, 84 A and 26 missing, maxmarg still answers 228 AA and 7 BB. Two explanations have been eliminated by measurement -- the code mapping (maxmarg returns genotype *names*; that is now derived from the data, so AA/BB map correctly) and the missing-value encoding (0 is already qtl2's missing). What is left is the converted cross itself: both HMM states appear to correspond to the same physical allele at many markers, which is a question for src/qtl2.rs, not for the imputation. So the reply now says so out loud: "NOT YET VALIDATED on a riself panel ... treat the hmm scan as experimental and prefer none or mean". A mode that runs and answers the wrong question silently is worse than one that says it is not ready. --- scripts/prepare-genotypes.sh | 8 +++--- scripts/qtl2-impute-bimbam.R | 62 +++++++++++++++++++++++++++++++++++++++++--- src/routes/gemma.rs | 46 ++++++++++++++++++++++++++++++-- 3 files changed, 108 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index 36a959b..9624e0e 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -15,13 +15,14 @@ # # scripts/prepare-genotypes.sh --mode mean|hmm|none \ # --geno --snps --out \ -# [--cross ] [--probs ] [--minprob N] +# [--cross ] [--probs ] [--minprob N] \ +# [--individuals-file ] # # Writes .bimbam.txt and .snps.txt and prints the prefix. # Exits 2 on bad arguments, 1 when a step fails. set -eu -mode= geno= snps= out= cross_dir= probs= minprob=0 +mode= geno= snps= out= cross_dir= probs= minprob=0 individuals_file= while [ $# -gt 0 ]; do case $1 in --mode) mode=$2; shift 2 ;; @@ -31,6 +32,7 @@ while [ $# -gt 0 ]; do --cross) cross_dir=$2; shift 2 ;; --probs) probs=$2; shift 2 ;; --minprob) minprob=$2; shift 2 ;; + --individuals-file) individuals_file=$2; shift 2 ;; -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; esac @@ -66,7 +68,7 @@ hmm) # R's own complaint last, so a caller that reports the final stderr line # reports the cause rather than our wrapper sentence. if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ - "$cross_dir" "${probs:--}" "$out" "$minprob" 2>&1); then + "$cross_dir" "${probs:--}" "$out" "$minprob" "$individuals_file" 2>&1); then echo "prepare-genotypes.sh: HMM imputation failed:" >&2 printf '%s\n' "$r_output" | tail -6 >&2 exit 1 diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R index 2e11a40..ae95b48 100755 --- a/scripts/qtl2-impute-bimbam.R +++ b/scripts/qtl2-impute-bimbam.R @@ -26,6 +26,13 @@ if (length(args) < 3) { } cross_dir <- args[1]; probs_path <- args[2]; out_prefix <- args[3] minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 +# Optional: the individuals the caller is actually serving, one per line. The +# cross carries the whole panel; a request that drops parents and F1s serves a +# subset, and a genotype file with more columns than the phenotype covers makes +# every comparison between modes meaningless (measured: none/mean fitted 198 +# individuals, hmm 235, and the peaks landed on different chromosomes). +individuals_file <- if (length(args) >= 5 && nzchar(args[5])) args[5] else NULL +wanted <- if (!is.null(individuals_file)) trimws(readLines(individuals_file)) else NULL setwd(cross_dir) cross <- read_cross2("control.json") @@ -51,7 +58,45 @@ probs <- if (identical(probs_path, "-")) { # maxmarg returns one call per marker and individual, at the highest # probability above MINPROB -- or NA when the HMM is less sure than that. At # minprob 0 every cell is filled, which is what the mdb needs. -imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1)) +# The genetic map the HMM smooths along. Ours is often degenerate -- the .geno +# files carry no cM, so the converter writes 0 for many markers ("19 markers with +# missing genetic map position; using 0"), and with no distance between markers +# the HMM has nothing to smooth with: measured, P(BB) never exceeded 0.5 and +# every individual was called AA at a marker where 125 of 235 are BB. When the +# map has gaps, positions come from the physical map at 1 cM per Mb, which is +# crude but monotone and infinitely better than 0. +if (!is.null(cross$pmap)) { + for (chr_name in names(cross$gmap)) { + g <- cross$gmap[[chr_name]] + p_mb <- cross$pmap[[chr_name]][names(g)] / 1e6 + if (anyNA(g) || any(diff(g) <= 0) || any(g == 0)) { + if (!anyNA(p_mb)) cross$gmap[[chr_name]] <- unname(p_mb) + } + } +} + +# return_char: the genotype LETTERS (A/B, plus H if it were kept), not qtl2's +# internal genotype *indices*. Measured the hard way: maxmarg returns 1..n_gen +# -- 1 and 2 for a riself cross -- which are not the cross's numeric codes +# (A=1, B=3 per control.json). Mapping 2 to 1 read every BB animal as a +# heterozygote, which collapsed the genotypes (sd 0.21 where the panel has +# 0.46) and quietly killed the scan: the same marker that is p 5.9e-07 in the +# other modes came out at 2.0e-01. +imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1, + return_char = TRUE)) +if (!is.null(wanted)) { + present <- rownames(imputed[[1]]) + keep <- wanted[wanted %in% present] + if (length(keep) == 0) { + stop("none of the requested individuals appear in the cross", call. = FALSE) + } + for (chr_name in names(imputed)) { + imputed[[chr_name]] <- imputed[[chr_name]][keep, , drop = FALSE] + } + wanted_kept <- keep +} else { + wanted_kept <- rownames(imputed[[1]]) +} # How much work the HMM did: cells the cross itself had as missing (a 0 in an # explicit genotype map, never NA -- see read_cross2's own convention). @@ -61,7 +106,18 @@ left <- sum(vapply(imputed, function(g) sum(is.na(g)), integer(1))) # The calls come back as genotype *codes* in qtl2's numeric convention for this # cross (A = 1, B = 3, H = 2 per control.json); pangemma wants 0/1/2. -codes <- c(`1` = 0, `2` = 1, `3` = 2) +# The alphabet comes from the data: return_char gives the genotype *names* +# ("AA"/"BB" for a riself cross, "A"/"B" for a plain one, one name per founder +# for multiparent), so the first is homozygote 1 (0), the last homozygote 2 (2) +# and anything in between a heterozygote (1). Hard-coding A/H/B skipped every +# marker, because the values are "AA" and "BB" -- the run then had no +# chromosomes and no association files. +present <- sort(unique(as.vector(unlist(imputed)))) +present <- present[!is.na(present)] +if (length(present) < 2) { + stop("the HMM returned a single genotype state; nothing to map", call. = FALSE) +} +codes <- stats::setNames(c(0, rep(1, max(0, length(present) - 2)), 2), present) rows <- list(); snps <- list() # maxmarg returns individuals x markers (rows are individuals, which is the # opposite of the BIMBAM's marker-per-line shape, and the reason a first version @@ -90,7 +146,7 @@ writeLines(vapply(rows, paste, character(1), collapse = ","), # has to align to this, or the two disagree by name and every individual is # missing (measured: gemma answered "no individuals in common" and ravanan # reported no association files at all). -writeLines(rownames(imputed[[1]]), paste0(out_prefix, ".individuals.txt")) +writeLines(wanted_kept, paste0(out_prefix, ".individuals.txt")) writeLines(vapply(snps, paste, character(1), collapse = ","), paste0(out_prefix, ".snps.txt")) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index e94ca72..31d5538 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -941,6 +941,7 @@ async fn prepare_genotypes( snps_file: &str, group: &Option, version: Option<&str>, + names: Option<&Vec>, rid: RequestInfo, ) -> Result { let stem = std::path::Path::new(genotype_file) @@ -952,7 +953,7 @@ async fn prepare_genotypes( // script would otherwise be masked by its own old output (measured: a // corrected individuals file was ignored and the run kept failing on the // stale one). Bump this when either script changes what it writes. - const IMPUTE_CACHE_VERSION: &str = "v2"; + const IMPUTE_CACHE_VERSION: &str = "v6"; let prefix = std::path::Path::new(&config.ravanan_cache_dir) .join("imputed") .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); @@ -1039,6 +1040,39 @@ async fn prepare_genotypes( std::path::PathBuf::new() }; + if let Some(parent) = std::path::Path::new(&prepared_geno).parent() { + if let Err(error) = std::fs::create_dir_all(parent) { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not create the imputation cache directory", + format!("creating {} failed: {error}", parent.display()), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + // The individuals the request actually serves, so the HMM output has the + // same columns as the other modes and the phenotype lines up positionally. + let individuals_path = format!("{}.panel.txt", prefix.to_string_lossy()); + if let Some(names) = names { + if !names.is_empty() { + if let Err(error) = std::fs::write( + &individuals_path, + names.iter().map(|n| format!("{n}\n")).collect::(), + ) { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the individual list", + format!("writing {individuals_path} failed: {error}"), + "compute_gemma_ravanan", + ) + .with_request_id(rid)); + } + } + } + let individuals_arg = individuals_path.clone(); let script = config.prepare_genotypes.clone(); let script_for_job = script.clone(); let geno = genotype_file.to_string(); @@ -1063,6 +1097,10 @@ async fn prepare_genotypes( args.push(cross_dir.to_string_lossy().into_owned()); args.push("--probs".to_string()); args.push("-".to_string()); + if std::path::Path::new(&individuals_arg).is_file() { + args.push("--individuals-file".to_string()); + args.push(individuals_arg.clone()); + } } std::process::Command::new(&script_for_job).args(&args).output() }) @@ -1109,7 +1147,10 @@ async fn prepare_genotypes( .to_string(), _ => "genotypes: missing calls predicted by R/qtl2's HMM (maxmarg on the \ group's cached genotype probabilities, the same calls /compute/qtl2 \ - maps on)" + maps on). NOT YET VALIDATED on a riself panel: measured on BXD.8 \ + the calls collapse towards one allele at markers that carry both \ + (228 AA against the panel's 125 BB at rsm10000005700), so treat the \ + hmm scan as experimental and prefer none or mean." .to_string(), }); Ok(PreparedGenotypes { @@ -1297,6 +1338,7 @@ pub async fn compute_gemma_ravanan( &snps_file, &Some(resolved_group.clone()), request.genotype_version.as_deref(), + resolved_names.as_ref(), rid.clone(), ) .await?; -- cgit 1.4.1 From b055c240c909e5c3628cc341fe1a2cbae9ed07f6 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 12:00:19 +0000 Subject: groups/{group}/strains: limit_to / ids_only / names_only, old shape by default Second of the six, and the same three edits as /groups: the params struct gains the three fields, the reply type becomes Rows (untagged, so no parameters still means the array of objects), and the handler shapes the rows where it builds the envelope, appending a note naming any limit_to value that matched nothing. Verified on the deployed build: GET /groups/BXD/strains 396 objects, keys as before GET /groups/BXD/strains?names_only=true 396 strings, first "B6D2F1" GET ...?names_only=true&limit_to=BXD1,BXD2,NOPE ["BXD1","BXD2"] + note: nope Read tier after deploy: 24 ok, 0 failed. --- src/routes/groups.rs | 67 +++++++++++++++++++++++++++++++++++++++++----------- 1 file changed, 53 insertions(+), 14 deletions(-) (limited to 'src') diff --git a/src/routes/groups.rs b/src/routes/groups.rs index eca9574..44fd605 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -251,6 +251,16 @@ pub async fn group_by_name( #[derive(serde::Deserialize)] pub struct GroupStrainsParams { used_for_mapping: Option, + /// 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, + /// Answer with one id per strain instead of objects. + #[serde(default)] + pub ids_only: Option, + /// Answer with one name per strain instead of objects. + #[serde(default)] + pub names_only: Option, } #[utoipa::path(get, path = "/groups/{group}/parents-and-f1s", @@ -368,7 +378,8 @@ pub async fn group_parental_design( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("used_for_mapping" = Option, Query, description = "Only strains/samples used for mapping") ), responses( - (status = 200, description = "The strains/samples belonging to the group", body = Envelope>), + (status = 200, description = "The strains/samples belonging to the group; \ +`ids_only`/`names_only` answer one value per strain instead", body = Envelope), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -379,8 +390,24 @@ pub async fn group_strains( Path(group): Path, Query(params): Query, _token: AuthToken, -) -> Result>>, ApiError> { +) -> Result>, 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 || { @@ -403,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 = 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( -- cgit 1.4.1 From 5419674c1f6635f31095b95ff4c1d5ca0e4fbcdc Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 12:15:56 +0000 Subject: groups/{group}/datasets: limit_to / ids_only / names_only, old shape by default Third of the six. This one had no query struct at all, so it reuses crate::listing::ListingParams directly (now IntoParams, so it documents itself) instead of growing a per-handler copy. Verified on the deployed build: GET /groups/BXD/datasets objects, keys as before GET ...?names_only=true&limit_to=HC_M2_0606_P,NOPE ["HC_M2_0606_P"] + note: nope Read tier: 24 ok, 0 failed. --- src/listing.rs | 4 ++-- src/routes/groups.rs | 31 ++++++++++++++++++++++++++++--- 2 files changed, 30 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/listing.rs b/src/listing.rs index 1e659ab..584429f 100644 --- a/src/listing.rs +++ b/src/listing.rs @@ -47,8 +47,8 @@ pub enum Rows { Plain(Vec), } -/// Query parameters three listings share. -#[derive(Debug, Clone, Default, Deserialize)] +/// 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)] diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 44fd605..727013a 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -1140,7 +1140,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>), + (status = 200, description = "The expression (ProbeSet) datasets belonging to the group; \ +`ids_only`/`names_only` answer one value per dataset instead", body = Envelope), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -1150,8 +1151,20 @@ pub async fn group_datasets( ctx: Ctx, Path(group): Path, _token: AuthToken, -) -> Result>>, ApiError> { + Query(params): Query, +) -> Result>, 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 { @@ -1186,13 +1199,25 @@ pub async fn group_datasets( ), ) }); + let rows: Vec = 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); } -- cgit 1.4.1 From 9be4832dd827a3486848bd45960e51111e2e589d Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 12:21:18 +0000 Subject: qtl2: number the surviving alleles 1..n, because the HMM cannot use 3 A riself cross is converted with its heterozygous calls dropped, so the CSV carries two genotypes -- but the control file still numbered them A=1, H=2, B=3. Allele code 3 does not exist in a two-state HMM: qtl2 read the second allele as unusable, P(BB) never rose above 0.5 at a marker where 125 of 235 individuals are BB, every individual was called AA, and the scan was left with nothing of the signal (2.0e-01 where the same marker is 5.9e-07 from the BIMBAM, /compute/qtl2's own top hit 3.685 LOD elsewhere). Numbering the genotypes the file actually carries, 1 and 2, gives agreement with the calls 209 of 209. The codes now follow the crosstype and the heterozygous policy, and CONVERSION_VERSION is v5 so no cached cross is reused. This is a holding fix: the conversion belongs in an R script, where qtl2's write_control_file owns this metadata. --- src/qtl2.rs | 25 +++++++++++++++++++++++-- 1 file changed, 23 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/qtl2.rs b/src/qtl2.rs index 2bb11f7..44011de 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -214,7 +214,15 @@ pub fn prepare_cross( // 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"; + // v4: the allele *codes*. With H=2, B=3 in a cross where the + // heterozygous class is dropped, the surviving pair is 1/3 -- and qtl2's + // two-state riself HMM cannot use an allele code outside 1..2. It treats + // that allele as unusable: measured, P(BB) never rose above 0.5, every + // individual was called AA at a marker where 125 of 235 are BB, and a scan + // built on those calls had nothing left of the signal (p 2.0e-01 where the + // same marker is 5.9e-07 from the BIMBAM). Recoding to 1/2 fixed it + // completely: agreement with the calls 209 of 209. + const CONVERSION_VERSION: &str = "v5"; let directory = cache_dir.join("crosses").join(format!( "{CONVERSION_VERSION}-{}-{}-{stamp}", het.as_str(), @@ -363,7 +371,20 @@ pub fn prepare_cross( "pheno": "pheno.csv", "sep": ",", "na.strings": [""], - "genotypes": {"A": 1, "H": 2, "B": 3}, + // The codes must be 1..n over the genotypes the CSV actually + // carries. A riself cross with the heterozygous class dropped + // (the default) carries only A and B, so they are 1 and 2: leaving + // B as 3 hands qtl2 an allele code outside 1..2, which its + // two-state HMM cannot use -- it then reads that allele as + // unusable, P(BB) never rises above 0.5, every individual is + // called AA, and a scan built on those calls loses the signal + // (measured: 2.0e-01 where the same marker is 5.9e-07 from the + // BIMBAM; recoded, agreement with the calls is 209 of 209). + "genotypes": if crosstype != "riself" || het == Het::Keep { + serde_json::json!({"A": 1, "H": 2, "B": 3}) + } else { + serde_json::json!({"A": 1, "B": 2}) + }, // Our own CSVs are markers-in-rows, individuals-in-columns. "geno_transposed": true, }); -- cgit 1.4.1 From d480e89997eb44c7867756ce2d8716a63fe2feaa Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 12:25:06 +0000 Subject: groups/{group}/traits: limit_to / ids_only / names_only, old shape by default Fourth of the six, and the first with a payload worth trimming: BXDPublish has 15 060 traits, so `names_only` takes the answer from megabytes of objects to a list a dropdown can use. Verified on the deployed build: GET /groups/BXD/traits 15 060 objects, keys as before GET ...?ids_only=true&limit_to=10001,NOPE ["10001"] + note: nope The listing is parsed before the auth-server round trip, so a contradictory request (ids_only + names_only) is refused without spending a gn-auth call. Read tier: 24 ok, 0 failed. --- src/routes/groups.rs | 57 +++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/routes/groups.rs b/src/routes/groups.rs index 727013a..28e9c03 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -807,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, + /// 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, + /// Answer with one id per trait instead of objects. + #[serde(default)] + pub ids_only: Option, + /// Answer with one name per trait instead of objects. + #[serde(default)] + pub names_only: Option, } enum GroupTraitsLookup { @@ -844,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>), + (status = 200, description = "The published traits belonging to the group; \ +`ids_only`/`names_only` answer one value per trait instead", body = Envelope), 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), @@ -856,8 +867,24 @@ pub async fn group_traits( Path(group): Path, token: AuthToken, Query(params): Query, -) -> Result>>, ApiError> { +) -> Result>, 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 || { @@ -893,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 = 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, -- cgit 1.4.1 From 1fa28faac92bd206cca46b6987c4973360ddadbe Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 12:40:20 +0000 Subject: datasets/{dataset}/probesets: limit_to / ids_only / names_only Fifth of the six. 45 101 probesets in HC_M2_0606_P, so this is the listing where the slim answer matters most: names_only turns a multi-megabyte array of objects into a list of probe names. Verified on the deployed build: GET /datasets/HC_M2_0606_P/probesets 45 101 objects, as before GET ...?names_only=true&limit_to=1427571_at,NOPE ["1427571_at"] + note: nope Two mechanical notes that cost a build each: the handler had no Query extractor, so it takes crate::listing::ListingParams and needs axum::extract::Query in scope; and the Found branch built its envelope inline (Ok(Json(ctx.envelope(...)))), so shaping the rows meant opening the branch into a block. Read tier: 24 ok, 0 failed. --- src/routes/datasets.rs | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) (limited to 'src') 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>), + (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata; \ +`ids_only`/`names_only` answer one value per probeset instead", body = Envelope), 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, token: AuthToken, -) -> Result>>, ApiError> { + axum::extract::Query(params): axum::extract::Query, +) -> Result>, 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 = 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", -- cgit 1.4.1 From 14622e57629d19451cad03f4a69fdd89e81a433f Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 16:05:11 +0000 Subject: qtl2: the .geno conversion is an R script now, and the Rust writer is gone The conversion wrote qtl2's control file and CSVs by hand in Rust. Its output is an R/qtl2 cross, so the script does it and write_control_file describes it: one implementation of the format, qtl2's. What Rust keeps is the endpoint's own limit -- a .geno panel carries no founder genotypes, so a multiparent crosstype is a 422 with a reason, and the cross type follows @type and the heterozygous policy. prepare_cross now runs Rscript scripts/qtl2-convert-geno.R --geno GROUP.geno --out DIR --het drop|keep --crosstype riself|f2 writes the cross into the same versioned cache directory (now v6: the files it writes are qtl2's own layout), and reads back the report the script leaves beside it -- markers, non-autosomal, individuals, het_dropped, cells -- instead of counting them itself. A failed conversion reports R's own complaint. New configuration key QTL2_CONVERT_SCRIPT (default scripts/qtl2-convert-geno.R). The Rust writer's 250 lines are deleted, along with count_calls and metadata_het. Measured, BXD trait 10001 on the same request: before (Rust, alleles 1/3) top rsm10000005730 chr8 LOD 3.685 after (R/qtl2, alleles 1/2) top rs32579649 chr8 LOD 3.8917, rsm10000005700 3.8916 GEMMA LMM, same trait rsm10000005700 p 5.90e-07 so the wrong allele code was flattening this endpoint's own scan too: it still found chromosome 8, at a neighbouring marker and 0.21 LOD lower, with the marker GEMMA picks not in its top three. The two engines now agree on the locus. Cost: 38.3 s cold for 20453 autosomal markers (the R conversion is ~35 s of it), 3.5 s with the cross cached. --- README.md | 13 +- scripts/qtl2-convert-geno.R | 18 ++- src/config.rs | 9 ++ src/qtl2.rs | 350 +++++++++++++------------------------------- src/routes/gemma.rs | 10 +- src/routes/qtl2.rs | 10 +- 6 files changed, 153 insertions(+), 257 deletions(-) (limited to 'src') diff --git a/README.md b/README.md index fc9a5fc..0bbaba4 100644 --- a/README.md +++ b/README.md @@ -1967,8 +1967,17 @@ directory the data is not in, declare no genotype-code map (every genotype reads as missing) and no orientation (individuals read as markers) — four traps that each produce a plausible flat scan rather than an error. The conversion also drops heterozygous calls on a `riself` panel, as R/qtl's -`convert2riself` does. Configuration: `QTL2_SCRIPT_PATH`, -`QTL2_CACHE_DIR`. +`convert2riself` does, and recodes the surviving alleles to 1 and 2 — a second +allele numbered 3 is not an allele a two-state HMM can use, and the scan built +on it was flat (BXD 10001: LOD 3.685 at the wrong marker, against 3.892 at the +locus GEMMA reports, p 5.9e-07). + +The conversion is an R script, `scripts/qtl2-convert-geno.R`, not Rust: its +output is an R/qtl2 cross, and `write_control_file` describes it, so the layout +and the codes come from the format's definition rather than from a second +implementation of it. Cost: 38 s cold for BXD's 20 453 autosomal markers, 3.5 s +once the cross is cached. Configuration: `QTL2_SCRIPT_PATH`, +`QTL2_CONVERT_SCRIPT`, `QTL2_CACHE_DIR`. ### Gene link-outs diff --git a/scripts/qtl2-convert-geno.R b/scripts/qtl2-convert-geno.R index c688930..48b4779 100755 --- a/scripts/qtl2-convert-geno.R +++ b/scripts/qtl2-convert-geno.R @@ -31,7 +31,7 @@ get <- function(flag, default = NULL) { geno_path <- get("--geno") out_dir <- get("--out") het <- match.arg(get("--het", "drop"), c("drop", "keep")) -crosstype <- match.arg(get("--crosstype", "riself"), c("riself", "f2")) +crosstype <- get("--crosstype") if (is.null(geno_path) || is.null(out_dir)) { stop("usage: qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2]", call. = FALSE) @@ -44,7 +44,7 @@ meta <- function(key) { } # The allele letters are declared by the file, not assumed: GeneNetwork panels # use B/D as often as A/B. -mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het") +mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het"); type <- meta("type") if (is.null(mat) || is.null(pat)) { stop("the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded", call. = FALSE) @@ -59,12 +59,12 @@ body <- lines[!startsWith(lines, "#") & lines != hdr] autosomes <- as.character(1:19) geno <- list(); gmap <- list(); pmap <- list() -dropped <- 0L +dropped <- 0L; non_autosomal <- 0L; markers_seen <- 0L for (line in body) { f <- strsplit(line, "\t")[[1]] if (length(f) < 5) next chr <- f[1] - if (!(chr %in% autosomes)) next + if (!(chr %in% autosomes)) { non_autosomal <- non_autosomal + 1L; next } marker <- f[2] calls <- f[-(1:4)] # A call is A, B or (if the heterozygous class is kept) H; anything else -- @@ -78,6 +78,7 @@ for (line in body) { } calls[!(calls %in% c("A", "B", "H"))] <- "" geno[[marker]] <- calls + markers_seen <- markers_seen + 1L gmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[3]))) pmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[4])) * 1e6) } @@ -130,6 +131,15 @@ write_control_file( na.strings = "", geno_codes = codes, overwrite = TRUE) +# The report the caller reads back: what this cross holds, and what the +# conversion dropped. It is written beside the cross so a cached one costs +# nothing. +writeLines(jsonlite::toJSON(list( + crosstype = crosstype, markers = length(geno), non_autosomal = non_autosomal, + individuals = as.list(individuals), het_dropped = dropped, + cells = length(individuals) * length(geno)), auto_unbox = TRUE), + file.path(out_dir, "conversion.json")) + cat(sprintf("geno2cross: %d markers, %d individuals, %d heterozygous calls %s, crosstype %s -> %s\n", length(geno), length(individuals), dropped, if (het == "drop") "dropped" else "kept", crosstype, out_dir)) diff --git a/src/config.rs b/src/config.rs index 118b12b..ce2b038 100644 --- a/src/config.rs +++ b/src/config.rs @@ -139,6 +139,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, @@ -343,6 +346,10 @@ impl Config { "QTL2_SCRIPT_PATH".to_string(), "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() @@ -493,6 +500,7 @@ impl Config { "RQTL_WRAPPER_PATH", "FITQTL_SCRIPT_PATH", "QTL2_SCRIPT_PATH", + "QTL2_CONVERT_SCRIPT", "QTL2_CACHE_DIR", "RQTL_CACHE_DIR", "WIKIDATA_CACHE_DIR", @@ -576,6 +584,7 @@ impl Config { 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(), diff --git a/src/qtl2.rs b/src/qtl2.rs index 44011de..0c0622f 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -155,47 +155,22 @@ pub struct Qtl2Output { pub permutation_note: Option, } -/// 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 { - 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 { let geno = &resolved.geno; let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?; @@ -209,45 +184,20 @@ 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. - // v4: the allele *codes*. With H=2, B=3 in a cross where the - // heterozygous class is dropped, the surviving pair is 1/3 -- and qtl2's - // two-state riself HMM cannot use an allele code outside 1..2. It treats - // that allele as unusable: measured, P(BB) never rose above 0.5, every - // individual was called AA at a marker where 125 of 235 are BB, and a scan - // built on those calls had nothing left of the signal (p 2.0e-01 where the - // same marker is 5.9e-07 from the BIMBAM). Recoding to 1/2 fixed it - // completely: agreement with the calls 209 of 209. - const CONVERSION_VERSION: &str = "v5"; - 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 = BTreeMap::new(); - let mut cross_type = String::new(); + // 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", @@ -261,205 +211,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 = 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 = 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::().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": [""], - // The codes must be 1..n over the genotypes the CSV actually - // carries. A riself cross with the heterozygous class dropped - // (the default) carries only A and B, so they are 1 and 2: leaving - // B as 3 hands qtl2 an allele code outside 1..2, which its - // two-state HMM cannot use -- it then reads that allele as - // unusable, P(BB) never rises above 0.5, every individual is - // called AA, and a scan built on those calls loses the signal - // (measured: 2.0e-01 where the same marker is 5.9e-07 from the - // BIMBAM; recoded, agreement with the calls is 209 of 209). - "genotypes": if crosstype != "riself" || het == Het::Keep { - serde_json::json!({"A": 1, "H": 2, "B": 3}) - } else { - serde_json::json!({"A": 1, "B": 2}) - }, - // 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 = 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 { let name = requested.trim(); if name.is_empty() { @@ -509,6 +360,13 @@ fn control_path(control: &Path, json: &Value, key: &str) -> Option { .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, Qtl2Error> { let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?; diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 31d5538..baf4d6d 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -997,6 +997,7 @@ async fn prepare_genotypes( let directory = config.genotype_files_dir.clone(); let cache = config.qtl2_cache_dir.clone(); let version = version.map(|v| v.to_string()); + let convert = config.qtl2_convert_script.clone(); let prepared = tokio::task::spawn_blocking(move || { let resolved = genotypes::resolve( std::path::Path::new(&directory), @@ -1007,8 +1008,13 @@ async fn prepare_genotypes( // 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) - .map_err(|error| error.to_string()) + 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| { diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index 896c0e9..bf2ba06 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -675,10 +675,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) } -- cgit 1.4.1 From f2ec41256c3cb6b2952cb06f5f45d97b9814fc82 Mon Sep 17 00:00:00 2001 From: Pjotr Date: Tue, 17 Nov 2026 16:18:01 +0000 Subject: gemma/ravanan: the hmm note reports what it now measures, not the collapse The note still told callers that hmm collapses to one allele and to prefer none or mean. That was true with the allele coded 3; with the codes fixed the path keeps all 20453 autosomal markers polymorphic and puts its top at rsm10000005700, p 6.6e-07 -- the locus /compute/qtl2 (3.8916 LOD) and plain GEMMA (5.90e-07) both name. Before the fix it was 11912 markers peaking on chromosome 5. The warning that survives is the honest one: this mode can still fail quietly if the HMM has nothing to go on, so a surprising scan is worth checking rather than trusting. --- src/routes/gemma.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index baf4d6d..6ce8bff 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1151,12 +1151,16 @@ async fn prepare_genotypes( file, so every individual is analysed; GEMMA's own treatment is \ complete-case per marker, which this replaces)" .to_string(), - _ => "genotypes: missing calls predicted by R/qtl2's HMM (maxmarg on the \ - group's cached genotype probabilities, the same calls /compute/qtl2 \ - maps on). NOT YET VALIDATED on a riself panel: measured on BXD.8 \ - the calls collapse towards one allele at markers that carry both \ - (228 AA against the panel's 125 BB at rsm10000005700), so treat the \ - hmm scan as experimental and prefer none or mean." + _ => "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) rather than filled with a mean. The heterozygous calls a \ + riself panel carries are dropped first, as convert2riself does, and \ + the HMM re-predicts those too. Validated on BXD.8 after the allele \ + codes were fixed (alleles 1 and 2, not 1 and 3): all 20453 autosomal \ + markers stay polymorphic and the top is rsm10000005700, p 6.6e-07 -- \ + the locus the other two engines name. Before that fix it was 11912 \ + markers with the peak on chromosome 5, so a collapse this mode can \ + still produce silently is worth checking when a scan looks wrong." .to_string(), }); Ok(PreparedGenotypes { -- cgit 1.4.1 From 6bd032d565233016f2c658840ab2769cf2359fe2 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Thu, 19 Nov 2026 11:41:28 +0000 Subject: gemma: /compute/gemma runs the Slurm route, and the wrapper is its fallback Slurm is now the default engine (GEMMA_ENGINE=slurm) because a ravanan step is keyed on (script, inputs) and the K matrix is one of those inputs, while gemma-wrapper keys its GWA cache on the phenotype file and the chromosome alone. Measured on BXD.8 (198 strains, lmm 9, synthetic trait 4242): with a stale chr1 LOCO K left in the wrapper's cache, 2060 of 21055 rows disagreed with both Slurm routes -- gemma through ravanan and pangemma on lmdb -- and clearing that GWA entry made all three agree cell for cell. A rebuilt K can therefore leave stale association rows behind on the wrapper path, and cannot on the Slurm one. compute_gemma_ravanan's body moved into gemma_via_ravanan(...), parameterised by the endpoint name it reports in errors and claims, so /compute/gemma calls it first and keeps its own body as the fallback. Only a 5xx falls back: Slurm or ravanan unreachable, or the engine exiting non-zero. A 4xx is the caller's error and is returned as such, and a numerical disagreement never falls back, because that would hide a regression behind an answer from the other engine. The fallback takes a fresh light claim -- the first went with the Slurm attempt -- and adds an "Engine: the Slurm route was unavailable ( ), so this answer comes from the local gemma-wrapper run instead" note, so a reply says which engine produced it. Clone derives on ComputeGemmaParams, GemmaRequest and GemmaSample, and a Clone impl for Ctx: a request id and a start instant, so a clone is another handle on the same request. Validated on two scratch instances of the built tree against the live database: :3002 answers warm from ravanan in 3.79 s, and :3003 with RAVANAN_SLURM_API_ENDPOINT pointed at a dead port answers 200 in 21.38 s from the local wrapper, with the note naming "502 gemma_failed", on 21055 rows identical to the Slurm answer. --- src/config.rs | 19 ++++++++++ src/response.rs | 9 +++++ src/routes/gemma.rs | 101 +++++++++++++++++++++++++++++++++++++++++++++------- 3 files changed, 117 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/config.rs b/src/config.rs index ce2b038..7e4fa2c 100644 --- a/src/config.rs +++ b/src/config.rs @@ -120,6 +120,19 @@ 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 @@ -293,6 +306,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() @@ -486,6 +502,7 @@ impl Config { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", @@ -561,6 +578,7 @@ impl Config { gemma_ravanan_manifest: values["GEMMA_RAVANAN_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 @@ -840,6 +858,7 @@ mod tests { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", diff --git a/src/response.rs b/src/response.rs index 5e6fcff..f830054 100644 --- a/src/response.rs +++ b/src/response.rs @@ -245,6 +245,15 @@ pub struct Ctx { info: RequestInfo, } +// `Ctx` is a request id and a start instant, 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. +impl Clone for Ctx { + fn clone(&self) -> Self { + Ctx { info: self.info.clone() } + } +} + impl Ctx { /// For `ApiError::with_request_id`: stamps an error with the /// request id and the time taken so far. diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 6ce8bff..e0dc411 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -33,12 +33,15 @@ use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; /// 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, } -#[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 @@ -133,7 +136,7 @@ pub struct GemmaRequest { } /// One trait value, by individual name. -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaSample { pub name: String, pub value: Option, @@ -571,6 +574,57 @@ pub async fn compute_gemma( Json(mut request): Json, ) -> Result>, ApiError> { let rid = ctx.request_info(); + + // 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(); + let mut fallback_note: Option = None; + if !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 => { + 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 @@ -811,6 +865,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); } @@ -1229,6 +1286,26 @@ pub async fn compute_gemma_ravanan( token: AuthToken, Query(params): Query, Json(mut request): Json, +) -> Result>, ApiError> { + gemma_via_ravanan(ctx, token, params, request, __gn4_claim, "compute_gemma_ravanan").await +} +/// 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>, ApiError> { let rid = ctx.request_info(); let lmm = request.lmm.unwrap_or(9); @@ -1240,7 +1317,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)); } @@ -1251,7 +1328,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)); } @@ -1273,7 +1350,7 @@ pub async fn compute_gemma_ravanan( names: resolved_names, group: resolved_group, notes: input_notes, - } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; + } = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?; if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, @@ -1282,7 +1359,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)); } @@ -1299,7 +1376,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)); } @@ -1311,7 +1388,7 @@ 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)); } @@ -1333,7 +1410,7 @@ pub async fn compute_gemma_ravanan( "invalid_impute", "Invalid impute mode", format!("'{}' is not a mode; use none, mean or hmm.", impute), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1377,7 +1454,7 @@ pub async fn compute_gemma_ravanan( "internal_error", "Could not align individuals", format!("reading {individuals} failed: {error}"), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1419,7 +1496,7 @@ 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()), -- cgit 1.4.1 From 7863db3ff8b124c43211572987359e2d69d0951f Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 14:39:17 +0000 Subject: gemma: "engine": "pangemma" runs the same workflow on an lmdb store The pangemma workflow (cwl/gemma/gemma-loco-mdb.scm, committed but until now unreachable: nothing pointed at it) is now selected per request. It differs from its gemma twin in the genotype input only -- pangemma reads the chromosome from the store's key, so it needs neither `-g` BIMBAM nor the `-a` annotation -- so the two run the same kinship-then-GWA scatter and answer the same question: gemma 21,055 rows in 4.1 s af and l_mle identical to pangemma pangemma 21,055 rows in 3.9 s beta/se/p_lrt median |d| 2.6e-4/3.6e-5/1.3e-4, max 1.2e-3/5.4e-4/6.2e-4 (trait 10001, BXD.8, lmm 9, warm; pangemma builds its GRM in float32, which is where that third decimal goes -- verified against the store itself: Gf, 198 samples, 21,056 markers, 21,056 geno records.) At BXD.8 size there is nothing to win; on HLC the same 23 chromosomes cost 141 s of cluster job time against 958 s for gemma on BIMBAM, which is the point of the engine. Selection is a request field, defaulting to gemma, so no existing caller changes: - GemmaEngine::{Gemma,Pangemma} carries the workflow's input list and the compiled-CWL suffix as well as the parse aliases (gemma-gn2, pangemma-lmdb); an unknown value is 422 invalid_engine, not a silent gemma. - check_workflow_inputs now takes the engine's own list, so a stale workflow is still refused by name -- the mdb workflow declares `store` where the gemma one declares `genotype_file` and `snps_file`, and handing it the wrong one fails deep inside cwltool as "expected File but got null". - The store is built once per genotype file, not per trait, by geno2mdb.py (GENO2MDB_CMD) into GEMMA_LMDB_CACHE_DIR, keyed on the genotype file's path, size and mtime plus the annotation's contents. Gf always: exact for a mean-genotype panel, where Gb is exact only for integer calls. Written aside and renamed, so a concurrent identical request sees no store or a complete one; two first-runs both build it, which the rename makes harmless rather than wrong. Measured: 22.3 s cold (store built), 3.9 s warm, and a second trait on the same panel reuses the store. - There is no fallback for this engine. The in-process runner is gemma-wrapper on BIMBAM, so falling back would answer a different question under the requested engine's name: pangemma forces the ravanan route even when GEMMA_ENGINE=local, and its failures are returned as they are. Also fixed on the way: GemmaError::CommandFailed said "gemma-wrapper () failed" for every step, which blamed the wrapper for geno2mdb and ccwl compile; the step now names its own tool ("gemma-wrapper gwa failed", "geno2mdb failed"). Deployment knobs (README and docs/ravanan-slurm.md updated): GEMMA_RAVANAN_WORKFLOW_MDB, GEMMA_RAVANAN_MANIFEST_MDB (a manifest naming pangemma-git -- a manifest change needs a cold run, since ravanan keys a step on (script, inputs)), GENO2MDB_CMD and GEMMA_LMDB_CACHE_DIR. Deployed and verified on the production instance: both engines answer 200 on the same request through ravanan on Slurm, and bin/monitor-gn4 --tier all is 50 ok / 0 failed. One deployment detail worth recording: geno2mdb.py needs numpy and python-lmdb, which the store script's own shebang interpreter does not have, so the server now runs with PYTHONPATH pointing at the profile's site-packages -- without it the engine answers 502 "No module named 'numpy'". --- README.md | 45 ++++++ docs/ravanan-slurm.md | 8 +- src/config.rs | 60 +++++++ src/gemma.rs | 436 ++++++++++++++++++++++++++++++++++++++++++++------ src/routes/gemma.rs | 61 ++++++- 5 files changed, 560 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/README.md b/README.md index 0bbaba4..6f80fc6 100644 --- a/README.md +++ b/README.md @@ -1799,6 +1799,51 @@ pair, not the `.geno` file (see [docs/genotypes.md](docs/genotypes.md)) -- and the values must likewise line up one for one with that file's individuals. +##### `"engine": "pangemma"` -- the same workflow, reading an lmdb store + +`engine` selects which binary the per-chromosome workflow runs: +`gemma` (the default, `gemma-gn2` on the BIMBAM pair) or `pangemma` +(the GeneNetwork fork, which reads genotypes from an lmdb store instead +of parsing BIMBAM text). Only the genotype input differs, and the two +agree to the precision pangemma's float32 arithmetic allows: on BXD.8 +(198 strains, `lmm` 9, 21,055 rows, trait 10001) `af` and `l_mle` are +identical, and `beta`/`se`/`p_lrt` differ with median 2.6e-4 / 3.6e-5 / +1.3e-4 and maximum 1.2e-3 / 5.4e-4 / 6.2e-4 -- pangemma builds its GRM +in float32, so a p-value in the third decimal can move. The payoff is +cluster time: on HLC the same 23 chromosomes cost **141 s against +958 s** for gemma on BIMBAM (358,454 markers, integer calls). At BXD.8 +size there is nothing to gain (4.1 s either way, warm). + +What changes underneath, all of it pinned by the deployment: + +* the workflow is `cwl/gemma/gemma-loco-mdb.scm` + (`GEMMA_RAVANAN_WORKFLOW_MDB`) and the manifest that resolves the + steps' commands is `cwl/gemma/manifest-mdb.scm` + (`GEMMA_RAVANAN_MANIFEST_MDB`, naming `pangemma-git` rather than + `gemma-gn2`); +* the workflow's inputs are `store`, `pheno_file`, + `kinship_pheno_file`, `lmm`, `chromosomes` -- one file where gemma + takes `genotype_file` **and** `snps_file`, because pangemma reads the + chromosome from the store's key and needs no `-a` annotation. The + pre-flight check (`check_workflow_inputs`) compares against that list, + so a stale workflow in the checkout is refused by name rather than + failing deep inside cwltool; +* the store is built once per genotype file by `geno2mdb.py` + (`GENO2MDB_CMD`) into `GEMMA_LMDB_CACHE_DIR`, keyed on the genotype + file's path, size and mtime plus the annotation's contents -- not on + the trait, because every trait over a panel shares one store. It is + written aside and renamed, so a concurrent identical request sees + either no store or a complete one. Format is Gf (one float32 per + sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller + and exact only for integer calls. + +**There is no fallback for this engine.** The in-process runner is +gemma-wrapper on BIMBAM, so falling back would answer a different +question under the requested engine's name: a pangemma request forces +the ravanan route even when `GEMMA_ENGINE=local`, and its failures are +returned as they are. The reply's `notes` say which engine ran and +whether the store was built or reused. + ravanan's batch system is configurable too: by default each CWL step is a local child process, and `RAVANAN_BATCH_SYSTEM=slurm-api` submits every step to a Slurm cluster through slurmrestd instead (endpoint, JWT diff --git a/docs/ravanan-slurm.md b/docs/ravanan-slurm.md index 391c447..616e924 100644 --- a/docs/ravanan-slurm.md +++ b/docs/ravanan-slurm.md @@ -28,6 +28,10 @@ backend): …`). | `RAVANAN_SLURM_NICE` | optional integer `--slurm-nice` | | `RAVANAN_SCRATCH` | optional `--scratch`; defaults to `RAVANAN_CACHE_DIR` when the backend is slurm | | `RAVANAN_CACHE_DIR` | where pheno files, logs, the compiled CWL and ravanan's `--store` live | +| `GEMMA_RAVANAN_WORKFLOW_MDB` | ccwl source for `"engine": "pangemma"` (default `cwl/gemma/gemma-loco-mdb.scm`) | +| `GEMMA_RAVANAN_MANIFEST_MDB` | manifest naming `pangemma-git` for that workflow (default `cwl/gemma/manifest-mdb.scm`); a manifest change needs a cold run, since ravanan keys a step on (script, inputs) | +| `GENO2MDB_CMD` | the lmdb store builder (`geno2mdb.py` from gemma-wrapper's `bin/` -- it is not on `PATH` in every deployment) | +| `GEMMA_LMDB_CACHE_DIR` | where built lmdb stores live, one per genotype file; **must be durable**, since rebuilding one is the expensive part of a pangemma run | Selecting slurm without an endpoint or a JWT file is a startup error (fail closed, like `GN4_DB_MODE`): ravanan would fail every step, and a @@ -45,7 +49,9 @@ Two things the cluster needs that a plain dev box may not have: - `gemma` reachable in the profile ravanan builds from `GEMMA_RAVANAN_MANIFEST` (the workflow invokes `gemma` itself, not - `gemma-wrapper` -- see `cwl/gemma/gemma-loco.scm`); ravanan resolves that + `gemma-wrapper` -- see `cwl/gemma/gemma-loco.scm`); `"engine": + "pangemma"` instead needs `pangemma` from `GEMMA_RAVANAN_MANIFEST_MDB`. + ravanan resolves that manifest against the *ambient* Guix process, so `GUIX_PACKAGE_PATH` (or a pulled `guix-bioinformatics` channel) must be set in the server's environment, as it already must for the single-machine diff --git a/src/config.rs b/src/config.rs index 7e4fa2c..849b30a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -107,6 +107,28 @@ pub struct Config { /// the working directory the server is started from, same /// convention as `gemma_ravanan_workflow`. pub gemma_ravanan_manifest: String, + /// The pangemma twin of `gemma_ravanan_workflow`: + /// cwl/gemma/gemma-loco-mdb.scm, which reads genotypes from an lmdb + /// store instead of parsing BIMBAM, so its inputs are a single + /// `store` file where the gemma workflow takes `genotype_file` plus + /// `snps_file`. Selected per request by `"engine": "pangemma"` + /// (see src/gemma.rs's `GemmaEngine`). Set via + /// GEMMA_RAVANAN_WORKFLOW_MDB. + pub gemma_ravanan_workflow_mdb: String, + /// The manifest that workflow's steps resolve against, i.e. one + /// naming `pangemma-git` rather than `gemma-gn2` + /// (GEMMA_RAVANAN_MANIFEST_MDB). + pub gemma_ravanan_manifest_mdb: String, + /// The lmdb store builder `geno2mdb.py` (in gemma-wrapper's bin/, + /// which is not on PATH in every deployment): turns a BIMBAM + /// genotype file plus its annotation into the store pangemma reads. + /// Set via GENO2MDB_CMD. + pub geno2mdb_cmd: String, + /// Where those stores are kept, one file per genotype file + /// (`GEMMA_LMDB_CACHE_DIR`). They are the expensive part of a + /// pangemma run -- built once, reused by every trait over the same + /// panel -- so a deployment must point this somewhere durable. + pub gemma_lmdb_cache_dir: String, /// Directory POST /compute/gemma/ravanan uses for phenotype files, /// run logs, and ravanan's own --store and --output-directory. /// Separate from `gemma_cache_dir` so the two runners don't share @@ -326,6 +348,22 @@ impl Config { "GEMMA_RAVANAN_MANIFEST".to_string(), "cwl/gemma/manifest.scm".to_string(), ); + values.insert( + "GEMMA_RAVANAN_WORKFLOW_MDB".to_string(), + "cwl/gemma/gemma-loco-mdb.scm".to_string(), + ); + values.insert( + "GEMMA_RAVANAN_MANIFEST_MDB".to_string(), + "cwl/gemma/manifest-mdb.scm".to_string(), + ); + values.insert("GENO2MDB_CMD".to_string(), "geno2mdb.py".to_string()); + values.insert( + "GEMMA_LMDB_CACHE_DIR".to_string(), + std::env::temp_dir() + .join("gn4-gemma-lmdb") + .to_string_lossy() + .into_owned(), + ); values.insert( "RAVANAN_CACHE_DIR".to_string(), std::env::temp_dir() @@ -506,6 +544,10 @@ impl Config { "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "GENO2MDB_CMD", + "GEMMA_LMDB_CACHE_DIR", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -576,6 +618,10 @@ impl Config { ccwl_cmd: values["CCWL_CMD"].clone(), gemma_ravanan_workflow: values["GEMMA_RAVANAN_WORKFLOW"].clone(), gemma_ravanan_manifest: values["GEMMA_RAVANAN_MANIFEST"].clone(), + gemma_ravanan_workflow_mdb: values["GEMMA_RAVANAN_WORKFLOW_MDB"].clone(), + gemma_ravanan_manifest_mdb: values["GEMMA_RAVANAN_MANIFEST_MDB"].clone(), + geno2mdb_cmd: values["GENO2MDB_CMD"].clone(), + gemma_lmdb_cache_dir: values["GEMMA_LMDB_CACHE_DIR"].clone(), ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), gemma_engine: values["GEMMA_ENGINE"].clone(), @@ -862,6 +908,10 @@ mod tests { "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "GENO2MDB_CMD", + "GEMMA_LMDB_CACHE_DIR", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -905,6 +955,16 @@ mod tests { assert_eq!(config.ccwl_cmd, "ccwl"); assert_eq!(config.gemma_ravanan_workflow, "cwl/gemma/gemma-loco.scm"); assert_eq!(config.gemma_ravanan_manifest, "cwl/gemma/manifest.scm"); + assert_eq!( + config.gemma_ravanan_workflow_mdb, + "cwl/gemma/gemma-loco-mdb.scm" + ); + assert_eq!( + config.gemma_ravanan_manifest_mdb, + "cwl/gemma/manifest-mdb.scm" + ); + assert_eq!(config.geno2mdb_cmd, "geno2mdb.py"); + assert!(config.gemma_lmdb_cache_dir.ends_with("gn4-gemma-lmdb")); assert!(config.ravanan_cache_dir.ends_with("gn4-gemma-ravanan")); assert_eq!(config.rqtl_wrapper_path, "scripts/rqtl_wrapper.R"); assert!(config.rqtl_cache_dir.ends_with("gn4-rqtl")); diff --git a/src/gemma.rs b/src/gemma.rs index c502903..e9f6a60 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -13,7 +13,7 @@ //! shared infrastructure; see `crate::streaming`. use std::io; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::process::Output; use serde_json::Value; @@ -73,8 +73,12 @@ impl std::fmt::Display for GemmaError { GemmaError::Spawn { command, error } => { write!(f, "failed to run {command}: {error}") } + // The step already names its tool: gemma-wrapper's own steps are + // prefixed, and the ones that are not its (geno2mdb, ccwl compile) + // would otherwise be blamed on the wrapper -- which is what a + // missing numpy in the store builder once looked like. GemmaError::CommandFailed { step, stderr } => { - write!(f, "gemma-wrapper ({step}) failed: {stderr}") + write!(f, "{step} failed: {stderr}") } GemmaError::WrapperError { step, detail } => { write!(f, "gemma-wrapper ({step}) reported an error: {detail}") @@ -744,7 +748,7 @@ async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Resu .map_err(GemmaError::Io)?; if !output.status.success() { return Err(GemmaError::CommandFailed { - step: "extract-archive", + step: "gemma-wrapper extract-archive", stderr: String::from_utf8_lossy(&output.stderr).into_owned(), }); } @@ -991,7 +995,7 @@ pub async fn compute( .get("archive") .and_then(Value::as_str) .ok_or_else(|| GemmaError::WrapperError { - step: "gwa", + step: "gemma-wrapper gwa", detail: "gemma-wrapper's response did not list an output archive".to_string(), })?; let extract_dir = Path::new(cache_dir).join(format!("{unique}-gwa-extract")); @@ -1275,24 +1279,252 @@ fn chromosomes_from(contents: &str) -> Vec { chromosomes } +/// Which mapping engine the per-chromosome workflow runs. +/// +/// The two are the same computation through the same CWL shape (kinship per +/// chromosome, then GWA per chromosome) and differ only in what reads the +/// genotypes: `gemma` parses BIMBAM text every invocation and needs the +/// `-a` annotation to know which markers to leave out, while `pangemma` +/// reads an lmdb store whose keys carry the chromosome, so it needs neither. +/// The store is built once per panel (see [`lmdb_store`]) and is what makes +/// pangemma cheaper at scale -- measured on HLC (358,454 markers): 141 s of +/// cluster job time against 958 s for gemma on BIMBAM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GemmaEngine { + /// gemma-gn2 on BIMBAM: `-g` plus the `-a` annotation. + Gemma, + /// pangemma on an lmdb store: one `store` input, no BIMBAM parse, no `-a`. + Pangemma, +} + +impl GemmaEngine { + /// Parse the request's `engine` value; `None` for anything unknown. + pub fn parse(value: &str) -> Option { + match value.trim().to_ascii_lowercase().as_str() { + "gemma" | "gemma-gn2" => Some(GemmaEngine::Gemma), + "pangemma" | "pangemma-lmdb" => Some(GemmaEngine::Pangemma), + _ => None, + } + } + + pub const fn as_str(self) -> &'static str { + match self { + GemmaEngine::Gemma => "gemma", + GemmaEngine::Pangemma => "pangemma", + } + } + + /// The compiled-CWL suffix, so the two engines never share one artifact. + const fn cwl_suffix(self) -> &'static str { + match self { + GemmaEngine::Gemma => "gemma-loco", + GemmaEngine::Pangemma => "gemma-loco-mdb", + } + } + + /// The inputs this engine's ccwl workflow declares, which is what the + /// pre-flight check in `check_workflow_inputs` compares against. + pub const fn workflow_inputs(self) -> &'static [&'static str] { + match self { + GemmaEngine::Gemma => &[ + "genotype_file", + "pheno_file", + "kinship_pheno_file", + "snps_file", + "lmm", + "chromosomes", + ], + GemmaEngine::Pangemma => &[ + "store", + "pheno_file", + "kinship_pheno_file", + "lmm", + "chromosomes", + ], + } + } +} + +/// The per-chromosome workflow to run and the engine behind it: what a +/// deployment pins in `GEMMA_RAVANAN_WORKFLOW`/`_MANIFEST` (gemma) and their +/// `_MDB` twins (pangemma), plus what pangemma needs to build its store. +pub struct RavananWorkflow<'a> { + pub engine: GemmaEngine, + /// The ccwl source compiled to CWL before every run. + pub source: &'a str, + /// The Guix manifest ravanan resolves the steps' commands against. + pub manifest: &'a str, + /// `geno2mdb.py`, used only by the pangemma engine. + pub geno2mdb: &'a str, + /// Where built lmdb stores live, one per genotype file. + pub lmdb_cache_dir: &'a str, +} + +/// A key for one genotype file's lmdb store: path, size and mtime plus the +/// annotation's contents and the store format. +/// +/// Not the genotype *contents*: a 200 MB BIMBAM file is not hashed on every +/// request (the same reason `kinship_input_key` uses path and size). The +/// mtime is what catches an in-place rewrite, which size alone would miss +/// when a prepared file is regenerated with the same byte count. +fn lmdb_store_key(genotype_file: &str, snps_file: &str) -> String { + let mut material = Vec::new(); + material.extend_from_slice(genotype_file.as_bytes()); + material.push(0); + if let Ok(metadata) = std::fs::metadata(genotype_file) { + material.extend_from_slice(&metadata.len().to_le_bytes()); + if let Ok(modified) = metadata.modified() { + if let Ok(since) = modified.duration_since(std::time::UNIX_EPOCH) { + material.extend_from_slice(&since.as_nanos().to_le_bytes()); + } + } + } + material.push(0); + if let Ok(snps) = std::fs::read(snps_file) { + material.extend_from_slice(&snps); + } + material.push(0); + // Gf: one float32 per sample, exact for a mean-genotype panel (0, 0.5, 1 + // all fit). Gb is 4x smaller but exact only for integer calls, where it + // would move p-values in the third decimal. + material.extend_from_slice(b"Gf"); + sha16(&material) +} + +/// Build (or reuse) the lmdb genotype store pangemma reads with `-g`. +/// +/// One store per genotype file, not per trait: the store holds the panel's +/// markers and samples, and pangemma does GEMMA's own per-marker +/// mean-substitution at run time, so every trait over the panel shares it and +/// a repeat request costs one `stat`. +/// +/// Written aside and renamed, so a concurrent identical request sees either no +/// store or a complete one; two simultaneous first-runs both build it, which +/// the rename makes harmless rather than wrong. +async fn lmdb_store( + cmd: &str, + cache_dir: &str, + genotype_file: &str, + snps_file: &str, +) -> Result<(PathBuf, String), GemmaError> { + std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; + let key = lmdb_store_key(genotype_file, snps_file); + let stem = Path::new(genotype_file) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| "genotypes".to_string()); + let store_path = Path::new(cache_dir).join(format!("{stem}-{key}.mdb")); + if store_path.is_file() { + return Ok(( + store_path.clone(), + format!( + "pangemma's lmdb genotype store was already built ({})", + store_path.display() + ), + )); + } + + let tmp_path = Path::new(cache_dir).join(format!( + "{stem}-{key}.tmp-{}.mdb", + std::process::id() + )); + let _ = std::fs::remove_file(&tmp_path); + let tmp_arg = tmp_path.to_string_lossy().into_owned(); + let args = [ + genotype_file, + "--snps", + snps_file, + "--format", + "Gf", + "--out", + tmp_arg.as_str(), + ]; + let output = streaming::run_streaming(cmd, &args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: cmd.to_string(), + error, + })?; + if !output.status.success() { + let _ = std::fs::remove_file(&tmp_path); + return Err(GemmaError::CommandFailed { + step: "geno2mdb", + stderr: format!( + "{}\n{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ), + }); + } + std::fs::rename(&tmp_path, &store_path).map_err(GemmaError::Io)?; + // lmdb leaves a `-lock` companion beside the temporary name. + let _ = std::fs::remove_file(tmp_path.with_extension("mdb-lock")); + Ok(( + store_path.clone(), + format!( + "pangemma's lmdb genotype store was built from {genotype_file} ({})", + store_path.display() + ), + )) +} + +/// The ravanan inputs YAML for one engine: same fields the workflow declares, +/// and the store stands exactly where `genotype_file`/`snps_file` would. +fn ravanan_inputs_yaml( + engine: GemmaEngine, + genotype_file: &str, + snps_file: &str, + store_path: Option<&Path>, + pheno_path: &Path, + kinship_pheno_path: &Path, + lmm: u8, + chromosomes_yaml: &str, +) -> String { + match engine { + GemmaEngine::Gemma => format!( + "genotype_file: {{class: File, path: {genotype_file}}}\n\ + pheno_file: {{class: File, path: {}}}\n\ + kinship_pheno_file: {{class: File, path: {}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n\ + lmm: \"{lmm}\"\n\ + chromosomes: [{chromosomes_yaml}]\n", + pheno_path.display(), + kinship_pheno_path.display(), + ), + GemmaEngine::Pangemma => format!( + "store: {{class: File, path: {}}}\n\ + pheno_file: {{class: File, path: {}}}\n\ + kinship_pheno_file: {{class: File, path: {}}}\n\ + lmm: \"{lmm}\"\n\ + chromosomes: [{chromosomes_yaml}]\n", + store_path + .map(|path| path.display().to_string()) + .unwrap_or_default(), + pheno_path.display(), + kinship_pheno_path.display(), + ), + } +} + /// The same GEMMA `--loco` kinship-then-GWA computation as `compute`, /// but run via `ravanan` (https://github.com/vepiteski/ravanan) driving /// a CWL workflow compiled from the ccwl (https://ccwl.systemreboot.net/) -/// source at `workflow_scm_path` (see `cwl/gemma/gemma-loco.scm`). +/// source at `workflow.source` (see `cwl/gemma/gemma-loco.scm` and its +/// pangemma twin `cwl/gemma/gemma-loco-mdb.scm`). /// -/// This runner invokes **gemma itself**, one invocation per -/// chromosome, relying on `-loco ` 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 ` being native to both for `-gk` +/// and `-lmm` -- where `compute` still drives gemma-wrapper. That /// is deliberate: it is what makes the two endpoints comparable, the /// same computation through two stacks, and the day the numbers stop /// agreeing the difference is visible rather than assumed away. -/// Backs `POST /compute/gemma/ravanan`. +/// Backs `POST /compute/gemma/ravanan`, and is the engine behind +/// `/compute/gemma` unless `GEMMA_ENGINE=local`. pub async fn compute_ravanan( ravanan_cmd: &str, batch: &crate::config::RavananBatch, ccwl_cmd: &str, - workflow_scm_path: &str, - manifest_path: &str, + workflow: &RavananWorkflow<'_>, cache_dir: &str, scratch_dir: &str, genotype_file: &str, @@ -1312,9 +1544,12 @@ pub async fn compute_ravanan( // Two keys, not one: the kinship step is keyed on the *individual set* // only (see `kinship_input_key`), so a second trait over the same animals // reuses all twenty K matrices, and only the GWA step's inputs change. + let engine = workflow.engine; + let workflow_scm_path = workflow.source; + let manifest_path = workflow.manifest; let kinship_key = kinship_input_key(genotype_file, snps_file, trait_values, lmm); let trait_key = trait_input_key(&kinship_key, trait_values); - let workflow = workflow_key(workflow_scm_path); + let workflow_hash = workflow_key(workflow_scm_path); // A constant-valued phenotype file with the trait's missing-data pattern: // what the kinship step gets, so its files are the same for every trait @@ -1340,13 +1575,14 @@ pub async fn compute_ravanan( // call (cheap: ccwl compile is pure macro expansion, no Guix build // involved) and never checked into the repo -- see the doc comment // on Config::gemma_ravanan_workflow. + let cwl_suffix = engine.cwl_suffix(); let compiled_workflow_path = - Path::new(cache_dir).join(format!("{workflow}-gemma-loco.cwl")); + Path::new(cache_dir).join(format!("{workflow_hash}-{cwl_suffix}.cwl")); // Compile to a per-process path and rename: the compiled CWL is // deterministic, so two concurrent identical requests would otherwise // race on the same file. - let compiled_tmp = - Path::new(cache_dir).join(format!("{workflow}-gemma-loco.tmp-{}.cwl", std::process::id())); + let compiled_tmp = Path::new(cache_dir) + .join(format!("{workflow_hash}-{cwl_suffix}.tmp-{}.cwl", std::process::id())); let ccwl_output_arg = format!("--output={}", compiled_tmp.display()); let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), workflow_scm_path]; let ccwl_output = streaming::run_streaming(ccwl_cmd, &ccwl_args, None) @@ -1364,17 +1600,7 @@ pub async fn compute_ravanan( std::fs::rename(&compiled_tmp, &compiled_workflow_path).map_err(GemmaError::Io)?; // Before anything is staged for ravanan: does the workflow in this // deployment's checkout take what this build is about to send it? - check_workflow_inputs( - &compiled_workflow_path, - &[ - "genotype_file", - "pheno_file", - "kinship_pheno_file", - "snps_file", - "lmm", - "chromosomes", - ], - )?; + check_workflow_inputs(&compiled_workflow_path, engine.workflow_inputs())?; let compiled_workflow_arg = compiled_workflow_path.to_string_lossy().into_owned(); let store_dir = Path::new(cache_dir).join("ravanan-store"); @@ -1395,23 +1621,37 @@ pub async fn compute_ravanan( .collect::>() .join(", "); + // pangemma reads an lmdb store instead of BIMBAM plus its annotation, so + // that store has to exist before anything is staged -- and it is the one + // expensive input, built once per genotype file rather than per trait. + let (store_path, store_note) = match engine { + GemmaEngine::Gemma => (None, None), + GemmaEngine::Pangemma => { + let (path, note) = lmdb_store( + workflow.geno2mdb, + workflow.lmdb_cache_dir, + genotype_file, + snps_file, + ) + .await?; + (Some(path), Some(note)) + } + }; + let inputs_yaml_path = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.yaml")); let inputs_tmp = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.tmp-{}.yaml", std::process::id())); - std::fs::write( - &inputs_tmp, - format!( - "genotype_file: {{class: File, path: {genotype_file}}}\n\ - pheno_file: {{class: File, path: {}}}\n\ - kinship_pheno_file: {{class: File, path: {}}}\n\ - snps_file: {{class: File, path: {snps_file}}}\n\ - lmm: \"{lmm}\"\n\ - chromosomes: [{chromosomes_yaml}]\n", - pheno_path.display(), - kinship_pheno_path.display(), - ), - ) - .map_err(GemmaError::Io)?; + let inputs_yaml = ravanan_inputs_yaml( + engine, + genotype_file, + snps_file, + store_path.as_deref(), + &pheno_path, + &kinship_pheno_path, + lmm, + &chromosomes_yaml, + ); + std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?; std::fs::rename(&inputs_tmp, &inputs_yaml_path).map_err(GemmaError::Io)?; let store_arg = format!("--store={}", store_dir.display()); @@ -1448,11 +1688,25 @@ pub async fn compute_ravanan( args.join(" ") ); let chromosomes_note = format!( - "Scattered gemma itself over {} chromosome(s) via CWL scatter, one \ + "Scattered {} itself over {} chromosome(s) via CWL scatter, one \ invocation per chromosome: {}", + engine.as_str(), chromosomes.len(), chromosomes.join(", "), ); + // Which engine ran, and for pangemma where its genotypes came from: the + // two produce identical rows on the same input, so without this a reply + // cannot say which cost its caller what. + let engine_note = match (&store_note, engine) { + (Some(note), _) => Some(format!( + "Engine: {} (lmdb genotypes rather than BIMBAM): {note}", + engine.as_str() + )), + (None, GemmaEngine::Gemma) => None, + (None, GemmaEngine::Pangemma) => { + Some(format!("Engine: {}", engine.as_str())) + } + }; let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref()) .await @@ -1513,6 +1767,9 @@ pub async fn compute_ravanan( chromosomes_note, format!("workflow: {workflow_scm_path} (compiled to {compiled_workflow_arg})"), ]; + if let Some(note) = engine_note { + notes.push(note); + } notes.extend(ephemeral_note); if let Some(note) = variance_components_note(&components) { notes.push(note); @@ -1867,10 +2124,7 @@ mod tests { let err = parse_wrapper_output("kinship", output).unwrap_err(); assert!(matches!( err, - GemmaError::WrapperError { - step: "kinship", - .. - } + GemmaError::WrapperError { step: "kinship", .. } )); assert_eq!( err.to_string(), @@ -2040,3 +2294,95 @@ FATAL ERROR: gemma-wrapper bailed out with pid 42 exit 130 assert!(got.contains("bailed out"), "{got}"); } } + +#[cfg(test)] +mod engine_tests { + use super::*; + + // ---- the two engines ---------------------------------------------------- + + #[test] + fn the_engines_parse_and_declare_their_own_inputs() { + assert_eq!(GemmaEngine::parse("pangemma"), Some(GemmaEngine::Pangemma)); + assert_eq!(GemmaEngine::parse(" GEMMA "), Some(GemmaEngine::Gemma)); + // Not an engine, and not silently gemma either. + assert_eq!(GemmaEngine::parse("gemma-wrapper"), None); + assert_eq!(GemmaEngine::parse(""), None); + + let gemma = GemmaEngine::Gemma.workflow_inputs(); + assert!(gemma.contains(&"genotype_file")); + assert!(gemma.contains(&"snps_file")); + let pangemma = GemmaEngine::Pangemma.workflow_inputs(); + assert!(pangemma.contains(&"store")); + // The store replaces both BIMBAM inputs; a workflow declaring `store` + // cannot be handed them, which is what the pre-flight check enforces. + assert!(!pangemma.contains(&"genotype_file")); + assert!(!pangemma.contains(&"snps_file")); + assert_ne!(GemmaEngine::Gemma.cwl_suffix(), GemmaEngine::Pangemma.cwl_suffix()); + } + + /// The staged inputs file must name exactly what the compiled workflow + /// declares -- a workflow that wants `store` and is handed + /// `genotype_file` fails inside cwltool as "expected File but got null", + /// long after the request looked fine. + #[test] + fn the_inputs_yaml_names_the_workflows_own_fields() { + let pheno = Path::new("/c/1-pheno.txt"); + let kin = Path::new("/c/1-kin-pheno.txt"); + let gemma = ravanan_inputs_yaml( + GemmaEngine::Gemma, + "/g/BXD_geno.txt.gz", + "/g/BXD_snps.txt", + None, + pheno, + kin, + 9, + "\"1\", \"2\"", + ); + let pangemma = ravanan_inputs_yaml( + GemmaEngine::Pangemma, + "/g/BXD_geno.txt.gz", + "/g/BXD_snps.txt", + Some(Path::new("/s/BXD_geno.txt.gz-ab.mdb")), + pheno, + kin, + 9, + "\"1\", \"2\"", + ); + for field in GemmaEngine::Gemma.workflow_inputs() { + assert!(gemma.contains(&format!("{field}:")), "gemma lacks {field}"); + } + for field in GemmaEngine::Pangemma.workflow_inputs() { + assert!( + pangemma.contains(&format!("{field}:")), + "pangemma lacks {field}" + ); + } + assert!(gemma.contains("path: /g/BXD_geno.txt.gz")); + assert!(pangemma.contains("path: /s/BXD_geno.txt.gz-ab.mdb")); + assert!(!pangemma.contains("genotype_file")); + assert!(!pangemma.contains("snps_file")); + } + + /// A store belongs to a genotype file, not to a trait: every trait over + /// the panel must reuse it, or the expensive half of a pangemma run is + /// paid again per request. The annotation is part of the key because it + /// decides which markers and chromosomes the store holds. + #[test] + fn the_store_key_follows_the_genotype_file_and_annotation_only() { + let dir = std::env::temp_dir().join(format!("gn4-lmdbkey-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let geno = dir.join("G.txt"); + let snps = dir.join("S.txt"); + std::fs::write(&geno, "s1\ts2\nm1\t1\t1\t0\t2\n").unwrap(); + std::fs::write(&snps, "m1 150 1\n").unwrap(); + let geno_s = geno.to_string_lossy().into_owned(); + let snps_s = snps.to_string_lossy().into_owned(); + + let first = lmdb_store_key(&geno_s, &snps_s); + assert_eq!(first, lmdb_store_key(&geno_s, &snps_s), "must be stable"); + std::fs::write(&snps, "m1 150 2\n").unwrap(); + assert_ne!(first, lmdb_store_key(&geno_s, &snps_s), "annotation counts"); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index e0dc411..c36c1c2 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -133,6 +133,13 @@ pub struct GemmaRequest { /// `hmm` needs a group-scoped request, since the cross it predicts from is /// the group's. pub impute: Option, + /// 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, } /// One trait value, by individual name. @@ -584,8 +591,16 @@ pub async fn compute_gemma( // reason to fall back: that would hide a regression behind an answer from // the other engine. let engine_config = Config::load(); + // pangemma has no in-process counterpart: the wrapper runs gemma on + // BIMBAM, so falling back would answer a different question under the + // requested engine's name. It therefore forces the Slurm route even when + // GEMMA_ENGINE=local, and its failures are returned as they are. + let pangemma = matches!( + request.engine.as_deref(), + Some(value) if crate::gemma::GemmaEngine::parse(value) == Some(crate::gemma::GemmaEngine::Pangemma) + ); let mut fallback_note: Option = None; - if !engine_config.gemma_engine.eq_ignore_ascii_case("local") { + if pangemma || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { match gemma_via_ravanan( ctx.clone(), token.clone(), @@ -597,7 +612,7 @@ pub async fn compute_gemma( .await { Ok(answer) => return Ok(answer), - Err(error) if error.status >= 500 => { + Err(error) if error.status >= 500 && !pangemma => { eprintln!( "compute_gemma: slurm route failed ({} {}); falling back to the local gemma-wrapper run", error.status, error.code @@ -1308,6 +1323,24 @@ pub(crate) async fn gemma_via_ravanan( endpoint: &'static str, ) -> Result>, ApiError> { let rid = ctx.request_info(); + let engine = match request.engine.as_deref() { + None => crate::gemma::GemmaEngine::Gemma, + Some(value) => match crate::gemma::GemmaEngine::parse(value) { + Some(engine) => engine, + None => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_engine", + "Invalid engine", + format!( + "'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)." + ), + endpoint, + ) + .with_request_id(rid)) + } + }, + }; let lmm = request.lmm.unwrap_or(9); if !matches!(lmm, 1 | 2 | 3 | 4 | 9) { return Err(ApiError::new( @@ -1475,12 +1508,32 @@ pub(crate) async fn gemma_via_ravanan( let job_rid = rid.clone(); compute_gate::ravanan() .run(__gn4_claim, async move { + // The workflow pair follows the engine: gemma-gn2 on BIMBAM, or + // pangemma on an lmdb store, each with the manifest that resolves + // its own step commands. Both are pinned by the deployment, so a + // checkout that lacks one fails here by name rather than producing + // a workflow that cannot find its binary. + let (workflow_source, manifest_source) = match engine { + gemma::GemmaEngine::Gemma => { + (&config.gemma_ravanan_workflow, &config.gemma_ravanan_manifest) + } + gemma::GemmaEngine::Pangemma => ( + &config.gemma_ravanan_workflow_mdb, + &config.gemma_ravanan_manifest_mdb, + ), + }; + let ravanan_workflow = gemma::RavananWorkflow { + engine, + source: workflow_source, + manifest: manifest_source, + geno2mdb: &config.geno2mdb_cmd, + lmdb_cache_dir: &config.gemma_lmdb_cache_dir, + }; gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, - &config.gemma_ravanan_workflow, - &config.gemma_ravanan_manifest, + &ravanan_workflow, &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, -- cgit 1.4.1 From f681a06b58879968e7b385e22d6c0560fa0588ba Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 14:53:57 +0000 Subject: docs: pangemma's store does hold gaps, so `impute` is optional for both engines Two places still said pangemma "cannot represent a gap at all" and that its store builder refuses impute=none -- written against an older pangemma. The store keeps them (NaN for Gf, 255 for Gb) and pangemma mean-substitutes per marker as GEMMA does: measured, impute=none through the pangemma engine answers 21,055 rows with `af` identical to GEMMA's on the same panel. What `impute` does change is which markers and individuals map, and it does so before the store is built, so each mode has its own store (they are different genotype files). Measured warm on BXD.8 trait 10001: none 21,055 rows, 20 chromosomes gemma 4.0 s pangemma 3.9 s hmm 20,453 rows, 19 chromosomes gemma 26.8 s pangemma 15.8 s mean 21,056 rows, 20 chromosomes gemma 16.3 s pangemma 16.0 s The hmm figures include the R/qtl2 imputation the first time and reuse it from RAVANAN_CACHE_DIR/imputed/ afterwards; mean maps one marker that complete-case treatment drops, which is why the three are not interchangeable answers. --- README.md | 11 +++++++++++ scripts/prepare-genotypes.sh | 7 ++++--- src/routes/gemma.rs | 15 ++++++++++++--- 3 files changed, 27 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/README.md b/README.md index 6f80fc6..7ad2841 100644 --- a/README.md +++ b/README.md @@ -1837,6 +1837,17 @@ What changes underneath, all of it pinned by the deployment: sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller and exact only for integer calls. +`impute` is applied *before* the store is built, so every mode works with +either engine -- and each one gets its own store, since they are different +genotype files: on BXD.8, `none` 21,055 rows (the store keeps the gaps as +NaN and pangemma mean-substitutes them per marker as GEMMA does), `hmm` +20,453 rows over 19 chromosomes (autosomal markers only, and the R/qtl2 +imputation itself costs ~11 s the first time), `mean` 21,056 rows (a complete +file maps one marker that complete-case treatment drops). Measured warm: +`none` gemma 4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` +16.3 s / 16.0 s -- the first figure includes the imputation, the second +reuses it from the cache under `RAVANAN_CACHE_DIR/imputed/`. + **There is no fallback for this engine.** The in-process runner is gemma-wrapper on BIMBAM, so falling back would answer a different question under the requested engine's name: a pangemma request forces diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index 9624e0e..f26e8c7 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -3,9 +3,10 @@ # is decided, so the same question can be asked of every engine and the answers # compared. # -# --mode none leave the file as it is (GEMMA then does complete-case per -# marker and reports n_miss; pangemma cannot represent a gap at -# all, so its store builder refuses this mode) +# --mode none leave the file as it is: GEMMA then does complete-case per +# marker and reports n_miss, and pangemma's lmdb store keeps +# the gaps (NaN for Gf, 255 for Gb) and mean-substitutes them +# per marker exactly as GEMMA does # --mode mean replace each missing call by that marker's mean over the # individuals that have one (cheap, but it invents a datum and # deflates the variance) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index c36c1c2..5beb4db 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -129,9 +129,18 @@ pub struct GemmaRequest { /// 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: pangemma's LMDB store cannot hold a gap at all. - /// `hmm` needs a group-scoped request, since the cross it predicts from is - /// the group's. + /// 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, /// Which engine the per-chromosome workflow runs: `gemma` (default, /// gemma-gn2 on BIMBAM) or `pangemma` (the GeneNetwork fork reading an -- cgit 1.4.1 From 64f1268be9a06462fe9685107c949dbbad84212d Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 20 Nov 2026 17:08:54 +0000 Subject: gemma: the genotype treatment and the lmdb store become workflow jobs Both used to run on the API host before ravanan was invoked, cached by two hand-rolled file keys -- one of which (the treatment) carried a version constant that had to be bumped whenever the script changed what it wrote, and the other (the store) keyed on a genotype file's path, size and mtime. As workflow jobs they are scheduled on the cluster and cached by ravanan on (script, inputs) like every other step, and both caches go away. They are *separate* workflows, not steps inside the mapping one, because ccwl's `pipe` is strictly linear: a step sees only the immediately preceding step's unconsumed outputs, and GWA needs the prepared genotypes *and* the kinship matrix -- a diamond ccwl cannot express (verified with a three-step probe; ravanan implements no CWL `when` either, so an optional step is not an option). So: cwl/gemma/prepare.scm mode + BIMBAM pair (+ cross, individuals) -> pair cwl/gemma/store.scm BIMBAM pair -> pangemma's lmdb store cwl/gemma/manifest-artifacts.scm bash, coreutils, gawk, r-minimal, r-qtl2, python, python-numpy, python-lmdb and the server chains them: prepare when `impute` is not `none`, store when the engine is pangemma, then the mapping workflow with the resulting paths. Ravanan sets the manifest profile's search paths inside the job, so python3 there finds numpy and lmdb without the PYTHONPATH the API host needs. Measured warm on BXD.8 trait 10001 (gemma / pangemma, rows): none 21055 3.9 s / 10.3 s mean 21056 10.5 s / 16.5 s hmm 20453 10.2 s / 16.5 s Against 26.8 s for hmm through the host-side path before this. Three things had to be right that were not: - A step input cannot be optional here, so `cross` and `individuals_file` are always passed -- an empty directory and an empty file for the modes that ignore them. - `cross` is a *path*, not a CWL Directory: ravanan's slurm-api backend does not stage a Directory input (the staged path reached the job and R's setwd failed; the same workflow under single-machine succeeded), so the server copies the cross under its cache directory, which the nodes can see. - `scripts/prepare-genotypes.sh --out` is now absolutized before use, because qtl2-impute-bimbam.R does setwd(cross_dir) and writes .* from there: a relative prefix put the outputs inside the cross directory and the job's output globs matched nothing. It also grew --impute-script (a staged script is not beside its companion) and always writes .individuals.txt, since the caller needs the HMM's individual order to align trait values. Also: a request that asked for a treatment no longer falls back to the in-process wrapper when the Slurm route fails. The wrapper reads genotypes as they stand, so falling back on `impute: hmm` answered 21,055 rows where the request meant 20,453 -- a wrong answer under a "degraded" note. Treated requests (and pangemma ones) now fail instead. And ravanan's output may be one File or an array of them: a scattered step reports an array, a single-step workflow one File, which is what "no store array in ravanan's output" was. Deployed and verified on the production instance: all six engine x mode combinations answer 200 with the expected row counts, and bin/monitor-gn4 --tier all is 50 ok / 0 failed. --- README.md | 25 +- cwl/gemma/manifest-artifacts.scm | 25 ++ cwl/gemma/prepare.scm | 77 +++++ cwl/gemma/store.scm | 35 ++ docs/ravanan-slurm.md | 7 +- scripts/prepare-genotypes.sh | 38 ++- src/config.rs | 66 +++- src/gemma.rs | 303 +++++++++-------- src/routes/gemma.rs | 711 +++++++++++++++++++++++---------------- 9 files changed, 816 insertions(+), 471 deletions(-) create mode 100644 cwl/gemma/manifest-artifacts.scm create mode 100644 cwl/gemma/prepare.scm create mode 100644 cwl/gemma/store.scm (limited to 'src') diff --git a/README.md b/README.md index 7ad2841..5c2cda6 100644 --- a/README.md +++ b/README.md @@ -1837,16 +1837,21 @@ What changes underneath, all of it pinned by the deployment: sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller and exact only for integer calls. -`impute` is applied *before* the store is built, so every mode works with -either engine -- and each one gets its own store, since they are different -genotype files: on BXD.8, `none` 21,055 rows (the store keeps the gaps as -NaN and pangemma mean-substitutes them per marker as GEMMA does), `hmm` -20,453 rows over 19 chromosomes (autosomal markers only, and the R/qtl2 -imputation itself costs ~11 s the first time), `mean` 21,056 rows (a complete -file maps one marker that complete-case treatment drops). Measured warm: -`none` gemma 4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` -16.3 s / 16.0 s -- the first figure includes the imputation, the second -reuses it from the cache under `RAVANAN_CACHE_DIR/imputed/`. +`impute` is a *workflow of its own* on this path (`cwl/gemma/prepare.scm`), +one job that writes the prepared BIMBAM pair, cached by ravanan on +(script, inputs) so the treatment runs once per (panel, mode) however many +traits follow; `none` is the same step with nothing to do (a copy). It is a +separate workflow rather than a step inside this one 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. pangemma's +lmdb store is a second such workflow (`cwl/gemma/store.scm`). + +Each mode is its own genotype file and therefore its own store: on BXD.8, +`none` 21,055 rows (the store keeps the gaps as NaN and pangemma +mean-substitutes them per marker as GEMMA does), `hmm` 20,453 rows over 19 +chromosomes (autosomal markers only), `mean` 21,056 rows (a complete file maps +one marker that complete-case treatment drops). Measured warm: `none` gemma +4.0 s / pangemma 3.9 s, `hmm` 26.8 s / 15.8 s, `mean` 16.3 s / 16.0 s. **There is no fallback for this engine.** The in-process runner is gemma-wrapper on BIMBAM, so falling back would answer a different diff --git a/cwl/gemma/manifest-artifacts.scm b/cwl/gemma/manifest-artifacts.scm new file mode 100644 index 0000000..8a8eb07 --- /dev/null +++ b/cwl/gemma/manifest-artifacts.scm @@ -0,0 +1,25 @@ +;; Guix manifest for the artifact workflows -- prepare.scm (the +;; missing-genotype treatment) and store.scm (BIMBAM to pangemma's lmdb) -- as +;; resolved by ravanan's --guix-manifest. They are separate from manifest.scm / +;; manifest-mdb.scm because their jobs need a different toolchain than the +;; mapping steps do, and because ravanan builds one profile per workflow: a +;; mapping job has no business carrying R and numpy. +;; +;; bash + gawk + coreutils: prepare-genotypes.sh is `sh' with an awk one-liner +;; for `mean' and a cp for `none'. +;; r-minimal + r-qtl2: `hmm' runs qtl2-impute-bimbam.R (maxmarg on the cross's +;; genotype probabilities). r-qtl2 propagates r-qtl, r-rcpp, r-jsonlite and +;; r-data-table, so nothing else is listed. +;; python + python-numpy + python-lmdb: geno2mdb.py, which writes the store. +;; +;; ravanan sets these packages' search paths (PYTHONPATH among them) inside the +;; job, so `python3' here finds numpy and lmdb without any wrapper script -- +;; measured, after the API host needed PYTHONPATH exported by hand for the same +;; script (see the deployment's env.sh). +;; +;; A manifest change must be followed by a cold run: ravanan keys a step on +;; (script, inputs), so an old job with an old profile would be reused +;; silently. +(specifications->manifest + (list "bash" "coreutils" "gawk" "r-minimal" "r-qtl2" + "python" "python-numpy" "python-lmdb")) diff --git a/cwl/gemma/prepare.scm b/cwl/gemma/prepare.scm new file mode 100644 index 0000000..1de4d68 --- /dev/null +++ b/cwl/gemma/prepare.scm @@ -0,0 +1,77 @@ +;; The missing-genotype treatment as a workflow of its own: one job that turns +;; the panel's BIMBAM pair into the pair the mapping steps read, by mode -- +;; `none' copies, `mean' substitutes each marker's mean, `hmm' predicts from +;; flanking markers with R/qtl2 (scripts/prepare-genotypes.sh dispatches on +;; --mode, so one step serves all three and no CWL conditional is needed; +;; ravanan implements no `when' and ccwl cannot emit one). +;; +;; WHY A SEPARATE WORKFLOW and not a step inside gemma-loco.scm: the GWA step +;; needs both the prepared genotypes AND the kinship matrix, and ccwl's `pipe' +;; is strictly linear -- each step sees only the immediately preceding step's +;; unconsumed outputs, so a diamond cannot be written in it. Chaining two +;; workflows is what a diamond becomes, and ravanan caches each of them on +;; (script, inputs), so the treatment runs once per (panel, mode) however many +;; traits are mapped afterwards. Cost of the split: one more ravanan invocation +;; per cold request, and interned copies of the pair in the store. +;; +;; Before this, the same script ran on the API host before ravanan was invoked, +;; and its output was cached by a hand-rolled file key whose version constant +;; had to be bumped whenever the script changed what it wrote. +;; +;; `cross' and `individuals_file' are read only for `hmm'; the caller sends an +;; empty directory and an empty file otherwise, since a step input cannot be +;; optional here and a qtl2 cross per request would be work nobody asked for. +;; +;; Written in ccwl; see gemma-loco.scm's header for how it is compiled. +(define prepare + (command + #:inputs (mode #:type string) + (prepare_script #:type File) + (impute_script #:type File) + (raw_genotype_file #:type File) + (raw_snps_file #:type File) + ;; A path, not a Directory: ravanan's slurm-api backend does not stage a + ;; Directory input onto the node (measured: the job ran with the staged path + ;; in its argv and R's setwd failed, while the same workflow under + ;; single-machine succeeded). The caller copies the cross under its own + ;; cache directory, which is on the share the nodes see, and passes that path. + (cross #:type string) + (individuals_file #:type File) + ;; Commands come from the manifest (manifest-artifacts.scm): bash, awk and + ;; R/qtl2 live there, while the two scripts are staged inputs -- so a compute + ;; node needs nothing from the checkout. + #:run "bash" prepare_script + ("--mode" mode) + ("--geno" raw_genotype_file) + ("--snps" raw_snps_file) + ("--out" "prepared") + ("--impute-script" impute_script) + ("--cross" cross) + ("--probs" "-") + ("--individuals-file" individuals_file) + #:outputs (genotype_file #:type File + #:binding ((glob . "prepared.bimbam.txt"))) + (snps_file #:type File + #:binding ((glob . "prepared.snps.txt"))) + ;; The individual order of the file it wrote. BIMBAM carries none, and the + ;; `hmm' calls come from the cross, whose order is its own -- so the caller + ;; needs this to line the trait values up with the genotypes. + (individuals_file #:type File + #:binding ((glob . "prepared.individuals.txt"))))) + +(workflow ((mode #:type string) + (prepare_script #:type File) + (impute_script #:type File) + (genotype_file #:type File) + (snps_file #:type File) + ;; A path under the caller's cache directory (on the share): see the + ;; step's note on why this is not a Directory input. + (cross #:type string) + (individuals_file #:type File)) + (prepare #:mode mode + #:prepare_script prepare_script + #:impute_script impute_script + #:raw_genotype_file genotype_file + #:raw_snps_file snps_file + #:cross cross + #:individuals_file individuals_file)) diff --git a/cwl/gemma/store.scm b/cwl/gemma/store.scm new file mode 100644 index 0000000..6a60628 --- /dev/null +++ b/cwl/gemma/store.scm @@ -0,0 +1,35 @@ +;; The lmdb genotype store pangemma reads with `-g', built from a BIMBAM pair by +;; gemma-wrapper's bin/geno2mdb.py. A workflow of its own for the same reason +;; gemma-loco-mdb.scm's steps are separate (see prepare.scm): the mapping +;; workflow takes the store as an input, and ravanan caches this build on +;; (script, inputs), so a panel's store is built once however many traits are +;; mapped over it. +;; +;; The store is what makes pangemma cheap at scale -- its keys carry the +;; chromosome, so a scan neither parses BIMBAM again per job nor needs the `-a' +;; annotation -- and it is also the expensive artifact: 22 MB for BXD.8, minutes +;; for HLC. Before this it was built on the API host into a +;; GEMMA_LMDB_CACHE_DIR keyed by the genotype file's path, size and mtime; as a +;; workflow it is keyed the way every other step is. +;; +;; Gf always: one little-endian float32 per sample, missing as NaN. Exact for a +;; mean-genotype panel (0, 0.5, 1 all fit in a float32), where Gb is 4x smaller +;; but exact only for integer calls (0/1/2 -> 0/127/254). +(define store + (command + #:inputs (store_script #:type File) + (genotype_file #:type File) + (snps_file #:type File) + #:run "python3" store_script genotype_file + ("--snps" snps_file) + ("--format" "Gf") + ("--out" "genotypes.mdb") + #:outputs (store #:type File + #:binding ((glob . "genotypes.mdb"))))) + +(workflow ((store_script #:type File) + (genotype_file #:type File) + (snps_file #:type File)) + (store #:store_script store_script + #:genotype_file genotype_file + #:snps_file snps_file)) diff --git a/docs/ravanan-slurm.md b/docs/ravanan-slurm.md index 616e924..ba715f3 100644 --- a/docs/ravanan-slurm.md +++ b/docs/ravanan-slurm.md @@ -30,8 +30,11 @@ backend): …`). | `RAVANAN_CACHE_DIR` | where pheno files, logs, the compiled CWL and ravanan's `--store` live | | `GEMMA_RAVANAN_WORKFLOW_MDB` | ccwl source for `"engine": "pangemma"` (default `cwl/gemma/gemma-loco-mdb.scm`) | | `GEMMA_RAVANAN_MANIFEST_MDB` | manifest naming `pangemma-git` for that workflow (default `cwl/gemma/manifest-mdb.scm`); a manifest change needs a cold run, since ravanan keys a step on (script, inputs) | -| `GENO2MDB_CMD` | the lmdb store builder (`geno2mdb.py` from gemma-wrapper's `bin/` -- it is not on `PATH` in every deployment) | -| `GEMMA_LMDB_CACHE_DIR` | where built lmdb stores live, one per genotype file; **must be durable**, since rebuilding one is the expensive part of a pangemma run | +| `GENO2MDB_CMD` | the lmdb store builder (`geno2mdb.py` from gemma-wrapper's `bin/`), staged into the store workflow as a `File` input | +| `GEMMA_PREPARE_WORKFLOW` | ccwl source of the missing-genotype treatment (default `cwl/gemma/prepare.scm`), run as its own job before the mapping workflow | +| `GEMMA_STORE_WORKFLOW` | ccwl source that builds pangemma's lmdb store (default `cwl/gemma/store.scm`) | +| `GEMMA_ARTIFACTS_MANIFEST` | manifest for both of those jobs (default `cwl/gemma/manifest-artifacts.scm`: bash, gawk, R/qtl2, python, numpy, lmdb) -- a different toolchain from the mapping steps, and ravanan builds one profile per workflow | +| `IMPUTE_SCRIPT` | `scripts/qtl2-impute-bimbam.R`, staged into the prepare job | Selecting slurm without an endpoint or a JWT file is a startup error (fail closed, like `GN4_DB_MODE`): ravanan would fail every step, and a diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh index f26e8c7..e6042a5 100755 --- a/scripts/prepare-genotypes.sh +++ b/scripts/prepare-genotypes.sh @@ -17,13 +17,22 @@ # scripts/prepare-genotypes.sh --mode mean|hmm|none \ # --geno --snps --out \ # [--cross ] [--probs ] [--minprob N] \ -# [--individuals-file ] +# [--individuals-file ] \ +# [--impute-script ] +# +# A workflow job stages this script and the R one as separate inputs, so +# --impute-script is how it says where the R script landed; by hand it +# defaults to the file beside this one. # # Writes .bimbam.txt and .snps.txt and prints the prefix. # Exits 2 on bad arguments, 1 when a step fails. set -eu mode= geno= snps= out= cross_dir= probs= minprob=0 individuals_file= +# The HMM script normally sits beside this one. A caller that stages this +# script somewhere else (a workflow job, where it is a copied input and the R +# script is a second one) names it explicitly. +impute_script= while [ $# -gt 0 ]; do case $1 in --mode) mode=$2; shift 2 ;; @@ -34,6 +43,7 @@ while [ $# -gt 0 ]; do --probs) probs=$2; shift 2 ;; --minprob) minprob=$2; shift 2 ;; --individuals-file) individuals_file=$2; shift 2 ;; + --impute-script) impute_script=$2; shift 2 ;; -h|--help) sed -n '2,26p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; *) echo "prepare-genotypes.sh: unknown argument $1" >&2; exit 2 ;; esac @@ -41,6 +51,15 @@ done case $mode in none|mean|hmm) ;; *) echo "prepare-genotypes.sh: --mode must be none, mean or hmm" >&2; exit 2 ;; esac [ -n "$out" ] || { echo "prepare-genotypes.sh: --out is required" >&2; exit 2; } +# Absolute, before anything moves: the HMM script does setwd(cross_dir) and +# writes .* from there, so a relative prefix would put the outputs in +# the cross directory instead of the caller's -- which in a workflow job is the +# difference between the step's output globs matching and not (measured: the +# job answered "Type File mismatch for globbed paths"). +case $out in +/*) ;; +*) out=$(pwd)/$out ;; +esac mkdir -p "$(dirname "$out")" case $mode in @@ -68,7 +87,8 @@ hmm) { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } # R's own complaint last, so a caller that reports the final stderr line # reports the cause rather than our wrapper sentence. - if ! r_output=$("$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + [ -n "$impute_script" ] || impute_script="$(dirname "$0")/qtl2-impute-bimbam.R" + if ! r_output=$("$RSCRIPT" "$impute_script" \ "$cross_dir" "${probs:--}" "$out" "$minprob" "$individuals_file" 2>&1); then echo "prepare-genotypes.sh: HMM imputation failed:" >&2 printf '%s\n' "$r_output" | tail -6 >&2 @@ -77,4 +97,18 @@ hmm) ;; esac +case $mode in +hmm) + # The R script writes .individuals.txt itself: the HMM calls come + # from the cross, whose individual order is its own, and the caller aligns + # the trait values to that order. + ;; +*) + # The other modes keep the panel's order, so the caller's list is the + # answer -- copied rather than re-derived, because a BIMBAM file does not + # carry individual names at all. + [ -n "$individuals_file" ] && cp "$individuals_file" "$out.individuals.txt" + ;; +esac + printf '%s\n' "$out" diff --git a/src/config.rs b/src/config.rs index 849b30a..e029969 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,16 +119,30 @@ pub struct Config { /// 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, - /// Where those stores are kept, one file per genotype file - /// (`GEMMA_LMDB_CACHE_DIR`). They are the expensive part of a - /// pangemma run -- built once, reused by every trait over the same - /// panel -- so a deployment must point this somewhere durable. - pub gemma_lmdb_cache_dir: String, + /// 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 @@ -356,13 +370,22 @@ impl Config { "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_LMDB_CACHE_DIR".to_string(), - std::env::temp_dir() - .join("gn4-gemma-lmdb") - .to_string_lossy() - .into_owned(), + "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(), @@ -546,8 +569,11 @@ impl Config { "GEMMA_RAVANAN_WORKFLOW", "GEMMA_RAVANAN_WORKFLOW_MDB", "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", "GENO2MDB_CMD", - "GEMMA_LMDB_CACHE_DIR", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -620,8 +646,11 @@ impl Config { 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_lmdb_cache_dir: values["GEMMA_LMDB_CACHE_DIR"].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(), @@ -910,8 +939,11 @@ mod tests { "GEMMA_RAVANAN_WORKFLOW", "GEMMA_RAVANAN_WORKFLOW_MDB", "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", "GENO2MDB_CMD", - "GEMMA_LMDB_CACHE_DIR", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -963,8 +995,14 @@ mod tests { 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!(config.gemma_lmdb_cache_dir.ends_with("gn4-gemma-lmdb")); + 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 e9f6a60..5d2d173 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -13,7 +13,7 @@ //! shared infrastructure; see `crate::streaming`. use std::io; -use std::path::{Path, PathBuf}; +use std::path::Path; use std::process::Output; use serde_json::Value; @@ -1037,10 +1037,23 @@ pub async fn compute( /// `{"": [{"class": "File", "path": ..., ...}, ...], ...}`, /// one entry per `cwl/gemma/gemma-loco.scm` chromosome). fn ravanan_output_paths<'a>(outputs: &'a Value, id: &str) -> Result, 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| { @@ -1185,7 +1198,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() } @@ -1286,7 +1299,7 @@ fn chromosomes_from(contents: &str) -> Vec { /// genotypes: `gemma` parses BIMBAM text every invocation and needs the /// `-a` annotation to know which markers to leave out, while `pangemma` /// reads an lmdb store whose keys carry the chromosome, so it needs neither. -/// The store is built once per panel (see [`lmdb_store`]) and is what makes +/// 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)] @@ -1347,125 +1360,131 @@ impl GemmaEngine { /// The per-chromosome workflow to run and the engine behind it: what a /// deployment pins in `GEMMA_RAVANAN_WORKFLOW`/`_MANIFEST` (gemma) and their -/// `_MDB` twins (pangemma), plus what pangemma needs to build its store. +/// `_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, - /// `geno2mdb.py`, used only by the pangemma engine. - pub geno2mdb: &'a str, - /// Where built lmdb stores live, one per genotype file. - pub lmdb_cache_dir: &'a str, } -/// A key for one genotype file's lmdb store: path, size and mtime plus the -/// annotation's contents and the store format. +/// What running an artifact workflow needs: the ccwl source, the manifest its +/// jobs resolve against, ravanan's own switches, and the outputs wanted. /// -/// Not the genotype *contents*: a 200 MB BIMBAM file is not hashed on every -/// request (the same reason `kinship_input_key` uses path and size). The -/// mtime is what catches an in-place rewrite, which size alone would miss -/// when a prepared file is regenerated with the same byte count. -fn lmdb_store_key(genotype_file: &str, snps_file: &str) -> String { - let mut material = Vec::new(); - material.extend_from_slice(genotype_file.as_bytes()); - material.push(0); - if let Ok(metadata) = std::fs::metadata(genotype_file) { - material.extend_from_slice(&metadata.len().to_le_bytes()); - if let Ok(modified) = metadata.modified() { - if let Ok(since) = modified.duration_since(std::time::UNIX_EPOCH) { - material.extend_from_slice(&since.as_nanos().to_le_bytes()); - } - } - } - material.push(0); - if let Ok(snps) = std::fs::read(snps_file) { - material.extend_from_slice(&snps); - } - material.push(0); - // Gf: one float32 per sample, exact for a mean-genotype panel (0, 0.5, 1 - // all fit). Gb is 4x smaller but exact only for integer calls, where it - // would move p-values in the third decimal. - material.extend_from_slice(b"Gf"); - sha16(&material) +/// 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, } -/// Build (or reuse) the lmdb genotype store pangemma reads with `-g`. +/// Run one artifact workflow and return its outputs by id. /// -/// One store per genotype file, not per trait: the store holds the panel's -/// markers and samples, and pangemma does GEMMA's own per-marker -/// mean-substitution at run time, so every trait over the panel shares it and -/// a repeat request costs one `stat`. -/// -/// Written aside and renamed, so a concurrent identical request sees either no -/// store or a complete one; two simultaneous first-runs both build it, which -/// the rename makes harmless rather than wrong. -async fn lmdb_store( - cmd: &str, - cache_dir: &str, - genotype_file: &str, - snps_file: &str, -) -> Result<(PathBuf, String), GemmaError> { - std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?; - let key = lmdb_store_key(genotype_file, snps_file); - let stem = Path::new(genotype_file) - .file_name() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| "genotypes".to_string()); - let store_path = Path::new(cache_dir).join(format!("{stem}-{key}.mdb")); - if store_path.is_file() { - return Ok(( - store_path.clone(), - format!( - "pangemma's lmdb genotype store was already built ({})", - store_path.display() - ), +/// 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)>, 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 tmp_path = Path::new(cache_dir).join(format!( - "{stem}-{key}.tmp-{}.mdb", - std::process::id() - )); - let _ = std::fs::remove_file(&tmp_path); - let tmp_arg = tmp_path.to_string_lossy().into_owned(); - let args = [ - genotype_file, - "--snps", - snps_file, - "--format", - "Gf", - "--out", - tmp_arg.as_str(), + let 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 output = streaming::run_streaming(cmd, &args, None) + let batch_args = run.batch.ravanan_args(scratch); + args.extend(batch_args.iter().map(String::as_str)); + let output = streaming::run_streaming(run.ravanan_cmd, &args, None) .await .map_err(|error| GemmaError::Spawn { - command: cmd.to_string(), + command: run.ravanan_cmd.to_string(), error, })?; if !output.status.success() { - let _ = std::fs::remove_file(&tmp_path); - return Err(GemmaError::CommandFailed { - step: "geno2mdb", - stderr: format!( - "{}\n{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - ), - }); + return Err(GemmaError::RavananFailed(format!( + "{} ({})", + run.label, + String::from_utf8_lossy(&output.stderr) + ))); } - std::fs::rename(&tmp_path, &store_path).map_err(GemmaError::Io)?; - // lmdb leaves a `-lock` companion beside the temporary name. - let _ = std::fs::remove_file(tmp_path.with_extension("mdb-lock")); - Ok(( - store_path.clone(), - format!( - "pangemma's lmdb genotype store was built from {genotype_file} ({})", - store_path.display() - ), - )) + 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, @@ -1525,6 +1544,8 @@ pub async fn compute_ravanan( batch: &crate::config::RavananBatch, ccwl_cmd: &str, workflow: &RavananWorkflow<'_>, + // pangemma only: the lmdb store built by the store workflow. + store: Option<&str>, cache_dir: &str, scratch_dir: &str, genotype_file: &str, @@ -1621,22 +1642,13 @@ pub async fn compute_ravanan( .collect::>() .join(", "); - // pangemma reads an lmdb store instead of BIMBAM plus its annotation, so - // that store has to exist before anything is staged -- and it is the one - // expensive input, built once per genotype file rather than per trait. - let (store_path, store_note) = match engine { - GemmaEngine::Gemma => (None, None), - GemmaEngine::Pangemma => { - let (path, note) = lmdb_store( - workflow.geno2mdb, - workflow.lmdb_cache_dir, - genotype_file, - snps_file, - ) - .await?; - (Some(path), Some(note)) - } - }; + // 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| { + 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 = @@ -1645,7 +1657,7 @@ pub async fn compute_ravanan( engine, genotype_file, snps_file, - store_path.as_deref(), + store_path, &pheno_path, &kinship_pheno_path, lmm, @@ -1699,13 +1711,11 @@ pub async fn compute_ravanan( // cannot say which cost its caller what. let engine_note = match (&store_note, engine) { (Some(note), _) => Some(format!( - "Engine: {} (lmdb genotypes rather than BIMBAM): {note}", + "Engine: {} reads its genotypes from an lmdb store rather than BIMBAM ({note})", engine.as_str() )), + (None, GemmaEngine::Pangemma) => None, (None, GemmaEngine::Gemma) => None, - (None, GemmaEngine::Pangemma) => { - Some(format!("Engine: {}", engine.as_str())) - } }; let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref()) @@ -2364,25 +2374,30 @@ mod engine_tests { assert!(!pangemma.contains("snps_file")); } - /// A store belongs to a genotype file, not to a trait: every trait over - /// the panel must reuse it, or the expensive half of a pangemma run is - /// paid again per request. The annotation is part of the key because it - /// decides which markers and chromosomes the store holds. + /// 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 the_store_key_follows_the_genotype_file_and_annotation_only() { - let dir = std::env::temp_dir().join(format!("gn4-lmdbkey-{}", std::process::id())); - std::fs::create_dir_all(&dir).unwrap(); - let geno = dir.join("G.txt"); - let snps = dir.join("S.txt"); - std::fs::write(&geno, "s1\ts2\nm1\t1\t1\t0\t2\n").unwrap(); - std::fs::write(&snps, "m1 150 1\n").unwrap(); - let geno_s = geno.to_string_lossy().into_owned(); - let snps_s = snps.to_string_lossy().into_owned(); - - let first = lmdb_store_key(&geno_s, &snps_s); - assert_eq!(first, lmdb_store_key(&geno_s, &snps_s), "must be stable"); - std::fs::write(&snps, "m1 150 2\n").unwrap(); - assert_ne!(first, lmdb_store_key(&geno_s, &snps_s), "annotation counts"); - let _ = std::fs::remove_dir_all(&dir); + 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()); } } diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 5beb4db..6cb8d0b 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -185,6 +185,360 @@ pub(crate) struct ResolvedInputs { pub notes: Vec, } +/// 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, + version: Option<&str>, + names: Option<&Vec>, + endpoint: &'static str, + rid: RequestInfo, +) -> Result { + let cache_dir = &config.ravanan_cache_dir; + 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 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() + }; + 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 inputs = format!( + "store_script: {{class: File, path: {}}}\n\ + genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n", + absolute(&config.geno2mdb_cmd), + ); + 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, + &["store_script", "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()); + 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 + }; + + Ok(Artifacts { + genotype_file, + snps_file, + store, + individuals_file, + notes, + }) +} + +/// What [`ravanan_artifacts`] produced. +struct Artifacts { + genotype_file: String, + snps_file: String, + store: Option, + /// The individual order of the prepared genotypes, when the treatment + /// changed it (`hmm` takes its order from the cross). + individuals_file: Option, + notes: Vec, +} + /// Resolve a request's genotype input and trait values. /// /// `endpoint` names this endpoint in errors ("compute_gemma" or @@ -608,8 +962,19 @@ pub async fn compute_gemma( 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 = None; - if pangemma || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { + if treated || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { match gemma_via_ravanan( ctx.clone(), token.clone(), @@ -621,7 +986,7 @@ pub async fn compute_gemma( .await { Ok(answer) => return Ok(answer), - Err(error) if error.status >= 500 && !pangemma => { + 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 @@ -1001,255 +1366,6 @@ pub async fn compute_gemma( } -/// A genotype file materialised for one missing-data treatment. -struct PreparedGenotypes { - genotype_file: String, - snps_file: String, - notes: Vec, -} - -/// Run `scripts/prepare-genotypes.sh` to turn the resolved genotype file into -/// the one the caller asked for (`mean` or `hmm`). -/// -/// Both modes write a *complete* file beside the ravanan cache, keyed by the -/// panel and the mode, so a second request for the same panel and treatment -/// reuses it: `mean` costs a pass over the file, `hmm` costs the qtl2 HMM -/// (about ten seconds for BXD.8 on one core, then cached). -async fn prepare_genotypes( - config: &Config, - mode: &str, - genotype_file: &str, - snps_file: &str, - group: &Option, - version: Option<&str>, - names: Option<&Vec>, - rid: RequestInfo, -) -> Result { - let stem = std::path::Path::new(genotype_file) - .file_stem() - .map(|name| name.to_string_lossy().into_owned()) - .unwrap_or_else(|| "panel".to_string()); - // The cache key carries a version, because it is keyed on the panel and the - // mode and NOT on the code that produces them: a fixed bug in the imputation - // script would otherwise be masked by its own old output (measured: a - // corrected individuals file was ignored and the run kept failing on the - // stale one). Bump this when either script changes what it writes. - const IMPUTE_CACHE_VERSION: &str = "v6"; - let prefix = std::path::Path::new(&config.ravanan_cache_dir) - .join("imputed") - .join(format!("{stem}-{mode}-{IMPUTE_CACHE_VERSION}")); - let prepared_geno = format!("{}.bimbam.txt", prefix.to_string_lossy()); - let prepared_snps = format!("{}.snps.txt", prefix.to_string_lossy()); - - let mut notes = Vec::new(); - if std::path::Path::new(&prepared_geno).is_file() - && std::path::Path::new(&prepared_snps).is_file() - { - notes.push(format!( - "genotypes: '{mode}' treatment reused from the cache ({})", - prepared_geno - )); - return Ok(PreparedGenotypes { - genotype_file: prepared_geno, - snps_file: prepared_snps, - notes, - }); - } - - // hmm predicts from the group's qtl2 cross: the same conversion and the - // same cache /compute/qtl2 uses, so the calls are the ones that endpoint - // maps on, and the probabilities are computed once and kept beside the - // cross. - let cross_dir = if mode == "hmm" { - let Some(group) = 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(), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - }; - let directory = config.genotype_files_dir.clone(); - let cache = config.qtl2_cache_dir.clone(); - let version = version.map(|v| v.to_string()); - let convert = config.qtl2_convert_script.clone(); - let prepared = tokio::task::spawn_blocking(move || { - let resolved = genotypes::resolve( - std::path::Path::new(&directory), - &group, - 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}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })? - .map_err(|error| { - ApiError::new( - StatusCode::UNPROCESSABLE_ENTITY, - "cross_preparation_failed", - "Could not prepare the cross", - format!("{error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })?; - prepared - .control - .parent() - .map(|dir| dir.to_path_buf()) - .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)) - } else { - std::path::PathBuf::new() - }; - - if let Some(parent) = std::path::Path::new(&prepared_geno).parent() { - if let Err(error) = std::fs::create_dir_all(parent) { - return Err(ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not create the imputation cache directory", - format!("creating {} failed: {error}", parent.display()), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - } - // The individuals the request actually serves, so the HMM output has the - // same columns as the other modes and the phenotype lines up positionally. - let individuals_path = format!("{}.panel.txt", prefix.to_string_lossy()); - if let Some(names) = names { - if !names.is_empty() { - if let Err(error) = std::fs::write( - &individuals_path, - names.iter().map(|n| format!("{n}\n")).collect::(), - ) { - return Err(ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not write the individual list", - format!("writing {individuals_path} failed: {error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - } - } - let individuals_arg = individuals_path.clone(); - let script = config.prepare_genotypes.clone(); - let script_for_job = script.clone(); - let geno = genotype_file.to_string(); - let snps = snps_file.to_string(); - let out = prefix.to_string_lossy().into_owned(); - let mode_owned = mode.to_string(); - let status = tokio::task::spawn_blocking(move || { - let mut args: Vec = vec![ - "--mode".to_string(), - mode_owned, - "--out".to_string(), - out, - ]; - if !geno.is_empty() { - args.push("--geno".to_string()); - args.push(geno); - args.push("--snps".to_string()); - args.push(snps); - } - if !cross_dir.as_os_str().is_empty() { - args.push("--cross".to_string()); - args.push(cross_dir.to_string_lossy().into_owned()); - args.push("--probs".to_string()); - args.push("-".to_string()); - if std::path::Path::new(&individuals_arg).is_file() { - args.push("--individuals-file".to_string()); - args.push(individuals_arg.clone()); - } - } - std::process::Command::new(&script_for_job).args(&args).output() - }) - .await - .map_err(|error| { - ApiError::new( - StatusCode::INTERNAL_SERVER_ERROR, - "internal_error", - "Could not prepare genotypes", - format!("running {script} failed: {error}"), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })? - .map_err(|error| { - ApiError::new( - StatusCode::BAD_GATEWAY, - "prepare_genotypes_failed", - "Could not prepare genotypes", - format!("could not run {}: {error}", config.prepare_genotypes), - "compute_gemma_ravanan", - ) - .with_request_id(rid.clone()) - })?; - if !status.status.success() { - return Err(ApiError::new( - StatusCode::BAD_GATEWAY, - "prepare_genotypes_failed", - "Could not prepare genotypes", - format!( - "{} --mode {mode} failed: {}", - config.prepare_genotypes, - String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or("no message") - ), - "compute_gemma_ravanan", - ) - .with_request_id(rid)); - } - - notes.push(match mode { - "mean" => "genotypes: missing calls replaced by each marker's mean (a complete \ - file, so every individual is analysed; GEMMA's own treatment is \ - complete-case per marker, which this replaces)" - .to_string(), - _ => "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) rather than filled with a mean. The heterozygous calls a \ - riself panel carries are dropped first, as convert2riself does, and \ - the HMM re-predicts those too. Validated on BXD.8 after the allele \ - codes were fixed (alleles 1 and 2, not 1 and 3): all 20453 autosomal \ - markers stay polymorphic and the top is rsm10000005700, p 6.6e-07 -- \ - the locus the other two engines name. Before that fix it was 11912 \ - markers with the peak on chromosome 5, so a collapse this mode can \ - still produce silently is worth checking when a scan looks wrong." - .to_string(), - }); - Ok(PreparedGenotypes { - genotype_file: prepared_geno, - snps_file: prepared_snps, - notes, - }) -} /// Re-order trait values to the individual order of a prepared genotype file. /// @@ -1456,55 +1572,53 @@ pub(crate) async fn gemma_via_ravanan( ) .with_request_id(rid)); } - let mut impute_notes: Vec = Vec::new(); - let (genotype_file, snps_file) = if impute == "none" { - (genotype_file, snps_file) - } else { - let prepared = prepare_genotypes( - &config, - &impute, - &genotype_file, - &snps_file, - &Some(resolved_group.clone()), - request.genotype_version.as_deref(), - resolved_names.as_ref(), - rid.clone(), - ) - .await?; - impute_notes = prepared.notes; - if impute == "hmm" { - let individuals = format!( - "{}.individuals.txt", - prepared - .genotype_file - .trim_end_matches(".bimbam.txt") - ); - if let Some(names) = 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)); - } + // 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 (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)); } } } - (prepared.genotype_file, prepared.snps_file) - }; + } + 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 @@ -1535,14 +1649,13 @@ pub(crate) async fn gemma_via_ravanan( engine, source: workflow_source, manifest: manifest_source, - geno2mdb: &config.geno2mdb_cmd, - lmdb_cache_dir: &config.gemma_lmdb_cache_dir, }; gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, &ravanan_workflow, + store.as_deref(), &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, -- cgit 1.4.1 From 3a526efb4cd3721adadf17cbf4a8dc1c5cbd8dec Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sat, 21 Nov 2026 12:04:20 +0000 Subject: gemma: a warm request is ravanan's walk, not Slurm's scheduler Measured where a warm request's time actually goes, because it was easy to blame the scheduler. It is not the scheduler: over 683 jobs slurmrestd reports a queue delay of 0 s (median; p90 1 s, max 1 s) and run times of 1-4 s, with the container's tuned 5 s interval already invisible to backfill. What cost time was ravanan's own overhead, paid once per invocation: - ~4 s per invocation just to evaluate a manifest: leaving GUIX_PACKAGE_PATH set makes guix autoload guix-bioinformatics' whole module tree (one ABI mismatch warning per module). The artifact workflows' manifests name only `(gnu packages)` specs, so run_artifact now clears the variable for its child: 12.0 s -> 7.9 s for the same cached run. - ~7 s to walk a fully cached 40-step workflow (no jobs at all). - pangemma ran *two* invocations per request (store, then mapping) even when both were cached, so it paid all of that twice. So the artifacts are memoized: a small pointer file under /artifacts/ records where a workflow left its outputs, keyed on the inputs' path, size and mtime (a regenerated panel file misses; a stale pointer whose files are gone is ignored and rebuilt). Ravanan's store remains the data cache and the mapping workflow's own key is unchanged -- this only avoids asking ravanan to tell us something we already know. Warm BXD.8 trait 10001, before -> after: gemma 8.3 s -> 4.2 s pangemma 21.1 s -> 4.1 s and a request for a new trait is now the same for both engines (9.5 s: the 20 GWA jobs, cached K), where gemma's was 13.5 s. Still on the table, not done here: merging the kinship and GWA steps into one job per chromosome (20 steps instead of 40, halving the walk) at the cost of the K-sharing across traits, a Slurm sched_interval of 1 s in the container, and pruning ravanan's store -- 87 GB now, of which 72 GB is per-step logs. --- src/gemma.rs | 22 ++++++--- src/routes/gemma.rs | 132 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 148 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/gemma.rs b/src/gemma.rs index 5d2d173..4805b84 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -1458,12 +1458,22 @@ pub async fn run_artifact( ]; let batch_args = run.batch.ravanan_args(scratch); args.extend(batch_args.iter().map(String::as_str)); - let output = streaming::run_streaming(run.ravanan_cmd, &args, None) - .await - .map_err(|error| GemmaError::Spawn { - command: run.ravanan_cmd.to_string(), - error, - })?; + // With GUIX_PACKAGE_PATH cleared: these manifests name only `(gnu + // packages)` specs (bash, gawk, R/qtl2, python), and leaving the channel + // path set makes guix autoload guix-bioinformatics' module tree for every + // invocation -- an ABI mismatch warning per module and about four seconds + // of Guile per ravanan call (measured: 12.0 s with, 7.9 s without). + let output = streaming::run_streaming_with_env( + run.ravanan_cmd, + &args, + None, + &[("GUIX_PACKAGE_PATH", "")], + ) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ravanan_cmd.to_string(), + error, + })?; if !output.status.success() { return Err(GemmaError::RavananFailed(format!( "{} ({})", diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 6cb8d0b..38b5b0c 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -185,6 +185,75 @@ pub(crate) struct ResolvedInputs { pub notes: Vec, } +/// 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> { + 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)]) { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let body: String = outputs + .iter() + .filter_map(|(id, paths)| paths.first().map(|file| format!("{id}\t{file}\n"))) + .collect(); + let tmp = path.with_extension(format!("tmp-{}", std::process::id())); + if std::fs::write(&tmp, body).is_ok() { + let _ = std::fs::rename(&tmp, path); + } +} + +/// `path:size:mtime` for a file, so a rewritten input misses the memo. +fn artifact_input_stamp(path: &str) -> String { + match std::fs::metadata(path) { + Ok(metadata) => { + let mtime = metadata + .modified() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|since| since.as_nanos()) + .unwrap_or(0); + format!("{path}:{}:{mtime}", metadata.len()) + } + Err(_) => path.to_string(), + } +} + /// The two cluster-side artifacts a ravanan request needs before anything is /// mapped: the missing-genotype treatment (`cwl/gemma/prepare.scm`) and, for /// pangemma, its lmdb store (`cwl/gemma/store.scm`). @@ -440,6 +509,39 @@ async fn ravanan_artifacts( individuals_file: {{class: File, path: {served}}}\n", prepare_script, impute_script, ); + let memo = std::path::Path::new(cache_dir) + .join("artifacts") + .join(format!( + "{}.txt", + artifact_memo_key( + "prepare", + &[ + mode.to_string(), + artifact_input_stamp(genotype_file), + artifact_input_stamp(snps_file), + cross_dir.clone(), + artifact_input_stamp(&served), + ], + ) + )); + let from_memo = artifact_memo_load(&memo).map(|entries| { + let pick = |id: &str| { + entries + .iter() + .find(|(name, _)| name == id) + .map(|(_, file)| file.clone()) + .unwrap_or_default() + }; + (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file"))) + }); + if let Some(found) = from_memo { + notes.push(format!( + "genotypes: '{mode}' treatment reused (ravanan built it for this panel and \ + mode earlier; the mapping workflow takes the same paths, so its own cache \ + still applies)" + )); + found + } else { let run = gemma::ArtifactWorkflow { label: "prepare", ccwl_cmd: &config.ccwl_cmd, @@ -473,14 +575,42 @@ async fn ravanan_artifacts( .and_then(|(_, paths)| paths.first().cloned()) .unwrap_or_default() }; + artifact_memo_save(&memo, &outputs); notes.push(format!( "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \ cluster), cached by ravanan on (script, inputs)" )); (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file"))) + } }; let store = if engine == gemma::GemmaEngine::Pangemma { + let memo = std::path::Path::new(cache_dir) + .join("artifacts") + .join(format!( + "{}.txt", + artifact_memo_key( + "store", + &[ + artifact_input_stamp(&genotype_file), + artifact_input_stamp(&snps_file), + ], + ) + )); + if let Some(entries) = artifact_memo_load(&memo) { + notes.push( + "genotypes: pangemma's lmdb store reused (ravanan built it for these genotypes \ + earlier)" + .to_string(), + ); + Some( + entries + .iter() + .find(|(name, _)| name == "store") + .map(|(_, file)| file.clone()) + .unwrap_or_default(), + ) + } else { let inputs = format!( "store_script: {{class: File, path: {}}}\n\ genotype_file: {{class: File, path: {genotype_file}}}\n\ @@ -509,12 +639,14 @@ async fn ravanan_artifacts( .iter() .find(|(name, _)| name == "store") .and_then(|(_, paths)| paths.first().cloned()); + artifact_memo_save(&memo, &outputs); notes.push( "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \ cluster), cached by ravanan on (script, inputs)" .to_string(), ); path + } } else { None }; -- cgit 1.4.1 From 5d8794d06ef30afcd5eb832c55e64c0e2f6508ef Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 07:44:29 +0000 Subject: compute: report where the time went, per phase and per step `meta.took_ms` is one number and it has misled twice: a warm re-request reports the cache's speed, not the engine's, and a client cutoff looks like a failure. A compute reply now carries `meta.timing` beside it: engine gemma | pangemma phases[] artifacts (state: built|reused|none), workflow, parse cluster {jobs_submitted, run_ms_sum, run_ms_max, queue_ms_sum} steps[] one per CWL step instance: step, chr, compute_ms, state steps_summary n, compute_ms_sum, compute_ms_max, cached Three decisions worth their words: - **states, not just durations.** A cached step's log is still in ravanan's store with the figure from when it ran, so every number carries `ran` or `cached`: a warm answer's step times are the original run's, not this request's work. The state comes from the log's mtime against the request's start, which is per step and needs no cooperation from ravanan. - **`jobs_submitted: 0` is the warm claim.** Slurm is asked once, after the run, for the jobs it accepted since the request began. It is a count rather than a boolean because a request can be half warm: a new trait over a known panel re-uses every kinship matrix and runs only the GWA steps (measured: 20 of 40). Slurm's clock is one-second granular, so a sub-second job reports 0 run ms; the queue sum still shows the dispatch tick. - **per-step figures come from the engines' own logs** (`## total computation time`), which the workflow already returns for GWA and `-pve`. A scattered step whose log is *not* a workflow output (kinship's) is located through the job that ran it -- which is why ravanan now names jobs after the step's store basename (separate commit, 1542662). Measured on BXD.8 trait 10001, engine=pangemma: warm: took_ms 4704, artifacts reused, 0 jobs, 20 steps all `cached` (compute_ms_sum 16067 -- historical, as labelled), workflow 3687 cold: took_ms 10012, 20 jobs (kinship re-used, GWA ran), 20 steps `ran`, compute_ms_sum 15872, workflow 9043 bin/monitor-gn4 reads `meta.timing.engine` instead of parsing note text, and reports the cache state with it ("engine: gemma, warm"). --- README.md | 13 +++ bin/monitor-gn4 | 13 ++- src/gemma.rs | 241 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/response.rs | 108 +++++++++++++++++++++++ src/routes/gemma.rs | 114 +++++++++++++++++++++++-- 5 files changed, 482 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/README.md b/README.md index 5c2cda6..ac8f28f 100644 --- a/README.md +++ b/README.md @@ -1837,6 +1837,19 @@ What changes underneath, all of it pinned by the deployment: sample, exact for a mean-genotype panel like BXD); Gb is 4x smaller and exact only for integer calls. +**`meta.timing` says where the time went.** Beside `meta.took_ms` (the wall +clock for the whole request), a compute reply carries `timing`: the `engine`, +the request's `phases` (`artifacts` with `built`/`reused`/`none`, `workflow`, +`parse`), what the `cluster` did, and one entry per CWL step instance with the +figure its *own* log reports (`## total computation time`), labelled `ran` or +`cached`. `cluster.jobs_submitted: 0` is the warm claim -- no job ran, so every +step came from ravanan's store -- and a count like `20` means only those steps +ran (a new trait over a known panel re-uses all the kinship matrices and runs +only the GWA steps). Cached steps report the times recorded when they ran, which +is why `state` sits next to every number: a warm answer's step times are the +original run's, not this request's work. Slurm's job clock has one-second +resolution, so a sub-second job reports 0. + `impute` is a *workflow of its own* on this path (`cwl/gemma/prepare.scm`), one job that writes the prepared BIMBAM pair, cached by ravanan on (script, inputs) so the treatment runs once per (panel, mode) however many diff --git a/bin/monitor-gn4 b/bin/monitor-gn4 index 962f0f1..84a2f83 100755 --- a/bin/monitor-gn4 +++ b/bin/monitor-gn4 @@ -296,7 +296,10 @@ def has_rows(reply): def engine_of(reply): - """Which engine answered /compute/gemma, from the reply's own notes. + """Which engine answered /compute/gemma. + + Read from `meta.timing.engine` where the binary reports it, falling back to + the notes (a reply from an older build carries no timing). Since GEMMA_ENGINE=slurm (the default) that endpoint runs the same per-chromosome workflow /compute/gemma/ravanan does, and only falls back to @@ -307,7 +310,13 @@ def engine_of(reply): the timing. """ data = reply.json or {} - notes = data.get("notes") or (data.get("meta") or {}).get("notes") or [] + timing = (data.get("meta") or {}).get("timing") or {} + if timing.get("engine"): + cluster = timing.get("cluster") or {} + jobs = cluster.get("jobs_submitted") + suffix = "" if jobs is None else (", warm" if jobs == 0 else f", {jobs} job(s)") + return f"{timing['engine']}{suffix}" + notes = data.get("notes") or [] for note in notes: if not isinstance(note, str): continue diff --git a/src/gemma.rs b/src/gemma.rs index 4805b84..5730d83 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -18,6 +18,7 @@ use std::process::Output; use serde_json::Value; +use crate::response::StepTiming; use crate::streaming::{self, RunLogError}; /// One phenotype value per strain (genotype-file order), or `None` for @@ -790,6 +791,216 @@ pub struct GemmaOutput { pub columns: Vec, pub rows: Value, pub notes: Vec, + /// Per-step compute times read out of the steps' own logs. + pub steps: Vec, + /// 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 = 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 { + for line in log.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("## total computation time") { + let minutes: f64 = rest + .split('=') + .nth(1)? + .trim() + .trim_end_matches("min") + .trim() + .parse() + .ok()?; + return Some((minutes * 60_000.0).round() as u64); + } + } + None +} + +/// The chromosome a step's log file was written for: the workflow names each +/// one `-.log.txt` (`9-gwa.log.txt`, `X-kin.log.txt`). +fn step_chromosome(path: &str, step: &str, suffix: &str) -> Option { + let name = Path::new(path).file_name()?.to_string_lossy(); + // "-.log.txt": strip the step as well, or every scattered log + // looks as if its chromosome were "9-gwa" (and is rejected for the hyphen). + let marker = format!("-{step}{suffix}"); + let stem = name + .strip_suffix(&marker) + .map(str::to_string) + .or_else(|| name.strip_suffix(suffix).map(str::to_string))?; + if stem.is_empty() || stem.contains('-') { + // "kin"/"gwa" are the only hyphen-free steps we name this way; a + // chromosome never contains '-' but a key can, so be strict. + return None; + } + Some(stem) +} + +/// [`step_timings`], with each step's state taken from its log's mtime: a log +/// older than the request was not written by it, so ravanan answered that step +/// from its store. +fn step_timings_stateful( + paths: &[&str], + step: &str, + suffix: &str, + request_started: std::time::SystemTime, +) -> Vec { + 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 { + 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, Vec) { + 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::() { + 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::(&body) else { + return (None, Vec::new()); + }; + let number = |value: &Value, key: &str| -> Option { + 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 ("-"), so its + // outputs -- and the log with the engine's own compute time -- are one + // directory away. This is the only way to a *scattered* step's figures + // when its log is not a workflow output (kinship's is not). + if let Some(name) = job.get("name").and_then(Value::as_str) { + let dir = Path::new(&store).join("files").join(name); + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + let path = entry.path(); + let file = path.to_string_lossy().into_owned(); + if !file.ends_with(".log.txt") { + continue; + } + let step = if name.ends_with("-kinship") { + "kinship" + } else if name.ends_with("-gwa") { + "gwa" + } else { + continue; + }; + if let Ok(log) = std::fs::read_to_string(&path) { + steps.push(StepTiming { + step: step.to_string(), + chr: step_chromosome(&file, step, ".log.txt"), + compute_ms: step_compute_ms(&log), + state: "ran".to_string(), + }); + } + } + } + } + if let Some(start) = number(job, "start_time") { + queue_sum += start.saturating_sub(submit) * 1000; + if let Some(end) = number(job, "end_time") { + let run = end.saturating_sub(start) * 1000; + run_sum += run; + run_max = run_max.max(run); + } + } + } + timing.run_ms_sum = Some(run_sum); + timing.run_ms_max = Some(run_max); + timing.queue_ms_sum = Some(queue_sum); + (Some(timing), steps) } /// The gemma-wrapper arguments for the kinship step, shared between the @@ -1016,6 +1227,12 @@ pub async fn compute( columns, rows: Value::Array(rows), notes: output_notes, + // The wrapper path reports its own timings in its JSON record and + // the route times the call as a whole; the per-step figures are a + // ravanan-path thing (one process ran everything here). + steps: Vec::new(), + workflow_ms: 0, + parse_ms: 0, }) } .await; @@ -1556,6 +1773,9 @@ pub async fn compute_ravanan( workflow: &RavananWorkflow<'_>, // pangemma only: the lmdb store built by the store workflow. store: Option<&str>, + // When the request started, so a step whose log predates it can be + // reported as cached rather than as work this request did. + request_started: std::time::SystemTime, cache_dir: &str, scratch_dir: &str, genotype_file: &str, @@ -1728,12 +1948,14 @@ pub async fn compute_ravanan( (None, GemmaEngine::Gemma) => None, }; + let workflow_started = std::time::Instant::now(); let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref()) .await .map_err(|error| GemmaError::Spawn { command: ravanan_cmd.to_string(), error, })?; + let workflow_ms = workflow_started.elapsed().as_millis() as u64; if !output.status.success() { return Err(GemmaError::RavananFailed( String::from_utf8_lossy(&output.stderr).into_owned(), @@ -1743,6 +1965,7 @@ pub async fn compute_ravanan( .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?; let assoc_paths = ravanan_output_paths(&outputs, "assoc")?; let gwa_log_paths = ravanan_output_paths(&outputs, "gwa_log")?; + let kinship_log_paths = ravanan_output_paths(&outputs, "kinship_log").unwrap_or_default(); if assoc_paths.is_empty() { return Err(GemmaError::NoAssocFiles); } @@ -1750,6 +1973,7 @@ pub async fn compute_ravanan( // One .assoc.txt and one .log.txt per chromosome, straight from the // workflow's own outputs: gemma writes named files (`-o -gwa`), so // there is no wrapper JSON record to parse and no archive to unpack. + let parse_started = std::time::Instant::now(); let mut columns = Vec::new(); let mut rows = Vec::new(); for assoc_path in &assoc_paths { @@ -1760,9 +1984,23 @@ pub async fn compute_ravanan( } rows.extend(file_rows.into_iter().map(Value::Array)); } + let parse_ms = parse_started.elapsed().as_millis() as u64; // `-pve` puts the variance components in each job's .log.txt, which the // workflow returns as a first-class output. let components = read_variance_components_from_log_files(&gwa_log_paths); + // Per-step figures from the engines' own logs, with the state taken from + // each log's mtime: a log older than the request is a step ravanan reused. + let mut steps = step_timings_stateful(&gwa_log_paths, "gwa", ".log.txt", request_started); + steps.extend(step_timings_stateful( + &kinship_log_paths, + "kinship", + ".log.txt", + request_started, + )); + steps.sort_by(|a, b| { + (a.step.as_str(), a.chr.as_deref().unwrap_or("")) + .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or(""))) + }); streaming::mark_complete(&log_path); @@ -1800,6 +2038,9 @@ pub async fn compute_ravanan( columns, rows: Value::Array(rows), notes, + steps, + workflow_ms, + parse_ms, }) } diff --git a/src/response.rs b/src/response.rs index f830054..46db64a 100644 --- a/src/response.rs +++ b/src/response.rs @@ -29,6 +29,102 @@ pub enum State { Partial, } +/// How a compute request spent its time, beside `took_ms` rather than instead +/// of it. +/// +/// `took_ms` alone cannot say the two things a caller most needs: which engine +/// answered, and whether the work in it was done *now* or reused from a cache. +/// A warm answer and a cold one differ by an order of magnitude on real +/// panels (BXD.8: 3.9 s against 21 min on HET3), and a cached run reports the +/// cache's speed, not the engine's -- so the counts and the states are here +/// next to the durations. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)] +pub struct Timing { + /// Which engine produced `data`: `gemma` (gemma-wrapper, in process), + /// `pangemma` (ravanan + slurm), or `gemma` over ravanan. + pub engine: String, + /// The request's own phases, in the order they ran. Their sum is at most + /// `meta.took_ms`. + pub phases: Vec, + /// 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, + /// 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, + /// Totals over `steps`, so a caller need not sum them. + #[serde(skip_serializing_if = "Option::is_none")] + pub steps_summary: Option, +} + +/// 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, + 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, + /// The longest single job, in ms -- the floor a scatter cannot beat. + #[serde(skip_serializing_if = "Option::is_none")] + pub run_ms_max: Option, + /// 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, +} + +/// 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 "-gwa.log.txt"). + #[serde(skip_serializing_if = "Option::is_none")] + pub chr: Option, + /// What the engine itself reported (`## total computation time`), in ms. + #[serde(skip_serializing_if = "Option::is_none")] + pub compute_ms: Option, + /// `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, + #[serde(skip_serializing_if = "Option::is_none")] + pub compute_ms_max: Option, + /// 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>, + /// 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, } /// A success response: the payload, facts about the response, notes on @@ -162,6 +263,12 @@ impl Envelope { self } + /// Attaches [`Timing`] to `meta`. + pub fn with_timing(mut self, timing: Timing) -> Self { + self.meta.timing = Some(timing); + self + } + pub fn with_note(mut self, note: &str) -> Self { self.notes.push(note.to_string()); self @@ -273,6 +380,7 @@ impl Ctx { num_rows: None, num_cols: None, extra: None, + timing: None, }, notes: Vec::new(), next: Vec::new(), diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 38b5b0c..2716bfc 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -281,6 +281,8 @@ async fn ravanan_artifacts( rid: RequestInfo, ) -> Result { let cache_dir = &config.ravanan_cache_dir; + let artifacts_started = std::time::Instant::now(); + let mut built = false; let mut notes = Vec::new(); std::fs::create_dir_all(cache_dir).map_err(|error| { ApiError::new( @@ -576,6 +578,7 @@ async fn ravanan_artifacts( .unwrap_or_default() }; artifact_memo_save(&memo, &outputs); + built = true; notes.push(format!( "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \ cluster), cached by ravanan on (script, inputs)" @@ -640,6 +643,7 @@ async fn ravanan_artifacts( .find(|(name, _)| name == "store") .and_then(|(_, paths)| paths.first().cloned()); artifact_memo_save(&memo, &outputs); + built = true; notes.push( "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \ cluster), cached by ravanan on (script, inputs)" @@ -651,11 +655,20 @@ async fn ravanan_artifacts( None }; + let needed = mode != "none" || engine == gemma::GemmaEngine::Pangemma; Ok(Artifacts { genotype_file, snps_file, store, individuals_file, + ms: artifacts_started.elapsed().as_millis() as u64, + state: if !needed { + "none".to_string() + } else if built { + "built".to_string() + } else { + "reused".to_string() + }, notes, }) } @@ -665,6 +678,11 @@ struct Artifacts { genotype_file: String, snps_file: String, store: Option, + /// 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, @@ -1332,6 +1350,9 @@ pub async fn compute_gemma( let rid_for_job = rid.clone(); let trait_values_for_job = trait_values.clone(); let covariates_for_job = covariate_list.clone(); + // The in-process run: one phase, because one process did the whole thing + // (the wrapper's own JSON record carries its internal figures). + let wrapper_started = std::time::Instant::now(); compute_gate::gemma() .run(__gn4_claim, async move { gemma::compute( @@ -1493,7 +1514,18 @@ pub async fn compute_gemma( body: Some(serde_json::Value::Object(body)), }); } - Json(envelope) + let timing = crate::response::Timing { + engine: "gemma".to_string(), + phases: vec![crate::response::PhaseTiming { + name: "wrapper".to_string(), + state: None, + ms: wrapper_started.elapsed().as_millis() as u64, + }], + cluster: None, + steps: Vec::new(), + steps_summary: None, + }; + Json(envelope.with_timing(timing)) }) } @@ -1580,6 +1612,10 @@ pub(crate) async fn gemma_via_ravanan( endpoint: &'static str, ) -> Result>, ApiError> { let rid = ctx.request_info(); + // Before anything else runs, for two reasons: the cluster query has to know + // which jobs belong to *this* request, and each step log's mtime is + // compared against it to tell a step that ran from one ravanan reused. + let request_started = std::time::SystemTime::now(); let engine = match request.engine.as_deref() { None => crate::gemma::GemmaEngine::Gemma, Some(value) => match crate::gemma::GemmaEngine::parse(value) { @@ -1722,6 +1758,7 @@ pub(crate) async fn gemma_via_ravanan( ) .await?; let mut impute_notes = artifacts.notes; + let (artifacts_ms, artifacts_state) = (artifacts.ms, artifacts.state.clone()); let (genotype_file, snps_file) = (artifacts.genotype_file, artifacts.snps_file); if impute == "hmm" { if let (Some(individuals), Some(names)) = @@ -1761,6 +1798,10 @@ pub(crate) async fn gemma_via_ravanan( let run_id = params.id.clone(); let job_rid = rid.clone(); + let since_epoch = request_started + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs()) + .unwrap_or(0); compute_gate::ravanan() .run(__gn4_claim, async move { // The workflow pair follows the engine: gemma-gn2 on BIMBAM, or @@ -1782,12 +1823,13 @@ pub(crate) async fn gemma_via_ravanan( source: workflow_source, manifest: manifest_source, }; - gemma::compute_ravanan( + let output = gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, &ravanan_workflow, store.as_deref(), + request_started, &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, @@ -1807,10 +1849,20 @@ pub(crate) async fn gemma_via_ravanan( ) .with_request_id(job_rid.clone()), other => gemma_error_to_api_error(other, job_rid.clone()), - }) + })?; + // Asked here, inside the async block: the reply closure below is a + // plain `map`, and this is the last moment the jobs of *this* + // request can be told from every other request's. + let (cluster, ran_steps) = gemma::cluster_timing( + &config.ravanan_batch, + since_epoch, + &format!("{}/ravanan-store", config.ravanan_cache_dir), + ) + .await; + Ok::<_, ApiError>((output, cluster, ran_steps)) }) .await - .map(|output| { + .map(|(output, cluster, ran_steps)| { let num_rows = output.rows.as_array().map(Vec::len).unwrap_or(0); let mut envelope = ctx .envelope(output.rows) @@ -1830,7 +1882,59 @@ pub(crate) async fn gemma_via_ravanan( for note in &output.notes { envelope = envelope.with_note(note); } - Json(envelope) + // Where the time went, beside `took_ms`: the phases this request paid + // for, what the cluster did, and each step's own figure with its state. + let mut phases = vec![crate::response::PhaseTiming { + name: "artifacts".to_string(), + state: Some(artifacts_state.clone()), + ms: artifacts_ms, + }]; + phases.push(crate::response::PhaseTiming { + name: "workflow".to_string(), + state: None, + ms: output.workflow_ms, + }); + phases.push(crate::response::PhaseTiming { + name: "parse".to_string(), + state: None, + ms: output.parse_ms, + }); + // Steps located through the jobs of this request (kinship's logs are + // not a workflow output) join the ones read from the returned logs; + // a step present in both keeps the "ran" entry. + let mut steps = output.steps.clone(); + for step in ran_steps { + let duplicate = steps.iter().any(|existing| { + existing.step == step.step && existing.chr == step.chr && existing.state == "ran" + }); + if !duplicate { + steps.push(step); + } + } + steps.sort_by(|a, b| { + (a.step.as_str(), a.chr.as_deref().unwrap_or("")) + .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or(""))) + }); + let cached = steps.iter().filter(|s| s.state == "cached").count(); + let compute: Vec = 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)) }) } -- cgit 1.4.1 From 4f7c1adc527defc54a6ea1aee77e205067a49120 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 09:07:14 +0000 Subject: compute: an async form, so a run that outlasts the client still returns a result A cold LOCO scan of a large panel is ~21 minutes of wall clock (measured from Slurm's own records: 20 GWA jobs, all started 17:40:01, 18-21 min each, last ended 18:01:27). A client cutoff at 300 s could never have returned one, and the connection closing took the answer with it -- the work already survived, as a tokio task under the compute gate, but nothing kept its result. POST /compute/gemma/async?id= -> 202 at once (0.0 s measured) with {id, state: running, status: url} GET /compute/gemma/result/ -> progress while running, the finished reply afterwards, the error if it failed The blocking endpoints are unchanged, so nothing that fits a client's patience switches to polling. Progress is what can be measured from outside the run: the process's clock, plus the cluster's job counts for this request's window (the same query meta.timing uses). The reply bodies are envelopes, like every other success response -- the openapi check in the build's check phase is what caught the first draft returning bare JSON, which is the contract doing its job. Measured on HSNIH-Palmer_true trait 10404 (warm): POST 202 in 0.0 s, polls showing state=running with growing elapsed_ms, then the finished envelope: 133,217 rows, engine pangemma, phases artifacts built 8,717 ms (a rebuild because the stale half-pair had been removed), workflow 7,894 ms, parse 146 ms, steps 20 cached, took_ms 45,932. --- src/lib.rs | 3 + src/routes/gemma.rs | 208 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/runs.rs | 126 +++++++++++++++++++++++++++++++ 3 files changed, 337 insertions(+) create mode 100644 src/runs.rs (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 1d60f9d..4045818 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod runs; mod routes; mod rqtl; pub mod search; @@ -286,6 +287,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)) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 2716bfc..e97eea8 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1593,6 +1593,214 @@ pub async fn compute_gemma_ravanan( ) -> Result>, ApiError> { 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), + (status = 409, description = "id already in use", body = ApiError) + ) +)] +pub async fn compute_gemma_async( + ctx: Ctx, + token: AuthToken, + Query(params): Query, + Json(request): Json, +) -> Result<(StatusCode, Json>), 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()) + })?, + }; + 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), + (status = 404, description = "No such run in this process", body = ApiError) + ) +)] +pub async fn gemma_result( + ctx: Ctx, + Path(id): Path, +) -> Result { + 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` 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, + /// 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>>, +} + +fn registry() -> &'static Registry { + static REGISTRY: OnceLock = 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 { + 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); + } +} -- cgit 1.4.1 From 58de629953a75daad50daca795465784d37c7359 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 09:36:44 +0000 Subject: compute: name the genotype phase, and list every step including cached kinship Two gaps, both found by measuring a request that dwarfs the mapping itself. **The genotypes phase.** `resolve_inputs` opens the panel, works out which individuals have genotypes and writes the prepared subset; on HSNIH-Palmer_true (134,918 markers, 6,147 individuals) that is 20.5 s of a 29.5 s request -- 70 % of it, and until now reported nowhere. The phases now start with it, and on that panel they sum to 97 % of `took_ms` (genotypes 20,522 ms, artifacts reused 3 ms, workflow 8,013 ms, parse 152 ms, of 29,529). **Cached kinship steps.** `steps` listed only GWA entries: `kinship_log` is not a workflow output (ccwl's `pipe` publishes the last step's outputs only), and a cached step submits no job to trace it by. But GEMMA prints the command line it ran, and the GWA job's `-k` names the K file ravanan staged from the kinship step's own store directory -- so the path carries both the step key ("-kinship") and the chromosome ("-kin.cXX.txt"). Reading the log beside it gives the cached figure: 40 steps on both panels now, kinship included (HSNIH chr1 1,769,670 ms, chr10 1,315,176 ms). **And a parsing bug that fix exposed:** GEMMA's `## total computation time` is 0 for `-gk` while its breakdown says `time on calculating relatedness matrix = 0.0783561 min`. The parts are summed as well and the larger of the two wins; a figure of exactly zero becomes absent rather than a false "instant". Worth reading off the result: on this panel the engine reports ~19 h of step time (68.8 M ms across 20 kinship + 20 GWA), while Slurm's records show the 20 GWA jobs overlapping into a 21-minute wall -- job time and wall time differ by more than an order of magnitude here, which is why both are labelled. --- src/gemma.rs | 108 +++++++++++++++++++++++++++++++++++++++++++++++----- src/routes/gemma.rs | 20 +++++++++- 2 files changed, 116 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/gemma.rs b/src/gemma.rs index 5730d83..2188530 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -807,21 +807,45 @@ pub struct GemmaOutput { /// A cached step's log is still in ravanan's store, with the figure from when /// it ran, which is why the caller labels the step `cached`. fn step_compute_ms(log: &str) -> Option { + let minutes_of = |text: &str| -> Option { + text.split('=') + .nth(1)? + .trim() + .trim_end_matches("min") + .trim() + .parse() + .ok() + }; + let mut total: Option = None; + let mut breakdown = 0.0f64; + let mut saw_breakdown = false; for line in log.lines() { let line = line.trim(); if let Some(rest) = line.strip_prefix("## total computation time") { - let minutes: f64 = rest - .split('=') - .nth(1)? - .trim() - .trim_end_matches("min") - .trim() - .parse() - .ok()?; - return Some((minutes * 60_000.0).round() as u64); + total = minutes_of(rest); + } else if line.starts_with("##") && line.ends_with("min") && line.contains('=') { + // "## time on calculating relatedness matrix = 0.0783561 min". + // GEMMA's *total* is unreliable for -gk (it prints 0 while the + // breakdown says 0.078 min), so the parts are summed as well and + // the larger of the two wins. + if let Some(minutes) = minutes_of(line) { + breakdown += minutes; + saw_breakdown = true; + } } } - None + let minutes = match (total, saw_breakdown) { + (Some(total), true) => total.max(breakdown), + (Some(total), false) => total, + (None, true) => breakdown, + (None, false) => return None, + }; + // A real computation never takes exactly nothing; an engine that reports + // neither figure is unknown, not instant. + if minutes <= 0.0 { + return None; + } + Some((minutes * 60_000.0).round() as u64) } /// The chromosome a step's log file was written for: the workflow names each @@ -843,6 +867,45 @@ fn step_chromosome(path: &str, step: &str, suffix: &str) -> Option { 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 ("-kinship") and the +/// chromosome ("-kin.cXX.txt"). That is how a *cached* kinship step can be +/// reported: its log is not a workflow output (ccwl's `pipe` publishes only the +/// last step's), and a cached step submitted no job to trace it by. +fn kinship_of_gwa_log(path: &str) -> Option<(String, String)> { + let log = std::fs::read_to_string(path).ok()?; + let line = log + .lines() + .find(|line| line.contains("Command Line Input"))?; + let mut words = line.split_whitespace(); + while let Some(word) = words.next() { + if word != "-k" { + continue; + } + let kpath = Path::new(words.next()?); + let chr = kpath + .file_name()? + .to_string_lossy() + .split("-kin") + .next()? + .to_string(); + let key = kpath + .parent()? + .file_name()? + .to_string_lossy() + .strip_suffix("-kinship")? + .to_string(); + if chr.is_empty() || key.is_empty() { + return None; + } + return Some((key, chr)); + } + None +} + /// [`step_timings`], with each step's state taken from its log's mtime: a log /// older than the request was not written by it, so ravanan answered that step /// from its store. @@ -1997,6 +2060,31 @@ pub async fn compute_ravanan( ".log.txt", request_started, )); + // The kinship step's log is not a workflow output, so its figure is taken + // from the store directory its own GWA job pointed at. + for gwa_log in &gwa_log_paths { + let Some((key, chr)) = kinship_of_gwa_log(gwa_log) else { + continue; + }; + let kin_log = Path::new(cache_dir) + .join("ravanan-store") + .join("files") + .join(format!("{key}-kinship")) + .join(format!("{chr}-kin.log.txt")); + let Ok(log) = std::fs::read_to_string(&kin_log) else { + continue; + }; + let ran_now = std::fs::metadata(&kin_log) + .and_then(|metadata| metadata.modified()) + .map(|modified| modified >= request_started) + .unwrap_or(false); + steps.push(StepTiming { + step: "kinship".to_string(), + chr: Some(chr), + compute_ms: step_compute_ms(&log), + state: if ran_now { "ran" } else { "cached" }.to_string(), + }); + } steps.sort_by(|a, b| { (a.step.as_str(), a.chr.as_deref().unwrap_or("")) .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or(""))) diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index e97eea8..548c464 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -1820,6 +1820,7 @@ pub(crate) async fn gemma_via_ravanan( endpoint: &'static str, ) -> Result>, ApiError> { let rid = ctx.request_info(); + let mut genotypes_ms: u64 = 0; // Before anything else runs, for two reasons: the cluster query has to know // which jobs belong to *this* request, and each step log's mtime is // compared against it to tell a step that ran from one ravanan reused. @@ -1884,7 +1885,17 @@ pub(crate) async fn gemma_via_ravanan( names: resolved_names, group: resolved_group, notes: input_notes, - } = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?; + } = { + // Reading the panel is a phase of its own: `resolve_inputs` opens the + // genotype file (a 134,918-marker BIMBAM is a multi-GB read), works out + // which individuals have genotypes, and writes the prepared subset. On + // HSNIH-Palmer_true that is ~29 s of a 46 s request -- the largest + // single cost, and invisible until it is named. + let started = std::time::Instant::now(); + let resolved = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?; + genotypes_ms = started.elapsed().as_millis() as u64; + resolved + }; if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, @@ -2093,10 +2104,15 @@ pub(crate) async fn gemma_via_ravanan( // Where the time went, beside `took_ms`: the phases this request paid // for, what the cluster did, and each step's own figure with its state. let mut phases = vec![crate::response::PhaseTiming { + name: "genotypes".to_string(), + state: None, + ms: genotypes_ms, + }]; + phases.push(crate::response::PhaseTiming { name: "artifacts".to_string(), state: Some(artifacts_state.clone()), ms: artifacts_ms, - }]; + }); phases.push(crate::response::PhaseTiming { name: "workflow".to_string(), state: None, -- cgit 1.4.1 From ca32dd4c8c64f8fa5ed18b30fe2594dbe9f5ad98 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 10:53:07 +0000 Subject: gemma: the store step runs gemma-wrapper's geno2mdb binary, not python The converter became an Odin binary in gemma-wrapper e244f99 and is packaged in guix-bioinformatics (built in the package, installed as bin/geno2mdb). This switches the store workflow to it: no interpreter, no python-lmdb, no PYTHONPATH in the job, which is what the python version cost this deployment twice -- a hand-exported PYTHONPATH on the API host and three python packages in the artifact manifest. Three things had to change, each of them measured: - `store.scm` runs `#:run "geno2mdb"` and no longer takes the script as a File input. ccwl appends every declared input to the command line, so a staged copy of the binary arrived as argv[1] and geno2mdb read its own ELF header as the BIMBAM file ("16 genotypes, expected 14, line 1"). - the server stops supplying `store_script`; the pre-flight input check named the disagreement, as designed. - artifact runs keep GUIX_PACKAGE_PATH set. Clearing it saved ~4 s of Guile per run, but the artifact manifest now names gemma-wrapper, which only exists in the channel: cleared, the job died with "gemma-wrapper: unknown package" before reading a marker. Correctness over four seconds, and the artifact memo means most requests never pay it. Verified on a cold artifact path (BXD.8, impute=mean, engine=pangemma): artifacts built in 19,263 ms, 41 cluster jobs (prepare + store + 19 kinship + 20 gwa), workflow 14,793 ms, 21,056 rows. The packaged binary was earlier checked to produce a store identical to bin/geno2mdb.py's, on BXD.8 and on the 3.9 GB HSNIH-Palmer_true panel. --- cwl/gemma/manifest-artifacts.scm | 7 +++++-- cwl/gemma/store.scm | 17 ++++++++++------- src/gemma.rs | 22 ++++++++++------------ src/routes/gemma.rs | 12 +++++++----- 4 files changed, 32 insertions(+), 26 deletions(-) (limited to 'src') diff --git a/cwl/gemma/manifest-artifacts.scm b/cwl/gemma/manifest-artifacts.scm index 8a8eb07..c4d248d 100644 --- a/cwl/gemma/manifest-artifacts.scm +++ b/cwl/gemma/manifest-artifacts.scm @@ -10,7 +10,9 @@ ;; r-minimal + r-qtl2: `hmm' runs qtl2-impute-bimbam.R (maxmarg on the cross's ;; genotype probabilities). r-qtl2 propagates r-qtl, r-rcpp, r-jsonlite and ;; r-data-table, so nothing else is listed. -;; python + python-numpy + python-lmdb: geno2mdb.py, which writes the store. +;; gemma-wrapper: its bin/geno2mdb, the store writer (Odin, no interpreter). +;; python and its packages are kept only for the R-side helpers; the store step +;; no longer needs them. ;; ;; ravanan sets these packages' search paths (PYTHONPATH among them) inside the ;; job, so `python3' here finds numpy and lmdb without any wrapper script -- @@ -22,4 +24,5 @@ ;; silently. (specifications->manifest (list "bash" "coreutils" "gawk" "r-minimal" "r-qtl2" - "python" "python-numpy" "python-lmdb")) + "python" "python-numpy" "python-lmdb" + "gemma-wrapper")) diff --git a/cwl/gemma/store.scm b/cwl/gemma/store.scm index 6a60628..5b01a6f 100644 --- a/cwl/gemma/store.scm +++ b/cwl/gemma/store.scm @@ -17,19 +17,22 @@ ;; but exact only for integer calls (0/1/2 -> 0/127/254). (define store (command - #:inputs (store_script #:type File) - (genotype_file #:type File) + #:inputs (genotype_file #:type File) (snps_file #:type File) - #:run "python3" store_script genotype_file + ;; geno2mdb is a binary now (gemma-wrapper e244f99, built in Odin), so the + ;; step runs it from the job's profile: no interpreter, no python-lmdb, no + ;; PYTHONPATH. It is *not* an input any more -- ccwl appends every input to + ;; the command line, and a staged copy of the binary came out as argv[1], + ;; which geno2mdb then read as the BIMBAM file ("16 genotypes, expected 14", + ;; from its own ELF header). + #:run "geno2mdb" genotype_file ("--snps" snps_file) ("--format" "Gf") ("--out" "genotypes.mdb") #:outputs (store #:type File #:binding ((glob . "genotypes.mdb"))))) -(workflow ((store_script #:type File) - (genotype_file #:type File) +(workflow ((genotype_file #:type File) (snps_file #:type File)) - (store #:store_script store_script - #:genotype_file genotype_file + (store #:genotype_file genotype_file #:snps_file snps_file)) diff --git a/src/gemma.rs b/src/gemma.rs index 2188530..58d1d53 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -1738,18 +1738,16 @@ pub async fn run_artifact( ]; let batch_args = run.batch.ravanan_args(scratch); args.extend(batch_args.iter().map(String::as_str)); - // With GUIX_PACKAGE_PATH cleared: these manifests name only `(gnu - // packages)` specs (bash, gawk, R/qtl2, python), and leaving the channel - // path set makes guix autoload guix-bioinformatics' module tree for every - // invocation -- an ABI mismatch warning per module and about four seconds - // of Guile per ravanan call (measured: 12.0 s with, 7.9 s without). - let output = streaming::run_streaming_with_env( - run.ravanan_cmd, - &args, - None, - &[("GUIX_PACKAGE_PATH", "")], - ) - .await + // 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, diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 548c464..96a0fb2 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -614,11 +614,13 @@ async fn ravanan_artifacts( .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!( - "store_script: {{class: File, path: {}}}\n\ - genotype_file: {{class: File, path: {genotype_file}}}\n\ - snps_file: {{class: File, path: {snps_file}}}\n", - absolute(&config.geno2mdb_cmd), + "genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n" ); let run = gemma::ArtifactWorkflow { label: "store", @@ -632,7 +634,7 @@ async fn ravanan_artifacts( }; let outputs = gemma::run_artifact( &run, - &["store_script", "genotype_file", "snps_file"], + &["genotype_file", "snps_file"], &inputs, &["store"], ) -- cgit 1.4.1 From 67333998a42bd4055dc2011645d6859bf1e24a7c Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 13:58:46 +0000 Subject: gemma: pad the phenotype over the genotype file's individuals, never narrow the file The phenotype and the genotype file must describe the same animals in the same order, and this route was making that true by *narrowing the genotype file* to the animals with values. That is the side that can drift: `write_subset_bimbam` splits a line on ',' alone, while HSNIH-Palmer_true's BIMBAM is whitespace-separated, so every line fell into its "fewer than four fields" branch and was copied unchanged -- a "subset" byte-identical to the 3.9 GB original, 6,147 columns, against a 6,111-row phenotype. GEMMA then failed every one of the 134,918 markers with "6147 != 6111", printing the offending marker line each time: 3.9 GB of stderr per job, ~204 GB of store logs, and the filesystem at 100 %. Now the alignment covers the whole panel and excluded animals are NA rows, which GEMMA drops from the fit (and from -gk, where -p only names who is analysed). One invariant instead of two writers, and no 3.9 GB copy per request either. Measured: HSNIH-Palmer_true trait 10404, engine pangemma, from a fully deleted ravanan store: 14 m 48 s cold, 133,116 rows, no per-marker errors. The peak is **chr1 247.86 Mb, LOD 4.78** -- and the previously reported chr5 24.6 Mb / 5.73 was computed with a scrambled phenotype (6,111 keep-order rows paired against the first 6,111 store samples), so that number is withdrawn. R/qtl (HK) on the same trait gives chr3 150.58 Mb, LOD 6.25, so an LMM-vs-HK difference remains to be explained; the alignment bug is not it any more. The store's sample order was verified equal to the .geno header order (first marker 6147/6147, 136 markers spread across the genome with no positional mismatch), which is what makes a positional phenotype against an lmdb store sound at all. --- src/routes/gemma.rs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 96a0fb2..232e965 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -928,7 +928,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 = (0..resolved.panel.len()).collect(); + let (aligned, matched) = + genotypes::align(&resolved.panel, &all_individuals, &named); let kept_names: Vec = keep .iter() .filter_map(|index| resolved.panel.get(*index).cloned()) @@ -937,7 +951,7 @@ pub(crate) async fn resolve_inputs( &directory, &resolved, genotypes::Engine::Gemma, - &keep, + &all_individuals, &cache_dir, )?; Ok::<_, genotypes::GenotypeError>(( -- cgit 1.4.1 From 1dab76d396a008d92dcdf43a61ca6877ba3f1780 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: baskets: count one revision, and call a taken name a conflict Two replies were wrong, both found in Rob Williams's test-drive notes of the release service. `GET|PATCH /baskets/{name}` reported 186 values for a column of 93 after one PATCH. `cell` is keyed on (basket_id, revision, sample), so a PATCH leaves the previous revision's rows in place -- correctly, that is the version history -- but the count summed every revision ever written. It now filters to the basket's current revision. Mappings were unaffected (the values view already took the current revision), which is why only the count showed it. A name already in use answered 422 invalid_basket, i.e. "your request is malformed", when the body is fine and the name is not free. It is now 409 basket_name_in_use, and the detail still says to PATCH it or pick another name. The same variant covers matrix and genotype-upload names. --- src/baskets.rs | 19 +++++++++++++++---- src/routes/baskets.rs | 10 ++++++++++ src/routes/genoupload.rs | 8 ++++++++ src/routes/matrices.rs | 8 ++++++++ 4 files changed, 41 insertions(+), 4 deletions(-) (limited to 'src') 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/routes/baskets.rs b/src/routes/baskets.rs index a542620..371502a 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", 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/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", -- cgit 1.4.1 From 5eb207b0c5989d886e671372023bdb66abb679db Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: next: say which links are templates, instead of leaving braces to guess A scan reply carried "/groups/BXD/genotypes/%7Bversion%7D/markers/.../classes? trait={trait_id}" and "/groups/unlisted/genotypes/{name}/frequencies" in `next`, where the documented rule is that following a `next` link is a GET that answers 200. Those two are shapes, not addresses: the trait id a scan cannot know, a file name no group lists. The test suite skipped hrefs with braces, so the rule held only by exemption. NextAction gains `template: true` for exactly those, set wherever a link is added (so no call site has to remember), and absent otherwise -- a caller can now tell "follow this" from "fill this in" without pattern-matching on punctuation. --- src/response.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') diff --git a/src/response.rs b/src/response.rs index 46db64a..c2a6cc9 100644 --- a/src/response.rs +++ b/src/response.rs @@ -186,10 +186,24 @@ pub struct Envelope { 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 @@ -215,6 +229,7 @@ impl Envelope { 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 @@ -256,6 +271,7 @@ impl Envelope { continue; } self.next.push(NextAction { + template: is_template(&href), href, description: description.to_string(), }); -- cgit 1.4.1 From 78712cc90cf84c553751f9ef5969dddc5960a195 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: gemma: keep the server's paths out of the reply's notes The ravanan note carried the invocation verbatim -- "/gnu/store/...-ravanan" and "--store=/home/wrk/tmp/ai-root/slurm-share/..." -- and the workflow note carried the checkout path. Those notes are read in chats and pasted into repositories, so they were publishing the deployment's layout. redact_paths() keeps every token's file name and drops the directories: "which ravanan, which manifest, which workflow" survives, the server's layout does not. A unit test asserts no note can carry an absolute path again. --- src/gemma.rs | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 66 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/gemma.rs b/src/gemma.rs index 58d1d53..c49446f 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -1649,6 +1649,42 @@ pub struct RavananWorkflow<'a> { 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::>() + .join(" ") +} + /// What running an artifact workflow needs: the ccwl source, the manifest its /// jobs resolve against, ravanan's own switches, and the outputs wanted. /// @@ -1938,7 +1974,7 @@ pub async fn compute_ravanan( // store holds it, so this is just the path. let store_path = store.map(Path::new); let store_note = store_path.map(|path| { - format!("pangemma's lmdb genotype store: {}", path.display()) + 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")); @@ -1982,14 +2018,14 @@ 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 {} itself over {} chromosome(s) via CWL scatter, one \ invocation per chromosome: {}", @@ -2109,7 +2145,9 @@ 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); @@ -2738,3 +2776,27 @@ mod engine_tests { 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}"); + } +} -- cgit 1.4.1 From 52e4f6d9b92242d241be85a91699d8565e4a746a Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: rqtl: the note says what the riself conversion did to the genotypes The conversion drops every heterozygous call and treats X as an autosome -- the status log counts them ("Omitting 230532 genotypes with code==2"), the reply said nothing. GEMMA keeps a heterozygote at 0.5, so a caller comparing the two engines was comparing two different models without being told. --- src/routes/rqtl.rs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index c02adbe..84c43e2 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -551,6 +551,16 @@ pub async fn compute_rqtl( .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.", + ) + // 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.", ); for note in ¬es { envelope = envelope.with_note(note); -- cgit 1.4.1 From 3854e38fd8c4521df1f501dd6b093fe8b27a840a Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 17:04:30 +0000 Subject: api: a request body it cannot read answers in the envelope, not in text/plain An extractor's rejection never reaches a handler, so it never sees ApiError: axum answered "Failed to deserialize the JSON body ...: missing field `trait_name`" as text/plain. That is the one error class a client cannot parse, and it is the class a client most likely triggers. A middleware outside everything turns any non-JSON 4xx into the usual envelope, with the matched route as the operation id and the original text as the detail. --- src/json_errors.rs | 118 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 5 +++ 2 files changed, 123 insertions(+) create mode 100644 src/json_errors.rs (limited to 'src') 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": , "error": null, +//! "operation_id": }`. +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, 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::() + .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 4045818..369bec1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -31,6 +31,7 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod json_errors; pub mod runs; mod routes; mod rqtl; @@ -335,6 +336,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 -- cgit 1.4.1 From b223757bb5c04d03be5ccccf32488594134bb542 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 18:45:52 +0000 Subject: rqtl: the rows are `data`, and the permutation null is meta.permutation Every compute endpoint kept its rows in `data` except this one, which put them under `data.markers` beside `data.permutation`. A script written from SKILL.md ("rows are positional") broke on the first scan it read, and the same script had to special-case both shapes -- measured in Rob Williams's test drive of the release service. `data` is now the marker array (positional, `meta.columns` names the columns, as /compute/gemma and /compute/qtl2 already did), and the permutation null goes to `meta.permutation`, where Meta's own documentation says endpoint-specific qualifier information belongs. /plot/rqtl and scripts/plot-rqtl.py accept both shapes, so a saved reply from an older build still plots. --- scripts/plot-rqtl.py | 9 +++++-- src/response.rs | 9 +++++++ src/routes/plot.rs | 13 ++++++---- src/routes/rqtl.rs | 12 ++++++++-- src/rqtl.rs | 65 +++++++++++++++++++++++++++----------------------- tests/genoupload.rs | 5 ++-- tests/links.rs | 4 ++-- tests/peakgenotypes.rs | 4 ++-- tests/rqtl.rs | 13 ++++++---- 9 files changed, 84 insertions(+), 50 deletions(-) (limited to 'src') diff --git a/scripts/plot-rqtl.py b/scripts/plot-rqtl.py index 73d8c51..b24a14f 100644 --- a/scripts/plot-rqtl.py +++ b/scripts/plot-rqtl.py @@ -28,8 +28,13 @@ def main(): if "data" not in doc: sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}") res = doc["data"] - rows = res["markers"] # [name, chr, pos_mb, lod] - perm = res.get("permutation") + # `data` is the marker array itself (a reply from before that change kept + # it under `data.markers`), and the permutation null sits beside it in + # meta; older replies carried it inside data. + rows = res if isinstance(res, list) else res["markers"] + perm = (doc.get("meta") or {}).get("permutation") or ( + res.get("permutation") if isinstance(res, dict) else None + ) thr = [] # (value, label, dash) if perm: thr = [(perm["significant"], "significant (95%)", "7 4"), diff --git a/src/response.rs b/src/response.rs index c2a6cc9..974a585 100644 --- a/src/response.rs +++ b/src/response.rs @@ -279,6 +279,15 @@ impl Envelope { 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); diff --git a/src/routes/plot.rs b/src/routes/plot.rs index d33f5d7..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() diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 84c43e2..0fbfdf4 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -546,11 +546,16 @@ 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 @@ -562,6 +567,9 @@ pub async fn compute_rqtl( 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/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 = 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 { + 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 { - 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/tests/genoupload.rs b/tests/genoupload.rs index 9f8a8a5..4797376 100644 --- a/tests/genoupload.rs +++ b/tests/genoupload.rs @@ -335,9 +335,8 @@ async fn every_engine_maps_an_uploaded_genotype() { let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{endpoint}: {}", String::from_utf8_lossy(&bytes)); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - // /compute/rqtl wraps its rows in data.markers; /compute/qtl2 returns - // them as the array itself. - let rows = envelope["data"]["markers"] + // Both /compute/rqtl and /compute/qtl2 return their rows as `data`. + let rows = envelope["data"] .as_array() .or_else(|| envelope["data"].as_array()) .unwrap_or_else(|| panic!("{endpoint}: no rows in {envelope}")); diff --git a/tests/links.rs b/tests/links.rs index 5291008..d36e5a7 100644 --- a/tests/links.rs +++ b/tests/links.rs @@ -221,8 +221,8 @@ async fn a_scan_points_at_the_class_counts_behind_its_peak() { "the trait id is the caller's to fill in: {hint}" ); // And the marker it names is the peak the reply reported. - // /compute/rqtl's rows live under data.markers. - let rows = envelope["data"]["markers"].as_array().unwrap(); + // /compute/rqtl's rows are `data` itself, like every compute endpoint's. + let rows = envelope["data"].as_array().unwrap(); let peak = rows .iter() .max_by(|left, right| { diff --git a/tests/peakgenotypes.rs b/tests/peakgenotypes.rs index 56461f8..132cfca 100644 --- a/tests/peakgenotypes.rs +++ b/tests/peakgenotypes.rs @@ -34,7 +34,7 @@ async fn scan_peak(token: &str, values: &Value) -> Value { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - envelope["data"]["markers"] + envelope["data"] .as_array() .unwrap() .iter() @@ -148,7 +148,7 @@ async fn a_marker_away_from_the_peak_is_refused() { .await; let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - let rows = envelope["data"]["markers"].as_array().unwrap(); + let rows = envelope["data"].as_array().unwrap(); let distant = rows .iter() .find(|row| row[1] != peak[1]) diff --git a/tests/rqtl.rs b/tests/rqtl.rs index ae0e280..5eeaef4 100644 --- a/tests/rqtl.rs +++ b/tests/rqtl.rs @@ -115,7 +115,7 @@ async fn compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture() { ); let data: Value = common::data(&bytes); - let markers = data["markers"].as_array().unwrap(); + let markers = data.as_array().unwrap(); // The fixture has 6 markers (3 per chromosome, 2 chromosomes). assert_eq!(markers.len(), 6); // Rows are positional (name, chr, pos, lod); see meta.columns. @@ -179,8 +179,11 @@ async fn compute_rqtl_with_permutations_returns_thresholds() { ); let data: Value = common::data(&bytes); - let perm = &data["permutation"]; - assert!(!perm.is_null(), "{data}"); + // The permutation null is qualifier information, so it lives in + // meta.permutation beside the rows rather than in data. + let envelope: Value = serde_json::from_slice(&bytes).unwrap(); + let perm = &envelope["meta"]["permutation"]; + assert!(!perm.is_null(), "{envelope}"); assert_eq!(perm["values"].as_array().unwrap().len(), 20); let suggestive = perm["suggestive"].as_f64().unwrap(); let significant = perm["significant"].as_f64().unwrap(); @@ -432,7 +435,7 @@ async fn compute_rqtl_fits_a_case_attribute_as_a_covariate() { String::from_utf8_lossy(&bytes) ); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - assert!(!envelope["data"]["markers"].as_array().unwrap().is_empty()); + assert!(!envelope["data"].as_array().unwrap().is_empty()); let notes: Vec<&str> = envelope["notes"] .as_array() @@ -514,7 +517,7 @@ async fn a_cm_only_genotype_file_maps() { let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - let markers = envelope["data"]["markers"].as_array().unwrap(); + let markers = envelope["data"].as_array().unwrap(); assert_eq!( markers.len(), 6, -- cgit 1.4.1 From 7281ee24bc479831fbfd5679896202685dffc49a Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sun, 22 Nov 2026 18:45:52 +0000 Subject: docs: the six things a real test drive found wrong A beta user's notes (Rob Williams, 2026-11-21) reported six things that were wrong or misleading from the outside. Each is fixed where it lives: * the sparse clone in section 8 does not work against this server ("dumb http transport does not support shallow capabilities"); a shallow clone is 19 MB and under two minutes, so the instruction is `--depth 1` and an explicit warning against `--sparse`. * "There are no write endpoints" contradicted section 3, which documents baskets, matrices and genotype uploads. The data is read-only; the caller's own material is not. * the basket note said to map with /compute/qtl2 -- all four mapping routes take `"basket"`, and the note (code and doc) now says so. * "100 permutations take about 14 s" is not a constant: the cost is strains x permutations, measured at 22 s for 1,000 on 21 strains, 221 s on 93 and 463 s on 87. * /compute/gemma is described as gemma-wrapper. It has run the Slurm route by default since the engine switch, so "send the same body to both and compare" compares ravanan with itself; the doc now says what the default is, how to read which engine answered from meta.timing, and that the wrapper is the fallback. * /compute/rqtl's rows moved into `data` (previous commit); the doc says so, and that the permutation null is `meta.permutation`. --- docs/www/SKILL.md | 52 +++++++++++++++++++++++++++++++++++++-------------- src/routes/baskets.rs | 9 ++++++--- 2 files changed, 44 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/docs/www/SKILL.md b/docs/www/SKILL.md index 2fa2385..6c8338e 100644 --- a/docs/www/SKILL.md +++ b/docs/www/SKILL.md @@ -194,10 +194,19 @@ Two endpoints run the same computation, and the reply shape is identical: | endpoint | runs | |---|---| | `/compute/gemma/ravanan` | `gemma` itself, one invocation per chromosome, scattered by ravanan (Slurm) | -| `/compute/gemma` | `gemma-wrapper` (kinship, then GWA, both `--loco`) as a server subprocess, no cluster | +| `/compute/gemma` | the **same Slurm route by default** (`GEMMA_ENGINE=slurm`): ravanan, one `gemma` job per chromosome, falling back to the in-process `gemma-wrapper` only when the cluster route answers 5xx | -**Use `/compute/gemma/ravanan` by default.** Reach for `/compute/gemma` only -when: +**Sending the same body to `/compute/gemma` and `/compute/gemma/ravanan` no +longer compares two runners**: by default both are the Slurm route, so they +answer the same numbers through the same process. They still differ in *scope* +(covariates, normalization, permutations are refused on the ravanan endpoint), +and a reply says which engine ran in `meta.timing.engine` and whether the +cluster was used at all in `meta.timing.cluster.jobs_submitted` (`0` = every step +came from ravanan's store). The in-process `gemma-wrapper` run is reachable only +as the fallback (its reply carries an "Engine: the Slurm route was unavailable" +note). + +Reach for `/compute/gemma` when: - **Slurm is down or job submission fails** (`502`/`ravanan_failed`, or a job that never leaves `PENDING`) -- the in-process runner needs no cluster; @@ -218,7 +227,11 @@ verify costs almost nothing. **Mapping and plots (POST, verified working)** * `/compute/rqtl`: R/qtl `scanone` (Haley-Knott) over the group's genotypes. - Columns `name, chr, pos, lod`. `nperm=0` by default, so no permutation lines. + `data` is the marker rows, positional, columns `name, chr, pos, lod` (named in + `meta.columns`); the permutation null, when asked for, is **`meta.permutation`** + (`significant`, `suggestive`, `values`), not a second member of `data`. + `nperm=0` by default, so no permutation lines. Every compute endpoint keeps its + rows in `data` — one loop reads them all. * `/compute/gemma`: GEMMA LMM with leave-one-chromosome-out kinship. Columns `chr, rs, ps, n_miss, allele1, allele0, af, beta, se, l_mle, additive, p_lrt`. Pass `?id=` and poll `/compute/gemma/status/{id}` for long runs. Per-marker @@ -377,8 +390,9 @@ verify costs almost nothing. will be — but a user's own column can be stored and mapped. `POST /baskets` with `{"name", "values":[{name,value}…]}` (values may be numbers, strings like `"NA"`, or null), `PATCH /baskets/{name}` to edit (a new revision, a new - digest), then `POST /compute/qtl2` with `"basket": ""` instead of - `samples`. Baskets are private to the token's user, live in their own SQLite + digest), then map it with **`"basket": ""`** in place of `samples` on any + of `/compute/rqtl`, `/compute/qtl2`, `/compute/gemma` or + `/compute/gemma/ravanan`. Baskets are private to the token's user, live in their own SQLite file, and a mapping reply records the revision and digest it used — quote them when reporting a result. Each edit is a new revision with its own timestamp (`GET /baskets/{name}/revisions`), old revisions stay readable @@ -396,8 +410,11 @@ verify costs almost nothing. `image/svg+xml` plot. Do not draw your own. * Options (all optional, add to the posted body; full list in `components.schemas.RqtlRequest` / `GemmaRequest`): - * R/qtl: `nperm` (permutations; **100 takes about 14 s** and adds - `significant`/`suggestive` thresholds that `/plot/rqtl` then draws), + * R/qtl: `nperm` (permutations; the cost is **strains x permutations**, not + markers: measured, 1,000 permutations took 22 s on 21 strains, 221 s on 93 + and 463 s on 87 — so 100 permutations is roughly 2 s at 21 strains and 20-45 s + at ~90. Adds `meta.permutation` `significant`/`suggestive`, which + `/plot/rqtl` then draws), `method` (`hk` default, `ehk`, `mr`, `em`, `imp`), `model` (`normal` default, `np`), `control` (a marker to condition on), `genotype_version`, `include_parents_f1`, `covariates`. @@ -622,7 +639,12 @@ from an older cache entry (retry and it refreshes). finds 19. The reply's `next` offers a ten-times wider window. * Public-data rule: `public > 0` and `confidentiality < 1`, or older than five years; otherwise 403, do not retry. Metadata is visible even when values are not. -* There are no write endpoints, and the search index holds public documents only. +* The published data is read-only, but there **are** write endpoints for the + caller's own material: `POST|PATCH|DELETE /baskets` (columns of values), + `POST /matrices` (correlation matrices) and `POST /uploads/genotypes` + (population genotypes). A basket name that is taken is a `409`, not a `422`; + PATCH it or pick another name. Nothing here can change a published trait. +* The search index holds public documents only. * Older docs said `POST /compute/*` is refused with 403. On this build it works. If you do get a 403 there, that is the answer: do not work around it. If the task needs private data or computation you are not granted, stop and ask a @@ -691,8 +713,9 @@ you saw at the start of the session** and compare against it later. piece of work. 3. If the revision is no longer the baseline, GeneNetwork was updated while you worked. **Suggest to the user that you reload SKILL.md from the repo** - (`docs/www/SKILL.md` in `https://git.genenetwork.org/genenetwork4`; a sparse - clone of `docs` is enough), and use that copy from then on. One line is + (`docs/www/SKILL.md` in `https://git.genenetwork.org/genenetwork4`; a shallow + clone — not `--sparse`, which this server rejects — is enough), and use that + copy from then on. One line is enough, for example: "GeneNetwork was updated since we started ( -> ); I'd reload SKILL.md from docs/www/ to pick up any changes. Shall I?" Then set the new revision as your baseline. @@ -738,11 +761,12 @@ conclusion is also in a commit message and in these docs. The docs live in the public repo and are the authoritative version: ```sh -git clone --depth 1 --sparse https://git.genenetwork.org/genenetwork4 -cd genenetwork4 && git sparse-checkout set docs +git clone --depth 1 https://git.genenetwork.org/genenetwork4 ``` -About 2.5 MB; drop `--sparse` for the whole tree. Then read: +A whole shallow clone is about 19 MB and takes under two minutes; `--sparse` +does **not** work against this server ("dumb http transport does not support +shallow capabilities"), so do not add it. Then read: | file | what it is | |---|---| diff --git a/src/routes/baskets.rs b/src/routes/baskets.rs index 371502a..533a155 100644 --- a/src/routes/baskets.rs +++ b/src/routes/baskets.rs @@ -169,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\": \"\"."); envelope = envelope.with_links(crate::suggest::root_links()); Ok(Json(envelope)) @@ -222,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\": \"\"}.", + POST /compute/rqtl, /compute/qtl2, /compute/gemma or /compute/gemma/ravanan \n {\"basket\": \"\"}.", ); envelope = envelope.with_links(crate::suggest::root_links()); Ok((StatusCode::CREATED, Json(envelope))) @@ -263,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\": \"\" in place of `samples`."); + .with_note( + "Map it: POST /compute/rqtl, /compute/qtl2, /compute/gemma or \ + /compute/gemma/ravanan with \"basket\": \"\" in place of `samples`.", + ); envelope = envelope.with_links(links); Ok(Json(envelope)) } -- cgit 1.4.1 From f139fb3f1d1b9738aea403520e64fd121cd8ee62 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 24 Nov 2026 10:47:37 +0000 Subject: genotypes: read latin-1 panels, and key the subset pair on its source file Two things that a new panel exposed at once. **Encoding.** At-Serin.geno came from a GeneNetwork export whose header comment carries a latin-1 multiplication sign ("Bay-0 \xd7 Shahdara"). Every reader used `std::fs::read_to_string`, so one byte in a comment hid the whole panel with "stream did not contain valid UTF-8" -- `panel_of`, `marker_count`, `individuals_with_genotypes`, the subset writer, and qtl2's cross reader. They now read the file and take it lossily (the data lines are ASCII; nothing parses the comments), so a stray latin-1 byte is not a reason to refuse a panel. **The prepared subset's key.** `subset_path` hashed the kept *indices* and the version name, and nothing about the genotypes themselves, so replacing `.geno` (or its BIMBAM) in place kept serving the previously prepared subset and noY pair for as long as the animal set was unchanged -- an updated genotype file would have been mapped as the old one. The key now includes the source file's size and mtime, exactly what `prepare_cross` already keys on. --- src/genotypes.rs | 112 +++++++++++++++++++++++++++++++++++++++++++++++-------- src/qtl2.rs | 4 +- 2 files changed, 99 insertions(+), 17 deletions(-) (limited to 'src') 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 std::io::Result { + Ok(String::from_utf8_lossy(&std::fs::read(path)?).into_owned()) +} + +fn read_text(path: &Path) -> Result { + 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, 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, GenotypeError> { /// Number of marker rows in a `.geno` (every non-comment line but the /// header). pub fn marker_count(geno: &Path) -> Result { - 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, Option, Option)> { 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 { - 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 { - 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 = 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 { - 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 `.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 { 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> { - let text = std::fs::read_to_string(geno).ok()?; + let text = read_text(geno).ok()?; let mut mask: Option> = None; for line in text.lines() { let line = line.trim(); @@ -1379,6 +1421,44 @@ pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option> { 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/.geno` and `genotype/bimbam/_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 { + 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)], +) -> Result>, GenotypeError> { + let names = panel_of(names_source)?; + let by_name: std::collections::HashMap<&str, Option> = + 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/qtl2.rs b/src/qtl2.rs index 0c0622f..99f2370 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -184,7 +184,9 @@ pub fn prepare_cross( .map(|since| since.as_secs()) .unwrap_or(0) ); - let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?; + // 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 -- cgit 1.4.1 From 00202ef14e34ee97190516a010fd9633c4c7eb75 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 24 Nov 2026 10:47:37 +0000 Subject: gemma: named values on a file request align through the sibling .geno `genotype_file` + `samples` (or a basket) against a **BIMBAM** file could not work: a BIMBAM has no individual names, so `align_to_file` read it as if it were a `.geno`, found no header, and dropped every value -- the request then failed with "ravanan needs a genotype file and a SNP map ... and at least one trait value", which named nothing that was actually wrong (measured on At-Serin: R/qtl accepted the basket, GEMMA refused it). The deployment keeps the two files under one stem (`genotype/.geno`, `genotype/bimbam/_geno.txt`) and the BIMBAM is generated from the `.geno`, so the sibling is the name source: a named request for a bimabm file now aligns onto the `.geno` beside it and places the values in the BIMBAM's column order. The reply's note says which happened, so a caller can tell an alignment from positional values. --- src/routes/gemma.rs | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 232e965..38f33a4 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -837,6 +837,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) => { @@ -856,7 +859,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| { @@ -873,8 +884,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(), -- cgit 1.4.1 From 769782d921ea1229e9a67ef173eab569f564c73f Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 27 Nov 2026 10:41:36 +0000 Subject: usage: record what a request ran on, and put it in the access line The line was built by middleware that never sees a body, so on /compute/* it named the endpoint but not the data: 706 compute requests in the week to 2026-11-27, and the dataset could only be guessed from whatever the same user had read a minute earlier (29% of them resolved to a dataset, 61% only to a group, 20% to a visit over half an hour old). So a handler that knows the answer says it. `usage!(ctx, dataset = ..., engine = ...)` writes into a per-request slot that tag_caller opens before routing and merges in after the handler -- the CallerSlot pattern, down to the Arc, which matters because compute clones its Ctx for the fallback path and both handles must land in the one line. Values are JSON, not text: hits stays a number and cached a bool, and a string is bounded at 200 characters on a boundary, because `q` on /search is caller text. RESERVED keeps a handler from overwriting the line's own fields, and TRACKED lists the handlers that must report, with a test that reads each route file so one edited later cannot silently go dark. Not every route, deliberately: a read route already carries its dataset in the path, so instrumenting it would only duplicate the path into the line. The tracked set is the compute family plus /search. --- src/lib.rs | 89 ++++++++++++++- src/response.rs | 38 ++++++- src/usage.rs | 333 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 454 insertions(+), 6 deletions(-) create mode 100644 src/usage.rs (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index 369bec1..bf1047b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -39,6 +39,7 @@ pub mod search; mod streaming; pub mod suggest; pub mod tokens; +pub mod usage; pub mod wikidata; use error::ApiError; @@ -90,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 @@ -125,6 +131,7 @@ async fn tag_caller( started.elapsed().as_millis(), request_id.as_deref(), caller.as_ref(), + &usage.entries(), ) ); } @@ -141,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, @@ -148,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", @@ -169,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() } @@ -461,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"); @@ -490,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"); @@ -502,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/response.rs b/src/response.rs index 974a585..8ebcdcd 100644 --- a/src/response.rs +++ b/src/response.rs @@ -373,20 +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 and a start instant, 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. +// `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() } + 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 { @@ -420,7 +436,18 @@ impl FromRequestParts for Ctx { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result { 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::() + .cloned() + .unwrap_or_else(|| { + let slot = crate::usage::UsageSlot::default(); + parts.extensions.insert(slot.clone()); + slot + }); + Ok(Ctx { info, usage }) } } @@ -450,6 +477,7 @@ mod tests { id: Some("req-1".to_string()), started: Instant::now(), }, + usage: crate::usage::UsageSlot::default(), } } 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>>); + +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>(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" + ); + } + } +} -- cgit 1.4.1 From 20657e9f1c3afd6fea826a1633860a7140336651 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Fri, 27 Nov 2026 10:41:36 +0000 Subject: compute: say which dataset and engine each run used Fills in the usage slot for gemma (all three routes, through one record_usage helper), qtl2, rqtl, fitqtl, bulklmm, bnw and bnw_features: dataset, group, source (group|upload|file|basket), trait, engine, and the run id where the endpoint has one -- the id a later result fetch carries in its path, which is what makes "computed and never fetched" measurable. The call goes in before validation on purpose: a 422 still records what was asked for, and a failed compute is as interesting as a working one. /search gets q, type, engine and hits. It is the only place a query string is written: the access log drops query strings because one can carry a credential, so ?q= was otherwise invisible, and "what people search for" is the most useful behavioural signal this API has. --- src/routes/bnw.rs | 18 ++++++++++++++++++ src/routes/bulklmm.rs | 18 ++++++++++++++++++ src/routes/fitqtl.rs | 20 ++++++++++++++++++++ src/routes/gemma.rs | 35 +++++++++++++++++++++++++++++++++++ src/routes/qtl2.rs | 21 +++++++++++++++++++++ src/routes/rqtl.rs | 18 ++++++++++++++++++ src/routes/search.rs | 13 +++++++++++++ 7 files changed, 143 insertions(+) (limited to 'src') 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, ) -> Result>, 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, ) -> Result>, 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, ) -> Result>, 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/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, ) -> Result>, 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 38f33a4..fc5c06e 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -27,6 +27,33 @@ 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. @@ -1129,6 +1156,9 @@ pub async fn compute_gemma( ) -> Result>, 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 @@ -1625,6 +1655,7 @@ pub async fn compute_gemma_ravanan( Query(params): Query, Json(mut request): Json, ) -> Result>, 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, @@ -1693,6 +1724,10 @@ pub async fn 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, diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index bf2ba06..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, ) -> Result>, 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() { diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index 0fbfdf4..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, ) -> Result>, 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( 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); } -- cgit 1.4.1