diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-19 11:41:28 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-19 11:41:28 +0000 |
| commit | 6bd032d565233016f2c658840ab2769cf2359fe2 (patch) | |
| tree | 6d7e10b9733fa761a8849b5737e7e1f90ffe90cd /src | |
| parent | 84de1f715cc013465efd7f6876e3ed5f7ffc2a3d (diff) | |
| download | genenetwork4-6bd032d565233016f2c658840ab2769cf2359fe2.tar.gz | |
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 (<status> <code>), 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.
Diffstat (limited to 'src')
| -rw-r--r-- | src/config.rs | 19 | ||||
| -rw-r--r-- | src/response.rs | 9 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 101 |
3 files changed, 117 insertions, 12 deletions
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<String>, } -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaRequest { /// Path to a BIMBAM genotype file (plain text or gzipped), passed /// as GEMMA's `-g`. Give this and `snps_file`, or `group` -- not @@ -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<f64>, @@ -571,6 +574,57 @@ pub async fn compute_gemma( Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, 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<String> = 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); } @@ -1230,6 +1287,26 @@ pub async fn compute_gemma_ravanan( Query(params): Query<ComputeGemmaParams>, Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, 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<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); let lmm = request.lmm.unwrap_or(9); if !matches!(lmm, 1 | 2 | 3 | 4 | 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()), |
