From 9aff34fad9df147c999e1bccb0e380f202dffed8 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 17 Nov 2026 17:39:46 +0000 Subject: docs: the listing shape -- what it does, what is wired, and the one open question Five of six listings take limit_to/ids_only/names_only with the old shape as the default; docs/listings.md is the client-facing description plus the mechanics (why the reply type is an untagged Rows enum, why the utoipa body= must move with it, and why that mismatch reports itself as a missing __path_ handler). It also records the one that is not done, with the measurement that matters: /traits/{dataset} answers the full list whatever parameters are sent, which is what a handler that never receives its Query does -- so the next step is the operationId of that path in /openapi.json, not another edit to traits.rs. --- docs/listings.md | 78 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ docs/migration.md | 2 +- 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 docs/listings.md (limited to 'docs') diff --git a/docs/listings.md b/docs/listings.md new file mode 100644 index 0000000..86b2fb0 --- /dev/null +++ b/docs/listings.md @@ -0,0 +1,78 @@ +# The listing shape: `limit_to`, `ids_only`, `names_only` + +Three optional query parameters, the ones GeneNetwork2 offers and this API did +not, on the listings a client has to enumerate: + +``` +GET /groups?names_only=true +GET /groups/BXD/traits?ids_only=true&limit_to=10001,BXD_0001 +GET /datasets/HC_M2_0606_P/probesets?names_only=true +``` + +## The rule that makes it safe + +**No listing parameters means exactly the answer this API has always given.** +The reply body is an untagged `Rows` enum (`Objects` or `Plain`), so the wire +shape is a plain JSON array either way and the default path is unchanged; only +the slim forms answer one value per row. That was the point of the design: the +default tenant of this API is an existing client, and a wrapper object would +have been a breaking change dressed up as a feature. + +* `limit_to=a,b,c` keeps the rows whose id, name, trait name, display name or + full name matches one of the values, case-insensitively. Rows keep their + order. +* `ids_only=true` answers one id per row; `names_only=true` one name. +* Asking for both shapes at once is a **422 `invalid_listing`** rather than a + parse-order coin toss. +* A `limit_to` value that matches nothing is **named in the reply's note**. A + silent empty answer is how "my trait is missing" becomes undiagnosable. + +## Where it is wired (2026-11-16) + +| endpoint | state | +|---|---| +| `GET /groups` | yes | +| `GET /groups/{group}/strains` | yes | +| `GET /groups/{group}/datasets` | yes | +| `GET /groups/{group}/traits` | yes — 15 060 traits in BXDPublish, the case that motivated this | +| `GET /datasets/{dataset}/probesets` | yes — 45 101 probesets | +| `GET /traits/{dataset}` | **no** — see below | + +Payloads for scale: `/datasets/HC_M2_0606_P/probesets` is 45 101 objects, +`/groups/BXD/traits` 15 060, `/groups/BXD/strains` 396. + +## Why `/traits/{dataset}` is not wired + +This listing returns probe *and* phenotype traits in one array, each row tagged +`category: "probeset"` (verified against a live reply — the rows are flattened, +so `category` is a field and a probeset's identifier is `probeset_id`; there is +no `id`). A bare id is therefore ambiguous, and the intended slim form is +`category:value` (`"probeset:1427571_at"`, `"publish:10001"`). + +Wire it was attempted and withdrawn: with the fields read correctly the +parameters were still ignored — every request answered the full 45 101 objects, +which is what a handler that never sees its `Query` does. Before editing that +handler again, settle one question: **which function serves `/traits/{dataset}`**. +`src/lib.rs` registers `traits`, `trait_info` and `trait_values` on overlapping +prefixes, so check the `operationId` of that path in `/openapi.json` rather than +assuming it is `traits.rs`'s `traits`. + +## Mechanics, for whoever adds the next one + +Three edits per handler plus one that is easy to miss: + +1. the three fields on the handler's query struct — or, if it has none, take + `crate::listing::ListingParams` directly (it is `IntoParams`, so it documents + itself); +2. the return type: `Envelope>` → `Envelope`; +3. shape the rows where the envelope is built, appending the `limit_to` note; +4. **and** the `body =` type in the handler's `utoipa::path` block. + `utoipa` typechecks that annotation against the return type, so changing one + and not the other fails as `could not find __path_` pointing at + `lib.rs`'s `routes!` macro — a misleading error that sends you to the wrong + file. This is the whole reason a `Rows` enum beats an `Envelope`: the + annotation changes by one word and the compiler keeps checking the real type. + +Also: `axum::extract::Query` must be in scope (three of the six handlers never +used it), and a handler whose `Found` branch builds its envelope inline +(`Ok(Json(ctx.envelope(...)))`) has to open that branch into a block. diff --git a/docs/migration.md b/docs/migration.md index b3f0d64..bd9879d 100644 --- a/docs/migration.md +++ b/docs/migration.md @@ -30,7 +30,7 @@ already exists in the API. | feature | GN1 | GN2 | GN3 | effort | why | +--------------------------------------+------+-----+------+--------+-----------------------------------------------------------+ | correlation matrix | yes | yes | no | S-M | decisions recorded; N^2 calls to the live correlate_named | - | limit_to / ids_only / names_only | no | yes | no | S | optional query params on existing listings | + | limit_to / ids_only / names_only | no | yes | no | S | 5 of 6 listings done 2026-11-16 (docs/listings.md); /traits/{dataset} open -- its rows are flattened and its Query never arrives, so check which handler serves it first | | tissue correlation | yes | yes | yes | S-M | TissueProbeSetData is in the DB; the maths already exists | | literature correlation | yes | yes | yes | S-M | LCorrRamin3 is a lookup table, no statistics involved | | whole-dataset sample matrix export | yes | yes | yes | S-M | one SQL sweep; the only choice is streaming/CSV vs JSON | -- cgit 1.4.1 From a621bb36303ad6c45fee88e9d3700abd36799a26 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Thu, 19 Nov 2026 12:02:34 +0000 Subject: docs: the auth stub is a second process, and its absence looks like a working API run.sh restart replaces the two instances only. On 2026-11-19 the stub on :8081 was down, so every authenticated endpoint answered 401 invalid_token: fetching http://127.0.0.1:8081/auth/public-jwks: io: Connection refused (os error 111) while /version and /mapping-methods still answered -- the deployment looked alive and the read surface was entirely dark. A monitor run is what names it, so the checklist now says what to look for (18 failed, all 401), how to start the stub, and that its key is fixed, which is why tokens minted before the outage were still valid afterwards. The stub's token file belongs under the deployment's state directory: /run does not survive a reboot, and this is the failure that follows. --- docs/www/operator-checklist.md | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) (limited to 'docs') diff --git a/docs/www/operator-checklist.md b/docs/www/operator-checklist.md index a6267de..77628d4 100644 --- a/docs/www/operator-checklist.md +++ b/docs/www/operator-checklist.md @@ -345,6 +345,36 @@ build problem: write the resolved pid into the pid file (and start the replacement only after `:3000` has stopped answering). `source_digest` changes on every build, so it distinguishes two builds of the same commit. +### The auth stub is not restarted with it + +`run.sh restart` replaces the two genenetwork4 instances and nothing else. +The stub on `:8081` is a separate long-running process, and while it is down +every authenticated endpoint answers + + 401 invalid_token: fetching http://127.0.0.1:8081/auth/public-jwks: + io: Connection refused (os error 111) + +That is how it was found on 2026-11-19, after a restart that looked clean -- +`/version` and `/mapping-methods` still answer without a token, so the +service looks alive. A monitor run is what names it (18 failed, all 401): + +```sh +bin/monitor-gn4 --tier all --token-file /.token +``` + +Start the stub again (its key is fixed, so tokens minted before the outage +stay valid -- only the JWKS was missing): + +```sh +cd && AUTH_SERVER_URL=http://127.0.0.1:8081/ \ + nohup scripts/gn-auth-stub.py --token-file /stub.token \ + >> /logs/stub.log 2>&1 & +``` + +It writes the token it mints to that file and prints it; keep it under the +deployment's state directory rather than `/run`, which does not survive a +reboot. + ## Optional but worth it * Rate limit per address at the proxy: `limit_req_zone` + -- 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 'docs') 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 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 'docs') 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 fd5807024b0b5553cbe6e7d6d2bf717d50ef8b05 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Sat, 21 Nov 2026 18:52:12 +0000 Subject: scripts: a .geno to BIMBAM projector that refuses to guess the projection HET3-ITP's `bimbam/HET3-ITP.*` pair is empty -- 5.76 M cells, all "NA" -- which is why every GEMMA route answers 422 no_samples_aligned on a panel that is 45.8% dense in the `.geno` R/qtl reads. The converter that made those files only understood the biallelic letter codes a `.geno` header declares, and a four-founder panel writes numeric ones. This adds the tool that can regenerate such a pair, and the experiment that says what a 4-way panel actually needs. Tried the only contrast the header supports -- parent-of-origin, maternal codes 1,2 -> 0, paternal 3,4 -> 1, mixed 5..8 -> 0.5 (order-insensitive, so it cannot transpose two founders): - the pair it produced is real: 2,639,235 of 5,757,171 calls, 893 markers; - pangemma ran on HET3-ITP trait 10000 for the first time: 1314 s (21.9 min, 893 markers x 6447 individuals, one LOCO eigen decomposition per chromosome on a 2-CPU node), HTTP 200; - and it found nothing: 881 of 893 markers came out with exactly zero variance, because an advanced 4-way intercross is ~99.4% heterozygous, so "maternal versus paternal dosage" is a constant. So the mechanism works and the contrast does not. What HET3 needs is a founder contrast (the dosage of one founder's allele), whose numeric-code -> founder-pair table is in neither the `.geno` header, this repository, nor the panel's `rdata/HET3-ITP.RData` (qtl2 allele-probability arrays, not calls). `--codes` is therefore required rather than defaulted: a guessed table produces a silently empty projection, which is exactly how the shipped pair came to be 23 MB of NA. The data is unchanged: the stubs were restored after the experiment. docs/genotypes.md now records this, since it previously described the pair as "a biallelic projection" when in this deployment it carries nothing. --- docs/genotypes.md | 17 +++++- scripts/geno-to-bimbam.py | 140 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 154 insertions(+), 3 deletions(-) create mode 100755 scripts/geno-to-bimbam.py (limited to 'docs') diff --git a/docs/genotypes.md b/docs/genotypes.md index 55f7a6d..127ff68 100644 --- a/docs/genotypes.md +++ b/docs/genotypes.md @@ -85,9 +85,20 @@ QTLReaper and R/qtl; 2 → GEMMA; 3 → R/qtl; 4 → GEMMA and PLINK. On this database: `BXD` = 1, `HET3-ITP` = 3, `HSNIH-Palmer` = 2, `HS` = NULL. `HET3-ITP` is UM-HET3, a 4-way cross (`@type:4-way`, `@mat:AB`, -`@pat:CD` in its `.geno` header), so R/qtl is the right engine even -though `bimbam/HET3-ITP.*` files exist — those are a biallelic -projection of a four-founder panel. +`@pat:CD` in its `.geno` header), so R/qtl is the right engine. The +`bimbam/HET3-ITP.*` files are **empty stubs** — every genotype cell is +`NA` — so every GEMMA route refuses them with `422 no_samples_aligned` +(after `individuals_with_genotypes` finds nobody with a call), while the +same panel is 45.8% dense in the `.geno` R/qtl reads. A real projection +has to pick a *founder* contrast: tried parent-of-origin +(`scripts/geno-to-bimbam.py`, maternal 1,2 -> 0, paternal 3,4 -> 1, mixed +-> 0.5) and it produced a working pair -- pangemma then ran HET3-ITP +10000 for 21.9 min -- but with **no associations**, because an advanced +4-way intercross is ~99.4% heterozygous, so that dosage is constant (881 +of 893 markers had exactly zero variance). The numeric-code -> +founder-pair table is not in the header, this repository, or +`rdata/HET3-ITP.RData` (qtl2 allele-probability arrays, not calls), so a +founder projection is a decision for the panel's owner. ## Measured runs (2026-11-07, this deployment) diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py new file mode 100755 index 0000000..089da45 --- /dev/null +++ b/scripts/geno-to-bimbam.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +"""Project a GeneNetwork `.geno` panel to the BIMBAM pair GEMMA reads. + +Why this exists: the deployment's `genotype/bimbam/_geno.txt` files +were generated by a converter that only understands the *biallelic* letter +codes a `.geno` header declares (`@mat:AB`, `@pat:CD` -> calls are "A"/"B"). +A four-founder panel declares the same two-letter header but writes its calls +as numeric codes, so every cell fell through to missing: HET3-ITP.12's BIMBAM +was 23 MB of "NA", which is why every GEMMA route refuses it (the panel has +45.8% data in the `.geno`) while R/qtl, which reads the `.geno`, runs fine. + +What the projection is. A 4-way panel (`@type:4-way`, `@mat:AB`, `@pat:CD`) +has eight genotype classes: the four founder homozygotes and the four +maternal-by-paternal combinations. Biallelic BIMBAM can carry one contrast, +and the one this tool takes is **maternal- versus paternal-derived**: a mouse +that inherited both alleles from the `@mat` founders scores 0, both from the +`@pat` founders scores 1, and a heterozygote (one from each) scores 0.5 -- +the mean-genotype scale BIMBAM and GEMMA already use. That projection needs +no knowledge of which numeric code is which heterozygous *pair*, only which +codes are the maternal homozygotes, the paternal homozygotes and everything +else, so it cannot silently transpose two founder alleles. + +Which codes are which is NOT assumed: `--codes` is required, because getting +it wrong is silent. Tried on HET3-ITP.12 with the only table its header +supports (1,2 -> 0; 3,4 -> 1; 5..8 -> 0.5): the projection produced a real +BIMBAM (2.6 M of 5.8 M calls) and pangemma ran on it for 21.9 min, but +answered no associations at all -- 881 of 893 markers came out with exactly +zero variance, because an advanced 4-way intercross is ~99.4% heterozygous, so +"maternal versus paternal dosage" is a constant. A parent-of-origin contrast +is therefore useless for that panel; what it needs is a *founder* contrast +(dosage of one founder's allele), and the numeric-code -> founder-pair table +is not in the `.geno` header, this repository, or the panel's `rdata/*.RData` +(which holds qtl2 allele-probability arrays, not calls). That is a modelling +decision for whoever owns the panel -- pick the founders, then pass the table +here. R/qtl remains the engine for 4-way panels (docs/genotypes.md). + + scripts/geno-to-bimbam.py --geno HET3-ITP.12.geno --out DIR +writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt. +""" + +import argparse +import sys + + +def read_geno(path): + """Yield (chr, locus, cM, Mb, calls) for every marker row.""" + header = None + with open(path) as handle: + for line in handle: + line = line.rstrip("\n") + if not line or line.startswith("#") or line.startswith("@"): + continue + fields = line.split("\t") + if header is None: + if fields[0].lower() != "chr": + continue + header = fields + continue + if len(fields) < 5: + continue + yield fields[0], fields[1], fields[2], fields[3], fields[4:] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--geno", required=True, help="the .geno panel to project") + parser.add_argument("--out", required=True, help="directory for the pair") + parser.add_argument( + "--name", + default=None, + help="basename for the outputs (default: the .geno's name)", + ) + parser.add_argument( + "--codes", + required=True, + help="projection table: '=' separated by ';', " + "e.g. '0=1,2;1=3,4;0.5=5,6,7,8' (required: a guessed table produces a " + "silently empty projection, see the docstring)", + ) + args = parser.parse_args() + + table = {} + for part in args.codes.split(";"): + dosage, codes = part.split("=") + for code in codes.split(","): + table[code.strip()] = dosage.strip() + + import os + + name = args.name or os.path.basename(args.geno).removesuffix(".geno") + geno_out = os.path.join(args.out, f"{name}_geno.txt") + snps_out = os.path.join(args.out, f"{name}_snps.txt") + + seen = {"markers": 0, "calls": 0, "missing": 0} + per_dosage = {} + with open(geno_out, "w") as geno, open(snps_out, "w") as snps: + for chrom, locus, _cm, mb, calls in read_geno(args.geno): + projected = [] + for call in calls: + call = call.strip() + dosage = table.get(call) + if dosage is None: + projected.append("NA") + seen["missing"] += 1 + else: + projected.append(dosage) + per_dosage[dosage] = per_dosage.get(dosage, 0) + 1 + seen["calls"] += 1 + # BIMBAM: marker, allele1, allele0, then one mean genotype per + # individual in column order (X/Y are the placeholders the + # deployment's other BIMBAM files use). + geno.write(f"{locus}, X, Y, " + ", ".join(projected) + "\n") + # The annotation file GEMMA takes as -a: marker, bp, chromosome. + # A `.geno` writes physical positions in Mb (`@scale:physic` and an + # "Mb" column); BIMBAM annotation wants bp, which is what the + # deployment's other `_snps.txt` files carry. + try: + position = str(int(round(float(mb) * 1e6))) + except (TypeError, ValueError): + position = "0" + snps.write(f"{locus}, {position}, {chrom}\n") + seen["markers"] += 1 + + if seen["markers"] == 0: + sys.exit("no marker rows: is this a .geno file?") + if seen["missing"] == seen["calls"]: + sys.exit( + "every call projected to missing -- the --codes table does not " + "match this panel's numeric codes" + ) + print( + f"{geno_out}: {seen['markers']} markers, {seen['calls'] - seen['missing']} " + f"calls projected ({100 * (1 - seen['missing'] / seen['calls']):.1f}% present), " + f"dosages {dict(sorted(per_dosage.items()))}" + ) + print(f"{snps_out}") + + +if __name__ == "__main__": + main() -- 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 'docs') 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 a24133abd0eeb5e4ecc9ae72fc4a9e055e33e3a7 Mon Sep 17 00:00:00 2001 From: Pjotr Prins Date: Tue, 24 Nov 2026 10:54:00 +0000 Subject: docs: the async form, template links, file-request names -- and a 409 that was a lie Four things a reader of the release docs would get wrong today: * **`/compute/gemma/async` did not exist in the doc at all.** A cold fit on a large panel is tens of minutes; a closed connection used to lose the answer. The section now shows the 202 + `/compute/gemma/result/{id}` form, says what the progress reply reports (`elapsed_ms`, `jobs_submitted`, `0` = all cached), and distinguishes it from `/compute/gemma/status/{id}`, which only tails text. * **`template` was documented for Wikidata URLs only**, while a compute reply's `next` can carry a shape (`{trait_id}`, a genotype file name). Those now carry `"template": true`; the doc says so, so nobody follows one and gets a 404. * **A file request can be named**, but a BIMBAM has no individual names, so for GEMMA they come from the `.geno` beside it. New paragraph; measured on At-Serin, where a basket worked on R/qtl and failed on GEMMA before the fix. * **"Uploading the same name again replaces it" was false**: it is a 409. DELETE then POST, and `updated_at` is the version that ran. (The dangling "The reply's" that followed it is finished too.) --- docs/www/SKILL.md | 47 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 9 deletions(-) (limited to 'docs') diff --git a/docs/www/SKILL.md b/docs/www/SKILL.md index 6c8338e..0b97fec 100644 --- a/docs/www/SKILL.md +++ b/docs/www/SKILL.md @@ -78,7 +78,10 @@ Every JSON reply is `{"data","meta","notes","next"}` and sometimes `"actions"`. * `notes`: read them. They say how many strains were matched, what was run, and caveats. * `next`: GET links to related things. Each `href` already includes `/gn4`: - resolve against the origin (`https://vesuvio.pu.ac.ke$href`). + resolve against the origin (`https://vesuvio.pu.ac.ke$href`). A link that is a + *shape* rather than an address — one still holding a `{placeholder}` the scan + cannot fill, such as `{trait_id}` or a genotype file name — carries + **`"template": true`**; following the rest returns 200 as it stands. * **`actions`: ready-to-send POSTs.** On a trait's `/values` they are the R/qtl and GEMMA calls with the body already filled in; on a **compute reply** they are the matching plot call (href with `?trait=` already set; post the reply @@ -206,6 +209,24 @@ 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). +**A run can outlast your client, so there is an async form.** A cold fit on a +large panel is tens of minutes (measured: 21 min for 20 concurrent GWA jobs on a +133 217-marker rat panel), and a closed connection used to take the answer with +it: + +```sh +POST /compute/gemma/async?id= # same body; 202 at once +{ "id": "", "state": "running", "status": "/compute/gemma/result/" } +GET /compute/gemma/result/ # progress, then the finished reply +``` + +The status route reports `state`, `elapsed_ms` and what the cluster is doing +(`meta.timing.cluster.jobs_submitted` — `0` means everything came from cache), +and returns exactly the body the blocking call would have. `?id=` on the +blocking endpoints still works with `/compute/gemma/status/{id}` for the run +log, but that one tails text; use `result` to collect the answer. Give a long +run an id *before* starting it, or a timeout leaves you nothing to poll. + Reach for `/compute/gemma` when: - **Slurm is down or job submission fails** (`502`/`ravanan_failed`, or a job @@ -373,19 +394,27 @@ verify costs almost nothing. `{"basket": "."}` on any compute endpoint. `GET /matrices` lists yours, `GET /matrices/{name}/values` reads the table back. `scripts/example-matrix.py` writes a valid example from a genotype file. +* **A file request can still be named.** `genotype_file` + `snps_file` takes + `samples` (or a `basket`) and aligns them by name onto the genotype file's + individuals — but a **BIMBAM has no names**, so for GEMMA the names come from + the `.geno` kept beside it (`genotype/.geno` next to + `genotype/bimbam/_geno.txt`), and the values are placed in the BIMBAM's + column order. With neither a `.geno` sibling nor a group, send positional + `trait_values`. The reply's `Genotype:` note says which happened. * **Uploading genotypes**: `POST /uploads/genotypes` with `{"name":"-GENONAME","base_version":"BXD.4","contents":""}` — tab-delimited, header = individuals from column 4, then marker/chr/pos. It **updates** a population: ≤50 new individuals, at least one overlapping, ≤200 000 markers, and the values must be the same kind as the base's - (letters, whole numbers, probabilities). The reply's - Every compute endpoint takes it by name — `{"genotype_upload": ""}` on - `/compute/{rqtl,gemma,qtl2,fitqtl}` — with `samples` (or a `basket`) matched - **by name**; the server writes the form each engine reads. Uploading the same - name again **replaces** it, and the digest in the reply says which version - ran. A one-chromosome upload scans flat or empty under LOCO - kinship — use `"kinship": "overall"` if that is all you have. `scripts/example-genotype-upload.py` - makes a valid one from any `.geno`. + (letters, whole numbers, probabilities); the reply reports the individuals, + markers and digest it stored. Every compute endpoint then takes it by name — + `{"genotype_upload": ""}` on `/compute/{rqtl,gemma,qtl2,fitqtl}` — with + `samples` (or a `basket`) matched **by name**; the server writes the form each + engine reads. Uploading the same name again is a **`409`**, not a replacement: + `DELETE /uploads/genotypes/{name}` and post it again, and `updated_at` in the + listing is the version that ran. A one-chromosome upload scans flat or empty + under LOCO kinship — use `"kinship": "overall"` if that is all you have. + `scripts/example-genotype-upload.py` makes a valid one from any `.geno`. * **Changing values**: there is no write endpoint for traits, and there never 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 -- cgit 1.4.1