diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-27 11:22:38 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-27 11:22:38 +0000 |
| commit | cd9f46633bcc55ab2a72cda1a0f1a667e79c2e57 (patch) | |
| tree | e56b04e85f9d69b28695ed57345c1dff28d8d14c | |
| parent | f76043bf82b6c86b5e844b27b53e957d770aeb33 (diff) | |
| parent | 4f609454ba5b8db543863d6f20b042ca15cfe99f (diff) | |
| download | genenetwork4-cd9f46633bcc55ab2a72cda1a0f1a667e79c2e57.tar.gz | |
Merge branch 'main' into search/extract-engine-merge
66 files changed, 6082 insertions, 465 deletions
diff --git a/.gitignore b/.gitignore index dd7adeb..8681d20 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,10 @@ tokens.sqlite-* # ai-memory keeps its store beside the checkout; the journals are runtime ai-memory.sqlite ai-memory.sqlite-* +# the xapian index beside it: a rebuildable cache, and binary churn on every +# write. (`ai-memory.sqlite-*` does not match the directory, which is how six +# index files got committed.) +ai-memory.sqlite.d/ # the operator tool lives in bin/ and is source: only bytecode is not bin/__pycache__/ diff --git a/README.md b/README.md index fc9a5fc..ac8f28f 100644 --- a/README.md +++ b/README.md @@ -1799,6 +1799,80 @@ 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. + +**`meta.timing` says where the time went.** Beside `meta.took_ms` (the wall +clock for the whole request), a compute reply carries `timing`: the `engine`, +the request's `phases` (`artifacts` with `built`/`reused`/`none`, `workflow`, +`parse`), what the `cluster` did, and one entry per CWL step instance with the +figure its *own* log reports (`## total computation time`), labelled `ran` or +`cached`. `cluster.jobs_submitted: 0` is the warm claim -- no job ran, so every +step came from ravanan's store -- and a count like `20` means only those steps +ran (a new trait over a known panel re-uses all the kinship matrices and runs +only the GWA steps). Cached steps report the times recorded when they ran, which +is why `state` sits next to every number: a warm answer's step times are the +original run's, not this request's work. Slurm's job clock has one-second +resolution, so a sub-second job reports 0. + +`impute` is a *workflow of its own* on this path (`cwl/gemma/prepare.scm`), +one job that writes the prepared BIMBAM pair, cached by ravanan on +(script, inputs) so the treatment runs once per (panel, mode) however many +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 +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 @@ -1967,8 +2041,17 @@ directory the data is not in, declare no genotype-code map (every genotype reads as missing) and no orientation (individuals read as markers) — four traps that each produce a plausible flat scan rather than an error. The conversion also drops heterozygous calls on a `riself` panel, as R/qtl's -`convert2riself` does. Configuration: `QTL2_SCRIPT_PATH`, -`QTL2_CACHE_DIR`. +`convert2riself` does, and recodes the surviving alleles to 1 and 2 — a second +allele numbered 3 is not an allele a two-state HMM can use, and the scan built +on it was flat (BXD 10001: LOD 3.685 at the wrong marker, against 3.892 at the +locus GEMMA reports, p 5.9e-07). + +The conversion is an R script, `scripts/qtl2-convert-geno.R`, not Rust: its +output is an R/qtl2 cross, and `write_control_file` describes it, so the layout +and the codes come from the format's definition rather than from a second +implementation of it. Cost: 38 s cold for BXD's 20 453 autosomal markers, 3.5 s +once the cross is cached. Configuration: `QTL2_SCRIPT_PATH`, +`QTL2_CONVERT_SCRIPT`, `QTL2_CACHE_DIR`. ### Gene link-outs diff --git a/ai-memory.sqlite.d/index/docdata.glass b/ai-memory.sqlite.d/index/docdata.glass deleted file mode 100644 index d027857..0000000 --- a/ai-memory.sqlite.d/index/docdata.glass +++ /dev/null Binary files differdiff --git a/ai-memory.sqlite.d/index/flintlock b/ai-memory.sqlite.d/index/flintlock deleted file mode 100644 index e69de29..0000000 --- a/ai-memory.sqlite.d/index/flintlock +++ /dev/null diff --git a/ai-memory.sqlite.d/index/iamglass b/ai-memory.sqlite.d/index/iamglass deleted file mode 100644 index 2b8a36e..0000000 --- a/ai-memory.sqlite.d/index/iamglass +++ /dev/null Binary files differdiff --git a/ai-memory.sqlite.d/index/position.glass b/ai-memory.sqlite.d/index/position.glass deleted file mode 100644 index b226c24..0000000 --- a/ai-memory.sqlite.d/index/position.glass +++ /dev/null Binary files differdiff --git a/ai-memory.sqlite.d/index/postlist.glass b/ai-memory.sqlite.d/index/postlist.glass deleted file mode 100644 index 988b645..0000000 --- a/ai-memory.sqlite.d/index/postlist.glass +++ /dev/null Binary files differdiff --git a/ai-memory.sqlite.d/index/termlist.glass b/ai-memory.sqlite.d/index/termlist.glass deleted file mode 100644 index 33a66e8..0000000 --- a/ai-memory.sqlite.d/index/termlist.glass +++ /dev/null Binary files differdiff --git a/bin/monitor-gn4 b/bin/monitor-gn4 index 609fdb8..84a2f83 100755 --- a/bin/monitor-gn4 +++ b/bin/monitor-gn4 @@ -295,6 +295,45 @@ def has_rows(reply): return FAIL, "answered, but no rows" +def engine_of(reply): + """Which engine answered /compute/gemma. + + Read from `meta.timing.engine` where the binary reports it, falling back to + the notes (a reply from an older build carries no timing). + + Since GEMMA_ENGINE=slurm (the default) that endpoint runs the same + per-chromosome workflow /compute/gemma/ravanan does, and only falls back to + the in-process gemma-wrapper run when the Slurm route answers 5xx. The + notes say which happened -- a ravanan note when the cluster answered, an + "Engine: the Slurm route was unavailable ..." note when the wrapper did -- + so the monitor can report it rather than leaving the reader to guess from + the timing. + """ + data = reply.json or {} + timing = (data.get("meta") or {}).get("timing") or {} + if timing.get("engine"): + cluster = timing.get("cluster") or {} + jobs = cluster.get("jobs_submitted") + suffix = "" if jobs is None else (", warm" if jobs == 0 else f", {jobs} job(s)") + return f"{timing['engine']}{suffix}" + notes = data.get("notes") or [] + for note in notes: + if not isinstance(note, str): + continue + if note.startswith("Engine: the Slurm route was unavailable"): + return "fallback: local gemma-wrapper" + if note.startswith("ravanan"): + return "slurm (ravanan)" + return "unstated" + + +def has_rows_and_engine(reply): + verdict, why = has_rows(reply) + if verdict != OK: + return verdict, why + return OK, "%s, engine: %s" % (why, engine_of(reply)) + + def has_permutation(reply): """A qtl2 reply carrying the permutation null: n, thresholds, and values.""" data = reply.json or {} @@ -663,10 +702,12 @@ def build_checks(found, tiers): judge=has_clustering, hint="no external tool: pure Rust + MariaDB")) add(Check("compute-gemma", "compute", "POST", "/compute/gemma", - "gemma-wrapper + gemma + R (R_LIBS_SITE)", + "slurm route (ravanan + ccwl + slurmrestd), wrapper fallback", body={"group": g, "lmm": 9, "samples": samples}, - judge=has_rows, caches=True, - hint="gemma-wrapper, GEMMA_WRAPPER_CMD/GEMMA_DIR")) + judge=has_rows_and_engine, caches=True, + hint="ravanan/ccwl/slurmrestd for the default engine; " + "gemma-wrapper, GEMMA_WRAPPER_CMD/GEMMA_DIR and R for " + "the fallback, and GEMMA_ENGINE=local to skip Slurm")) if found.control_trait: # The partial axis: same endpoint, a second trait held constant. # Two traits out of a publish set give a low n, but the path @@ -685,6 +726,14 @@ def build_checks(found, tiers): "top_n": 5}, judge=has_rows, hint="no external tool: pure Rust + MariaDB")) + # Two traits, their shared individuals, and the scatter data. + add(Check("compute-compare", "compute", "POST", "/compute/compare", + "two traits, shared individuals and r (pure Rust)", + body={"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, + judge=has_comparison, + hint="no external tool: pure Rust + MariaDB")) add(Check("compute-rqtl", "compute", "POST", "/compute/rqtl", "R + r-qtl", body={"group": g, "method": "hk", "trait_name": found.trait, @@ -741,6 +790,11 @@ def build_checks(found, tiers): "clustered matrix -> heatmap svg (HEATMAP_PLOTTER)", body=heatmap_plot_body(found), expect=200, hint="HEATMAP_PLOTTER and python3", judge=has_svg)) + if found.control_trait: + add(Check("plot-compare", "plots", "POST", "/plot/compare", + "comparison -> scatter svg (COMPARE_PLOTTER)", + body=compare_plot_body(found), expect=200, + hint="COMPARE_PLOTTER and python3", judge=has_svg)) if found.samples: # The Manhattan plot: a GEMMA run's reply, posted back as-is. add(Check("plot-gemma", "plots", "POST", "/plot/gemma", @@ -785,6 +839,19 @@ def perturbed(body): return None +def has_comparison(reply): + """r, n and the pairs behind them.""" + data = (reply.json or {}).get("data") or {} + pairs = data.get("pairs") + if not isinstance(pairs, list) or len(pairs) < 2: + return FAIL, "no pairs in the answer" + if data.get("n") != len(pairs): + return FAIL, "n=%s but %d pairs" % (data.get("n"), len(pairs)) + if not isinstance(data.get("r"), (int, float)): + return FAIL, "r is %r" % (data.get("r"),) + return OK, "r %.4f over %d individual(s)" % (data["r"], len(pairs)) + + def has_clustering(reply): """A clustered order that is a permutation, with n-1 merges.""" data = (reply.json or {}).get("data") or {} @@ -868,6 +935,15 @@ def _post_result(client, path, body, what): return reply.json or {} +def compare_plot_body(found): + def build(client): + return _post_result(client, "/compute/compare", + {"a": {"dataset": found.publish, "trait_name": found.trait}, + "b": {"dataset": found.publish, + "trait_name": found.control_trait}}, "comparison") + return build + + def heatmap_plot_body(found): def build(client): return _post_result(client, "/compute/correlation/matrix", @@ -955,6 +1031,36 @@ def bnw_matrix(): variable("V4", [0.4, 5.1, 1.3, 4.8, 2.2])] +def slurm_probe(): + """Ping slurmrestd directly, so a dead cluster is named before it is waited on. + + Every /compute/gemma request now goes through ravanan to Slurm first, so + "Slurm is down" is the most likely reason for that endpoint to fall back. + The monitor cannot see that from the HTTP side (the fallback answers 200), + hence this out-of-band probe: it reads RAVANAN_SLURM_API_ENDPOINT and + RAVANAN_SLURM_JWT (the same two variables the server is configured with), + and SKIPs when they are not set on the monitoring side. + """ + endpoint = os.environ.get("RAVANAN_SLURM_API_ENDPOINT", "http://127.0.0.1:6820") + jwt_file = os.environ.get("RAVANAN_SLURM_JWT", "") + if not jwt_file or not os.path.exists(jwt_file): + return SKIP, "no RAVANAN_SLURM_JWT on the monitoring side" + try: + request = urllib.request.Request(endpoint.rstrip("/") + "/slurm/v0.0.41/ping") + request.add_header("X-SLURM-USER-TOKEN", open(jwt_file).read().strip()) + request.add_header("X-SLURM-USER-NAME", os.environ.get("SLURM_USER", "testuser")) + with urllib.request.urlopen(request, timeout=10) as answer: + data = json.load(answer) + except Exception as error: # noqa: BLE001 + return FAIL, "%s: %s" % (endpoint, error) + pings = data.get("pings") or [{}] + first = pings[0] + if first.get("pinged") != "UP": + return FAIL, "%s: %s" % (endpoint, first.get("pinged")) + return OK, "%s -> %s UP (%s us)" % (endpoint, first.get("hostname"), + first.get("latency")) + + def report(results, quiet_skips=True): width = max([len(r.name) for r in results] + [12]) print("%-*s %-8s %-7s %7s %s" % (width, "check", "tier", "verdict", @@ -1068,6 +1174,14 @@ def main(argv): results.append(Result(LocalCheck("listener", "core", "the listening process, from /proc"), Reply(0, None, 0), verdict, text)) + if "compute" in tiers: + # The default engine's first dependency, probed out of band: the Slurm + # route can fail while /compute/gemma still answers 200 from the + # fallback, and a monitor should say which of the two happened. + verdict, text = slurm_probe() + results.append(Result(LocalCheck("slurmrestd", "compute", + "ravanan's slurm-api endpoint (direct probe)"), + Reply(0, None, 0), verdict, text)) for check in checks: if not token and needs_token(check.path): results.append(Result(check, Reply(0, None, 0), SKIP, "no token")) diff --git a/cwl/gemma/gemma-loco-mdb.scm b/cwl/gemma/gemma-loco-mdb.scm new file mode 100644 index 0000000..1d94075 --- /dev/null +++ b/cwl/gemma/gemma-loco-mdb.scm @@ -0,0 +1,96 @@ +;; GEMMA --loco mapping on PANGEMMA, from an lmdb genotype store, one +;; invocation PER CHROMOSOME, scattered by ravanan. The pangemma twin of +;; gemma-loco.scm: same two steps, same scatter, same outputs -- the engine and +;; the genotype store are what differ. +;; +;; Why a separate workflow rather than a flag: the store replaces two of the +;; three genotype inputs. GEMMA needs `-g` (BIMBAM) plus `-a` (the annotation +;; that says which markers are on which chromosome, which is how `-loco <chr>` +;; knows what to leave out); pangemma reads the chromosome from the store's key +;; and needs neither. So this workflow takes a single `store` File. +;; +;; The store is built once per panel by gemma-wrapper's bin/geno2mdb.py +;; ("name<TAB>allele1<TAB>allele0" in the marker records, genotypes as float32 +;; for Gf or one byte for Gb). Gf is exact for a mean-genotype panel like BXD +;; (0, 0.5, 1 all fit in a float32); Gb is 4x smaller and exact only for integer +;; calls (0/1/2 -> 0/127/254), so a BXD store in Gb moves the p-values in the +;; third decimal. Measured on HLC (integer calls, 358454 markers): the same 23 +;; chromosomes take 141 s of cluster job time through this workflow against +;; 958 s for gemma on BIMBAM, with identical rows. +;; +;; Missing genotypes stay missing in the store (255 for Gb, NaN for Gf) and +;; pangemma drops and mean-substitutes them per marker exactly as GEMMA does, +;; so no imputation step is needed here -- the reason genenetwork4 imputed at +;; all was an older pangemma that could not hold a gap in its GRM. +;; +;; The chromosome list is still derived from the panel's SNP map by the caller +;; (src/gemma.rs), because CWL's scatter needs a concrete array. +;; +;; `-outdir .` keeps each job's outputs flat and unique by chromosome, as in +;; gemma-loco.scm. + +(define kinship + ;; pangemma's own LOCO kinship (-gk) from the store: every chromosome but + ;; this one. The kinship depends on the genotypes and on WHICH individuals + ;; are analysed, never on the phenotype values, so it is given a + ;; constant-valued pheno with the trait's missing-data pattern and shared + ;; between traits over the same animals. + (command + #:inputs (chr #:type string) + (store #:type File) + (kinship_pheno_file #:type File) + #:run "pangemma" + ("-g" store) + ("-p" kinship_pheno_file) + "-gk" + ("-loco" chr) + ("-o" "$(inputs.chr)-kin") + ("-outdir" ".") + #:outputs (kinship_file #:type File + #:binding ((glob . "$(inputs.chr)-kin.cXX.txt"))) + (kinship_log #:type File + #:binding ((glob . "$(inputs.chr)-kin.log.txt"))))) + +(define gwa + ;; pangemma's LOCO GWA (-lmm) given that chromosome's kinship matrix. `-pve` + ;; asks for the null model's variance components: four log lines, nothing in + ;; the .assoc.txt, read back out of this job's log by src/gemma.rs. + (command + #:inputs (chr #:type string) + (kinship_file #:type File) + (store #:type File) + (pheno_file #:type File) + (lmm #:type string) + #:run "pangemma" + ("-g" store) + ("-p" pheno_file) + ("-k" kinship_file) + ("-lmm" lmm) + ("-loco" chr) + "-pve" + ("-o" "$(inputs.chr)-gwa") + ("-outdir" ".") + #:outputs (assoc #:type File + #:binding ((glob . "$(inputs.chr)-gwa.assoc.txt"))) + (gwa_log #:type File + #:binding ((glob . "$(inputs.chr)-gwa.log.txt"))))) + +(workflow ((store #:type File) + ;; The trait's own values, for the GWA step. + (pheno_file #:type File) + ;; The same individuals, constant values: the kinship step's input. + (kinship_pheno_file #:type File) + (lmm #:type string) + ;; The distinct chromosomes, computed by the caller from the panel's + ;; SNP map (the store's keys carry them, but a CWL scatter needs a + ;; concrete array at invocation time). + (chromosomes #:type (array string))) + (pipe + (scatter (kinship #:store store + #:kinship_pheno_file kinship_pheno_file) + #:chr chromosomes) + (scatter (gwa #:store store + #:pheno_file pheno_file + #:lmm lmm) + #:chr chromosomes + #:kinship_file kinship_file))) diff --git a/cwl/gemma/manifest-artifacts.scm b/cwl/gemma/manifest-artifacts.scm new file mode 100644 index 0000000..c4d248d --- /dev/null +++ b/cwl/gemma/manifest-artifacts.scm @@ -0,0 +1,28 @@ +;; 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. +;; gemma-wrapper: its bin/geno2mdb, the store writer (Odin, no interpreter). +;; python and its packages are kept only for the R-side helpers; the store step +;; no longer needs them. +;; +;; ravanan sets these packages' search paths (PYTHONPATH among them) inside the +;; job, so `python3' here finds numpy and lmdb without any wrapper script -- +;; 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" + "gemma-wrapper")) diff --git a/cwl/gemma/manifest-mdb.scm b/cwl/gemma/manifest-mdb.scm new file mode 100644 index 0000000..9382f3b --- /dev/null +++ b/cwl/gemma/manifest-mdb.scm @@ -0,0 +1,13 @@ +;; Guix manifest ravanan's --guix-manifest resolves gemma-loco-mdb.scm's jobs' +;; commands against -- the pangemma twin of manifest.scm. +;; +;; `pangemma`, not `gemma`: this workflow's steps invoke pangemma, whose +;; `-g <store>.mdb` reads genotypes from an lmdb store instead of parsing +;; BIMBAM text. The package installs the binary under that name precisely so a +;; profile can hold both engines (see guix-bioinformatics' +;; gn/packages/gemma.scm), and `gemma-gn2` stays the engine of the other +;; workflows. +;; +;; ravanan keys a step on (script, inputs), so a manifest change must be +;; followed by a cold run. +(specifications->manifest (list "pangemma-git")) 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..5b01a6f --- /dev/null +++ b/cwl/gemma/store.scm @@ -0,0 +1,38 @@ +;; 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 (genotype_file #:type File) + (snps_file #:type File) + ;; geno2mdb is a binary now (gemma-wrapper e244f99, built in Odin), so the + ;; step runs it from the job's profile: no interpreter, no python-lmdb, no + ;; PYTHONPATH. It is *not* an input any more -- ccwl appends every input to + ;; the command line, and a staged copy of the binary came out as argv[1], + ;; which geno2mdb then read as the BIMBAM file ("16 genotypes, expected 14", + ;; from its own ELF header). + #:run "geno2mdb" genotype_file + ("--snps" snps_file) + ("--format" "Gf") + ("--out" "genotypes.mdb") + #:outputs (store #:type File + #:binding ((glob . "genotypes.mdb"))))) + +(workflow ((genotype_file #:type File) + (snps_file #:type File)) + (store #:genotype_file genotype_file + #:snps_file snps_file)) 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/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<Vec<T>>` → `Envelope<crate::listing::Rows>`; +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_<handler>` 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<Value>`: 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 | diff --git a/docs/ravanan-slurm.md b/docs/ravanan-slurm.md index 391c447..ba715f3 100644 --- a/docs/ravanan-slurm.md +++ b/docs/ravanan-slurm.md @@ -28,6 +28,13 @@ 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/`), 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 @@ -45,7 +52,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/docs/www/SKILL.md b/docs/www/SKILL.md index 2fa2385..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 @@ -194,10 +197,37 @@ 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 | + +**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). + +**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: -**Use `/compute/gemma/ravanan` by default.** Reach for `/compute/gemma` only -when: +```sh +POST /compute/gemma/async?id=<name> # same body; 202 at once +{ "id": "<name>", "state": "running", "status": "/compute/gemma/result/<name>" } +GET /compute/gemma/result/<name> # 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 that never leaves `PENDING`) -- the in-process runner needs no cluster; @@ -218,7 +248,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 @@ -360,25 +394,34 @@ verify costs almost nothing. `{"basket": "<matrix>.<column>"}` 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/<stem>.geno` next to + `genotype/bimbam/<stem>_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":"<user>-GENONAME","base_version":"BXD.4","contents":"<tsv>"}` — 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": "<name>"}` 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": "<name>"}` 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 like `"NA"`, or null), `PATCH /baskets/{name}` to edit (a new revision, a new - digest), then `POST /compute/qtl2` with `"basket": "<name>"` instead of - `samples`. Baskets are private to the token's user, live in their own SQLite + digest), then map it with **`"basket": "<name>"`** 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 +439,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 +668,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 +742,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 (<old> -> <new>); 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 +790,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/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 <state>/<user>.token +``` + +Start the stub again (its key is fixed, so tokens minted before the outage +stay valid -- only the JWKS was missing): + +```sh +cd <checkout> && AUTH_SERVER_URL=http://127.0.0.1:8081/ \ + nohup scripts/gn-auth-stub.py --token-file <state>/stub.token \ + >> <state>/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` + diff --git a/guix.scm b/guix.scm index c5067d4..f14142c 100644 --- a/guix.scm +++ b/guix.scm @@ -76,9 +76,21 @@ (package (name "genenetwork4-git") (version "0.1.0") + ;; The exclusion list is the .gitignore, minus the two entries that must + ;; stay in the build (tokens.sqlite is a secret the build never sees, and + ;; the *.cwl is regenerated): everything else there is a runtime artifact, + ;; and ai-memory.sqlite is the one that used to matter -- it is 1.9 MB and + ;; rewritten on every memory sync, so the source hash (and the whole + ;; ~9-minute recompile) changed without a line of code changing, and a + ;; store path could never match a commit's. (source (local-file %source-dir #:recursive? #t - #:select? (lambda (file stat) - (not (string-contains file "/target/"))))) + #:select? + (lambda (file stat) + (not (or (string-contains file "/target/") + (string-contains file "__pycache__") + (string-contains file "/ai-memory.sqlite") + (string-suffix? ".swp" file) + (string-suffix? "/gemma-loco.cwl" file)))))) (build-system cargo-build-system) ;; The xapian-rs git dependency (the native search engine's ;; bindings) needs the vendored-graph build to deviate from the diff --git a/scripts/geno-to-bimbam.py b/scripts/geno-to-bimbam.py new file mode 100755 index 0000000..b31829d --- /dev/null +++ b/scripts/geno-to-bimbam.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +"""Project a GeneNetwork `.geno` panel to the BIMBAM pair GEMMA reads. + +Why this exists: the deployment's `genotype/bimbam/<version>_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 --pairwise +writes DIR/HET3-ITP.12_geno.txt and DIR/HET3-ITP.12_snps.txt. + +NOT every panel needs a fixed table. A panel whose markers are each biallelic +but whose *code pair* varies from marker to marker (HET3-ITP.12: 486 markers +carry codes {5,6}, 395 carry {7,8}, a handful more) needs `--pairwise`: for +each marker its two present codes become 0 and 1 (lower code -> 0), anything +else missing. That is the biallelic projection the panel actually supports -- +a single global table cannot express it, and forcing one there was measured to +be constant (881 of 893 markers with zero variance). +""" + +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( + "--pairwise", + action="store_true", + help="per-marker biallelic coding: each marker's two present codes " + "become 0 and 1. Use this for a panel whose code pair varies by " + "marker (see the docstring); it conflicts with --codes.", + ) + parser.add_argument( + "--codes", + required=False, + help="projection table: '<dosage>=<code,code,...>' 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() + + if bool(args.pairwise) == bool(args.codes): + sys.exit("give exactly one of --pairwise or --codes") + table = {} + for part in (args.codes or "").split(";"): + if not part: + continue + 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 = {} + pairwise_seen = {} + with open(geno_out, "w") as geno, open(snps_out, "w") as snps: + for chrom, locus, _cm, mb, calls in read_geno(args.geno): + marker_table = table + if args.pairwise: + present = sorted({c.strip() for c in calls if c.strip() not in ("NA", "", ".")}) + # Exactly two classes is what a biallelic marker looks like. + # One class (monomorphic) or more than two (a genuinely + # multi-allelic marker, which BIMBAM cannot carry) is left + # missing rather than silently folded. + if len(present) == 2: + marker_table = {present[0]: "0", present[1]: "1"} + pairwise_seen[(present[0], present[1])] = ( + pairwise_seen.get((present[0], present[1]), 0) + 1 + ) + else: + marker_table = {} + projected = [] + for call in calls: + call = call.strip() + dosage = marker_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()))}" + ) + if args.pairwise: + print( + "per-marker code pairs: " + + ", ".join( + f"{a}/{b}: {n}" for (a, b), n in sorted(pairwise_seen.items(), key=lambda kv: -kv[1]) + ) + ) + print(f"{snps_out}") + + +if __name__ == "__main__": + main() diff --git a/scripts/gn4-log.py b/scripts/gn4-log.py index a14e653..42031a2 100755 --- a/scripts/gn4-log.py +++ b/scripts/gn4-log.py @@ -25,6 +25,15 @@ Use it on a process log or a proxy log that carries `x-gn4-user`: scripts/gn4-log.py -f log.jsonl --json # enriched JSON, for jq scripts/gn4-log.py -f log.jsonl --summary # who ran what, counted +A compute request names its panel in its *body*, not its path, so the line +carries what the handler recorded about the work (`crate::usage`): `dataset`, +`group`, `source`, `trait`, `engine`, `cached`, `run`, and on `/search` the +query itself as `q` (the path has no query string on purpose). The table shows +them in a short suffix; `--datasets` and `--queries` count them: + + scripts/gn4-log.py -f log.jsonl --since 2026-11-20 --datasets + scripts/gn4-log.py -f log.jsonl --queries --limit 20 + Lines that are not JSON (a Ruby backtrace, a GEMMA progress bar) pass through unchanged unless --quiet; that is deliberate, because the process log interleaves them and dropping them would hide the interesting failures. @@ -150,6 +159,29 @@ def enrich(record: dict, registry: Registry, when: int | None) -> dict: return out +USAGE_FIELDS = ("dataset", "group", "source", "trait", "traits", "engine", "cached", "run") + + +def usage_suffix(record: dict) -> str: + """What the handler recorded about the work, short enough for a table. + + `q` is shown quoted (it is caller text and may contain spaces); the rest + as `key=value`. Nothing here is a secret: see `crate::usage`. + """ + parts = [] + if record.get("q") is not None: + parts.append(f'q="{record["q"]}"') + if record.get("type"): + parts.append(f"type={record['type']}") + if record.get("hits") is not None: + parts.append(f"hits={record['hits']}") + for field in USAGE_FIELDS: + value = record.get(field) + if value not in (None, ""): + parts.append(f"{field}={value}") + return " " + " ".join(parts) if parts else "" + + def format_line(record: dict, when: str) -> str: who = record.get("user") or "-" credential = record.get("scheme") or "-" @@ -165,6 +197,7 @@ def format_line(record: dict, when: str) -> str: f"{when or '-':<19} {who:<20} {credential:<34} " f"{record.get('method', '-'):<6} {record.get('status', '-'):>4} " f"{took:>6} ms {record.get('path', '')}" + f"{usage_suffix(record)}" ) @@ -179,6 +212,9 @@ def main() -> int: parser.add_argument("--grep", default=None, help="only lines containing this text (matches the raw line)") parser.add_argument("--json", action="store_true", help="emit enriched JSON instead of a table") parser.add_argument("--summary", action="store_true", help="count requests per caller and credential") + parser.add_argument("--datasets", action="store_true", help="count requests per dataset (and source), with the distinct callers") + parser.add_argument("--queries", action="store_true", help="count /search queries, most frequent first") + parser.add_argument("--limit", type=int, default=25, help="how many rows --datasets/--queries print (default 25)") parser.add_argument("--quiet", action="store_true", help="drop lines that are not request records") args = parser.parse_args() @@ -212,7 +248,8 @@ def main() -> int: # through in table mode -- the process log interleaves them, and # dropping them would hide the interesting failures -- but never # in a machine-readable mode. - if not args.quiet and not args.json and not args.summary: + if not (args.quiet or args.json or args.summary + or args.datasets or args.queries): print(line) continue rows.append((when, enrich(record, registry, None))) @@ -230,6 +267,39 @@ def main() -> int: print(f"{len(rows):>7} {'total':<{width}}") return 0 + if args.datasets: + # The question this file was written to answer: which data is used, + # by how many separate callers. Computes are attributed by what the + # handler recorded, reads by what the path spells out. + counts: Counter = Counter() + callers: dict[tuple[str, str], set[str]] = {} + for _, record in rows: + dataset, source = record.get("dataset"), record.get("source") or "-" + if not dataset: + continue + counts[(dataset, source)] += 1 + callers.setdefault((dataset, source), set()).add(record.get("user") or "-") + width = max((len(name) for (name, _) in counts), default=10) + print(f"{'requests':>8} {'callers':>7} {'dataset':<{width}} source") + for (dataset, source), count in counts.most_common(args.limit): + print(f"{count:>8} {len(callers[(dataset, source)]):>7} {dataset:<{width}} {source}") + unattributed = sum(1 for _, record in rows if not record.get("dataset")) + print(f"{len(rows) - unattributed:>8} {len({(u) for c in callers.values() for u in c}):>7} total (plus {unattributed} with no dataset recorded)") + return 0 + + if args.queries: + queries: Counter = Counter() + callers: dict[str, set[str]] = {} + for _, record in rows: + query = record.get("q") + if query is None: + continue + queries[query] += 1 + callers.setdefault(query, set()).add(record.get("user") or "-") + for query, count in queries.most_common(args.limit): + print(f"{count:>7} {len(callers[query]):>3} callers {query}") + return 0 + for when, record in rows: if args.json: print(json.dumps(record)) diff --git a/scripts/make-mdb.sh b/scripts/make-mdb.sh new file mode 100755 index 0000000..e5b753e --- /dev/null +++ b/scripts/make-mdb.sh @@ -0,0 +1,150 @@ +#!/bin/sh +# make-mdb.sh -- build pangemma's genotype store (an LMDB environment) from a +# BIMBAM genotype file and its marker annotation. +# +# Two of gemma-wrapper's helpers do the work: +# +# anno2mdb.rb snps.txt -> <name>.snps.mdb (chr/pos -> marker name) +# geno2mdb.rb geno.txt --anno <name>.snps.mdb -> <name>.geno.mdb +# +# and this script exists for the three things they leave to the caller: +# +# 1. the lock file. An LMDB environment is data.mdb *plus* lock.mdb, and +# lock.mdb's bytes change on every open -- measured: 8d3d268b after writing, +# a different sha1 after one read-only open, different again after a +# read-write open, while data.mdb never changed. A directory whose hash is +# its identity (ravanan interns inputs by content) must therefore not +# contain one, so it is removed last and the tree is made read-only to stop +# anything recreating it. +# 2. the name. pangemma decides "this is an mdb" by looking for ".mdb" in the +# -g path (src/param.cpp:943), so the directory must end in .mdb and the +# outer name should say which translation it holds. +# 3. atomicity. A half-written environment must never be visible under the +# final name: build under a temporary name in the destination directory and +# rename when whole. +# +# scripts/make-mdb.sh --geno <bimbam geno> --snps <snps.txt> \ +# [--eval Gf|Gb|G0_1|G0_2] [--name NAME] [--out DIR] \ +# [--keep-missing] +# +# Missing genotypes are imputed to the marker's mean by default, because +# pangemma's mdb path cannot represent them: see the note further down. +# +# Prints the directory it built. Exit 2 on bad arguments, 1 on a maker failure. +set -eu + +geno= snps= eval_=Gf name= out=. keep_missing=no impute= cross_dir= probs_rds= +while [ $# -gt 0 ]; do + case $1 in + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --eval) eval_=$2; shift 2 ;; + --keep-missing) keep_missing=yes; shift ;; + --impute) impute=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs_rds=$2; shift 2 ;; + --name) name=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + -h|--help) sed -n '2,30p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;; + *) echo "make-mdb.sh: unknown argument $1" >&2; exit 2 ;; + esac +done +if [ "$impute" != qtl2 ]; then + [ -n "$geno" ] && [ -n "$snps" ] || + { echo "make-mdb.sh: --geno and --snps are required (or --impute qtl2)" >&2; exit 2; } + for f in "$geno" "$snps"; do + [ -r "$f" ] || { echo "make-mdb.sh: cannot read $f" >&2; exit 2; } + done +fi +case $eval_ in Gf|Gb|G0_1|G0_2) ;; *) echo "make-mdb.sh: unknown --eval $eval_" >&2; exit 2 ;; esac + +# The makers, and something to run them with. MAKE_MDB_ANNO / MAKE_MDB_GENO +# let a caller point at a different checkout; ANNO2MDB_OK is set by the caller +# when it has checked they exist. +ANNO=${ANNO2MDB:-anno2mdb.rb} +GENO=${GENO2MDB:-geno2mdb.rb} +for tool in "$ANNO" "$GENO"; do + command -v "$tool" >/dev/null 2>&1 || { echo "make-mdb.sh: $tool is not on PATH" >&2; exit 1; } +done + +mkdir -p "$out" +[ -n "$name" ] || name=$(basename "$geno" | sed 's/\.\(txt\|gz\|bimbam\)$//') +work=$(mktemp -d "$out/.$name.XXXXXX") +trap 'rm -rf "$work"' EXIT + +# 1. Where do the genotypes come from? With --impute qtl2 they come from +# R/qtl2's HMM (maxmarg on the cached genotype probabilities), which is the +# genotype set /compute/qtl2 maps on -- complete by construction, and +# predicted from flanking markers rather than averaged. That replaces both +# the BIMBAM and the snps file, so --geno/--snps are then optional. +if [ "$impute" = qtl2 ]; then + [ -n "$cross_dir" ] && [ -n "$probs_rds" ] || + { echo "make-mdb.sh: --impute qtl2 needs --cross DIR and --probs FILE.rds" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "make-mdb.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + "$RSCRIPT" "$(dirname "$0")/qtl2-impute-bimbam.R" \ + "$cross_dir" "$probs_rds" "$work/hmm" "${IMPUTE_MINPROB:-0}" >/dev/null 2>&1 || + { echo "make-mdb.sh: qtl2 HMM imputation failed" >&2; exit 1; } + geno=$work/hmm.bimbam.txt + snps=$work/hmm.snps.txt + [ -n "$name" ] || name=$(basename "$cross_dir") +else + # The makers write <input>.mdb *beside their input* and take it as a + # positional argument, so they get links to work on: nothing is written + # next to the caller's files. + ln -s "$(cd "$(dirname "$geno")" && pwd)/$(basename "$geno")" "$work/geno.txt" + ln -s "$(cd "$(dirname "$snps")" && pwd)/$(basename "$snps")" "$work/snps.txt" + geno=$work/geno.txt + snps=$work/snps.txt +fi + +# 2. the annotation half. It is an intermediate: pangemma is given the snps +# file itself (-a) and only geno2mdb needs this database, so it is not kept. +# Both makers name their output after the *argument they were given* and write +# it in the current directory, so they run inside the work directory with bare +# names: an absolute path would put the .mdb beside the caller's inputs (measured: +# a hand run left a 2 MB .mdb inside gn4-data). +( cd "$work" && "$ANNO" "$(basename "$snps")" ) >/dev/null 2>&1 || + { echo "make-mdb.sh: anno2mdb.rb failed" >&2; exit 1; } +anno_db=$work/$(basename "$snps").mdb + +# 2. missing genotypes (only for raw input: the HMM output has no gaps). pangemma's mdb path has NO missing-data handling +# (src/gemma_io.cpp's mdb_calc_kin still carries the "[ ] handle missing +# data" TODO), and one NA poisons every cell: measured, a BIMBAM with 0.1% +# NAs gave a 235x235 matrix of -nan while the same data imputed gave a clean +# one, with "**** INFO: Done." and exit 0 either way. So NAs are replaced +# per marker by that marker's mean -- which is what GEMMA does to a BIMBAM +# before it looks at it -- unless --keep-missing asks otherwise. +if [ "$keep_missing" = no ] && [ "$impute" != qtl2 ]; then + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$work/geno-imputed.txt" + mv "$work/geno-imputed.txt" "$geno" +fi + +# 3. the genotypes, translated the way pangemma expects +( cd "$work" && "$GENO" --eval "$eval_" --anno "$(basename "$snps").mdb" "$(basename "$geno")" ) >/dev/null 2>&1 || + { echo "make-mdb.sh: geno2mdb.rb failed" >&2; exit 1; } +store=$work/$(basename "$geno").mdb + +# 4. the lock file. These environments are single files (MDB_NOSUBDIR), so the +# lock is a *sibling*, <name>.mdb-lock -- measured on a real store: every +# open recreates it with different bytes while the .mdb itself never changes. +# The .mdb is what gets interned and hashed (a File input hashes its +# content), so the lock only needs to go so the directory we hand out +# contains nothing but the store itself. +rm -f "$store-lock" "$anno_db-lock" +chmod a-w "$store" + +rm -f "$out/$name.geno.mdb" "$out/$name.geno.mdb-lock" +mv "$store" "$out/$name.geno.mdb" +trap 'rm -rf "$work"' EXIT +rm -rf "$work" +trap - EXIT +printf '%s\n' "$out/$name.geno.mdb" diff --git a/scripts/plot-compare.py b/scripts/plot-compare.py new file mode 100755 index 0000000..77aeae2 --- /dev/null +++ b/scripts/plot-compare.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Scatter plot of two compared traits, as one SVG panel. + +Input is the JSON response of POST /compute/compare (saved as-is): the paired +values, the individual names, and the r/p/n they came with. The line is the +ordinary least-squares line implied by r and the two means -- nothing is +refitted here, and nothing is invented beyond what the reply carries. + + python3 plot-compare.py compare.json -o compare.svg --trait "1427571_at vs 1427641_at" + +Standard library only; writes plain SVG (light/dark aware). +""" +import argparse +import json +import sys + +W, H = 760, 520 +L, R, T, B = 64, 150, 78, 64 + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + ap.add_argument("result", help="saved /compute/compare response (JSON)") + ap.add_argument("-o", "--out", default="compare.svg") + ap.add_argument("--trait", default="", help="label for the title") + ap.add_argument("--title", default=None) + a = ap.parse_args() + + doc = json.load(open(a.result)) + data = doc.get("data") if isinstance(doc.get("data"), dict) else doc + pairs = data.get("pairs") or [] + if len(pairs) < 2: + sys.exit(f"{a.result}: no `pairs` -- post a /compute/compare reply") + r_value = data.get("r") + p_value = data.get("p") + n = data.get("n") or len(pairs) + first = (data.get("a") or {}) + second = (data.get("b") or {}) + + xs = [float(row[1]) for row in pairs] + ys = [float(row[2]) for row in pairs] + xmin, xmax = min(xs), max(xs) + ymin, ymax = min(ys), max(ys) + pad_x = (xmax - xmin) * 0.06 or 0.5 + pad_y = (ymax - ymin) * 0.06 or 0.5 + xmin, xmax = xmin - pad_x, xmax + pad_x + ymin, ymax = ymin - pad_y, ymax + pad_y + + pw, ph = W - L - R, H - T - B + + def X(v): + return L + (v - xmin) / (xmax - xmin) * pw + + def Y(v): + return T + ph - (v - ymin) / (ymax - ymin) * ph + + label = a.trait or (f"{first.get('trait_name', 'a')} vs {second.get('trait_name', 'b')}") + title = a.title or f"{label}: scatter" + method = data.get("method") or "pearson" + sub = (f"{method} r = {r_value:+.4f}" if isinstance(r_value, (int, float)) else f"{method} r = ?") + if isinstance(p_value, (int, float)): + sub += f", p = {p_value:.3g}" + sub += f", n = {n}" + if data.get("only_one_side"): + sub += f" · {data['only_one_side']} individual(s) had a value for only one trait" + desc = (f"Scatter of {first.get('trait_name', 'a')} ({first.get('dataset', '')}) against " + f"{second.get('trait_name', 'b')} ({second.get('dataset', '')}) over {n} individuals, " + f"{method} r {r_value}.") + + s = [f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" role="img" aria-labelledby="t d" font-family="system-ui,-apple-system,Segoe UI,sans-serif"> +<title id="t">{title}</title> +<desc id="d">{desc}</desc> +<style> +:root{{--surface:#fcfcfb;--ink:#0b0b0b;--ink2:#52514e;--grid:#e6e5e1;--dot:#2a6fdb;--line:#eb6834}} +@media (prefers-color-scheme:dark){{:root{{--surface:#1a1a19;--ink:#f0efec;--ink2:#c3c2b7;--grid:#333330;--dot:#5b8def;--line:#d95926}}}} +text{{fill:var(--ink2);font-size:12px}} .ttl{{fill:var(--ink);font-size:16px;font-weight:600}} +</style> +<rect width="{W}" height="{H}" fill="var(--surface)"/> +<text class="ttl" x="{L}" y="26">{title}</text> +<text x="{L}" y="46">{sub}</text>'''] + + for step in range(5): + value = ymin + (ymax - ymin) * step / 4 + y = Y(value) + s.append(f'<line x1="{L}" x2="{W - R}" y1="{y:.1f}" y2="{y:.1f}" stroke="var(--grid)" stroke-width="1"/>') + s.append(f'<text x="{L - 8}" y="{y + 4:.1f}" text-anchor="end">{value:.3g}</text>') + for step in range(5): + value = xmin + (xmax - xmin) * step / 4 + x = X(value) + s.append(f'<text x="{x:.1f}" y="{T + ph + 16}" text-anchor="middle">{value:.3g}</text>') + + # Least-squares line implied by r and the two standard deviations. + if isinstance(r_value, (int, float)) and n > 2: + mean_x = sum(xs) / n + mean_y = sum(ys) / n + var_x = sum((v - mean_x) ** 2 for v in xs) / (n - 1) + var_y = sum((v - mean_y) ** 2 for v in ys) / (n - 1) + if var_x > 0 and var_y > 0: + slope = r_value * (var_y / var_x) ** 0.5 + y_at = lambda v: mean_y + slope * (v - mean_x) + s.append(f'<line x1="{X(xmin):.1f}" y1="{Y(y_at(xmin)):.1f}" ' + f'x2="{X(xmax):.1f}" y2="{Y(y_at(xmax)):.1f}" stroke="var(--line)" ' + f'stroke-width="2" stroke-dasharray="6 4"/>') + + for row in pairs: + name, xv, yv = row[0], float(row[1]), float(row[2]) + s.append(f'<circle cx="{X(xv):.1f}" cy="{Y(yv):.1f}" r="4" fill="var(--dot)" ' + f'fill-opacity="0.85"><title>{name}: {xv:.4g} vs {yv:.4g}</title></circle>') + + s.append(f'<text transform="translate(18 {T + ph / 2}) rotate(-90)" text-anchor="middle">' + f'{second.get("trait_name", "b")}</text>') + s.append(f'<text x="{L + pw / 2:.1f}" y="{H - 16}" text-anchor="middle">' + f'{first.get("trait_name", "a")}</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 14}">r = {r_value:+.4f}</text>' if isinstance(r_value, (int, float)) else "") + s.append(f'<text x="{W - R + 12}" y="{T + 34}">n = {n}</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 54}" opacity="0.75">dashed: OLS</text>') + s.append(f'<text x="{W - R + 12}" y="{T + 70}" opacity="0.75">from r and the means</text>') + s.append("</svg>") + open(a.out, "w").write("\n".join(s) + "\n") + print(f"{a.out}: {n} points, r {r_value}") + + +if __name__ == "__main__": + main() diff --git a/scripts/plot-rqtl.py b/scripts/plot-rqtl.py index 73d8c51..b24a14f 100644 --- a/scripts/plot-rqtl.py +++ b/scripts/plot-rqtl.py @@ -28,8 +28,13 @@ def main(): if "data" not in doc: sys.exit(f"{a.result}: no 'data' member (error response?): {str(doc)[:200]}") res = doc["data"] - rows = res["markers"] # [name, chr, pos_mb, lod] - perm = res.get("permutation") + # `data` is the marker array itself (a reply from before that change kept + # it under `data.markers`), and the permutation null sits beside it in + # meta; older replies carried it inside data. + rows = res if isinstance(res, list) else res["markers"] + perm = (doc.get("meta") or {}).get("permutation") or ( + res.get("permutation") if isinstance(res, dict) else None + ) thr = [] # (value, label, dash) if perm: thr = [(perm["significant"], "significant (95%)", "7 4"), diff --git a/scripts/prepare-genotypes.sh b/scripts/prepare-genotypes.sh new file mode 100755 index 0000000..e6042a5 --- /dev/null +++ b/scripts/prepare-genotypes.sh @@ -0,0 +1,114 @@ +#!/bin/sh +# prepare-genotypes.sh -- one place where "how do we treat a missing genotype?" +# is decided, so the same question can be asked of every engine and the answers +# compared. +# +# --mode none leave the file as it is: GEMMA then does complete-case per +# marker and reports n_miss, and pangemma's lmdb store keeps +# the gaps (NaN for Gf, 255 for Gb) and mean-substitutes them +# per marker exactly as GEMMA does +# --mode mean replace each missing call by that marker's mean over the +# individuals that have one (cheap, but it invents a datum and +# deflates the variance) +# --mode hmm predict the missing calls from flanking markers with R/qtl2's +# HMM (maxmarg on genotype probabilities) -- the genotype set +# /compute/qtl2 maps on, and the one that does not invent a value +# +# scripts/prepare-genotypes.sh --mode mean|hmm|none \ +# --geno <bimbam geno> --snps <snps file> --out <prefix> \ +# [--cross <qtl2 cross dir>] [--probs <probs.rds|->] [--minprob N] \ +# [--individuals-file <names, one per line>] \ +# [--impute-script <qtl2-impute-bimbam.R>] +# +# 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 <prefix>.bimbam.txt and <prefix>.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 ;; + --geno) geno=$2; shift 2 ;; + --snps) snps=$2; shift 2 ;; + --out) out=$2; shift 2 ;; + --cross) cross_dir=$2; shift 2 ;; + --probs) probs=$2; shift 2 ;; + --minprob) minprob=$2; shift 2 ;; + --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 +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 <prefix>.* 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 +none) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + cp "$geno" "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +mean) + [ -n "$geno" ] && [ -n "$snps" ] || { echo "prepare-genotypes.sh: --geno and --snps are required" >&2; exit 2; } + awk -F, 'BEGIN { OFS = "," } + { + sum = 0; n = 0 + for (i = 4; i <= NF; i++) if ($i != "NA" && $i != "") { sum += $i; n++ } + mean = (n ? sum / n : 0) + for (i = 4; i <= NF; i++) if ($i == "NA" || $i == "") $i = sprintf("%.4f", mean) + print + }' "$geno" > "$out.bimbam.txt" + cp "$snps" "$out.snps.txt" + ;; +hmm) + [ -n "$cross_dir" ] || { echo "prepare-genotypes.sh: --mode hmm needs --cross DIR" >&2; exit 2; } + RSCRIPT=${RSCRIPT:-Rscript} + command -v "$RSCRIPT" >/dev/null 2>&1 || + { echo "prepare-genotypes.sh: $RSCRIPT is not on PATH (R with qtl2)" >&2; exit 1; } + # R's own complaint last, so a caller that reports the final stderr line + # reports the cause rather than our wrapper sentence. + [ -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 + exit 1 + fi + ;; +esac + +case $mode in +hmm) + # The R script writes <prefix>.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/scripts/qtl2-convert-geno.R b/scripts/qtl2-convert-geno.R new file mode 100755 index 0000000..48b4779 --- /dev/null +++ b/scripts/qtl2-convert-geno.R @@ -0,0 +1,145 @@ +#!/usr/bin/env Rscript +# qtl2-convert-geno.R -- convert a GeneNetwork `.geno` file into an R/qtl2 cross. +# +# This is the conversion that used to live in src/qtl2.rs, done where it belongs: +# the output *is* an R/qtl2 cross, the format is qtl2's own, and the JSON +# metadata that describes it is written by qtl2's `write_control_file` rather +# than by hand. Writing those files in Rust meant reimplementing qtl2's +# conventions in another language, and one of them was wrong: the genotype +# codes. With the heterozygous class dropped (the `riself` default) the cross +# carries two alleles, and they must be numbered 1 and 2. Numbering the second +# one 3 gave qtl2's two-state HMM an allele code it cannot use -- it read that +# allele as unusable, P(second allele) never rose above 0.5, every individual +# was called the first allele, and a scan on those calls lost the signal +# (2.0e-01 where the same marker is 5.9e-07 from the BIMBAM). +# +# qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2] +# +# writes DIR/{control.json,geno.csv,gmap.csv,pmap.csv,pheno.csv} -- the layout +# `read_cross2(DIR/control.json)` reads back -- and prints a one-line summary. +# Autosomes only: the X needs a sex covariate and the other chromosomes +# degenerate the per-chromosome kinship (the same limit /compute/qtl2 has). + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +get <- function(flag, default = NULL) { + i <- match(flag, args) + if (is.na(i)) return(default) + args[i + 1] +} +geno_path <- get("--geno") +out_dir <- get("--out") +het <- match.arg(get("--het", "drop"), c("drop", "keep")) +crosstype <- get("--crosstype") +if (is.null(geno_path) || is.null(out_dir)) { + stop("usage: qtl2-convert-geno.R --geno GROUP.geno --out DIR [--het drop|keep] [--crosstype riself|f2]", + call. = FALSE) +} + +lines <- readLines(geno_path, warn = FALSE) +meta <- function(key) { + hit <- grep(paste0("^@", key, ":"), lines, value = TRUE) + if (length(hit) == 0) NULL else trimws(sub(paste0("^@", key, ":"), "", hit[1])) +} +# The allele letters are declared by the file, not assumed: GeneNetwork panels +# use B/D as often as A/B. +mat <- meta("mat"); pat <- meta("pat"); het_code <- meta("het"); type <- meta("type") +if (is.null(mat) || is.null(pat)) { + stop("the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded", + call. = FALSE) +} + +hdr <- lines[tolower(substr(lines, 1, 4)) == "chr\t"][1] +if (is.na(hdr)) stop("the .geno file has no 'Chr' header row", call. = FALSE) +cols <- strsplit(hdr, "\t")[[1]] +individuals <- cols[-(1:4)] + +body <- lines[!startsWith(lines, "#") & lines != hdr] +autosomes <- as.character(1:19) + +geno <- list(); gmap <- list(); pmap <- list() +dropped <- 0L; non_autosomal <- 0L; markers_seen <- 0L +for (line in body) { + f <- strsplit(line, "\t")[[1]] + if (length(f) < 5) next + chr <- f[1] + if (!(chr %in% autosomes)) { non_autosomal <- non_autosomal + 1L; next } + marker <- f[2] + calls <- f[-(1:4)] + # A call is A, B or (if the heterozygous class is kept) H; anything else -- + # U or blank -- is missing and stays missing, because that is what the HMM is + # for. + calls[calls == mat] <- "A" + calls[calls == pat] <- "B" + if (!is.null(het_code)) { + calls[calls == het_code] <- if (het == "keep") "H" else "" + dropped <- dropped + if (het == "drop") sum(f[-(1:4)] == het_code) else 0L + } + calls[!(calls %in% c("A", "B", "H"))] <- "" + geno[[marker]] <- calls + markers_seen <- markers_seen + 1L + gmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[3]))) + pmap[[marker]] <- c(chr = chr, pos = suppressWarnings(as.numeric(f[4])) * 1e6) +} + +if (length(geno) == 0) stop("no autosomal markers in the .geno file", call. = FALSE) + +# A degenerate genetic map leaves the HMM nothing to smooth along (the .geno +# files carry no cM), so missing positions fall back to physical distance at +# 1 cM per Mb -- crude, monotone, and better than zeros. +for (marker in names(gmap)) { + g <- gmap[[marker]] + if (!is.finite(as.numeric(g["pos"]))) { + p <- pmap[[marker]] + gmap[[marker]]["pos"] <- if (is.finite(as.numeric(p["pos"]))) as.numeric(p["pos"]) / 1e6 else 0 + } +} + +dir.create(out_dir, recursive = TRUE, showWarnings = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(gmap, `[`, "", "chr"), + pos = as.numeric(vapply(gmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "gmap.csv"), row.names = FALSE, quote = FALSE) +write.csv( + data.frame(marker = names(geno), chr = vapply(pmap, `[`, "", "chr"), + pos = as.numeric(vapply(pmap, `[`, "", "pos")), row.names = NULL), + file.path(out_dir, "pmap.csv"), row.names = FALSE, quote = FALSE) +# qtl2's default genotype file has one row per individual and one column per +# marker, with the first column named `id` (see qtl2's own iron example). +geno_df <- data.frame(id = individuals, + do.call(cbind, lapply(geno, function(calls) calls)), + check.names = FALSE, stringsAsFactors = FALSE) +names(geno_df) <- c("id", names(geno)) +write.csv(geno_df, file.path(out_dir, "geno.csv"), row.names = FALSE, quote = FALSE) +# qtl2 wants a phenotype column to be able to read a cross; the trait comes from +# the request, through the scan script's --pheno. +write.csv(data.frame(id = individuals, trait = 1), + file.path(out_dir, "pheno.csv"), row.names = FALSE, quote = FALSE) + +# The JSON metadata is qtl2's own description of a cross: one call, no +# hand-rolled keys, and it stays right when qtl2 changes. +# 1..n over the genotypes the file carries: A/B for a riself cross with the +# heterozygous class dropped, A/H/B when it is kept. +codes <- if (crosstype == "riself" && het == "drop") c(A = 1L, B = 2L) else c(A = 1L, H = 2L, B = 3L) +write_control_file( + file.path(out_dir, "control.json"), + crosstype = crosstype, + geno_file = "geno.csv", gmap_file = "gmap.csv", pmap_file = "pmap.csv", + pheno_file = "pheno.csv", + geno_transposed = FALSE, sep = ",", + na.strings = "", + geno_codes = codes, overwrite = TRUE) + +# The report the caller reads back: what this cross holds, and what the +# conversion dropped. It is written beside the cross so a cached one costs +# nothing. +writeLines(jsonlite::toJSON(list( + crosstype = crosstype, markers = length(geno), non_autosomal = non_autosomal, + individuals = as.list(individuals), het_dropped = dropped, + cells = length(individuals) * length(geno)), auto_unbox = TRUE), + file.path(out_dir, "conversion.json")) + +cat(sprintf("geno2cross: %d markers, %d individuals, %d heterozygous calls %s, crosstype %s -> %s\n", + length(geno), length(individuals), dropped, + if (het == "drop") "dropped" else "kept", crosstype, out_dir)) diff --git a/scripts/qtl2-impute-bimbam.R b/scripts/qtl2-impute-bimbam.R new file mode 100755 index 0000000..4d33d51 --- /dev/null +++ b/scripts/qtl2-impute-bimbam.R @@ -0,0 +1,162 @@ +#!/usr/bin/env Rscript +# qtl2-impute-bimbam.R -- write a BIMBAM genotype file from qtl2's HMM, so that +# pangemma's mdb can be built from the same genotype calls /compute/qtl2 uses. +# +# Why this exists: the BIMBAM the GEMMA path uses carries 0.1% unknown calls +# and the riself conversion used by R/qtl2 drops 12.7% (every heterozygous +# call). Filling those with a marker mean would be inventing data where there +# is a real prediction to be had, so the calls come from qtl2's HMM instead: +# `maxmarg` on the cached genotype probabilities, which predicts a missing call +# from its flanking markers -- and that is the call set /compute/qtl2 maps on, +# so a GEMMA scan and a qtl2 scan over this file describe the same data. +# +# It is not here because an engine cannot cope: an older pangemma could not +# hold a gap in its GRM (one NA made the whole kinship matrix NaN, silently), +# which is what introduced this step, but the current build keeps the gaps +# (NaN in a Gf store, 255 in a Gb one) and mean-substitutes them per marker as +# GEMMA does -- measured: `impute: none` through pangemma answers the same +# rows and the same allele frequencies as GEMMA. So this is a modelling +# choice, not a workaround. +# +# qtl2-impute-bimbam.R <cross dir> <probs.rds> <out prefix> [minprob] +# +# writes <prefix>.bimbam.txt (marker, X, Y, genotypes -- positions come from +# the annotation database, as the makers expect) and <prefix>.snps.txt +# (marker, pos, chr, the order anno2mdb.rb parses). Autosomes only: the qtl2 +# cross this reads has no X, which is the same limit /compute/qtl2 has. + +suppressPackageStartupMessages(library(qtl2)) + +args <- commandArgs(trailingOnly = TRUE) +if (length(args) < 3) { + stop("usage: qtl2-impute-bimbam.R <cross dir> <probs.rds> <out prefix> [minprob]", + call. = FALSE) +} +cross_dir <- args[1]; probs_path <- args[2]; out_prefix <- args[3] +minprob <- if (length(args) >= 4) as.numeric(args[4]) else 0 +# Optional: the individuals the caller is actually serving, one per line. The +# cross carries the whole panel; a request that drops parents and F1s serves a +# subset, and a genotype file with more columns than the phenotype covers makes +# every comparison between modes meaningless (measured: none/mean fitted 198 +# individuals, hmm 235, and the peaks landed on different chromosomes). +individuals_file <- if (length(args) >= 5 && nzchar(args[5])) args[5] else NULL +wanted <- if (!is.null(individuals_file)) trimws(readLines(individuals_file)) else NULL + +setwd(cross_dir) +cross <- read_cross2("control.json") + +# Passing "-" as the probabilities means "compute them": a caller that only has +# the converted cross (the GEMMA path has no qtl2 scan to borrow a cache entry +# from) should not have to run /compute/qtl2 first just to get genotypes. The +# result is cached in the cross directory, which is itself content-keyed, so a +# second call is free. +probs <- if (identical(probs_path, "-")) { + cached <- "probs-imputed.rds" + if (file.exists(cached)) { + readRDS(cached) + } else { + p <- calc_genoprob(cross, error_prob = 0.002, cores = 1, quiet = TRUE) + saveRDS(p, cached) + p + } +} else { + readRDS(probs_path) +} + +# maxmarg returns one call per marker and individual, at the highest +# probability above MINPROB -- or NA when the HMM is less sure than that. At +# minprob 0 every cell is filled, which is what the mdb needs. +# The genetic map the HMM smooths along. Ours is often degenerate -- the .geno +# files carry no cM, so the converter writes 0 for many markers ("19 markers with +# missing genetic map position; using 0"), and with no distance between markers +# the HMM has nothing to smooth with: measured, P(BB) never exceeded 0.5 and +# every individual was called AA at a marker where 125 of 235 are BB. When the +# map has gaps, positions come from the physical map at 1 cM per Mb, which is +# crude but monotone and infinitely better than 0. +if (!is.null(cross$pmap)) { + for (chr_name in names(cross$gmap)) { + g <- cross$gmap[[chr_name]] + p_mb <- cross$pmap[[chr_name]][names(g)] / 1e6 + if (anyNA(g) || any(diff(g) <= 0) || any(g == 0)) { + if (!anyNA(p_mb)) cross$gmap[[chr_name]] <- unname(p_mb) + } + } +} + +# return_char: the genotype LETTERS (A/B, plus H if it were kept), not qtl2's +# internal genotype *indices*. Measured the hard way: maxmarg returns 1..n_gen +# -- 1 and 2 for a riself cross -- which are not the cross's numeric codes +# (A=1, B=3 per control.json). Mapping 2 to 1 read every BB animal as a +# heterozygote, which collapsed the genotypes (sd 0.21 where the panel has +# 0.46) and quietly killed the scan: the same marker that is p 5.9e-07 in the +# other modes came out at 2.0e-01. +imputed <- suppressWarnings(maxmarg(probs, minprob = minprob, cores = 1, + return_char = TRUE)) +if (!is.null(wanted)) { + present <- rownames(imputed[[1]]) + keep <- wanted[wanted %in% present] + if (length(keep) == 0) { + stop("none of the requested individuals appear in the cross", call. = FALSE) + } + for (chr_name in names(imputed)) { + imputed[[chr_name]] <- imputed[[chr_name]][keep, , drop = FALSE] + } + wanted_kept <- keep +} else { + wanted_kept <- rownames(imputed[[1]]) +} + +# How much work the HMM did: cells the cross itself had as missing (a 0 in an +# explicit genotype map, never NA -- see read_cross2's own convention). +missing <- sum(vapply(cross$geno, function(g) sum(g == 0 | is.na(g)), integer(1))) +filled <- sum(is.na(vapply(cross$geno, function(g) sum(is.na(g)), integer(1)))) +left <- sum(vapply(imputed, function(g) sum(is.na(g)), integer(1))) + +# The calls come back as genotype *codes* in qtl2's numeric convention for this +# cross (A = 1, B = 3, H = 2 per control.json); pangemma wants 0/1/2. +# The alphabet comes from the data: return_char gives the genotype *names* +# ("AA"/"BB" for a riself cross, "A"/"B" for a plain one, one name per founder +# for multiparent), so the first is homozygote 1 (0), the last homozygote 2 (2) +# and anything in between a heterozygote (1). Hard-coding A/H/B skipped every +# marker, because the values are "AA" and "BB" -- the run then had no +# chromosomes and no association files. +present <- sort(unique(as.vector(unlist(imputed)))) +present <- present[!is.na(present)] +if (length(present) < 2) { + stop("the HMM returned a single genotype state; nothing to map", call. = FALSE) +} +codes <- stats::setNames(c(0, rep(1, max(0, length(present) - 2)), 2), present) +rows <- list(); snps <- list() +# maxmarg returns individuals x markers (rows are individuals, which is the +# opposite of the BIMBAM's marker-per-line shape, and the reason a first version +# of this wrote 4 465 lines naming individuals as markers). +for (chr_name in names(imputed)) { + calls <- imputed[[chr_name]] + markers <- colnames(calls) + # pmap (base pairs) when the cross has one: it is what the annotation lookup + # and the plot positions want, exactly as /compute/qtl2 reports them. + positions <- (if (!is.null(cross$pmap)) cross$pmap else cross$gmap)[[chr_name]][markers] + for (marker in markers) { + row <- codes[as.character(calls[, marker])] + if (any(is.na(row))) next # a cell the HMM could not call + rows[[length(rows) + 1]] <- c(marker, "X", "Y", as.character(row)) + snps[[length(snps) + 1]] <- c(marker, as.character(round(positions[[marker]])), chr_name) + } +} + +writeLines(vapply(rows, paste, character(1), collapse = ","), + paste0(out_prefix, ".bimbam.txt")) +# The individual order of the calls -- rownames, because maxmarg returns +# individuals x markers and colnames are therefore markers (measured: writing +# colnames put 1452 marker names in a file of individuals, every value aligned +# to nothing, and the run reported "number of analyzed individuals equals 0") -- +# because it is the *cross's* order and not necessarily the panel's: a caller that writes a phenotype file positionally +# has to align to this, or the two disagree by name and every individual is +# missing (measured: gemma answered "no individuals in common" and ravanan +# reported no association files at all). +writeLines(wanted_kept, paste0(out_prefix, ".individuals.txt")) +writeLines(vapply(snps, paste, character(1), collapse = ","), + paste0(out_prefix, ".snps.txt")) + +cat(sprintf("hmm: %d markers, %d individuals, minprob %g, %d cells uncertain, %d written to %s.bimbam.txt\n", + length(rows), nrow(imputed[[1]]), minprob, left, length(rows), out_prefix)) diff --git a/scripts/wire-listing.py b/scripts/wire-listing.py new file mode 100755 index 0000000..3170106 --- /dev/null +++ b/scripts/wire-listing.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +# Mechanical first pass at wiring src/listing.rs into the six listing handlers. +# It changed 3 of 6 (groups, group_strains, group_traits) before the return-type +# rewrite needed hand care; see the module docs in src/listing.rs for the plan. +"""Wire the listing shape into the six listing handlers, mechanically. + +Per handler: add the three query fields, change the utoipa `body =` type and +the return type to Envelope<serde_json::Value>, and shape the rows where the +envelope is built. +""" +import re, sys + +def field_block(indent): + i = ' ' * indent + return (f"\n{i}/// Keep only these ids or names, comma-separated.\n{i}#[serde(default)]\n{i}pub limit_to: Option<String>,\n" + f"{i}/// Answer with one id per row instead of objects.\n{i}#[serde(default)]\n{i}pub ids_only: Option<bool>,\n" + f"{i}/// Answer with one name per row instead of objects.\n{i}#[serde(default)]\n{i}pub names_only: Option<bool>,\n") + +def shape(rows_expr, ind, params_name='params'): + i = ' ' * ind + return (f"let listing = crate::listing::Listing::parse(&crate::listing::ListingParams {{\n" + f"{i} limit_to: {params_name}.limit_to.clone(),\n" + f"{i} ids_only: {params_name}.ids_only,\n" + f"{i} names_only: {params_name}.names_only,\n" + f"{i}}})\n" + f"{i}.map_err(|detail| crate::listing::refuse(detail, &listing_rid, \"{op}\"))?;\n" + f"{i}let rows = serde_json::to_value({rows_expr}).unwrap_or(serde_json::Value::Null);\n" + f"{i}let (shaped, missing) = listing.apply(&rows, {params_name}.limit_to.as_deref());\n") + +handlers = [ + # file, handler fn, struct to extend, params type name, rows variable, operation id + ('src/routes/groups.rs', 'groups', 'GroupsParams', 'groups', 'groups'), + ('src/routes/groups.rs', 'group_strains', 'GroupStrainsParams', 'strains', 'group_strains'), + ('src/routes/groups.rs', 'group_datasets', 'GroupDatasetsParams', 'datasets', 'group_datasets'), + ('src/routes/groups.rs', 'group_traits', 'GroupTraitsParams', 'traits', 'group_traits'), + ('src/routes/datasets.rs', 'dataset_probesets', 'DatasetProbesetsParams', 'probesets', 'dataset_probesets'), + ('src/routes/traits.rs', 'traits', 'TraitsParams', 'traits', 'dataset_traits'), +] +status = [] +for path, handler, params, rows_var, op in handlers: + s = open(path).read() + before = s + # 1. add the fields to the params struct + m = re.search(r'pub struct %s \{(.*?)\n\}' % params, s, re.S) + if not m: + status.append(f'{handler}: params struct {params} NOT FOUND') + continue + if 'pub limit_to' not in m.group(0): + s = s.replace(m.group(0), m.group(0)[:-2] + field_block(4) + '}', 1) + # 2. body= type in the handler's utoipa block (the one nearest above the fn) + idx = s.index('pub async fn %s(' % handler) + head = s[:idx] + cut = head.rfind('body = Envelope<Vec<') + if cut == -1: + status.append(f'{handler}: no body= to change') + else: + end = head.index('>', cut) + 1 + s = head[:cut] + 'body = Envelope<serde_json::Value>' + head[end:] + s[idx:] + # 3. return type + s = re.sub(r'(pub async fn %s\([^)]*?\) -> Result<Json<Envelope<Vec<[^>]*>>, ApiError>)' % handler, + lambda mm: mm.group(1).replace('Envelope<Vec<', 'Envelope<serde_json::Value>[').split('Envelope<serde_json::Value>[')[0] + + 'Envelope<serde_json::Value>>, ApiError>', s, count=1, flags=re.S) + open(path, 'w').write(s) + status.append(f'{handler}: {"changed" if s != before else "UNCHANGED"}') +print('\n'.join(status)) diff --git a/src/baskets.rs b/src/baskets.rs index c6410bf..54e2ce2 100644 --- a/src/baskets.rs +++ b/src/baskets.rs @@ -97,6 +97,10 @@ pub struct Version { /// Why a basket operation failed. #[derive(Debug)] pub enum BasketError { + /// The caller picked a name that is taken. Its own variant because it is a + /// conflict (409), not a malformed request (422): the body is fine, the + /// name is not free. + NameInUse(String), /// No basket with that name for this user. NotFound(String), /// The request could not be stored as asked (a bad name, a bad value). @@ -108,7 +112,10 @@ pub enum BasketError { impl std::fmt::Display for BasketError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - BasketError::NotFound(what) | BasketError::Invalid(what) | BasketError::Store(what) => { + BasketError::NotFound(what) + | BasketError::Invalid(what) + | BasketError::NameInUse(what) + | BasketError::Store(what) => { write!(f, "{what}") } } @@ -432,7 +439,7 @@ pub fn create( .optional() .map_err(|error| BasketError::Store(error.to_string()))?; if exists.is_some() { - return Err(BasketError::Invalid(format!( + return Err(BasketError::NameInUse(format!( "a basket named '{name}' already exists; PATCH it, or pick another name" ))); } @@ -582,9 +589,13 @@ pub fn get( }; let counts: (i64, i64) = connection .query_row( + // The current revision only: `cell` is keyed on (basket_id, + // revision, sample), so a PATCH leaves the previous revision's + // rows in place. Without this the reply counted every revision + // ever written -- 93 values reported as 186 after one PATCH. "SELECT COALESCE(SUM(status = 'ok'), 0), COALESCE(SUM(status = 'missing'), 0) \ - FROM cell WHERE basket_id = ?1", - params![id], + FROM cell WHERE basket_id = ?1 AND revision = ?2", + params![id, revision], |row| Ok((row.get(0)?, row.get(1)?)), ) .map_err(|error| BasketError::Store(error.to_string()))?; diff --git a/src/config.rs b/src/config.rs index c6a1553..e029969 100644 --- a/src/config.rs +++ b/src/config.rs @@ -107,6 +107,42 @@ pub struct Config { /// the working directory the server is started from, same /// convention as `gemma_ravanan_workflow`. pub gemma_ravanan_manifest: String, + /// The pangemma twin of `gemma_ravanan_workflow`: + /// cwl/gemma/gemma-loco-mdb.scm, which reads genotypes from an lmdb + /// store instead of parsing BIMBAM, so its inputs are a single + /// `store` file where the gemma workflow takes `genotype_file` plus + /// `snps_file`. Selected per request by `"engine": "pangemma"` + /// (see src/gemma.rs's `GemmaEngine`). Set via + /// GEMMA_RAVANAN_WORKFLOW_MDB. + pub gemma_ravanan_workflow_mdb: String, + /// The manifest that workflow's steps resolve against, i.e. one + /// naming `pangemma-git` rather than `gemma-gn2` + /// (GEMMA_RAVANAN_MANIFEST_MDB). + pub gemma_ravanan_manifest_mdb: String, + /// The R script the `hmm` treatment runs (`IMPUTE_SCRIPT`, + /// scripts/qtl2-impute-bimbam.R), passed to the prepare workflow as a + /// staged input so a compute node needs nothing from the checkout. + pub impute_script: String, + /// The lmdb store builder `geno2mdb.py` (in gemma-wrapper's bin/, + /// which is not on PATH in every deployment): turns a BIMBAM + /// genotype file plus its annotation into the store pangemma reads. + /// Set via GENO2MDB_CMD. + pub geno2mdb_cmd: String, + /// The workflow that applies the missing-genotype treatment + /// (`GEMMA_PREPARE_WORKFLOW`, cwl/gemma/prepare.scm): one cluster job + /// that writes the prepared BIMBAM pair, cached by ravanan on + /// (script, inputs) so the treatment runs once per (panel, mode). + pub gemma_prepare_workflow: String, + /// The workflow that builds pangemma's lmdb store + /// (`GEMMA_STORE_WORKFLOW`, cwl/gemma/store.scm), cached the same way + /// -- the store is the expensive artifact of a pangemma run (22 MB for + /// BXD.8, minutes for HLC), so it is built once per panel. + pub gemma_store_workflow: String, + /// The manifest those two workflows' jobs resolve their commands + /// against (`GEMMA_ARTIFACTS_MANIFEST`): bash, awk, R/qtl2, python, + /// numpy and lmdb -- a different toolchain from the mapping steps', + /// and ravanan builds one profile per workflow. + pub gemma_artifacts_manifest: String, /// Directory POST /compute/gemma/ravanan uses for phenotype files, /// run logs, and ravanan's own --store and --output-directory. /// Separate from `gemma_cache_dir` so the two runners don't share @@ -120,12 +156,28 @@ pub struct Config { /// through slurmrestd's REST API). Set via RAVANAN_BATCH_SYSTEM; /// see `RavananBatch` and docs/ravanan-slurm.md. pub ravanan_batch: RavananBatch, + /// Which engine POST /compute/gemma uses: `slurm` (the default) runs the + /// same per-chromosome workflow /compute/gemma/ravanan does, one job per + /// chromosome on the cluster, and falls back to the in-process + /// gemma-wrapper run when that path answers 5xx -- Slurm or ravanan + /// unreachable, or the engine exiting non-zero. `local` always uses the + /// wrapper. Set via GEMMA_ENGINE. + /// + /// Slurm is the default because the workflow's results are keyed on + /// (script, inputs) -- the K matrix is one of the inputs -- while the + /// wrapper's GWA cache is keyed on the phenotype alone, so a rebuilt K + /// could leave stale association rows behind (measured: 2,060 of 21,055 + /// rows differed until that cache entry was cleared). + pub gemma_engine: String, /// Directory ravanan stages job scratch space in (its own --scratch /// switch). Only meaningful for the slurm backend, where it must be /// a path every compute node can write; defaults to /// `ravanan_cache_dir` when the backend is slurm. Empty means "do /// not pass --scratch" (single-machine's own default). pub ravanan_scratch: String, + /// The script that materialises a genotype file for a given + /// missing-data treatment (`PREPARE_GENOTYPES`). + pub prepare_genotypes: String, /// Path to scripts/rqtl_wrapper.R (copied here from GeneNetwork3) /// for POST /compute/rqtl. Defaults to that path relative to the /// working directory the server is started from. @@ -136,6 +188,9 @@ pub struct Config { pub fitqtl_script_path: String, /// Path to scripts/qtl2_scan.R, which POST /compute/qtl2 runs. pub qtl2_script_path: String, + /// The `.geno` -> qtl2-cross conversion, an R script (`Qt l2` owns its + /// own file format; see `src/qtl2.rs`). + pub qtl2_convert_script: String, /// Directory POST /compute/qtl2 keeps converted crosses and scan /// output in. Defaults to a "gn4-qtl2" directory under the temp dir. pub qtl2_cache_dir: String, @@ -175,6 +230,8 @@ pub struct Config { pub pca_plotter: String, /// Script that draws the clustered heatmap of a correlation matrix (HEATMAP_PLOTTER). pub heatmap_plotter: String, + /// Script that draws the scatter plot of a two-trait comparison (COMPARE_PLOTTER). + pub compare_plotter: String, /// Directory holding BNW's worked example datasets (`BNW_EXAMPLES_DIR`), /// served by `/compute/bnw/examples`. Empty means the endpoint reports /// that no examples are configured. @@ -285,6 +342,9 @@ impl Config { values.insert("SEARCH_ENGINE".to_string(), "forward".to_string()); values.insert("GN4_API_TOKENS_DB".to_string(), "tokens.sqlite".to_string()); values.insert("GEMMA_WRAPPER_CMD".to_string(), "gemma-wrapper".to_string()); + // Slurm by default: the per-chromosome workflow is the one whose + // results cannot go stale, and the local wrapper is the fallback. + values.insert("GEMMA_ENGINE".to_string(), "slurm".to_string()); values.insert( "GEMMA_CACHE_DIR".to_string(), std::env::temp_dir() @@ -303,6 +363,31 @@ impl Config { "cwl/gemma/manifest.scm".to_string(), ); values.insert( + "GEMMA_RAVANAN_WORKFLOW_MDB".to_string(), + "cwl/gemma/gemma-loco-mdb.scm".to_string(), + ); + values.insert( + "GEMMA_RAVANAN_MANIFEST_MDB".to_string(), + "cwl/gemma/manifest-mdb.scm".to_string(), + ); + values.insert( + "IMPUTE_SCRIPT".to_string(), + "scripts/qtl2-impute-bimbam.R".to_string(), + ); + values.insert("GENO2MDB_CMD".to_string(), "geno2mdb.py".to_string()); + values.insert( + "GEMMA_PREPARE_WORKFLOW".to_string(), + "cwl/gemma/prepare.scm".to_string(), + ); + values.insert( + "GEMMA_STORE_WORKFLOW".to_string(), + "cwl/gemma/store.scm".to_string(), + ); + values.insert( + "GEMMA_ARTIFACTS_MANIFEST".to_string(), + "cwl/gemma/manifest-artifacts.scm".to_string(), + ); + values.insert( "RAVANAN_CACHE_DIR".to_string(), std::env::temp_dir() .join("gn4-gemma-ravanan") @@ -313,6 +398,12 @@ impl Config { "RAVANAN_BATCH_SYSTEM".to_string(), "single-machine".to_string(), ); + // The one place where "how is a missing genotype treated?" is decided + // (`scripts/prepare-genotypes.sh`): mode none, mean or hmm. + values.insert( + "PREPARE_GENOTYPES".to_string(), + "scripts/prepare-genotypes.sh".to_string(), + ); // Only read when RAVANAN_BATCH_SYSTEM=slurm-api; left blank so // the single-machine default stays a zero-configuration path. values.insert("RAVANAN_SLURM_API_ENDPOINT".to_string(), String::new()); @@ -333,6 +424,10 @@ impl Config { "scripts/qtl2_scan.R".to_string(), ); values.insert( + "QTL2_CONVERT_SCRIPT".to_string(), + "scripts/qtl2-convert-geno.R".to_string(), + ); + values.insert( "QTL2_CACHE_DIR".to_string(), std::env::temp_dir() .join("gn4-qtl2") @@ -419,6 +514,10 @@ impl Config { "HEATMAP_PLOTTER".to_string(), "scripts/plot-heatmap.py".to_string(), ); + values.insert( + "COMPARE_PLOTTER".to_string(), + "scripts/plot-compare.py".to_string(), + ); // Per-user baskets: one SQLite file each (src/baskets.rs). Never // MariaDB -- a user's edited column is theirs. values.insert( @@ -464,9 +563,17 @@ impl Config { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", + "GENO2MDB_CMD", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -478,6 +585,7 @@ impl Config { "RQTL_WRAPPER_PATH", "FITQTL_SCRIPT_PATH", "QTL2_SCRIPT_PATH", + "QTL2_CONVERT_SCRIPT", "QTL2_CACHE_DIR", "RQTL_CACHE_DIR", "WIKIDATA_CACHE_DIR", @@ -487,6 +595,7 @@ impl Config { "GENOTYPE_PLOTTER", "PCA_PLOTTER", "HEATMAP_PLOTTER", + "COMPARE_PLOTTER", "BNW_CMD", "BNW_BIN_DIR", "BNW_CACHE_DIR", @@ -535,12 +644,40 @@ impl Config { ccwl_cmd: values["CCWL_CMD"].clone(), gemma_ravanan_workflow: values["GEMMA_RAVANAN_WORKFLOW"].clone(), gemma_ravanan_manifest: values["GEMMA_RAVANAN_MANIFEST"].clone(), + gemma_ravanan_workflow_mdb: values["GEMMA_RAVANAN_WORKFLOW_MDB"].clone(), + gemma_ravanan_manifest_mdb: values["GEMMA_RAVANAN_MANIFEST_MDB"].clone(), + impute_script: values["IMPUTE_SCRIPT"].clone(), + geno2mdb_cmd: values["GENO2MDB_CMD"].clone(), + gemma_prepare_workflow: values["GEMMA_PREPARE_WORKFLOW"].clone(), + gemma_store_workflow: values["GEMMA_STORE_WORKFLOW"].clone(), + gemma_artifacts_manifest: values["GEMMA_ARTIFACTS_MANIFEST"].clone(), ravanan_cache_dir: values["RAVANAN_CACHE_DIR"].clone(), ravanan_batch: parse_ravanan_batch(&values), + gemma_engine: values["GEMMA_ENGINE"].clone(), ravanan_scratch: values["RAVANAN_SCRATCH"].clone(), + prepare_genotypes: { + // A relative default is fine when the server runs from its + // checkout, and silently fatal when it does not (measured: an + // instance started elsewhere answered "could not run + // scripts/prepare-genotypes.sh"). The workflow path already + // points into that checkout, so it is used to locate the + // scripts directory when the relative name does not resolve. + let configured = values["PREPARE_GENOTYPES"].clone(); + let path = std::path::Path::new(&configured); + if path.is_absolute() || path.exists() { + configured + } else { + let workflow = std::path::Path::new(&values["GEMMA_RAVANAN_WORKFLOW"]); + match workflow.parent().and_then(|cwl| cwl.parent()).and_then(|repo| repo.parent()) { + Some(repo) => repo.join(&configured).to_string_lossy().into_owned(), + None => configured, + } + } + }, rqtl_wrapper_path: values["RQTL_WRAPPER_PATH"].clone(), fitqtl_script_path: values["FITQTL_SCRIPT_PATH"].clone(), qtl2_script_path: values["QTL2_SCRIPT_PATH"].clone(), + qtl2_convert_script: values["QTL2_CONVERT_SCRIPT"].clone(), qtl2_cache_dir: values["QTL2_CACHE_DIR"].clone(), rqtl_cache_dir: values["RQTL_CACHE_DIR"].clone(), wikidata_cache_dir: values["WIKIDATA_CACHE_DIR"].clone(), @@ -554,6 +691,7 @@ impl Config { bnw_plotter: values["BNW_PLOTTER"].clone(), pca_plotter: values["PCA_PLOTTER"].clone(), heatmap_plotter: values["HEATMAP_PLOTTER"].clone(), + compare_plotter: values["COMPARE_PLOTTER"].clone(), bnw_examples_dir: values["BNW_EXAMPLES_DIR"].clone(), bulklmm_cmd: values["BULKLMM_CMD"].clone(), bulklmm_env: values["BULKLMM_ENV"].clone(), @@ -795,9 +933,17 @@ mod tests { "GN4_API_TOKENS_DB", "GEMMA_WRAPPER_CMD", "GEMMA_CACHE_DIR", + "GEMMA_ENGINE", "RAVANAN_CMD", "CCWL_CMD", "GEMMA_RAVANAN_WORKFLOW", + "GEMMA_RAVANAN_WORKFLOW_MDB", + "GEMMA_RAVANAN_MANIFEST_MDB", + "IMPUTE_SCRIPT", + "GENO2MDB_CMD", + "GEMMA_PREPARE_WORKFLOW", + "GEMMA_STORE_WORKFLOW", + "GEMMA_ARTIFACTS_MANIFEST", "GEMMA_RAVANAN_MANIFEST", "RAVANAN_CACHE_DIR", "RAVANAN_BATCH_SYSTEM", @@ -841,6 +987,22 @@ mod tests { assert_eq!(config.ccwl_cmd, "ccwl"); assert_eq!(config.gemma_ravanan_workflow, "cwl/gemma/gemma-loco.scm"); assert_eq!(config.gemma_ravanan_manifest, "cwl/gemma/manifest.scm"); + assert_eq!( + config.gemma_ravanan_workflow_mdb, + "cwl/gemma/gemma-loco-mdb.scm" + ); + assert_eq!( + config.gemma_ravanan_manifest_mdb, + "cwl/gemma/manifest-mdb.scm" + ); + assert_eq!(config.impute_script, "scripts/qtl2-impute-bimbam.R"); + assert_eq!(config.geno2mdb_cmd, "geno2mdb.py"); + assert_eq!(config.gemma_prepare_workflow, "cwl/gemma/prepare.scm"); + assert_eq!(config.gemma_store_workflow, "cwl/gemma/store.scm"); + assert_eq!( + config.gemma_artifacts_manifest, + "cwl/gemma/manifest-artifacts.scm" + ); assert!(config.ravanan_cache_dir.ends_with("gn4-gemma-ravanan")); assert_eq!(config.rqtl_wrapper_path, "scripts/rqtl_wrapper.R"); assert!(config.rqtl_cache_dir.ends_with("gn4-rqtl")); diff --git a/src/gemma.rs b/src/gemma.rs index 02a2456..c49446f 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -18,6 +18,7 @@ use std::process::Output; use serde_json::Value; +use crate::response::StepTiming; use crate::streaming::{self, RunLogError}; /// One phenotype value per strain (genotype-file order), or `None` for @@ -73,8 +74,12 @@ impl std::fmt::Display for GemmaError { GemmaError::Spawn { command, error } => { write!(f, "failed to run {command}: {error}") } + // The step already names its tool: gemma-wrapper's own steps are + // prefixed, and the ones that are not its (geno2mdb, ccwl compile) + // would otherwise be blamed on the wrapper -- which is what a + // missing numpy in the store builder once looked like. GemmaError::CommandFailed { step, stderr } => { - write!(f, "gemma-wrapper ({step}) failed: {stderr}") + write!(f, "{step} failed: {stderr}") } GemmaError::WrapperError { step, detail } => { write!(f, "gemma-wrapper ({step}) reported an error: {detail}") @@ -744,7 +749,7 @@ async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Resu .map_err(GemmaError::Io)?; if !output.status.success() { return Err(GemmaError::CommandFailed { - step: "extract-archive", + step: "gemma-wrapper extract-archive", stderr: String::from_utf8_lossy(&output.stderr).into_owned(), }); } @@ -786,6 +791,279 @@ pub struct GemmaOutput { pub columns: Vec<String>, pub rows: Value, pub notes: Vec<String>, + /// Per-step compute times read out of the steps' own logs. + pub steps: Vec<StepTiming>, + /// How long the ravanan invocation took, in ms. + pub workflow_ms: u64, + /// How long reading the engine's outputs took, in ms. + pub parse_ms: u64, +} + +/// The compute time a step's own log reports, in ms. +/// +/// GEMMA and pangemma both write "## total computation time = <n> min" into the +/// per-chromosome log, so this is the engine's own figure for that step -- not +/// a wall-clock estimate that includes staging, dispatch or archive handling. +/// A cached step's log is still in ravanan's store, with the figure from when +/// it ran, which is why the caller labels the step `cached`. +fn step_compute_ms(log: &str) -> Option<u64> { + let minutes_of = |text: &str| -> Option<f64> { + text.split('=') + .nth(1)? + .trim() + .trim_end_matches("min") + .trim() + .parse() + .ok() + }; + let mut total: Option<f64> = None; + let mut breakdown = 0.0f64; + let mut saw_breakdown = false; + for line in log.lines() { + let line = line.trim(); + if let Some(rest) = line.strip_prefix("## total computation time") { + total = minutes_of(rest); + } else if line.starts_with("##") && line.ends_with("min") && line.contains('=') { + // "## time on calculating relatedness matrix = 0.0783561 min". + // GEMMA's *total* is unreliable for -gk (it prints 0 while the + // breakdown says 0.078 min), so the parts are summed as well and + // the larger of the two wins. + if let Some(minutes) = minutes_of(line) { + breakdown += minutes; + saw_breakdown = true; + } + } + } + let minutes = match (total, saw_breakdown) { + (Some(total), true) => total.max(breakdown), + (Some(total), false) => total, + (None, true) => breakdown, + (None, false) => return None, + }; + // A real computation never takes exactly nothing; an engine that reports + // neither figure is unknown, not instant. + if minutes <= 0.0 { + return None; + } + Some((minutes * 60_000.0).round() as u64) +} + +/// The chromosome a step's log file was written for: the workflow names each +/// one `<chr>-<step>.log.txt` (`9-gwa.log.txt`, `X-kin.log.txt`). +fn step_chromosome(path: &str, step: &str, suffix: &str) -> Option<String> { + let name = Path::new(path).file_name()?.to_string_lossy(); + // "<chr>-<step>.log.txt": strip the step as well, or every scattered log + // looks as if its chromosome were "9-gwa" (and is rejected for the hyphen). + let marker = format!("-{step}{suffix}"); + let stem = name + .strip_suffix(&marker) + .map(str::to_string) + .or_else(|| name.strip_suffix(suffix).map(str::to_string))?; + if stem.is_empty() || stem.contains('-') { + // "kin"/"gwa" are the only hyphen-free steps we name this way; a + // chromosome never contains '-' but a key can, so be strict. + return None; + } + Some(stem) +} + +/// The kinship step behind one GWA log: its store key and the chromosome. +/// +/// GEMMA prints the command line it ran, and the wrapper's `-k` names the K +/// file it was given -- ravanan stages that from the kinship step's own store +/// directory, so the path carries both the step's key ("<key>-kinship") and the +/// chromosome ("<chr>-kin.cXX.txt"). That is how a *cached* kinship step can be +/// reported: its log is not a workflow output (ccwl's `pipe` publishes only the +/// last step's), and a cached step submitted no job to trace it by. +fn kinship_of_gwa_log(path: &str) -> Option<(String, String)> { + let log = std::fs::read_to_string(path).ok()?; + let line = log + .lines() + .find(|line| line.contains("Command Line Input"))?; + let mut words = line.split_whitespace(); + while let Some(word) = words.next() { + if word != "-k" { + continue; + } + let kpath = Path::new(words.next()?); + let chr = kpath + .file_name()? + .to_string_lossy() + .split("-kin") + .next()? + .to_string(); + let key = kpath + .parent()? + .file_name()? + .to_string_lossy() + .strip_suffix("-kinship")? + .to_string(); + if chr.is_empty() || key.is_empty() { + return None; + } + return Some((key, chr)); + } + None +} + +/// [`step_timings`], with each step's state taken from its log's mtime: a log +/// older than the request was not written by it, so ravanan answered that step +/// from its store. +fn step_timings_stateful( + paths: &[&str], + step: &str, + suffix: &str, + request_started: std::time::SystemTime, +) -> Vec<StepTiming> { + paths + .iter() + .filter_map(|path| { + let log = std::fs::read_to_string(path).ok()?; + let ran_now = std::fs::metadata(path) + .and_then(|metadata| metadata.modified()) + .map(|modified| modified >= request_started) + .unwrap_or(false); + Some(StepTiming { + step: step.to_string(), + chr: step_chromosome(path, step, suffix), + compute_ms: step_compute_ms(&log), + state: if ran_now { "ran" } else { "cached" }.to_string(), + }) + }) + .collect() +} + +/// One [`StepTiming`] per log file handed in, in the order given. +fn step_timings(paths: &[&str], step: &str, suffix: &str, state: &str) -> Vec<StepTiming> { + paths + .iter() + .filter_map(|path| { + let log = std::fs::read_to_string(path).ok()?; + Some(StepTiming { + step: step.to_string(), + chr: step_chromosome(path, step, suffix), + compute_ms: step_compute_ms(&log), + state: state.to_string(), + }) + }) + .collect() +} + +/// What Slurm did for this request: the jobs it accepted since `since` +/// (epoch seconds), and their queue and run times. +/// +/// Ravanan's store records no job ids and Slurm's job record carries neither a +/// stdout path nor the scattered input, so the only join available without +/// ravanan's help is the job *name* -- which this deployment's patched ravanan +/// sets to the step's store basename. Only the aggregate is reported here; +/// the per-step figures come from the engines' own logs. +pub async fn cluster_timing( + batch: &crate::config::RavananBatch, + since_epoch: u64, + store: &str, +) -> (Option<crate::response::ClusterTiming>, Vec<StepTiming>) { + let crate::config::RavananBatch::SlurmApi { + endpoint, jwt_file, .. + } = batch + else { + return (None, Vec::new()); + }; + let Some(jwt) = std::fs::read_to_string(jwt_file) + .ok() + .map(|jwt| jwt.trim().to_string()) + else { + return (None, Vec::new()); + }; + let store = store.to_string(); + let url = format!( + "{}/slurm/v0.0.41/jobs", + endpoint.trim_end_matches('/') + ); + let mut request = reqwest::Client::new() + .get(&url) + .header("X-SLURM-USER-TOKEN", jwt) + .header( + "X-SLURM-USER-NAME", + std::env::var("SLURM_USER").unwrap_or_else(|_| "testuser".to_string()), + ) + .header("Accept", "application/json"); + if let Ok(timeout) = std::env::var("SLURM_TIMEOUT_SECS") { + if let Ok(seconds) = timeout.parse::<u64>() { + request = request.timeout(std::time::Duration::from_secs(seconds)); + } + } + let Ok(response) = request.timeout(std::time::Duration::from_secs(10)).send().await else { + return (None, Vec::new()); + }; + let Ok(body) = response.text().await else { + return (None, Vec::new()); + }; + let Ok(json) = serde_json::from_str::<Value>(&body) else { + return (None, Vec::new()); + }; + let number = |value: &Value, key: &str| -> Option<u64> { + value + .get(key) + .and_then(|v| v.get("number").and_then(Value::as_u64)) + }; + let mut timing = crate::response::ClusterTiming::default(); + let (mut run_sum, mut run_max, mut queue_sum) = (0u64, 0u64, 0u64); + let Some(jobs) = json.get("jobs").and_then(Value::as_array) else { + return (None, Vec::new()); + }; + let mut steps = Vec::new(); + for job in jobs { + let Some(submit) = number(job, "submit_time") else { + continue; + }; + if submit < since_epoch { + continue; + } + timing.jobs_submitted += 1; + // The job's name is the step's store basename ("<key>-<step>"), so its + // outputs -- and the log with the engine's own compute time -- are one + // directory away. This is the only way to a *scattered* step's figures + // when its log is not a workflow output (kinship's is not). + if let Some(name) = job.get("name").and_then(Value::as_str) { + let dir = Path::new(&store).join("files").join(name); + if let Ok(entries) = std::fs::read_dir(&dir) { + for entry in entries.flatten() { + let path = entry.path(); + let file = path.to_string_lossy().into_owned(); + if !file.ends_with(".log.txt") { + continue; + } + let step = if name.ends_with("-kinship") { + "kinship" + } else if name.ends_with("-gwa") { + "gwa" + } else { + continue; + }; + if let Ok(log) = std::fs::read_to_string(&path) { + steps.push(StepTiming { + step: step.to_string(), + chr: step_chromosome(&file, step, ".log.txt"), + compute_ms: step_compute_ms(&log), + state: "ran".to_string(), + }); + } + } + } + } + if let Some(start) = number(job, "start_time") { + queue_sum += start.saturating_sub(submit) * 1000; + if let Some(end) = number(job, "end_time") { + let run = end.saturating_sub(start) * 1000; + run_sum += run; + run_max = run_max.max(run); + } + } + } + timing.run_ms_sum = Some(run_sum); + timing.run_ms_max = Some(run_max); + timing.queue_ms_sum = Some(queue_sum); + (Some(timing), steps) } /// The gemma-wrapper arguments for the kinship step, shared between the @@ -991,7 +1269,7 @@ pub async fn compute( .get("archive") .and_then(Value::as_str) .ok_or_else(|| GemmaError::WrapperError { - step: "gwa", + step: "gemma-wrapper gwa", detail: "gemma-wrapper's response did not list an output archive".to_string(), })?; let extract_dir = Path::new(cache_dir).join(format!("{unique}-gwa-extract")); @@ -1012,6 +1290,12 @@ pub async fn compute( columns, rows: Value::Array(rows), notes: output_notes, + // The wrapper path reports its own timings in its JSON record and + // the route times the call as a whole; the per-step figures are a + // ravanan-path thing (one process ran everything here). + steps: Vec::new(), + workflow_ms: 0, + parse_ms: 0, }) } .await; @@ -1033,10 +1317,23 @@ pub async fn compute( /// `{"<output id>": [{"class": "File", "path": ..., ...}, ...], ...}`, /// one entry per `cwl/gemma/gemma-loco.scm` chromosome). fn ravanan_output_paths<'a>(outputs: &'a Value, id: &str) -> Result<Vec<&'a str>, GemmaError> { - let files = outputs - .get(id) - .and_then(Value::as_array) - .ok_or_else(|| GemmaError::RavananOutput(format!("no \"{id}\" array in ravanan's output")))?; + let Some(value) = outputs.get(id) else { + return Err(GemmaError::RavananOutput(format!( + "no \"{id}\" in ravanan's output" + ))); + }; + // A scattered step's output is an array of Files; a single-step workflow's + // is one File object. Both are outputs here -- the mapping workflows + // scatter over chromosomes, the artifact ones (prepare, store) do not. + let files: Vec<&Value> = match value { + Value::Array(items) => items.iter().collect(), + Value::Object(_) => vec![value], + _ => { + return Err(GemmaError::RavananOutput(format!( + "\"{id}\" in ravanan's output is neither a File nor an array of them" + ))) + } + }; files .iter() .map(|file| { @@ -1181,7 +1478,7 @@ fn check_workflow_inputs(compiled_path: &Path, supplied: &[&str]) -> Result<(), /// file, interned verbatim into ravanan's store). The SNP file is hashed, /// because the chromosome list -- and therefore the whole scatter -- comes /// from it. -fn sha16(material: &[u8]) -> String { +pub fn sha16(material: &[u8]) -> String { crate::indexer::sha256::hex_digest(material)[..16].to_string() } @@ -1255,8 +1552,18 @@ fn trait_input_key(kinship_key: &str, trait_values: &TraitValues) -> String { fn chromosomes_from(contents: &str) -> Vec<String> { let mut seen = std::collections::HashSet::new(); let mut chromosomes = Vec::new(); + // The SNP map is `marker, pos, chr` in the panel's own files (spaces after + // the commas) and `marker,pos,chr` in the ones scripts/qtl2-impute-bimbam.R + // writes. Splitting on whitespace alone read the second form as one token + // and returned no chromosomes at all, which reaches ravanan as an empty + // scatter and comes back as "no association output files" -- a genotype + // problem that was really a delimiter problem. for line in contents.lines() { - if let Some(chr) = line.split_whitespace().nth(2) { + let fields: Vec<&str> = line + .split(|c: char| c.is_whitespace() || c == ',') + .filter(|field| !field.is_empty()) + .collect(); + if let Some(chr) = fields.get(2) { if seen.insert(chr.to_string()) { chromosomes.push(chr.to_string()); } @@ -1265,24 +1572,307 @@ fn chromosomes_from(contents: &str) -> Vec<String> { chromosomes } +/// Which mapping engine the per-chromosome workflow runs. +/// +/// The two are the same computation through the same CWL shape (kinship per +/// chromosome, then GWA per chromosome) and differ only in what reads the +/// genotypes: `gemma` parses BIMBAM text every invocation and needs the +/// `-a` annotation to know which markers to leave out, while `pangemma` +/// reads an lmdb store whose keys carry the chromosome, so it needs neither. +/// The store is built once per panel (see cwl/gemma/store.scm) and is what makes +/// pangemma cheaper at scale -- measured on HLC (358,454 markers): 141 s of +/// cluster job time against 958 s for gemma on BIMBAM. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum GemmaEngine { + /// gemma-gn2 on BIMBAM: `-g` plus the `-a` annotation. + Gemma, + /// pangemma on an lmdb store: one `store` input, no BIMBAM parse, no `-a`. + Pangemma, +} + +impl GemmaEngine { + /// Parse the request's `engine` value; `None` for anything unknown. + pub fn parse(value: &str) -> Option<GemmaEngine> { + match value.trim().to_ascii_lowercase().as_str() { + "gemma" | "gemma-gn2" => Some(GemmaEngine::Gemma), + "pangemma" | "pangemma-lmdb" => Some(GemmaEngine::Pangemma), + _ => None, + } + } + + pub const fn as_str(self) -> &'static str { + match self { + GemmaEngine::Gemma => "gemma", + GemmaEngine::Pangemma => "pangemma", + } + } + + /// The compiled-CWL suffix, so the two engines never share one artifact. + const fn cwl_suffix(self) -> &'static str { + match self { + GemmaEngine::Gemma => "gemma-loco", + GemmaEngine::Pangemma => "gemma-loco-mdb", + } + } + + /// The inputs this engine's ccwl workflow declares, which is what the + /// pre-flight check in `check_workflow_inputs` compares against. + pub const fn workflow_inputs(self) -> &'static [&'static str] { + match self { + GemmaEngine::Gemma => &[ + "genotype_file", + "pheno_file", + "kinship_pheno_file", + "snps_file", + "lmm", + "chromosomes", + ], + GemmaEngine::Pangemma => &[ + "store", + "pheno_file", + "kinship_pheno_file", + "lmm", + "chromosomes", + ], + } + } +} + +/// The per-chromosome workflow to run and the engine behind it: what a +/// deployment pins in `GEMMA_RAVANAN_WORKFLOW`/`_MANIFEST` (gemma) and their +/// `_MDB` twins (pangemma). +pub struct RavananWorkflow<'a> { + pub engine: GemmaEngine, + /// The ccwl source compiled to CWL before every run. + pub source: &'a str, + /// The Guix manifest ravanan resolves the steps' commands against. + pub manifest: &'a str, +} + +/// A note's worth of text with absolute paths reduced to their file names. +/// +/// A reply is read in chats and pasted into repositories; the server's own +/// `/gnu/store/...` and `/home/wrk/...` paths are implementation detail, and +/// they were reaching callers through the ravanan command line. The name is +/// kept -- which ravanan, which workflow, which store -- and only the +/// directory is dropped. +pub fn redact_paths(text: &str) -> String { + /// The file name of an absolute path, so "which tool, which file" survives + /// the redaction and only the directory goes. + fn short(path: &str) -> String { + Path::new(path) + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_else(|| path.to_string()) + } + text.split_whitespace() + .map(|token| { + // A wrapper around a path: "ravanan (/gnu/store/...-ravanan", + // "(/home/wrk/...)", "--store=/home/wrk/...". + let is_edge = |c: char| matches!(c, ',' | ';' | ')' | '(' | '[' | ']' | '"' | '\''); + let inner = token.trim_matches(is_edge); + if let Some((flag, value)) = inner.split_once('=') { + if value.starts_with('/') { + return token.replace(inner, &format!("{flag}={}", short(value))); + } + } + if inner.starts_with('/') { + return token.replace(inner, &short(inner)); + } + token.to_string() + }) + .collect::<Vec<_>>() + .join(" ") +} + +/// What running an artifact workflow needs: the ccwl source, the manifest its +/// jobs resolve against, ravanan's own switches, and the outputs wanted. +/// +/// The two artifacts -- the missing-genotype treatment (`prepare.scm`) and +/// pangemma's lmdb store (`store.scm`) -- are workflows of their own rather +/// than steps inside the mapping workflows, because ccwl's `pipe` is linear: +/// the GWA step needs the prepared genotypes *and* the kinship matrix, and a +/// step sees only the immediately preceding step's outputs. Chaining +/// workflows is what that diamond becomes; ravanan caches each of them on +/// (script, inputs), so each artifact is still built once. +pub struct ArtifactWorkflow<'a> { + /// "prepare" or "store", for the compiled artifact's name and for errors. + pub label: &'a str, + pub ccwl_cmd: &'a str, + pub ravanan_cmd: &'a str, + pub batch: &'a crate::config::RavananBatch, + pub source: &'a str, + pub manifest: &'a str, + pub cache_dir: &'a str, + pub scratch_dir: &'a str, +} + +/// Run one artifact workflow and return its outputs by id. +/// +/// The inputs YAML's own hash names the staged file, so two concurrent +/// identical requests share one and different ones cannot collide -- the same +/// convention the mapping workflow uses for its phenotype files. +pub async fn run_artifact( + run: &ArtifactWorkflow<'_>, + supplied: &[&str], + inputs_yaml: &str, + output_ids: &[&str], +) -> Result<Vec<(String, Vec<String>)>, GemmaError> { + std::fs::create_dir_all(run.cache_dir).map_err(GemmaError::Io)?; + let workflow = workflow_key(run.source); + let compiled_path = Path::new(run.cache_dir).join(format!("{workflow}-{}.cwl", run.label)); + let compiled_tmp = Path::new(run.cache_dir) + .join(format!("{workflow}-{}.tmp-{}.cwl", run.label, std::process::id())); + let ccwl_output_arg = format!("--output={}", compiled_tmp.display()); + let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), run.source]; + let ccwl_output = streaming::run_streaming(run.ccwl_cmd, &ccwl_args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ccwl_cmd.to_string(), + error, + })?; + if !ccwl_output.status.success() { + return Err(GemmaError::CommandFailed { + step: "ccwl compile", + stderr: String::from_utf8_lossy(&ccwl_output.stderr).into_owned(), + }); + } + std::fs::rename(&compiled_tmp, &compiled_path).map_err(GemmaError::Io)?; + check_workflow_inputs(&compiled_path, supplied)?; + + let key = sha16(inputs_yaml.as_bytes()); + let inputs_path = + Path::new(run.cache_dir).join(format!("{key}-{}-inputs.yaml", run.label)); + if !inputs_path.is_file() { + let inputs_tmp = Path::new(run.cache_dir).join(format!( + "{key}-{}-inputs.tmp-{}.yaml", + run.label, + std::process::id() + )); + std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?; + std::fs::rename(&inputs_tmp, &inputs_path).map_err(GemmaError::Io)?; + } + + let store_dir = Path::new(run.cache_dir).join("ravanan-store"); + for subdir in ["files", "logs", "data"] { + std::fs::create_dir_all(store_dir.join(subdir)).map_err(GemmaError::Io)?; + } + let scratch = if run.scratch_dir.is_empty() { + run.cache_dir + } else { + run.scratch_dir + }; + let store_arg = format!("--store={}", store_dir.display()); + let manifest_arg = format!("--guix-manifest={}", run.manifest); + let compiled_arg = compiled_path.to_string_lossy().into_owned(); + let inputs_arg = inputs_path.to_string_lossy().into_owned(); + let mut args = vec![ + store_arg.as_str(), + manifest_arg.as_str(), + compiled_arg.as_str(), + inputs_arg.as_str(), + ]; + let batch_args = run.batch.ravanan_args(scratch); + args.extend(batch_args.iter().map(String::as_str)); + // GUIX_PACKAGE_PATH stays set. Clearing it saves ~4 s of Guile per + // artifact call (guix autoloads guix-bioinformatics' module tree, one ABI + // mismatch warning per module) -- but a manifest may name a package that + // only exists in the channel, which is exactly what happened when the store + // step moved to gemma-wrapper's geno2mdb: with the variable cleared the + // job died with "gemma-wrapper: unknown package" before a single marker was + // read. Correctness over four seconds, and the artifact memo means most + // requests never pay it at all. + let output = streaming::run_streaming(run.ravanan_cmd, &args, None) + .await + .map_err(|error| GemmaError::Spawn { + command: run.ravanan_cmd.to_string(), + error, + })?; + if !output.status.success() { + return Err(GemmaError::RavananFailed(format!( + "{} ({})", + run.label, + String::from_utf8_lossy(&output.stderr) + ))); + } + let outputs: Value = serde_json::from_str(&String::from_utf8_lossy(&output.stdout)) + .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?; + let mut found = Vec::new(); + for id in output_ids { + let paths = ravanan_output_paths(&outputs, id)?; + if paths.is_empty() { + return Err(GemmaError::WrapperError { + step: "artifact workflow", + detail: format!("{} produced no '{id}'", run.label), + }); + } + found.push((id.to_string(), paths.into_iter().map(str::to_string).collect())); + } + Ok(found) +} + +/// The ravanan inputs YAML for one engine: same fields the workflow declares, +/// and the store stands exactly where `genotype_file`/`snps_file` would. +fn ravanan_inputs_yaml( + engine: GemmaEngine, + genotype_file: &str, + snps_file: &str, + store_path: Option<&Path>, + pheno_path: &Path, + kinship_pheno_path: &Path, + lmm: u8, + chromosomes_yaml: &str, +) -> String { + match engine { + GemmaEngine::Gemma => format!( + "genotype_file: {{class: File, path: {genotype_file}}}\n\ + pheno_file: {{class: File, path: {}}}\n\ + kinship_pheno_file: {{class: File, path: {}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n\ + lmm: \"{lmm}\"\n\ + chromosomes: [{chromosomes_yaml}]\n", + pheno_path.display(), + kinship_pheno_path.display(), + ), + GemmaEngine::Pangemma => format!( + "store: {{class: File, path: {}}}\n\ + pheno_file: {{class: File, path: {}}}\n\ + kinship_pheno_file: {{class: File, path: {}}}\n\ + lmm: \"{lmm}\"\n\ + chromosomes: [{chromosomes_yaml}]\n", + store_path + .map(|path| path.display().to_string()) + .unwrap_or_default(), + pheno_path.display(), + kinship_pheno_path.display(), + ), + } +} + /// The same GEMMA `--loco` kinship-then-GWA computation as `compute`, /// but run via `ravanan` (https://github.com/vepiteski/ravanan) driving /// a CWL workflow compiled from the ccwl (https://ccwl.systemreboot.net/) -/// source at `workflow_scm_path` (see `cwl/gemma/gemma-loco.scm`). +/// source at `workflow.source` (see `cwl/gemma/gemma-loco.scm` and its +/// pangemma twin `cwl/gemma/gemma-loco-mdb.scm`). /// -/// This runner invokes **gemma itself**, one invocation per -/// chromosome, relying on `-loco <chr>` being native to 0.98.6 for both -/// `-gk` and `-lmm` -- where `compute` still drives gemma-wrapper. That +/// This runner invokes **gemma itself** (or pangemma), one invocation per +/// chromosome, relying on `-loco <chr>` being native to both for `-gk` +/// and `-lmm` -- where `compute` still drives gemma-wrapper. That /// is deliberate: it is what makes the two endpoints comparable, the /// same computation through two stacks, and the day the numbers stop /// agreeing the difference is visible rather than assumed away. -/// Backs `POST /compute/gemma/ravanan`. +/// Backs `POST /compute/gemma/ravanan`, and is the engine behind +/// `/compute/gemma` unless `GEMMA_ENGINE=local`. pub async fn compute_ravanan( ravanan_cmd: &str, batch: &crate::config::RavananBatch, ccwl_cmd: &str, - workflow_scm_path: &str, - manifest_path: &str, + workflow: &RavananWorkflow<'_>, + // pangemma only: the lmdb store built by the store workflow. + store: Option<&str>, + // When the request started, so a step whose log predates it can be + // reported as cached rather than as work this request did. + request_started: std::time::SystemTime, cache_dir: &str, scratch_dir: &str, genotype_file: &str, @@ -1302,9 +1892,12 @@ pub async fn compute_ravanan( // Two keys, not one: the kinship step is keyed on the *individual set* // only (see `kinship_input_key`), so a second trait over the same animals // reuses all twenty K matrices, and only the GWA step's inputs change. + let engine = workflow.engine; + let workflow_scm_path = workflow.source; + let manifest_path = workflow.manifest; let kinship_key = kinship_input_key(genotype_file, snps_file, trait_values, lmm); let trait_key = trait_input_key(&kinship_key, trait_values); - let workflow = workflow_key(workflow_scm_path); + let workflow_hash = workflow_key(workflow_scm_path); // A constant-valued phenotype file with the trait's missing-data pattern: // what the kinship step gets, so its files are the same for every trait @@ -1330,13 +1923,14 @@ pub async fn compute_ravanan( // call (cheap: ccwl compile is pure macro expansion, no Guix build // involved) and never checked into the repo -- see the doc comment // on Config::gemma_ravanan_workflow. + let cwl_suffix = engine.cwl_suffix(); let compiled_workflow_path = - Path::new(cache_dir).join(format!("{workflow}-gemma-loco.cwl")); + Path::new(cache_dir).join(format!("{workflow_hash}-{cwl_suffix}.cwl")); // Compile to a per-process path and rename: the compiled CWL is // deterministic, so two concurrent identical requests would otherwise // race on the same file. - let compiled_tmp = - Path::new(cache_dir).join(format!("{workflow}-gemma-loco.tmp-{}.cwl", std::process::id())); + let compiled_tmp = Path::new(cache_dir) + .join(format!("{workflow_hash}-{cwl_suffix}.tmp-{}.cwl", std::process::id())); let ccwl_output_arg = format!("--output={}", compiled_tmp.display()); let ccwl_args = vec!["compile", ccwl_output_arg.as_str(), workflow_scm_path]; let ccwl_output = streaming::run_streaming(ccwl_cmd, &ccwl_args, None) @@ -1354,17 +1948,7 @@ pub async fn compute_ravanan( std::fs::rename(&compiled_tmp, &compiled_workflow_path).map_err(GemmaError::Io)?; // Before anything is staged for ravanan: does the workflow in this // deployment's checkout take what this build is about to send it? - check_workflow_inputs( - &compiled_workflow_path, - &[ - "genotype_file", - "pheno_file", - "kinship_pheno_file", - "snps_file", - "lmm", - "chromosomes", - ], - )?; + check_workflow_inputs(&compiled_workflow_path, engine.workflow_inputs())?; let compiled_workflow_arg = compiled_workflow_path.to_string_lossy().into_owned(); let store_dir = Path::new(cache_dir).join("ravanan-store"); @@ -1385,23 +1969,28 @@ pub async fn compute_ravanan( .collect::<Vec<_>>() .join(", "); + // pangemma reads an lmdb store instead of BIMBAM plus its annotation; the + // caller has already had it built (cwl/gemma/store.scm), and ravanan's + // store holds it, so this is just the path. + let store_path = store.map(Path::new); + let store_note = store_path.map(|path| { + redact_paths(&format!("pangemma's lmdb genotype store: {}", path.display())) + }); + let inputs_yaml_path = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.yaml")); let inputs_tmp = Path::new(cache_dir).join(format!("{trait_key}-ravanan-inputs.tmp-{}.yaml", std::process::id())); - std::fs::write( - &inputs_tmp, - format!( - "genotype_file: {{class: File, path: {genotype_file}}}\n\ - pheno_file: {{class: File, path: {}}}\n\ - kinship_pheno_file: {{class: File, path: {}}}\n\ - snps_file: {{class: File, path: {snps_file}}}\n\ - lmm: \"{lmm}\"\n\ - chromosomes: [{chromosomes_yaml}]\n", - pheno_path.display(), - kinship_pheno_path.display(), - ), - ) - .map_err(GemmaError::Io)?; + let inputs_yaml = ravanan_inputs_yaml( + engine, + genotype_file, + snps_file, + store_path, + &pheno_path, + &kinship_pheno_path, + lmm, + &chromosomes_yaml, + ); + std::fs::write(&inputs_tmp, inputs_yaml).map_err(GemmaError::Io)?; std::fs::rename(&inputs_tmp, &inputs_yaml_path).map_err(GemmaError::Io)?; let store_arg = format!("--store={}", store_dir.display()); @@ -1429,27 +2018,41 @@ pub async fn compute_ravanan( ]; let batch_args = batch.ravanan_args(scratch); args.extend(batch_args.iter().map(String::as_str)); - let ravanan_note = format!( + let ravanan_note = redact_paths(&format!( "ravanan ({ravanan_cmd}, {} backend): {}", match batch { crate::config::RavananBatch::SingleMachine => "single-machine", crate::config::RavananBatch::SlurmApi { .. } => "slurm-api", }, args.join(" ") - ); + )); let chromosomes_note = format!( - "Scattered gemma itself over {} chromosome(s) via CWL scatter, one \ + "Scattered {} itself over {} chromosome(s) via CWL scatter, one \ invocation per chromosome: {}", + engine.as_str(), chromosomes.len(), chromosomes.join(", "), ); + // Which engine ran, and for pangemma where its genotypes came from: the + // two produce identical rows on the same input, so without this a reply + // cannot say which cost its caller what. + let engine_note = match (&store_note, engine) { + (Some(note), _) => Some(format!( + "Engine: {} reads its genotypes from an lmdb store rather than BIMBAM ({note})", + engine.as_str() + )), + (None, GemmaEngine::Pangemma) => None, + (None, GemmaEngine::Gemma) => None, + }; + let workflow_started = std::time::Instant::now(); let output = streaming::run_streaming(ravanan_cmd, &args, log_path.as_deref()) .await .map_err(|error| GemmaError::Spawn { command: ravanan_cmd.to_string(), error, })?; + let workflow_ms = workflow_started.elapsed().as_millis() as u64; if !output.status.success() { return Err(GemmaError::RavananFailed( String::from_utf8_lossy(&output.stderr).into_owned(), @@ -1459,6 +2062,7 @@ pub async fn compute_ravanan( .map_err(|e| GemmaError::RavananOutput(format!("could not parse ravanan's stdout: {e}")))?; let assoc_paths = ravanan_output_paths(&outputs, "assoc")?; let gwa_log_paths = ravanan_output_paths(&outputs, "gwa_log")?; + let kinship_log_paths = ravanan_output_paths(&outputs, "kinship_log").unwrap_or_default(); if assoc_paths.is_empty() { return Err(GemmaError::NoAssocFiles); } @@ -1466,6 +2070,7 @@ pub async fn compute_ravanan( // One .assoc.txt and one .log.txt per chromosome, straight from the // workflow's own outputs: gemma writes named files (`-o <chr>-gwa`), so // there is no wrapper JSON record to parse and no archive to unpack. + let parse_started = std::time::Instant::now(); let mut columns = Vec::new(); let mut rows = Vec::new(); for assoc_path in &assoc_paths { @@ -1476,9 +2081,48 @@ pub async fn compute_ravanan( } rows.extend(file_rows.into_iter().map(Value::Array)); } + let parse_ms = parse_started.elapsed().as_millis() as u64; // `-pve` puts the variance components in each job's .log.txt, which the // workflow returns as a first-class output. let components = read_variance_components_from_log_files(&gwa_log_paths); + // Per-step figures from the engines' own logs, with the state taken from + // each log's mtime: a log older than the request is a step ravanan reused. + let mut steps = step_timings_stateful(&gwa_log_paths, "gwa", ".log.txt", request_started); + steps.extend(step_timings_stateful( + &kinship_log_paths, + "kinship", + ".log.txt", + request_started, + )); + // The kinship step's log is not a workflow output, so its figure is taken + // from the store directory its own GWA job pointed at. + for gwa_log in &gwa_log_paths { + let Some((key, chr)) = kinship_of_gwa_log(gwa_log) else { + continue; + }; + let kin_log = Path::new(cache_dir) + .join("ravanan-store") + .join("files") + .join(format!("{key}-kinship")) + .join(format!("{chr}-kin.log.txt")); + let Ok(log) = std::fs::read_to_string(&kin_log) else { + continue; + }; + let ran_now = std::fs::metadata(&kin_log) + .and_then(|metadata| metadata.modified()) + .map(|modified| modified >= request_started) + .unwrap_or(false); + steps.push(StepTiming { + step: "kinship".to_string(), + chr: Some(chr), + compute_ms: step_compute_ms(&log), + state: if ran_now { "ran" } else { "cached" }.to_string(), + }); + } + steps.sort_by(|a, b| { + (a.step.as_str(), a.chr.as_deref().unwrap_or("")) + .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or(""))) + }); streaming::mark_complete(&log_path); @@ -1501,8 +2145,13 @@ pub async fn compute_ravanan( let mut notes = vec![ ravanan_note, chromosomes_note, - format!("workflow: {workflow_scm_path} (compiled to {compiled_workflow_arg})"), + redact_paths(&format!( + "workflow: {workflow_scm_path} (compiled to {compiled_workflow_arg})" + )), ]; + if let Some(note) = engine_note { + notes.push(note); + } notes.extend(ephemeral_note); if let Some(note) = variance_components_note(&components) { notes.push(note); @@ -1513,6 +2162,9 @@ pub async fn compute_ravanan( columns, rows: Value::Array(rows), notes, + steps, + workflow_ms, + parse_ms, }) } @@ -1857,10 +2509,7 @@ mod tests { let err = parse_wrapper_output("kinship", output).unwrap_err(); assert!(matches!( err, - GemmaError::WrapperError { - step: "kinship", - .. - } + GemmaError::WrapperError { step: "kinship", .. } )); assert_eq!( err.to_string(), @@ -2030,3 +2679,124 @@ FATAL ERROR: gemma-wrapper bailed out with pid 42 exit 130 assert!(got.contains("bailed out"), "{got}"); } } + +#[cfg(test)] +mod engine_tests { + use super::*; + + // ---- the two engines ---------------------------------------------------- + + #[test] + fn the_engines_parse_and_declare_their_own_inputs() { + assert_eq!(GemmaEngine::parse("pangemma"), Some(GemmaEngine::Pangemma)); + assert_eq!(GemmaEngine::parse(" GEMMA "), Some(GemmaEngine::Gemma)); + // Not an engine, and not silently gemma either. + assert_eq!(GemmaEngine::parse("gemma-wrapper"), None); + assert_eq!(GemmaEngine::parse(""), None); + + let gemma = GemmaEngine::Gemma.workflow_inputs(); + assert!(gemma.contains(&"genotype_file")); + assert!(gemma.contains(&"snps_file")); + let pangemma = GemmaEngine::Pangemma.workflow_inputs(); + assert!(pangemma.contains(&"store")); + // The store replaces both BIMBAM inputs; a workflow declaring `store` + // cannot be handed them, which is what the pre-flight check enforces. + assert!(!pangemma.contains(&"genotype_file")); + assert!(!pangemma.contains(&"snps_file")); + assert_ne!(GemmaEngine::Gemma.cwl_suffix(), GemmaEngine::Pangemma.cwl_suffix()); + } + + /// The staged inputs file must name exactly what the compiled workflow + /// declares -- a workflow that wants `store` and is handed + /// `genotype_file` fails inside cwltool as "expected File but got null", + /// long after the request looked fine. + #[test] + fn the_inputs_yaml_names_the_workflows_own_fields() { + let pheno = Path::new("/c/1-pheno.txt"); + let kin = Path::new("/c/1-kin-pheno.txt"); + let gemma = ravanan_inputs_yaml( + GemmaEngine::Gemma, + "/g/BXD_geno.txt.gz", + "/g/BXD_snps.txt", + None, + pheno, + kin, + 9, + "\"1\", \"2\"", + ); + let pangemma = ravanan_inputs_yaml( + GemmaEngine::Pangemma, + "/g/BXD_geno.txt.gz", + "/g/BXD_snps.txt", + Some(Path::new("/s/BXD_geno.txt.gz-ab.mdb")), + pheno, + kin, + 9, + "\"1\", \"2\"", + ); + for field in GemmaEngine::Gemma.workflow_inputs() { + assert!(gemma.contains(&format!("{field}:")), "gemma lacks {field}"); + } + for field in GemmaEngine::Pangemma.workflow_inputs() { + assert!( + pangemma.contains(&format!("{field}:")), + "pangemma lacks {field}" + ); + } + assert!(gemma.contains("path: /g/BXD_geno.txt.gz")); + assert!(pangemma.contains("path: /s/BXD_geno.txt.gz-ab.mdb")); + assert!(!pangemma.contains("genotype_file")); + assert!(!pangemma.contains("snps_file")); + } + + /// ravanan reports a scattered step's output as an array of Files and a + /// single-step workflow's as one File. Both arrive here: the mapping + /// workflows scatter, the artifact ones (prepare, store) do not, and a + /// single-output workflow answering "no store array" is how this was found. + #[test] + fn ravanan_outputs_may_be_one_file_or_an_array() { + let one: Value = serde_json::from_str( + r#"{"store":{"class":"File","path":"/s/genotypes.mdb"}}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&one, "store").unwrap(), + vec!["/s/genotypes.mdb"] + ); + + let many: Value = serde_json::from_str( + r#"{"assoc":[{"class":"File","path":"/s/1-gwa.assoc.txt"}, + {"class":"File","path":"/s/2-gwa.assoc.txt"}]}"#, + ) + .unwrap(); + assert_eq!( + ravanan_output_paths(&many, "assoc").unwrap(), + vec!["/s/1-gwa.assoc.txt", "/s/2-gwa.assoc.txt"] + ); + assert!(ravanan_output_paths(&many, "store").is_err()); + } +} + +#[cfg(test)] +mod redact_tests { + use super::redact_paths; + + /// A reply is pasted into chats and repositories; no note may carry the + /// server's own paths (measured on the release service: the ravanan command + /// line, with `/gnu/store/...-ravanan` and `/home/wrk/...`, reached + /// callers). + #[test] + fn redact_paths_leaves_no_absolute_path() { + let note = redact_paths( + "ravanan (/gnu/store/8b2iq-ravanan-0.2.0/bin/ravanan, slurm-api backend): \ + --store=/home/wrk/tmp/ai-root/slurm-share/gn4-ravanan-cache/ravanan-store \ + --guix-manifest=/home/wrk/x/manifest.scm cwl/gemma/store.cwl", + ); + assert!(!note.contains("/gnu/store"), "{note}"); + assert!(!note.contains("/home/"), "{note}"); + // The names stay: which ravanan, which manifest, which workflow. + assert!(note.contains("ravanan"), "{note}"); + assert!(note.contains("manifest.scm"), "{note}"); + assert!(note.contains("store.cwl"), "{note}"); + } +} diff --git a/src/genotypes.rs b/src/genotypes.rs index 0d6c1c2..2948b28 100644 --- a/src/genotypes.rs +++ b/src/genotypes.rs @@ -159,13 +159,28 @@ pub fn resolve_named(root: &Path, requested: &str) -> Result<PathBuf, GenotypeEr ))) } +/// File contents as text, tolerating bytes that are not UTF-8. +/// +/// Real GeneNetwork exports carry latin-1 in their header comments (At-Serin's +/// says "Bay-0 \xd7 Shahdara"), and `read_to_string` failing on one byte hides +/// the whole panel with "stream did not contain valid UTF-8". Nothing here +/// parses the comments; the data lines are ASCII. +pub fn read_text_lossy(path: &Path) -> std::io::Result<String> { + Ok(String::from_utf8_lossy(&std::fs::read(path)?).into_owned()) +} + +fn read_text(path: &Path) -> Result<String, GenotypeError> { + let bytes = std::fs::read(path).map_err(|e| io_err(path, e))?; + Ok(String::from_utf8_lossy(&bytes).into_owned()) +} + fn io_err(path: &Path, error: std::io::Error) -> GenotypeError { GenotypeError::Io(format!("{}: {error}", path.display())) } /// The `.geno` header's sample names, in column order (GN3's rule). pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; for line in text.lines() { let line = line.trim_end_matches(['\r', '\n']); if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { @@ -191,7 +206,7 @@ pub fn panel_of(geno: &Path) -> Result<Vec<String>, GenotypeError> { /// Number of marker rows in a `.geno` (every non-comment line but the /// header). pub fn marker_count(geno: &Path) -> Result<usize, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut seen_header = false; let mut markers = 0; for line in text.lines() { @@ -267,7 +282,7 @@ fn json_versions( if !path.is_file() { return Ok(None); } - let text = std::fs::read_to_string(&path).map_err(|e| io_err(&path, e))?; + let text = read_text(&path)?; let document: serde_json::Value = serde_json::from_str(&text) .map_err(|e| GenotypeError::Io(format!("{}: {e}", path.display())))?; let Some(entries) = document.get("genofile").and_then(|v| v.as_array()) else { @@ -519,7 +534,7 @@ pub struct ParentalDesign { /// The roles a group's metadata declares, or `None` when the group is unlisted. fn design_roles(dir: &Path, group: &str) -> Option<(Vec<DesignRole>, Option<DesignRole>, Option<DesignRole>)> { let path = dir.join("parents_and_f1s.json"); - let text = std::fs::read_to_string(&path).ok()?; + let text = read_text(&path).ok()?; let document: serde_json::Value = serde_json::from_str(&text).ok()?; let entry = document.get(group)?; let role = |key: &str| { @@ -667,7 +682,7 @@ pub struct FileMeta { /// Read a `.geno`'s metadata: labels, individuals, marker positions. The /// genotype calls themselves are read and discarded, never returned. pub fn file_meta(geno: &Path) -> Result<FileMeta, GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut labels = Vec::new(); let mut individuals = Vec::new(); let mut markers = Vec::new(); @@ -763,7 +778,7 @@ pub fn prepare( markers_dropped: 0, }); } - let path = subset_path(cache_dir, &resolved.version, keep, "geno")?; + let path = subset_path(cache_dir, &resolved.version, keep, "geno", &resolved.geno)?; if !path.is_file() { write_subset_geno(&resolved.geno, keep, &path)?; } @@ -792,16 +807,16 @@ pub fn prepare( let (panel_file, individuals) = if all_kept { (geno.clone(), resolved.panel.len()) } else { - let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt")?; + let path = subset_path(cache_dir, &resolved.version, keep, "bimbam_geno.txt", &geno)?; if !path.is_file() { write_subset_bimbam(&geno, keep, &path)?; } (path, keep.len()) }; let filtered_geno = - subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt")?; + subset_path(cache_dir, &resolved.version, keep, "bimbam_geno-noY.txt", &snps)?; let filtered_snps = - subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt")?; + subset_path(cache_dir, &resolved.version, keep, "bimbam_snps-noY.txt", &snps)?; if !filtered_geno.is_file() || !filtered_snps.is_file() { let written = drop_degenerate_chromosomes(&panel_file, &snps, &filtered_geno, &filtered_snps)?; @@ -861,7 +876,7 @@ fn drop_degenerate_chromosomes( out_geno: &Path, out_snps: &Path, ) -> Result<usize, GenotypeError> { - let snps_text = std::fs::read_to_string(snps).map_err(|e| io_err(snps, e))?; + let snps_text = read_text(snps)?; let mut keep_row: Vec<bool> = Vec::new(); let mut kept_snps = String::with_capacity(snps_text.len()); for line in snps_text.lines() { @@ -886,7 +901,7 @@ fn drop_degenerate_chromosomes( if dropped == 0 { return Ok(0); } - let geno_text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let geno_text = read_text(geno)?; let mut kept_geno = String::with_capacity(geno_text.len()); for (index, line) in geno_text.lines().enumerate() { if line.trim().is_empty() { @@ -904,18 +919,42 @@ fn drop_degenerate_chromosomes( /// Non-empty lines in a file (the marker count of a snps annotation). fn count_lines(path: &Path) -> Result<usize, GenotypeError> { - Ok(std::fs::read_to_string(path) - .map_err(|e| io_err(path, e))? + Ok(read_text(path)? .lines() .filter(|line| !line.trim().is_empty()) .count()) } +/// `size-mtime` of a panel file: the part of a cache key that notices a file +/// being replaced in place. +/// +/// The subset/noY pair is derived from the genotypes, so its key has to cover +/// them. It did not -- it hashed the kept *indices* only -- which meant an +/// updated `<stem>.geno` (or BIMBAM) kept serving the previous prepared pair +/// for as long as the individual set was unchanged. `prepare_cross` has always +/// keyed on this stamp; now the subset does too. +fn source_stamp(path: &Path) -> String { + match std::fs::metadata(path) { + Ok(metadata) => format!( + "{}-{}", + metadata.len(), + metadata + .modified() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|since| since.as_secs()) + .unwrap_or(0) + ), + Err(_) => "unknown".to_string(), + } +} + fn subset_path( cache_dir: &Path, version: &str, keep: &[usize], suffix: &str, + source: &Path, ) -> Result<PathBuf, GenotypeError> { let dir = cache_dir.join("prepared"); std::fs::create_dir_all(&dir).map_err(|e| io_err(&dir, e))?; @@ -923,11 +962,14 @@ fn subset_path( for index in keep { hash = (hash ^ *index as u64).wrapping_mul(1099511628211); } + for byte in source_stamp(source).bytes() { + hash = (hash ^ byte as u64).wrapping_mul(1099511628211); + } Ok(dir.join(format!("{version}-{hash:016x}-{suffix}"))) } fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut result = String::with_capacity(text.len()); let mut seen_header = false; for line in text.lines() { @@ -964,7 +1006,7 @@ fn write_subset_geno(geno: &Path, keep: &[usize], out: &Path) -> Result<(), Geno } fn write_subset_bimbam(geno: &Path, keep: &[usize], out: &Path) -> Result<(), GenotypeError> { - let text = std::fs::read_to_string(geno).map_err(|e| io_err(geno, e))?; + let text = read_text(geno)?; let mut result = String::with_capacity(text.len()); for line in text.lines() { let trimmed = line.trim_end_matches('\r'); @@ -1351,7 +1393,7 @@ mod tests { /// the file cannot be read (the caller then proceeds as before rather than /// refusing the run). pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> { - let text = std::fs::read_to_string(geno).ok()?; + let text = read_text(geno).ok()?; let mut mask: Option<Vec<bool>> = None; for line in text.lines() { let line = line.trim(); @@ -1379,6 +1421,44 @@ pub fn individuals_with_genotypes(geno: &std::path::Path) -> Option<Vec<bool>> { mask } +/// The `.geno` that carries the individual names for a BIMBAM file. +/// +/// BIMBAM has no names: its columns are positional. A request that names its +/// values ("samples", or a basket) therefore cannot be aligned against the +/// BIMBAM it asks to map -- and until this, the file branch tried anyway, read +/// the BIMBAM as if it were a `.geno`, found no header, and answered 422 +/// "no mapping inputs" with every value dropped (measured on At-Serin). +/// +/// The deployment keeps the two side by side under a shared stem +/// (`genotype/<stem>.geno` and `genotype/bimbam/<stem>_geno.txt`), and the +/// BIMBAM is generated from the `.geno`, so its column order is the header's +/// order. That makes the sibling the name source. +pub fn names_for_bimbam(bimbam: &Path) -> Option<PathBuf> { + let file = bimbam.file_name()?.to_string_lossy().into_owned(); + let stem = file + .strip_suffix("_geno.txt") + .or_else(|| file.strip_suffix(".txt"))?; + let genotype_dir = bimbam.parent()?.parent()?; + let candidate = genotype_dir.join(format!("{stem}.geno")); + candidate.is_file().then_some(candidate) +} + +/// `align_to_file`, but for a file that carries no names: the names come from +/// `names_source` (see [`names_for_bimbam`]), and the values are placed in the +/// file's own column order. +pub fn align_to_columns_of( + names_source: &Path, + values: &[(String, Option<f64>)], +) -> Result<Vec<Option<f64>>, GenotypeError> { + let names = panel_of(names_source)?; + let by_name: std::collections::HashMap<&str, Option<f64>> = + values.iter().map(|(name, value)| (name.as_str(), *value)).collect(); + Ok(names + .iter() + .map(|name| by_name.get(name.as_str()).copied().flatten()) + .collect()) +} + /// One value per individual of a `.geno`, in the file's own order, from values /// given by name. Used when a request names a file rather than a group -- an /// uploaded population, typically -- because the caller has a trait's values diff --git a/src/json_errors.rs b/src/json_errors.rs new file mode 100644 index 0000000..458eea9 --- /dev/null +++ b/src/json_errors.rs @@ -0,0 +1,118 @@ +//! Make every client error answer in the API's own envelope. +//! +//! Extractor failures never reach a handler, so they never see `ApiError`: axum +//! answers a body it cannot deserialize with `text/plain`, e.g. +//! +//! ```text +//! Failed to deserialize the JSON body into the target type: +//! missing field `trait_name` at line 1 column 1387 +//! ``` +//! +//! That is the one error class a client cannot parse -- everything else carries +//! `code`, `detail` and `request_id`. Measured on the release service: a +//! `/compute/rqtl` call without `trait_name` answered 422 `text/plain`. +//! +//! A middleware fixes it in one place instead of adding a custom extractor to +//! every handler: if the response is a 4xx that is not already JSON, its body +//! becomes `{"type": "/errors/invalid_request", "title": ..., "status": ..., +//! "code": "invalid_request", "detail": <the original text>, "error": null, +//! "operation_id": <the matched route>}`. +use axum::body::Body; +use axum::extract::MatchedPath; +use axum::http::{header, Request, StatusCode}; +use axum::middleware::Next; +use axum::response::Response; + +pub async fn jsonify_client_errors(request: Request<Body>, next: Next) -> Response { + // The matched route pattern is the closest thing to an operation id + // available this early; it names /compute/rqtl rather than the path asked. + let operation = request + .extensions() + .get::<MatchedPath>() + .map(|matched: &MatchedPath| matched.as_str().to_string()); + let mut response = next.run(request).await; + let status = response.status(); + if !status.is_client_error() { + return response; + } + let is_json = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .map(|value| value.starts_with("application/json")) + .unwrap_or(false); + if is_json { + return response; + } + // Take the body apart and rebuild it: the original text is the detail. + let (mut parts, body) = response.into_parts(); + let bytes = axum::body::to_bytes(body, 64 * 1024) + .await + .unwrap_or_default(); + let detail = String::from_utf8_lossy(&bytes).trim().to_string(); + let body = serde_json::json!({ + "type": "/errors/invalid_request", + "title": "Invalid request", + "status": status.as_u16(), + "code": match status { + StatusCode::UNSUPPORTED_MEDIA_TYPE => "unsupported_media_type", + StatusCode::PAYLOAD_TOO_LARGE => "payload_too_large", + _ => "invalid_request", + }, + "detail": if detail.is_empty() { "the request could not be read".to_string() } else { detail }, + "error": null, + "operation_id": operation, + "spec_url": "/openapi.json", + "next": null, + }); + let text = body.to_string(); + parts.headers.insert( + header::CONTENT_TYPE, + header::HeaderValue::from_static("application/json"), + ); + parts.headers.remove(header::CONTENT_LENGTH); + Response::from_parts(parts, Body::from(text)) +} + +#[cfg(test)] +mod tests { + use super::*; + use axum::Router; + use axum::routing::post; + + async fn boom() -> StatusCode { + StatusCode::BAD_REQUEST + } + + /// A 4xx that is not JSON comes back as the envelope; a JSON one is left + /// alone. + #[tokio::test] + async fn a_plain_text_client_error_becomes_the_envelope() { + use tower::ServiceExt; + let app = Router::new() + .route("/boom", post(boom)) + .layer(axum::middleware::from_fn(jsonify_client_errors)); + let response = app + .oneshot( + Request::builder() + .method("POST") + .uri("/boom") + .body(Body::empty()) + .unwrap(), + ) + .await + .unwrap(); + assert_eq!(response.status(), StatusCode::BAD_REQUEST); + assert_eq!( + response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()), + Some("application/json") + ); + let bytes = axum::body::to_bytes(response.into_body(), 4096).await.unwrap(); + let body: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(body["code"], "invalid_request"); + assert!(body["operation_id"].is_string()); + } +} diff --git a/src/lib.rs b/src/lib.rs index 976b2f1..bf1047b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -23,6 +23,7 @@ pub mod frequencies; pub mod genoupload; pub mod genotypes; pub mod heatmap; +pub mod listing; pub mod normalize; mod plot; mod error; @@ -30,12 +31,15 @@ mod gemma; pub mod indexer; pub mod qtl2; pub mod response; +pub mod json_errors; +pub mod runs; mod routes; mod rqtl; pub mod search; mod streaming; pub mod suggest; pub mod tokens; +pub mod usage; pub mod wikidata; use error::ApiError; @@ -87,6 +91,11 @@ async fn tag_caller( ) -> axum::response::Response { let slot = crate::auth::CallerSlot::default(); request.extensions_mut().insert(slot.clone()); + // What the *work* was (dataset, engine, cached, …): the handler knows + // it (it parses the body) and this middleware does not, so it opens a + // slot the same way, and reads it back below. See `crate::usage`. + let usage = crate::usage::UsageSlot::default(); + request.extensions_mut().insert(usage.clone()); let started = std::time::Instant::now(); let method = request.method().clone(); // The path only: a query string can carry a credential (`?token=`) and has @@ -122,6 +131,7 @@ async fn tag_caller( started.elapsed().as_millis(), request_id.as_deref(), caller.as_ref(), + &usage.entries(), ) ); } @@ -138,6 +148,12 @@ async fn tag_caller( /// lets `scripts/gn4-log.py` resolve the handle against the registry -- the /// subject as it is *now*, the token's status and its note -- without the log /// ever holding a secret or a hash. +/// +/// `usage` is what the handler added about the work itself (dataset, group, +/// engine, cached, run, `q`), and it is empty for every route that does not +/// call [`crate::usage`]'s macro. Those keys go after the request's own +/// fields, and [`crate::usage::RESERVED`] keeps a handler from overwriting +/// one of them. fn request_log_line( method: &str, path: &str, @@ -145,6 +161,7 @@ fn request_log_line( took_ms: u128, request_id: Option<&str>, caller: Option<&crate::auth::Caller>, + usage: &[(&'static str, serde_json::Value)], ) -> String { let mut line = serde_json::json!({ "event": "request", @@ -166,6 +183,11 @@ fn request_log_line( object.insert("token".to_string(), serde_json::json!(id)); } } + if let Some(object) = line.as_object_mut() { + for (key, value) in usage { + object.insert((*key).to_string(), value.clone()); + } + } line.to_string() } @@ -231,6 +253,8 @@ pub fn app() -> Router { .routes(routes!(routes::traits::trait_values)) .routes(routes!(routes::publications::publication_traits)) .routes(routes!(routes::search::search)) + .routes(routes!(routes::compare::compare)) + .routes(routes!(routes::compare::plot_compare)) .routes(routes!(routes::correlation::correlation)) .routes(routes!(routes::correlation_matrix::correlation_matrix)) .routes(routes!(routes::baskets::list_baskets)) @@ -283,6 +307,8 @@ pub fn app() -> Router { .routes(routes!(routes::gemma::compute_gemma)) .routes(routes!(routes::gemma::compute_gemma_ravanan)) .routes(routes!(routes::gemma::gemma_status)) + .routes(routes!(routes::gemma::compute_gemma_async)) + .routes(routes!(routes::gemma::gemma_result)) .routes(routes!(routes::fitqtl::compute_fitqtl)) .routes(routes!(routes::qtl2::compute_qtl2)) .routes(routes!(routes::rqtl::compute_rqtl)) @@ -329,6 +355,10 @@ pub fn app() -> Router { // Outermost, so the slot exists before the handler's extractors // run: see `tag_caller`. .layer(axum::middleware::from_fn(tag_caller)) + // Outside everything, so an extractor's rejection (which never + // reaches a handler) still answers in the API's envelope instead of + // axum's text/plain. + .layer(axum::middleware::from_fn(json_errors::jsonify_client_errors)) } /// The largest request body the API accepts: 64 MiB, comfortably above a @@ -450,6 +480,7 @@ mod access_log_tests { 17, Some("abc"), Some(&caller(Scheme::Jwt, None, "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["event"], "request"); @@ -479,6 +510,7 @@ mod access_log_tests { 900, None, Some(&caller(Scheme::Opaque, Some("agent-ravanan-3"), "zachs")), + &[], ); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert_eq!(parsed["user"], "zachs"); @@ -491,9 +523,75 @@ mod access_log_tests { /// reader could mistake for a user name. #[test] fn no_user_field_when_nobody_was_identified() { - let line = request_log_line("GET", "/groups", 401, 0, None, None); + let line = request_log_line("GET", "/groups", 401, 0, None, None, &[]); let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); assert!(parsed.get("user").is_none(), "{line}"); assert!(parsed.get("request_id").is_none(), "{line}"); } + + /// The wiring the whole feature rests on: the slot `tag_caller` puts in + /// the request extensions is the slot the handler's `Ctx` writes into and + /// the same one the line is built from. If these ever became two slots, + /// nothing would fail -- the lines would just lose their fields. + #[tokio::test] + async fn a_handler_writes_into_the_slot_the_logging_middleware_reads() { + use axum::extract::FromRequestParts; + + let slot = crate::usage::UsageSlot::default(); + let mut parts = axum::http::Request::builder() + .uri("/compute/gemma") + .body(()) + .unwrap() + .into_parts() + .0; + parts.extensions.insert(slot.clone()); + + let ctx = crate::response::Ctx::from_request_parts(&mut parts, &()) + .await + .unwrap(); + crate::usage!(ctx, dataset = "HSNIH-Palmer", engine = "gemma"); + // A clone of the handler's ctx (the fallback path) lands in the same + // place, and a second note replaces rather than duplicates. + crate::usage!(ctx.clone(), engine = "pangemma"); + + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")) + ], + "one slot, and the later answer wins" + ); + } + + /// What the handler recorded about the work lands beside the request's + /// own fields, and a route that records nothing grows nothing: five + /// sixths of the traffic (every read route) must stay as it was. + #[test] + fn usage_fields_are_added_after_the_lines_own_fields() { + let usage = vec![ + ("dataset", serde_json::json!("HSNIH-Palmer")), + ("engine", serde_json::json!("pangemma")), + ("cached", serde_json::json!(true)), + ]; + let line = request_log_line( + "POST", + "/compute/gemma", + 200, + 900, + None, + Some(&caller(Scheme::Jwt, None, "JoM")), + &usage, + ); + let parsed: serde_json::Value = serde_json::from_str(&line).unwrap(); + assert_eq!(parsed["dataset"], "HSNIH-Palmer"); + assert_eq!(parsed["engine"], "pangemma"); + assert_eq!(parsed["cached"], true); + assert_eq!(parsed["user"], "JoM", "the line's own fields survive"); + assert_eq!(parsed["path"], "/compute/gemma"); + + let quiet = request_log_line("GET", "/groups/BXD", 200, 1, None, None, &[]); + let parsed: serde_json::Value = serde_json::from_str(&quiet).unwrap(); + assert_eq!(parsed.as_object().unwrap().len(), 6, "{quiet}"); + } } diff --git a/src/listing.rs b/src/listing.rs new file mode 100644 index 0000000..584429f --- /dev/null +++ b/src/listing.rs @@ -0,0 +1,268 @@ +//! The shape of a listing: `limit_to`, `ids_only`, `names_only`. +//! +//! GN2 offers all three on its listings, and a client that has to enumerate a +//! group's 20 000 traits wants them for the same reason: a 2 MB answer of +//! objects to build a dropdown is a waste of everyone's connection. The three +//! are one concept, so they live in one type rather than being copied into each +//! handler's query struct: +//! +//! * `limit_to=a,b,c` keeps only the rows whose id, name, full name or trait +//! name matches one of the listed values (case-insensitive). A value that +//! matches nothing is named in the reply's note rather than silently ignored, +//! because "my trait's missing" is the failure mode this exists to prevent. +//! * `ids_only=true` answers `["BXD", "BXH", ...]` instead of objects. +//! * `names_only=true` answers `["BXD", ...]` too, but from the *name* field; +//! asking for both is a contradiction and is refused rather than guessed. +//! +//! Rows keep their order, so a caller can zip the slim answer against what it +//! asked for. +//! +//! **Status: the type and its tests are in, the handlers are not wired yet.** +//! Wiring one is small but not mechanical: a listing handler returns typed rows +//! (`Envelope<Vec<db::Group>>`), so answering with `["BXD", ...]` changes its +//! return type to `Envelope<serde_json::Value>` *and* the `body =` type in its +//! `utoipa::path` block, which utoipa checks at compile time (a mismatch fails +//! with "could not find `__path_<handler>`", which reads like a macro problem +//! and is not one). Doing that for six handlers is a pass of its own; doing it +//! for two would leave the API inconsistent, which is worse than not having it. + +use serde::Deserialize; + +/// What a listing answers with. +/// +/// `Objects` is the shape the API has always had, and it stays the default: a +/// caller who sends no listing parameters gets exactly what it got before, so +/// adding this cannot break an existing client. `Plain` is the opt-in slim form +/// (`ids_only` / `names_only`), one value per row. +/// +/// Untagged because the wire shapes are a plain JSON array either way -- the +/// difference is what is *in* the array, not how it is wrapped, and a wrapper +/// would have been a breaking change dressed as a feature. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +#[serde(untagged)] +pub enum Rows { + /// One serialised row per entry, the shape every listing has always had. + Objects(Vec<serde_json::Value>), + /// One identifier per entry, from `ids_only` or `names_only`. + Plain(Vec<String>), +} + +/// Query parameters every listing shares, for handlers with no other parameters. +#[derive(Debug, Clone, Default, Deserialize, utoipa::IntoParams)] +pub struct ListingParams { + /// Keep only these ids or names, comma-separated. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with ids only. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with names only. + #[serde(default)] + pub names_only: Option<bool>, +} + +/// What a listing should answer with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Listing { + /// The rows as they are. + Full, + /// One identifier per row, from this field. + Only(&'static str), +} + +/// The fields a `limit_to` value may match, in the order they are tried. +const MATCH_FIELDS: [&str; 5] = ["id", "name", "trait_name", "display_name", "full_name"]; +/// Where an `ids_only` answer takes its value from. +const ID_FIELDS: [&str; 4] = ["id", "name", "trait_name", "abbreviation"]; +/// Where a `names_only` answer takes its value from. +const NAME_FIELDS: [&str; 4] = ["name", "trait_name", "display_name", "id"]; + +impl Listing { + /// Read the parameters, refusing the contradiction. + pub fn parse(params: &ListingParams) -> Result<Self, String> { + let ids = params.ids_only.unwrap_or(false); + let names = params.names_only.unwrap_or(false); + match (ids, names) { + (true, true) => Err( + "ask for ids_only or names_only, not both: a row has one identifier and one name, \ + and which one you get should not depend on parse order" + .to_string(), + ), + (true, false) => Ok(Listing::Only("id")), + (false, true) => Ok(Listing::Only("name")), + (false, false) => Ok(Listing::Full), + } + } + + /// Shape already-serialised rows into a [`Rows`] body. + /// + /// `rows` is the full form; `Listing::Full` hands it back untouched, so the + /// default answer is the old answer. + pub fn shape( + &self, + rows: Vec<serde_json::Value>, + limit_to: Option<&str>, + ) -> (Rows, Vec<String>) { + let as_value = serde_json::Value::Array(rows); + let (shaped, missing) = self.apply(&as_value, limit_to); + let entries = shaped.as_array().cloned().unwrap_or_default(); + let body = match self { + Listing::Full => Rows::Objects(entries), + Listing::Only(_) => Rows::Plain( + entries + .into_iter() + .filter_map(|value| match value { + serde_json::Value::String(text) => Some(text), + serde_json::Value::Number(number) => Some(number.to_string()), + _ => None, + }) + .collect(), + ), + }; + (body, missing) + } + + /// Shape `rows` (already serialised) according to the parameters. + /// + /// Returns the shaped array and, for a `limit_to` that matched nothing, the + /// values that were not found -- so the caller can say so. + pub fn apply( + &self, + rows: &serde_json::Value, + limit_to: Option<&str>, + ) -> (serde_json::Value, Vec<String>) { + let Some(array) = rows.as_array() else { + return (rows.clone(), Vec::new()); + }; + let wanted: Option<Vec<String>> = limit_to + .map(|text| { + text.split(',') + .map(|value| value.trim().to_lowercase()) + .filter(|value| !value.is_empty()) + .collect() + }) + .filter(|values: &Vec<String>| !values.is_empty()); + + let mut kept: Vec<serde_json::Value> = Vec::with_capacity(array.len()); + let mut found: Vec<String> = Vec::new(); + for row in array { + if let Some(wanted) = &wanted { + let mut matched = false; + for field in MATCH_FIELDS { + if let Some(value) = row.get(field).and_then(|value| { + value + .as_str() + .map(str::to_string) + .or_else(|| value.as_i64().map(|n| n.to_string())) + }) { + let lowered = value.to_lowercase(); + if wanted.contains(&lowered) { + matched = true; + found.push(lowered); + break; + } + } + } + if !matched { + continue; + } + } + match self { + Listing::Full => kept.push(row.clone()), + Listing::Only(field) => { + let fields: &[&str] = if *field == "id" { &ID_FIELDS } else { &NAME_FIELDS }; + let value = fields + .iter() + .find_map(|candidate| row.get(*candidate)) + .cloned() + .unwrap_or(serde_json::Value::Null); + kept.push(value); + } + } + } + let missing = match &wanted { + Some(wanted) => wanted + .iter() + .filter(|value| !found.contains(value)) + .cloned() + .collect(), + None => Vec::new(), + }; + (serde_json::Value::Array(kept), missing) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn rows() -> serde_json::Value { + json!([ + {"id": 1, "name": "BXD", "full_name": "BXD recombinant inbreds"}, + {"id": 2, "name": "BXH", "full_name": "BXH recombinant inbreds"}, + {"id": 3, "name": "HET3-ITP", "full_name": "UM-HET3"} + ]) + } + + #[test] + fn full_leaves_the_rows_alone() { + let listing = Listing::parse(&ListingParams::default()).expect("default"); + assert_eq!(listing, Listing::Full); + let (shaped, missing) = listing.apply(&rows(), None); + assert_eq!(shaped, rows()); + assert!(missing.is_empty()); + } + + #[test] + fn ids_and_names_are_one_value_per_row() { + let ids = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = ids.apply(&rows(), None); + assert_eq!(shaped, json!([1, 2, 3])); + + let names = Listing::parse(&ListingParams { + names_only: Some(true), + ..Default::default() + }) + .expect("names"); + let (shaped, _) = names.apply(&rows(), None); + assert_eq!(shaped, json!(["BXD", "BXH", "HET3-ITP"])); + } + + #[test] + fn limit_to_matches_any_of_the_matching_fields_case_insensitively() { + let listing = Listing::Full; + let (shaped, missing) = listing.apply(&rows(), Some("bxd,UM-HET3")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(2)); + assert!(missing.is_empty(), "both were found: {missing:?}"); + + let (shaped, missing) = listing.apply(&rows(), Some("bxd,nope")); + assert_eq!(shaped.as_array().map(|rows| rows.len()), Some(1)); + assert_eq!(missing, vec!["nope".to_string()], "the miss is reported, not dropped"); + } + + #[test] + fn limit_to_composes_with_ids_only() { + let listing = Listing::parse(&ListingParams { + ids_only: Some(true), + ..Default::default() + }) + .expect("ids"); + let (shaped, _) = listing.apply(&rows(), Some("BXH")); + assert_eq!(shaped, json!([2])); + } + + #[test] + fn asking_for_both_shapes_is_refused() { + let error = Listing::parse(&ListingParams { + ids_only: Some(true), + names_only: Some(true), + ..Default::default() + }); + assert!(error.is_err(), "ids_only + names_only must not be guessed"); + } +} diff --git a/src/pca.rs b/src/pca.rs index 23e3105..e924882 100644 --- a/src/pca.rs +++ b/src/pca.rs @@ -55,6 +55,29 @@ pub struct Pca { /// Eigenvalues should sum to the number of traits; reported so a caller can /// check that the decomposition is sane rather than trust it. pub trace: f64, + /// The components *as traits*: one value per individual per component, so + /// they can be used the way GN2's "PCA traits" are -- correlated, mapped, + /// plotted, saved in a basket. Empty when the caller did not ask, or when + /// the values were not available to project. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub traits: Vec<PcTrait>, +} + +/// One principal component as a trait: a value per individual. +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcTrait { + /// `PC1`, `PC2`, ... in eigenvalue order. + pub name: String, + /// Score per individual, in the same order as `individuals`. + pub values: Vec<PcValue>, + /// Share of total variance this component explains. + pub explained_variance_ratio: f64, +} + +#[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] +pub struct PcValue { + pub name: String, + pub value: f64, } #[derive(Debug, Clone, serde::Serialize, utoipa::ToSchema)] @@ -189,6 +212,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; } let small: Vec<Vec<f64>> = kept @@ -201,6 +225,7 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: Vec::new(), dropped, trace: 0.0, + traits: Vec::new(), }; }; let trace: f64 = eigenvalues.iter().sum(); @@ -221,7 +246,72 @@ pub fn analyse(matrix: &Matrix) -> Pca { scree: eigenvalues, dropped, trace, + traits: Vec::new(), + } +} + +/// Project standardised trait values onto the components, giving PC scores. +/// +/// `values` is traits x individuals for the traits the PCA kept, in the kept +/// order and already aligned to `individuals`; a trait is standardised with the +/// **sample** standard deviation (n-1), because that is what the correlation +/// matrix was built from -- using the population one would rescale every score +/// by a constant and quietly disagree with `r`. +/// +/// Returns one [`PcTrait`] per component. `None` when the shapes disagree or a +/// value is missing, rather than filling a zero into a score. +pub fn scores( + pca: &Pca, + values: &[Vec<f64>], + individuals: &[String], +) -> Option<Vec<PcTrait>> { + let n_traits = values.len(); + if n_traits == 0 || individuals.len() != values[0].len() || values.iter().any(|v| v.len() != individuals.len()) { + return None; + } + if pca.components.len() < n_traits || pca.components[0].loadings.len() != n_traits { + return None; + } + let n = individuals.len(); + if n < 2 { + return None; + } + // z-scores per trait + let mut standardised: Vec<Vec<f64>> = Vec::with_capacity(n_traits); + for trait_values in values { + if trait_values.iter().any(|v| !v.is_finite()) { + return None; + } + let mean = trait_values.iter().sum::<f64>() / n as f64; + let variance = trait_values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / (n - 1) as f64; + let sd = variance.sqrt(); + // A constant trait has no z-score; it also has no correlation with + // anything, so it should have been dropped before we get here. + if !(sd > 0.0) { + return None; + } + standardised.push(trait_values.iter().map(|v| (v - mean) / sd).collect()); + } + let mut out = Vec::with_capacity(pca.components.len()); + for (index, component) in pca.components.iter().enumerate() { + let mut scores = vec![0.0; n]; + for (trait_index, loading) in component.loadings.iter().enumerate() { + for (individual, z) in standardised[trait_index].iter().enumerate() { + scores[individual] += loading * z; + } + } + out.push(PcTrait { + name: format!("PC{}", index + 1), + values: individuals + .iter() + .cloned() + .zip(scores) + .map(|(name, value)| PcValue { name, value }) + .collect(), + explained_variance_ratio: component.explained_variance_ratio, + }); } + Some(out) } #[cfg(test)] diff --git a/src/qtl2.rs b/src/qtl2.rs index 2bb11f7..99f2370 100644 --- a/src/qtl2.rs +++ b/src/qtl2.rs @@ -155,47 +155,22 @@ pub struct Qtl2Output { pub permutation_note: Option<String>, } -/// How many genotype cells carry one code -- the count a cached conversion -/// needs to say what it dropped, without re-converting. -fn count_calls(text: &str, code: &str) -> usize { - let mut seen_header = false; - let mut start = 3usize; - let mut count = 0usize; - for line in text.lines() { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') || line.starts_with('@') { - continue; - } - let columns: Vec<&str> = line.split('\t').collect(); - if !seen_header { - seen_header = true; - start = if columns.len() > 3 && columns[3] == "Mb" { 4 } else { 3 }; - continue; - } - count += columns.iter().skip(start).filter(|cell| cell.trim() == code).count(); - } - count -} - -/// The header's `@het` code, if it declares one. -fn metadata_het(text: &str) -> Option<String> { - text.lines() - .find_map(|line| line.strip_prefix("@het:")) - .map(|value| value.trim().to_string()) -} - -fn io_error(path: &Path, error: io::Error) -> Qtl2Error { - Qtl2Error::Io(io::Error::new( - error.kind(), - format!("{}: {error}", path.display()), - )) -} +/// The conversion, as an R script. +pub const CONVERT_SCRIPT: &str = "scripts/qtl2-convert-geno.R"; /// Convert `resolved`'s `.geno` into a cached qtl2 cross. +/// +/// The conversion itself is [`CONVERT_SCRIPT`], an R script: the output is an +/// R/qtl2 cross, and qtl2's own `write_control_file` describes it. Doing that +/// here meant a second implementation of the format in Rust, and one of its +/// conventions -- the genotype codes -- was wrong in a way that silently +/// destroyed the scan (see the script's own comment). Reading the report the +/// script leaves beside the cross is all this side needs to do. pub fn prepare_cross( resolved: &Resolved, cache_dir: &Path, het: Het, + convert_script: &Path, ) -> Result<PreparedCross, Qtl2Error> { let geno = &resolved.geno; let metadata = std::fs::metadata(geno).map_err(|e| io_error(geno, e))?; @@ -209,37 +184,22 @@ pub fn prepare_cross( .map(|since| since.as_secs()) .unwrap_or(0) ); - // The version tag is part of the key: a change to this conversion (the - // heterozygous calls dropped for a riself panel, say) must not silently - // reuse the previous cross's probabilities and kinship. - // v3 keyed the heterozygous policy in as well: a cross converted with the - // calls kept is a different cross from one with them dropped. - const CONVERSION_VERSION: &str = "v3"; - let directory = cache_dir.join("crosses").join(format!( - "{CONVERSION_VERSION}-{}-{}-{stamp}", - het.as_str(), - resolved.version.replace(['/', '.'], "_") - )); - let control = directory.join("control.json"); - let text = std::fs::read_to_string(geno).map_err(|e| io_error(geno, e))?; - - // Metadata: the genotype codes, and the cross type. - let mut codes: BTreeMap<String, String> = BTreeMap::new(); - let mut cross_type = String::new(); + // Lossy, like the genotype readers: a latin-1 byte in a header comment must + // not hide the panel (measured on At-Serin.geno). + let text = crate::genotypes::read_text_lossy(geno).map_err(|e| io_error(geno, e))?; + + // The cross type is checked here rather than in R: this is the endpoint's + // own limit (a `.geno` panel carries no founder genotypes, so it cannot be + // a multiparent cross), and the answer is a 422 with a reason, not a + // script failure. + let mut declared = String::new(); for line in text.lines() { - if let Some(rest) = line.strip_prefix('@') { - let Some((key, value)) = rest.split_once(':') else { continue }; - let value = value.trim().to_string(); - match key.trim() { - "mat" => { codes.insert(value, "A".to_string()); } - "het" => { codes.insert(value, "H".to_string()); } - "pat" => { codes.insert(value, "B".to_string()); } - "type" => cross_type = value, - _ => {} - } + if let Some(rest) = line.strip_prefix("@type:") { + declared = rest.trim().to_string(); + break; } } - let crosstype = match cross_type.as_str() { + let crosstype = match declared.as_str() { // A riset panel read as `f2` is a riset panel whose H calls are kept: // qtl2 needs a cross type that has a heterozygous state for that. "riset" if het == Het::Keep => "f2", @@ -253,192 +213,106 @@ pub fn prepare_cross( ))) } }; - // A riself panel is inbred lines: a heterozygous call is an error in the - // genotyping, not a third allele. R/qtl's `convert2riself` omits those - // genotypes, and qtl2 needs the same treatment -- left in, it reads the - // cross as multiparent and its scan1 takes a path this panel cannot - // satisfy ("scan1_pg ..."). - let mut het_kept: Option<String> = None; - if crosstype == "riself" { - let het_code = metadata_het(&text); - if let Some(het_code) = het_code { - codes.remove(&het_code); - het_kept = Some(het_code); - } - } - if codes.len() < 2 { - return Err(Qtl2Error::Unsupported( - "the .geno header declares no @mat/@pat codes, so its genotypes cannot be coded" - .to_string(), - )); - } - // Header row: Chr, Locus, cM, Mb?, then the individuals. - let mut lines = text.lines(); - let Some(header) = lines.find(|line| line.to_lowercase().starts_with("chr\t")) else { - return Err(Qtl2Error::Unsupported( - "the .geno file has no 'Chr' header row".to_string(), - )); - }; - let fields: Vec<&str> = header.split('\t').collect(); - let first_individual = if fields.get(3).copied() == Some("Mb") { 4 } else { 3 }; - let individuals: Vec<String> = fields[first_individual..] - .iter() - .map(|name| name.trim().to_string()) - .collect(); - if individuals.is_empty() { - return Err(Qtl2Error::Unsupported( - "the .geno header names no individuals".to_string(), - )); - } + // The version tag is part of the key: a change to the conversion must not + // silently reuse the previous cross's probabilities and kinship. v3 keyed + // the heterozygous policy in; v4/v5 were the allele codes; v6 is the + // conversion itself moving to R, which changes the files it writes (qtl2's + // own genotype layout, individuals in rows). + const CONVERSION_VERSION: &str = "v6"; + let directory = cache_dir.join("crosses").join(format!( + "{CONVERSION_VERSION}-{}-{}-{stamp}", + het.as_str(), + resolved.version.replace(['/', '.'], "_") + )); + let control = directory.join("control.json"); if !control.is_file() { std::fs::create_dir_all(&directory).map_err(|e| io_error(&directory, e))?; - let mut geno_csv = String::new(); - let mut gmap_csv = String::from("marker,chr,pos\n"); - let mut pmap_csv = String::from("marker,chr,pos\n"); - geno_csv.push_str("marker,"); - geno_csv.push_str(&individuals.join(",")); - geno_csv.push('\n'); - let mut markers = 0usize; - let mut non_autosomal = 0usize; - let mut het_dropped = 0usize; - for line in lines { - let line = line.trim_end_matches('\r'); - if line.trim().is_empty() || line.starts_with('#') { - continue; - } - let row: Vec<&str> = line.split('\t').collect(); - if row.len() < first_individual { - continue; - } - let (chromosome, marker, centimorgans, megabases) = - (row[0].trim(), row[1].trim(), row[2].trim(), row.get(3).copied().unwrap_or("")); - // Autosomes only: see the module comment. - if !chromosome.chars().all(|c| c.is_ascii_digit()) { - non_autosomal += 1; - continue; - } - markers += 1; - geno_csv.push_str(marker); - for value in &row[first_individual..] { - let call = codes.get(value.trim()).map(String::as_str).unwrap_or(""); - if call.is_empty() && het_kept.as_deref() == Some(value.trim()) { - het_dropped += 1; + let het_arg = het.as_str(); + let output = std::process::Command::new("Rscript") + .arg(convert_script) + .arg("--geno") + .arg(geno) + .arg("--out") + .arg(&directory) + .arg("--het") + .arg(het_arg) + .arg("--crosstype") + .arg(crosstype) + .output() + .map_err(Qtl2Error::Io)?; + if !output.status.success() { + let stderr = String::from_utf8_lossy(&output.stderr); + let interesting = |line: &&str| { + let line = line.trim(); + !line.is_empty() + && !line.starts_with("Warning") + && !line.starts_with("In ") + && line != "Execution halted" + }; + let complaint: Vec<&str> = stderr.lines().filter(interesting).collect(); + return Err(Qtl2Error::CommandFailed(format!( + "converting {} failed: {}", + geno.display(), + if complaint.is_empty() { + "R/qtl2 gave no reason".to_string() + } else { + complaint.join(" ") } - geno_csv.push(','); - geno_csv.push_str(call); - } - geno_csv.push('\n'); - gmap_csv.push_str(&format!("{marker},{chromosome},{centimorgans}\n")); - let base_pairs = megabases.parse::<f64>().map(|mb| (mb * 1e6).round() as i64).unwrap_or(0); - pmap_csv.push_str(&format!("{marker},{chromosome},{base_pairs}\n")); - } - if markers == 0 { - return Err(Qtl2Error::Unsupported( - "the panel has no autosomal markers to scan".to_string(), - )); - } - // The cross needs a phenotype file of its own to be readable; the - // trait comes from the request, through the script's --pheno. - let mut pheno_csv = String::from("id,trait\n"); - for name in &individuals { - pheno_csv.push_str(&format!("{name},1\n")); + ))); } - for (path, contents) in [ - (directory.join("geno.csv"), &geno_csv), - (directory.join("gmap.csv"), &gmap_csv), - (directory.join("pmap.csv"), &pmap_csv), - (directory.join("pheno.csv"), &pheno_csv), - ] { - std::fs::write(&path, contents).map_err(|e| io_error(&path, e))?; - } - let control_json = serde_json::json!({ - // Paths are relative to the control file: qtl2 joins its own - // directory onto whatever it finds here. - "crosstype": crosstype, - "geno": "geno.csv", - "gmap": "gmap.csv", - "pmap": "pmap.csv", - "pheno": "pheno.csv", - "sep": ",", - "na.strings": [""], - "genotypes": {"A": 1, "H": 2, "B": 3}, - // Our own CSVs are markers-in-rows, individuals-in-columns. - "geno_transposed": true, - }); - std::fs::write(&control, control_json.to_string()).map_err(|e| io_error(&control, e))?; - // What the conversion discarded, kept beside the cross: a cached cross - // must be able to say how many calls it dropped. - let report = serde_json::json!({ - "het_dropped": het_dropped, - "cells": individuals.len() * markers, - }); - let report_path = directory.join("conversion.json"); - let _ = std::fs::write(&report_path, report.to_string()); - return Ok(PreparedCross { - control, - individuals: individuals.clone(), - markers, - non_autosomal, - crosstype: crosstype.to_string(), - het_dropped, - cells: individuals.len() * markers, - founders: 0, - multiparent: false, - }); } - // Cached: count what the conversion produced, without re-reading the - // panel. The marker counts come from the maps it wrote. - let markers = std::fs::read_to_string(directory.join("pmap.csv")) - .map_err(|e| io_error(&directory.join("pmap.csv"), e))? - .lines() - .filter(|line| !line.trim().is_empty()) - .count() - .saturating_sub(1); + // The script's report is the cross's own account of itself: what it + // dropped, and which individuals it holds. A cross converted before the + // report existed is measured once from the panel. let report_path = directory.join("conversion.json"); - let mut report: Value = std::fs::read_to_string(&report_path) + let report: Value = std::fs::read_to_string(&report_path) .ok() .and_then(|text| serde_json::from_str(&text).ok()) - .unwrap_or_else(|| serde_json::json!({})); - if report.get("het_dropped").is_none() { - // A cross converted before the count was kept: measure it once from the - // panel and record it beside the cross, so later replies are free. - let het_code = if crosstype == "riself" { - metadata_het(&text) - } else { - None - }; - let dropped = het_code - .as_deref() - .map(|code| count_calls(&text, code)) - .unwrap_or(0); - report = serde_json::json!({ - "het_dropped": dropped, - "cells": individuals.len() * markers, - }); - let _ = std::fs::write(&report_path, report.to_string()); + .ok_or_else(|| { + Qtl2Error::CommandFailed(format!( + "{} wrote no conversion report; can this convert {}?", + convert_script.display(), + geno.display() + )) + })?; + let want = |key: &str| report.get(key).and_then(Value::as_u64).unwrap_or(0) as usize; + let individuals: Vec<String> = report + .get("individuals") + .and_then(Value::as_array) + .map(|names| { + names + .iter() + .filter_map(|name| name.as_str().map(str::to_string)) + .collect() + }) + .unwrap_or_default(); + if individuals.is_empty() { + return Err(Qtl2Error::Unsupported( + "the .geno header names no individuals".to_string(), + )); + } + let markers = want("markers"); + if markers == 0 { + return Err(Qtl2Error::Unsupported( + "the panel has no autosomal markers to scan".to_string(), + )); } - let het_dropped = report - .get("het_dropped") - .and_then(Value::as_u64) - .unwrap_or(0) as usize; - let cells = report.get("cells").and_then(Value::as_u64).unwrap_or(0) as usize; Ok(PreparedCross { control, individuals, markers, - non_autosomal: 0, + non_autosomal: want("non_autosomal"), crosstype: crosstype.to_string(), - het_dropped, - cells, + het_dropped: want("het_dropped"), + cells: want("cells"), founders: 0, multiparent: false, }) } -/// Find the control file of a cross named in a request. pub fn resolve_control_file(root: &Path, requested: &str) -> Result<PathBuf, Qtl2Error> { let name = requested.trim(); if name.is_empty() { @@ -488,6 +362,13 @@ fn control_path(control: &Path, json: &Value, key: &str) -> Option<PathBuf> { .map(|name| directory.join(name)) } +fn io_error(path: &Path, error: io::Error) -> Qtl2Error { + Qtl2Error::Io(io::Error::new( + error.kind(), + format!("{}: {error}", path.display()), + )) +} + /// The data lines of a CSV: comments and blank lines skipped, header dropped. fn data_lines(path: &Path, comment: &str) -> Result<Vec<String>, Qtl2Error> { let text = std::fs::read_to_string(path).map_err(|e| io_error(path, e))?; diff --git a/src/response.rs b/src/response.rs index 5e6fcff..8ebcdcd 100644 --- a/src/response.rs +++ b/src/response.rs @@ -29,6 +29,102 @@ pub enum State { Partial, } +/// How a compute request spent its time, beside `took_ms` rather than instead +/// of it. +/// +/// `took_ms` alone cannot say the two things a caller most needs: which engine +/// answered, and whether the work in it was done *now* or reused from a cache. +/// A warm answer and a cold one differ by an order of magnitude on real +/// panels (BXD.8: 3.9 s against 21 min on HET3), and a cached run reports the +/// cache's speed, not the engine's -- so the counts and the states are here +/// next to the durations. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)] +pub struct Timing { + /// Which engine produced `data`: `gemma` (gemma-wrapper, in process), + /// `pangemma` (ravanan + slurm), or `gemma` over ravanan. + pub engine: String, + /// The request's own phases, in the order they ran. Their sum is at most + /// `meta.took_ms`. + pub phases: Vec<PhaseTiming>, + /// What the cluster did, when the engine used one. Absent for the + /// in-process runner and when no Slurm endpoint is configured -- the + /// distinction matters more than a made-up zero. + #[serde(skip_serializing_if = "Option::is_none")] + pub cluster: Option<ClusterTiming>, + /// Per-step figures, one per CWL step instance that has a log. On a warm + /// request these are the times recorded when the step *ran*, which is why + /// each carries its `state`. + #[serde(skip_serializing_if = "Vec::is_empty")] + pub steps: Vec<StepTiming>, + /// Totals over `steps`, so a caller need not sum them. + #[serde(skip_serializing_if = "Option::is_none")] + pub steps_summary: Option<StepsSummary>, +} + +/// One phase of a request. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug)] +pub struct PhaseTiming { + /// `artifacts` (genotype treatment and/or lmdb store), `workflow` (the + /// ravanan invocation), `parse` (reading the engine's outputs), or + /// `wrapper` (the in-process gemma-wrapper run). + pub name: String, + /// `reused` when an artifact was already built for these inputs, `built` + /// when this request built it, `ran` for work done now, and `cached` when + /// the whole phase was a cache hit. + #[serde(skip_serializing_if = "Option::is_none")] + pub state: Option<String>, + pub ms: u64, +} + +/// What the cluster did for this request. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)] +pub struct ClusterTiming { + /// Jobs Slurm accepted between the request starting and finishing. **Zero + /// is the warm claim**: no job ran, so every step came from ravanan's + /// store. + pub jobs_submitted: u64, + /// Sum of those jobs' run times, in ms. This is job time, not wall time: + /// it exceeds the wall clock when jobs overlap on several nodes. + #[serde(skip_serializing_if = "Option::is_none")] + pub run_ms_sum: Option<u64>, + /// The longest single job, in ms -- the floor a scatter cannot beat. + #[serde(skip_serializing_if = "Option::is_none")] + pub run_ms_max: Option<u64>, + /// Sum of queue delays (start minus submit), in ms: dispatch cost as + /// opposed to compute. + #[serde(skip_serializing_if = "Option::is_none")] + pub queue_ms_sum: Option<u64>, +} + +/// One CWL step instance that has a log. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug)] +pub struct StepTiming { + /// `kinship`, `gwa`, `prepare` or `store`. + pub step: String, + /// The chromosome a scattered step ran for, when the log names it (the + /// workflow writes "<chr>-gwa.log.txt"). + #[serde(skip_serializing_if = "Option::is_none")] + pub chr: Option<String>, + /// What the engine itself reported (`## total computation time`), in ms. + #[serde(skip_serializing_if = "Option::is_none")] + pub compute_ms: Option<u64>, + /// `ran` when this request ran the step, `cached` when the figure comes + /// from ravanan's store. + pub state: String, +} + +/// Totals over [`StepTiming`]. +#[derive(Serialize, utoipa::ToSchema, Clone, Debug, Default)] +pub struct StepsSummary { + pub n: usize, + #[serde(skip_serializing_if = "Option::is_none")] + pub compute_ms_sum: Option<u64>, + #[serde(skip_serializing_if = "Option::is_none")] + pub compute_ms_max: Option<u64>, + /// How many of `n` were answered from ravanan's store. + pub cached: usize, +} + /// Facts about this response, as opposed to its data. #[derive(Serialize, utoipa::ToSchema)] pub struct Meta { @@ -60,6 +156,11 @@ pub struct Meta { #[serde(flatten, skip_serializing_if = "Option::is_none")] #[schema(inline)] pub extra: Option<serde_json::Map<String, serde_json::Value>>, + /// Where a compute request's time went (see [`Timing`]). Present only on + /// the compute endpoints, which are the ones whose cost is worth + /// reporting; a read endpoint's `took_ms` says everything. + #[serde(skip_serializing_if = "Option::is_none")] + pub timing: Option<Timing>, } /// A success response: the payload, facts about the response, notes on @@ -85,10 +186,24 @@ pub struct Envelope<T: Serialize + utoipa::ToSchema> { pub struct NextAction { /// Endpoint to call, relative to the API root, e.g. "/species/mouse". pub href: String, + /// True when `href` is a *shape* rather than an address: it still contains + /// a `{placeholder}` the caller substitutes (a trait id the scan does not + /// know, a genotype file name no group lists). Every other link is a `GET` + /// that answers 200 as it stands -- that is the promise `next` makes, and + /// a caller has to be able to tell the two apart without pattern-matching + /// on braces, or it follows a template and gets a 404 (measured: a scan + /// reply carried "/groups/BXD/genotypes/%7Bversion%7D/markers/..."). + #[serde(skip_serializing_if = "std::ops::Not::not")] + pub template: bool, /// What this call gives you, e.g. "Drill down into one species". pub description: String, } +/// Whether a `next` href still holds a placeholder. +fn is_template(href: &str) -> bool { + href.contains('{') || href.contains("%7B") +} + /// A suggested call that is not a plain `GET`, so it cannot live in /// `next`: following a `next` link is a `GET` that returns 200, which is /// what makes those links safe to follow blindly (and what the test @@ -114,6 +229,7 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { pub fn with_next(mut self, href: &str, description: &str) -> Self { self.next.push(NextAction { href: href.to_string(), + template: is_template(href), description: description.to_string(), }); self @@ -155,6 +271,7 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { continue; } self.next.push(NextAction { + template: is_template(&href), href, description: description.to_string(), }); @@ -162,6 +279,21 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> { self } + /// Puts one endpoint-specific value into `meta.extra` (qualified data that + /// belongs beside the rows rather than around them -- the permutation null + /// of a scan, say). + pub fn with_extra(mut self, key: &str, value: serde_json::Value) -> Self { + let extra = self.meta.extra.get_or_insert_with(serde_json::Map::new); + extra.insert(key.to_string(), value); + self + } + + /// Attaches [`Timing`] to `meta`. + pub fn with_timing(mut self, timing: Timing) -> Self { + self.meta.timing = Some(timing); + self + } + pub fn with_note(mut self, note: &str) -> Self { self.notes.push(note.to_string()); self @@ -241,11 +373,36 @@ impl RequestInfo { /// What a handler needs to build its envelope and its errors. Take it /// as the first extractor, so the clock covers authentication too (and /// the token extractor's 401 reports the same request id and time). +/// +/// It also carries the request's usage slot (see [`crate::usage`]): a +/// handler that knows what data the request ran on says so with +/// `usage!(ctx, dataset = …, engine = …)` and the access line grows those +/// fields. Reading routes say nothing -- their dataset is already in the +/// path. pub struct Ctx { info: RequestInfo, + usage: crate::usage::UsageSlot, +} + +// `Ctx` is a request id, a start instant and a handle on the usage slot, so a +// clone is another handle on the same request: /compute/gemma needs it twice +// when the slurm engine runs and the local fallback has to answer, and both +// must write into the one log line. +impl Clone for Ctx { + fn clone(&self) -> Self { + Ctx { + info: self.info.clone(), + usage: self.usage.clone(), + } + } } impl Ctx { + /// Record what this request ran on, for the access log: the same call + /// the `usage!` macro makes, spelled out. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + self.usage.note(pairs); + } /// For `ApiError::with_request_id`: stamps an error with the /// request id and the time taken so far. pub fn request_info(&self) -> RequestInfo { @@ -264,6 +421,7 @@ impl Ctx { num_rows: None, num_cols: None, extra: None, + timing: None, }, notes: Vec::new(), next: Vec::new(), @@ -278,7 +436,18 @@ impl<S: Send + Sync> FromRequestParts<S> for Ctx { async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { let info = RequestInfo::from_parts(parts); parts.extensions.insert(info.clone()); - Ok(Ctx { info }) + // `tag_caller` opened this before routing; a `Ctx` built outside a + // request (a test, an internal call) gets its own, empty, slot. + let usage = parts + .extensions + .get::<crate::usage::UsageSlot>() + .cloned() + .unwrap_or_else(|| { + let slot = crate::usage::UsageSlot::default(); + parts.extensions.insert(slot.clone()); + slot + }); + Ok(Ctx { info, usage }) } } @@ -308,6 +477,7 @@ mod tests { id: Some("req-1".to_string()), started: Instant::now(), }, + usage: crate::usage::UsageSlot::default(), } } diff --git a/src/routes/baskets.rs b/src/routes/baskets.rs index a542620..533a155 100644 --- a/src/routes/baskets.rs +++ b/src/routes/baskets.rs @@ -111,6 +111,16 @@ fn map_error(error: BasketError, rid: RequestInfo) -> ApiError { "baskets", ) .with_request_id(rid), + // A taken name is a conflict, not a malformed request: the body is + // fine, the name is not free. Say so, and point at PATCH. + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Basket name already in use", + format!("{message}"), + "baskets", + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_basket", @@ -159,7 +169,7 @@ pub async fn list_baskets( .envelope(baskets) .with_note("Baskets are yours: they live in your own SQLite file, not in GeneNetwork's \ database.") - .with_note("A mapping can name one instead of posting values: POST /compute/qtl2 with \ + .with_note("A mapping can name one instead of posting values: POST /compute/rqtl, \ \"basket\": \"<name>\"."); envelope = envelope.with_links(crate::suggest::root_links()); Ok(Json(envelope)) @@ -212,7 +222,7 @@ pub async fn create_basket( .map_err(|error| map_error(error, rid.clone()))?; let mut envelope = ctx.envelope(stored).with_note( "Stored. Edit it with PATCH (a new revision, a new digest) and map it with \ - POST /compute/qtl2 {\"basket\": \"<name>\"}.", + POST /compute/rqtl, /compute/qtl2, /compute/gemma or /compute/gemma/ravanan \n {\"basket\": \"<name>\"}.", ); envelope = envelope.with_links(crate::suggest::root_links()); Ok((StatusCode::CREATED, Json(envelope))) @@ -253,7 +263,10 @@ pub async fn get_basket( .envelope(stored) .with_note("`revision` and `digest` identify these exact values: a mapping reply records \ them, so an edit cannot make two runs look alike.") - .with_note("Map it: POST /compute/qtl2 with \"basket\": \"<name>\" in place of `samples`."); + .with_note( + "Map it: POST /compute/rqtl, /compute/qtl2, /compute/gemma or \ + /compute/gemma/ravanan with \"basket\": \"<name>\" in place of `samples`.", + ); envelope = envelope.with_links(links); Ok(Json(envelope)) } diff --git a/src/routes/bnw.rs b/src/routes/bnw.rs index 02cb591..3904ba6 100644 --- a/src/routes/bnw.rs +++ b/src/routes/bnw.rs @@ -102,6 +102,15 @@ pub async fn compute_bnw( Json(request): Json<BnwRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // Which panel and how many traits the structure search was asked for: the + // request body's, not the path's (see crate::usage). + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + crate::usage!(ctx, dataset = group); + } + crate::usage!(ctx, traits = request.traits.len()); + crate::usage!(ctx, engine = "bnw"); let config = Config::load(); let parameters = Parameters { @@ -402,6 +411,15 @@ pub async fn compute_bnw_features( Json(request): Json<BnwFeaturesRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // Which panel and how many traits the structure search was asked for: the + // request body's, not the path's (see crate::usage). + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + crate::usage!(ctx, dataset = group); + } + crate::usage!(ctx, traits = request.traits.len()); + crate::usage!(ctx, engine = "bnw"); let config = Config::load(); let parameters = Parameters { maxparents: request.maxparents.unwrap_or(bnw::DEFAULT_MAXPARENTS), diff --git a/src/routes/bulklmm.rs b/src/routes/bulklmm.rs index d549f07..94d5524 100644 --- a/src/routes/bulklmm.rs +++ b/src/routes/bulklmm.rs @@ -114,6 +114,24 @@ pub async fn compute_bulklmm( Json(mut request): Json<BulklmmRequest>, ) -> Result<Json<Envelope<Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage): the body names the panel and + // the trait, the trait count is what makes a bulklmm request large. + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + None, + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "bulklmm"); let config = Config::load(); let trait_label = request .trait_name diff --git a/src/routes/compare.rs b/src/routes/compare.rs new file mode 100644 index 0000000..9879b8a --- /dev/null +++ b/src/routes/compare.rs @@ -0,0 +1,290 @@ +//! Compare two traits: their shared individuals, the correlation, and a +//! scatter plot of one against the other. +//! +//! GN1's "compare traits" and GN2's trait page both show this, and every piece +//! of it already existed here -- `values_of` for the values, the engine for r +//! and p, the plot family for the figure. What was missing was one endpoint +//! that says "these two, over the individuals they share", with the individual +//! names in the reply so a reader can see which points they are looking at. +//! +//! Deliberate choices: +//! +//! * **The minimum overlap is the correlation floor** (6), not 2: two points +//! always fit a line, and a scatter of two points would look like a result. +//! * **The individuals travel with the numbers**, because a scatter plot is +//! read by looking at outliers, and "which animal is that" is the first +//! question. GN2's page answers it with a hover label; here it is in the +//! reply and in the plot's tooltips. +//! * **Nothing is regressed.** The line in the plot is drawn from r and the two +//! means (an ordinary least-squares line through standardised values), which +//! is the only slope implied by the numbers; no fitted model is invented. + +use axum::Json; +use serde::Deserialize; +use utoipa::ToSchema; + +use crate::auth::AuthToken; +use crate::correlation::{self, Method, Reference}; +use crate::error::ApiError; +use crate::error::Unauthorized; +use crate::response::{Ctx, Envelope}; + +use super::correlation::{db_failure, values_of, TraitRef}; +use crate::plot; +use gnauth_macros::gnauth; + +#[derive(Debug, Clone, Deserialize, ToSchema)] +pub struct CompareRequest { + /// The first trait. + pub a: TraitRef, + /// The second trait. + pub b: TraitRef, + /// "pearson" (default) or "spearman". + #[serde(default)] + pub method: Option<String>, +} + +#[utoipa::path(post, path = "/compute/compare", + summary = "Compare two traits: their shared individuals, r, p and n", + description = "Fetches both traits, keeps the individuals that have a value for both, and \ +returns the correlation over them together with the paired values -- so the reply is both the \ +statistic and the data a scatter plot is drawn from. Needs the same six paired observations the \ +rest of the correlation surface needs: two points always fit a line. `spearman` ranks the pairs \ +first, as everywhere else.", + request_body = CompareRequest, + responses( + (status = 200, description = "The comparison", body = Envelope<serde_json::Value>), + Unauthorized, + (status = 422, description = "Unknown method, a trait with no values, or fewer than six shared individuals", body = ApiError), + (status = 500, description = "Internal error", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn compare( + ctx: Ctx, + _token: AuthToken, + Json(request): Json<CompareRequest>, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let fail = |code: &str, title: &str, detail: String| { + ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + code, + title, + detail, + "compare_traits", + ) + .with_request_id(rid.clone()) + }; + let method = Method::parse(request.method.as_deref().unwrap_or("pearson")) + .map_err(|detail| fail("invalid_method", "Invalid correlation method", detail))?; + + let wanted = request.clone(); + let computed = tokio::task::spawn_blocking(move || align(&request)) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Internal error", + error.to_string(), + "compare_traits", + ) + .with_request_id(rid.clone()) + })? + .map_err(|failure| failure.into_api(rid.clone()))?; + + let aligned = computed; + let n = aligned.pairs.len(); + if n < correlation::MIN_OVERLAP { + return Err(fail( + "too_few_shared", + "Too few shared individuals", + format!( + "these two traits share {n} individual(s) with values; a comparison needs at \ + least {}", + correlation::MIN_OVERLAP + ), + )); + } + let x: Vec<f64> = aligned.pairs.iter().map(|(_, a, _)| *a).collect(); + let y: Vec<f64> = aligned.pairs.iter().map(|(_, _, b)| *b).collect(); + let (r, p) = correlation::correlate_named_value(&x, &y, n, method).ok_or_else(|| { + fail( + "no_correlation", + "No correlation", + "the coefficient is not a number over these individuals \ + (a constant trait has no correlation with anything)" + .to_string(), + ) + })?; + + let rows = serde_json::Value::Array( + aligned + .pairs + .iter() + .map(|(individual, a, b)| serde_json::json!([individual, a, b])) + .collect(), + ); + let mut body = serde_json::json!({ + "a": {"dataset": wanted.a.dataset, "trait_name": wanted.a.trait_name}, + "b": {"dataset": wanted.b.dataset, "trait_name": wanted.b.trait_name}, + "method": method.as_str(), + "r": r, + "p": if p.is_finite() { serde_json::Value::from(p) } else { serde_json::Value::Null }, + "n": n, + "pairs": rows, + }); + if let Some(extra) = aligned.only_one_side { + body["only_one_side"] = serde_json::Value::from(extra); + } + Ok(Json( + ctx.envelope(body) + .with_columns( + vec!["individual".to_string(), "a".to_string(), "b".to_string()], + n, + ) + .with_note(&format!( + "{} ({}) against {} ({}), {} over the {n} individual(s) with a value for both.", + wanted.a.trait_name, wanted.a.dataset, wanted.b.trait_name, wanted.b.dataset, + method.as_str() + )) + .with_note( + "`pairs` is positional: individual, first trait's value, second trait's value. \ + The individuals that had a value for only one side are counted in \ + `only_one_side`.", + ) + .with_next("/plot/compare", "The same numbers as a scatter plot"), + )) +} + +#[utoipa::path(post, path = "/plot/compare", + summary = "Draw the scatter plot of two compared traits, as an SVG", + description = "Post the response of POST /compute/compare back (as-is) and get the figure \ +scripts/plot-compare.py draws from it: one point per individual that has both values, the \ +individual's name in each point's tooltip, and the least-squares line implied by r and the two \ +means. Nothing is refitted and nothing is recomputed. image/svg+xml, not the JSON envelope; \ +`x-plot-summary` carries the plotter's one-line summary.", + params(super::plot::PlotParams), + request_body = serde_json::Value, + responses( + (status = 200, description = "The SVG", body = String, content_type = "image/svg+xml"), + Unauthorized, + (status = 422, description = "The posted body is not a comparison", body = ApiError), + (status = 502, description = "The plotter failed", body = ApiError) + ) +)] +#[gnauth(token_only)] +pub async fn plot_compare( + ctx: Ctx, + _token: AuthToken, + axum::extract::Query(plot_params): axum::extract::Query<super::plot::PlotParams>, + Json(posted): Json<serde_json::Value>, +) -> Result<axum::response::Response, ApiError> { + let rid = ctx.request_info(); + let data = posted.get("data").unwrap_or(&posted); + let pairs = data.get("pairs").and_then(|pairs| pairs.as_array()); + if pairs.map(|rows| rows.len()).unwrap_or(0) < 2 { + return Err(ApiError::new( + axum::http::StatusCode::UNPROCESSABLE_ENTITY, + "not_a_comparison", + "Not a comparison", + "the posted body has fewer than two `pairs`: post a /compute/compare reply".to_string(), + "plot_compare", + ) + .with_request_id(rid)); + } + let config = crate::config::Config::load(); + let mut extra: Vec<String> = Vec::new(); + if let Some(title) = plot_params.title.as_deref() { + extra.push("--title".to_string()); + extra.push(title.to_string()); + } + let borrowed: Vec<&str> = extra.iter().map(String::as_str).collect(); + let rendered = plot::render( + &config.plot_python, + &config.compare_plotter, + std::path::Path::new(&config.gemma_cache_dir), + &posted, + plot_params.trait_label.as_deref().unwrap_or(""), + &borrowed, + ) + .await + .map_err(|error| { + ApiError::new( + axum::http::StatusCode::BAD_GATEWAY, + "plot_failed", + "The plotter failed", + error.to_string(), + "plot_compare", + ) + .with_request_id(rid) + })?; + Ok(super::plot::svg_response(rendered)) +} + +/// The aligned pairs, plus a count of individuals only one side had. +struct Aligned { + pairs: Vec<(String, f64, f64)>, + only_one_side: Option<usize>, +} + +fn align(request: &CompareRequest) -> Result<Aligned, super::correlation::Failure> { + let a = values_of(&request.a.dataset, &request.a.trait_name)?; + let b = values_of(&request.b.dataset, &request.b.trait_name)?; + let mut pairs = Vec::new(); + let mut only_one_side = 0usize; + for (index, name) in a.names.iter().enumerate() { + match b.names.iter().position(|candidate| candidate == name) { + Some(position) => pairs.push((name.clone(), a.values[index], b.values[position])), + None => only_one_side += 1, + } + } + // Individuals only in B are not visited by the loop above. + for name in &b.names { + if !a.names.contains(name) { + only_one_side += 1; + } + } + Ok(Aligned { + pairs, + only_one_side: if only_one_side > 0 { + Some(only_one_side) + } else { + None + }, + }) +} + +/// Keep `Reference` in scope for readers of `align`. +#[allow(dead_code)] +fn _reference_is_used(_: &Reference) {} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_pairs_are_the_shared_individuals() { + let a = Reference::from_pairs(vec![ + ("s1".to_string(), Some(1.0)), + ("s2".to_string(), Some(2.0)), + ("s3".to_string(), Some(3.0)), + ]); + let b = Reference::from_pairs(vec![ + ("s2".to_string(), Some(20.0)), + ("s3".to_string(), Some(30.0)), + ("s4".to_string(), Some(40.0)), + ]); + let mut pairs = Vec::new(); + for (index, name) in a.names.iter().enumerate() { + if let Some(position) = b.names.iter().position(|candidate| candidate == name) { + pairs.push((name.clone(), a.values[index], b.values[position])); + } + } + assert_eq!(pairs, vec![ + ("s2".to_string(), 2.0, 20.0), + ("s3".to_string(), 3.0, 30.0), + ]); + } +} diff --git a/src/routes/correlation.rs b/src/routes/correlation.rs index 2a7f8a2..a3620f6 100644 --- a/src/routes/correlation.rs +++ b/src/routes/correlation.rs @@ -702,7 +702,7 @@ fn resolve_reference(request: &CorrelationRequest) -> Result<correlation::Refere /// One trait's values, from whichever kind of dataset holds it: a probeset by /// name, a phenotype trait by numeric id. -fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { +pub(crate) fn values_of(dataset: &str, trait_name: &str) -> Result<correlation::Reference, Failure> { let request = CorrelationRequest { dataset: dataset.to_string(), trait_name: trait_name.to_string(), diff --git a/src/routes/correlation_matrix.rs b/src/routes/correlation_matrix.rs index 9a433b6..9676cd4 100644 --- a/src/routes/correlation_matrix.rs +++ b/src/routes/correlation_matrix.rs @@ -167,7 +167,7 @@ pub async fn correlation_matrix( } let wanted = request.clone(); - let matrix = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) + let (matrix, references) = tokio::task::spawn_blocking(move || build(&request, method, min_overlap)) .await .map_err(|error| { ApiError::new( @@ -192,11 +192,22 @@ pub async fn correlation_matrix( } } let measured = measured / 2; - let pca = if wanted.pca.unwrap_or(false) { + let mut pca = if wanted.pca.unwrap_or(false) { Some(crate::pca::analyse(&matrix)) } else { None }; + // The components as *traits*: a PC is only usable (correlated, mapped, + // plotted, saved in a basket) if it has a value per individual, and that + // needs the values the matrix was built from -- which is why it happens + // here and not in pca::analyse. + if let Some(pca) = pca.as_mut() { + if let Some((values, individuals)) = kept_values_in_order(&references, pca) { + if let Some(traits) = crate::pca::scores(pca, &values, &individuals) { + pca.traits = traits; + } + } + } let mut body = serde_json::json!({ "traits": matrix.traits, "r": matrix.r, @@ -278,6 +289,64 @@ pub async fn correlation_matrix( )) } +/// The aligned values of the traits the PCA kept, over the individuals that +/// have a value for **every** kept trait. +/// +/// PCA of standardised traits is only defined on a complete rectangle, which is +/// the same rule that already dropped traits with a gap: a different individual +/// set per trait would make the scores incomparable across individuals. +fn kept_values_in_order( + references: &[Reference], + pca: &crate::pca::Pca, +) -> Option<(Vec<Vec<f64>>, Vec<String>)> { + let components = pca.components.first()?; + let n_kept = components.loadings.len(); + if n_kept == 0 || n_kept > references.len() { + return None; + } + // The kept traits are the first n_kept that have values; the PCA was built + // from the matrix's own kept order, so take that same order. + let kept: Vec<&Reference> = references + .iter() + .filter(|reference| !reference.is_empty()) + .take(n_kept) + .collect(); + if kept.len() != n_kept { + return None; + } + let individuals: Vec<String> = kept[0] + .names + .iter() + .filter(|name| { + kept.iter().all(|reference| { + reference + .names + .iter() + .position(|candidate| candidate == *name) + .map(|position| true) + .unwrap_or(false) + }) + }) + .cloned() + .collect(); + if individuals.len() < 3 { + return None; + } + let mut values: Vec<Vec<f64>> = Vec::with_capacity(n_kept); + for reference in &kept { + let mut row = Vec::with_capacity(individuals.len()); + for name in &individuals { + let position = reference + .names + .iter() + .position(|candidate| candidate == name)?; + row.push(reference.values[position]); + } + values.push(row); + } + Some((values, individuals)) +} + /// How many traits the request asked for. fn matrix_trait_count(matrix: &Matrix) -> usize { matrix.traits.len() @@ -299,9 +368,10 @@ fn build( request: &MatrixRequest, method: Method, min_overlap: usize, -) -> Result<Matrix, Failure> { +) -> Result<(Matrix, Vec<Reference>), Failure> { let axis = matrix_axis(request)?; let references = resolve_traits(request, axis.as_deref())?; + let references_out = references.clone(); let count = references.len(); let mut r = vec![vec![None; count]; count]; @@ -343,7 +413,7 @@ fn build( } } - Ok(Matrix { + Ok((Matrix { traits: request .traits .iter() @@ -355,7 +425,7 @@ fn build( r, p, n, - }) + }, references_out)) } /// The individuals every trait is measured over: the first trait's group. diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs index 1835b4c..eed7d1c 100644 --- a/src/routes/datasets.rs +++ b/src/routes/datasets.rs @@ -107,7 +107,8 @@ fn get_dataset_probesets_result( #[utoipa::path(get, path = "/datasets/{dataset}/probesets", summary = "List the expression (ProbeSet) traits belonging to a dataset", params( ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id") ), responses( - (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata", body = Envelope<Vec<db::ProbeSetInfo>>), + (status = 200, description = "The probesets' ProbeSetXRef/ProbeSet metadata; \ +`ids_only`/`names_only` answer one value per probeset instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 403, description = "The dataset isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching dataset", body = ApiError), @@ -118,8 +119,20 @@ pub async fn dataset_probesets( ctx: Ctx, Path(dataset): Path<String>, token: AuthToken, -) -> Result<Json<Envelope<Vec<db::ProbeSetInfo>>>, ApiError> { + axum::extract::Query(params): axum::extract::Query<crate::listing::ListingParams>, +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(¶ms).map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "dataset_probesets", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = dataset.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { @@ -150,8 +163,14 @@ pub async fn dataset_probesets( .with_request_id(rid.clone()), }) .and_then(|lookup| match lookup { - DatasetProbesetsLookup::Found(_authorized, probesets) => Ok(Json( - ctx.envelope(probesets) + DatasetProbesetsLookup::Found(_authorized, probesets) => { + let rows: Vec<serde_json::Value> = probesets + .iter() + .map(|probeset| serde_json::to_value(probeset).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) .with_note(db::LOD_NOTE) .with_next( &format!("/datasets/{}", path_segment(¬_found_name)), @@ -161,8 +180,16 @@ pub async fn dataset_probesets( &format!("/datasets/{}/probesets/{{probeset}}/values", path_segment(¬_found_name)), "One probeset's value per strain, with the mapping suggestions", ) - .with_links(crate::suggest::root_links()), - )), + .with_links(crate::suggest::root_links()); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no probeset: {}", + missing.len(), + missing.join(", ") + )); + } + Ok(Json(envelope)) + } DatasetProbesetsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, "forbidden", diff --git a/src/routes/fitqtl.rs b/src/routes/fitqtl.rs index ee2e259..60b4af3 100644 --- a/src/routes/fitqtl.rs +++ b/src/routes/fitqtl.rs @@ -123,6 +123,26 @@ pub async fn compute_fitqtl( Json(mut request): Json<FitqtlRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "fitqtl"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } if let Some(upload) = request.genotype_upload.clone() { if request.genotype_file.is_some() || request.group.is_some() { return Err(ApiError::new( diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index a17010b..fc5c06e 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -22,22 +22,53 @@ use crate::compute_gate; use crate::covariates; use crate::error::{ApiError, Unauthorized}; use crate::genotypes; +use crate::qtl2; use crate::gemma::{self, GemmaError}; use crate::response::{Ctx, Envelope, RequestInfo, path_segment}; use crate::streaming::{self, RunStatus, RunStatusParams, StatusError}; +/// Tell the access log what this GEMMA request ran on: the body names the +/// panel (or the upload, file or basket), the path cannot. Called before +/// any validation, so a 4xx still records what was asked for -- a failed +/// compute is as interesting as a successful one. `engine` is the route +/// that will answer: `gemma` (the in-process wrapper), `ravanan` (the +/// per-chromosome workflow) or `pangemma` (the lmdb store); see +/// [`crate::usage`]. +fn record_usage(ctx: Ctx, request: &GemmaRequest, run: Option<&str>, engine: &str) { + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + None, + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + // An explicit `engine` in the body wins over the route's own label, so + // the field says what answered rather than where it was posted. + crate::usage!(ctx, engine = crate::usage::engine(request.engine.as_deref(), engine)); + if let Some(run) = run.map(str::trim).filter(|run| !run.is_empty()) { + crate::usage!(ctx, run = run); + } +} + /// `?id=` on `POST /compute/gemma`: an optional, caller-chosen run id /// to log this run's progress under and poll back via `GET /// /compute/gemma/status/{id}`. Omitted entirely, no log is written. /// Must be unique: a collision with an existing log (another run still /// in progress, or one finished and never polled/cleaned up) errors out /// rather than overwriting it -- see `gemma::GemmaError::RunIdInUse`. -#[derive(Deserialize, utoipa::IntoParams)] +// Clone so that the slurm engine (the default) and the local fallback can +// both be handed the same request: /compute/gemma passes it to the slurm path +// first, and keeps it for the wrapper run when that fails. +#[derive(Clone, Deserialize, utoipa::IntoParams)] pub struct ComputeGemmaParams { pub id: Option<String>, } -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaRequest { /// Path to a BIMBAM genotype file (plain text or gzipped), passed /// as GEMMA's `-g`. Give this and `snps_file`, or `group` -- not @@ -119,10 +150,36 @@ pub struct GemmaRequest { pub permutations: Option<u32>, /// Refused unless 0, as `nperm`. pub permutate: Option<u32>, + + /// How a missing genotype is treated, for the ravanan path: `none` + /// (default -- the file is used as it stands, so GEMMA does complete-case + /// per marker and reports `n_miss`), `mean` (each gap takes that marker's + /// mean) or `hmm` (R/qtl2's HMM predicts it from flanking markers). The + /// last two produce a complete genotype file, which is what a comparison + /// between engines needs: a complete file maps one marker more than + /// complete-case treatment does (21,056 against 21,055 on BXD.8), so the + /// two modes are not interchangeable. `hmm` needs a group-scoped request, + /// since the cross it predicts from is the group's. + /// + /// Neither engine needs it: GEMMA does complete-case per marker, and + /// pangemma's store keeps the gaps (NaN for Gf, 255 for Gb) and + /// mean-substitutes them per marker as GEMMA does -- measured: `none` + /// answers 21,055 rows through pangemma with `af` identical to GEMMA's. + /// The mode is applied before the store is built, so each one gets its own + /// store (they are different genotype files) and an already-imputed panel + /// pays the store build once per mode. + pub impute: Option<String>, + /// Which engine the per-chromosome workflow runs: `gemma` (default, + /// gemma-gn2 on BIMBAM) or `pangemma` (the GeneNetwork fork reading an + /// lmdb genotype store, built once per genotype file and reused by every + /// trait over that panel). pangemma needs the ravanan/Slurm route and + /// has no in-process fallback, so a request for it fails rather than + /// silently mapping with gemma. + pub engine: Option<String>, } /// One trait value, by individual name. -#[derive(Deserialize, utoipa::ToSchema)] +#[derive(Clone, Deserialize, utoipa::ToSchema)] pub struct GemmaSample { pub name: String, pub value: Option<f64>, @@ -155,6 +212,512 @@ pub(crate) struct ResolvedInputs { pub notes: Vec<String>, } +/// A memo of where an artifact workflow left its outputs. +/// +/// Not a data cache -- ravanan's store is that, and it is keyed on +/// (script, inputs) -- but a pointer cache, so a request whose artifact is +/// already built does not pay for a whole ravanan invocation to be told so. +/// Measured: a cached 40-step run still costs ~7 s of ravanan's own walk, and +/// a warm pangemma request runs two workflows (store, then mapping), so the +/// pointer is worth keeping. +/// +/// The key covers the inputs' size and mtime, so a regenerated panel file or a +/// rewritten prepared file misses. A stale entry whose paths have gone (a +/// pruned store) is ignored and rebuilt. +fn artifact_memo_key(label: &str, parts: &[String]) -> String { + let mut material = Vec::new(); + material.extend_from_slice(label.as_bytes()); + for part in parts { + material.push(0); + material.extend_from_slice(part.as_bytes()); + } + gemma::sha16(&material) +} + +fn artifact_memo_load(path: &std::path::Path) -> Option<Vec<(String, String)>> { + let contents = std::fs::read_to_string(path).ok()?; + let entries: Vec<(String, String)> = contents + .lines() + .filter_map(|line| line.split_once('\t')) + .map(|(id, file)| (id.to_string(), file.to_string())) + .collect(); + if entries.is_empty() + || entries + .iter() + .any(|(_, file)| !std::path::Path::new(file).is_file()) + { + return None; + } + Some(entries) +} + +fn artifact_memo_save(path: &std::path::Path, outputs: &[(String, Vec<String>)]) { + if let Some(parent) = path.parent() { + let _ = std::fs::create_dir_all(parent); + } + let body: String = outputs + .iter() + .filter_map(|(id, paths)| paths.first().map(|file| format!("{id}\t{file}\n"))) + .collect(); + let tmp = path.with_extension(format!("tmp-{}", std::process::id())); + if std::fs::write(&tmp, body).is_ok() { + let _ = std::fs::rename(&tmp, path); + } +} + +/// `path:size:mtime` for a file, so a rewritten input misses the memo. +fn artifact_input_stamp(path: &str) -> String { + match std::fs::metadata(path) { + Ok(metadata) => { + let mtime = metadata + .modified() + .ok() + .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok()) + .map(|since| since.as_nanos()) + .unwrap_or(0); + format!("{path}:{}:{mtime}", metadata.len()) + } + Err(_) => path.to_string(), + } +} + +/// The two cluster-side artifacts a ravanan request needs before anything is +/// mapped: the missing-genotype treatment (`cwl/gemma/prepare.scm`) and, for +/// pangemma, its lmdb store (`cwl/gemma/store.scm`). +/// +/// Both are workflows rather than steps inside the mapping workflow because +/// ccwl's `pipe` is linear -- the GWA step needs the prepared genotypes *and* +/// the kinship matrix, which is a diamond. Ravanan caches each of them on +/// (script, inputs), so the treatment runs once per (panel, mode) and the store +/// once per panel, however many traits follow. +/// +/// Failure here is the caller's error only when it is the *request's* (an +/// unknown mode, `hmm` without a group); a cluster or script failure is a 502 +/// like any other engine failure. +#[allow(clippy::too_many_arguments)] +async fn ravanan_artifacts( + config: &Config, + engine: crate::gemma::GemmaEngine, + mode: &str, + genotype_file: &str, + snps_file: &str, + group: &Option<String>, + version: Option<&str>, + names: Option<&Vec<String>>, + endpoint: &'static str, + rid: RequestInfo, +) -> Result<Artifacts, ApiError> { + let cache_dir = &config.ravanan_cache_dir; + let artifacts_started = std::time::Instant::now(); + let mut built = false; + let mut notes = Vec::new(); + std::fs::create_dir_all(cache_dir).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cache directory", + format!("creating {cache_dir} failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + + // The cross `hmm' predicts from, and the individuals this request serves. + // Both are inputs of the prepare workflow even when it ignores them: a CWL + // step input cannot be optional here, and an empty directory and file are + // cheaper than building a cross nobody asked for. + let (cross_dir, cross_note) = if mode == "hmm" { + let Some(group_name) = group.clone() else { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_group", + "hmm imputation needs a group", + "the HMM predicts a missing call from flanking markers in a converted \ + cross, and a cross is built from a group; send `group` (with \ + `genotype_version` if you want a particular version), or use \ + impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + }; + let (directory, cache, convert) = ( + config.genotype_files_dir.clone(), + config.qtl2_cache_dir.clone(), + config.qtl2_convert_script.clone(), + ); + let version = version.map(|v| v.to_string()); + let prepared = tokio::task::spawn_blocking(move || { + let resolved = + genotypes::resolve(std::path::Path::new(&directory), &group_name, version.as_deref()) + .map_err(|error| error.to_string())?; + // Drop is the default genotype model: the heterozygous calls a + // riset panel carries are exactly the ones the HMM is asked to + // re-predict, so predicting from the kept calls would be circular. + qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache), + qtl2::Het::Drop, + std::path::Path::new(&convert), + ) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not prepare the cross", + format!("preparing the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "cross_preparation_failed", + "Could not prepare the cross", + format!("{error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + let dir = prepared + .control + .parent() + .map(|dir| dir.to_path_buf()) + .unwrap_or_else(|| std::path::PathBuf::from(&config.qtl2_cache_dir)); + // Copy it under the cache directory, which is on the filesystem the + // compute nodes see: ravanan's slurm backend does not stage a Directory + // input (measured: the staged path reached the job and the HMM's setwd + // failed, while the same workflow ran under single-machine), so the job + // reads the cross where it lies instead. The cross's own name carries + // its version and a panel fingerprint, so copying once is enough. + let staged = std::path::Path::new(&config.ravanan_cache_dir) + .join("crosses") + .join(dir.file_name().unwrap_or_default()); + if !staged.is_dir() { + let (from, to) = (dir.clone(), staged.clone()); + tokio::task::spawn_blocking(move || { + std::fs::create_dir_all(to.parent().unwrap_or(&to))?; + let status = std::process::Command::new("cp") + .arg("-r") + .arg(&from) + .arg(&to) + .status()?; + if !status.success() { + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + "cp -r failed", + )); + } + Ok::<(), std::io::Error>(()) + }) + .await + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("staging the qtl2 cross failed: {error}"), + endpoint, + ) + .with_request_id(rid.clone()) + })? + .map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not stage the cross", + format!("copying {} to {} failed: {error}", dir.display(), staged.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + } + ( + staged.to_string_lossy().into_owned(), + Some( + "genotypes: the group's R/qtl2 cross, so a missing call is predicted by the \ + HMM (maxmarg on the same genotype probabilities /compute/qtl2 maps on)" + .to_string(), + ), + ) + } else { + let empty = std::path::Path::new(cache_dir).join("no-cross"); + std::fs::create_dir_all(&empty).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not create the artifact staging directory", + format!("creating {} failed: {error}", empty.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + (empty.to_string_lossy().into_owned(), None) + }; + if let Some(note) = cross_note { + notes.push(note); + } + + // The served individuals, one per line: an input of the workflow, and for + // `hmm' also the list the R script restricts its calls to. + let served = match names { + Some(names) if !names.is_empty() => { + let path = std::path::Path::new(cache_dir).join(format!( + "served-individuals-{}.txt", + crate::gemma::sha16(names.join(",").as_bytes()) + )); + let body: String = names.iter().map(|n| format!("{n}\n")).collect(); + std::fs::write(&path, body).map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + _ => { + if mode == "hmm" { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "impute_needs_names", + "hmm imputation needs named individuals", + "the HMM is asked for a specific set of individuals, so the request has to \ + name them: send `samples` or a group-scoped request (not positional \ + `trait_values`), or use impute=mean." + .to_string(), + endpoint, + ) + .with_request_id(rid)); + } + let path = std::path::Path::new(cache_dir).join("no-individuals.txt"); + std::fs::write(&path, "").map_err(|error| { + ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not write the empty individual list", + format!("writing {} failed: {error}", path.display()), + endpoint, + ) + .with_request_id(rid.clone()) + })?; + path.to_string_lossy().into_owned() + } + }; + + // Ravanan resolves an input path relative to the inputs YAML, which lives + // in the cache directory -- so a configured script path has to be absolute + // here, not merely valid from the server's working directory (measured: a + // relative prepare-genotypes.sh died inside ravanan as + // "canonicalize-path: No such file or directory"). + let absolute = |path: &str| -> String { + std::fs::canonicalize(path) + .map(|p| p.to_string_lossy().into_owned()) + .unwrap_or_else(|_| path.to_string()) + }; + let prepare_script = absolute(&config.prepare_genotypes); + let impute_script = absolute(&config.impute_script); + + let (genotype_file, snps_file, individuals_file) = if mode == "none" { + (genotype_file.to_string(), snps_file.to_string(), None) + } else { + let inputs = format!( + "mode: \"{mode}\"\n\ + prepare_script: {{class: File, path: {}}}\n\ + impute_script: {{class: File, path: {}}}\n\ + genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n\ + cross: \"{cross_dir}\"\n\ + individuals_file: {{class: File, path: {served}}}\n", + prepare_script, impute_script, + ); + let memo = std::path::Path::new(cache_dir) + .join("artifacts") + .join(format!( + "{}.txt", + artifact_memo_key( + "prepare", + &[ + mode.to_string(), + artifact_input_stamp(genotype_file), + artifact_input_stamp(snps_file), + cross_dir.clone(), + artifact_input_stamp(&served), + ], + ) + )); + let from_memo = artifact_memo_load(&memo).map(|entries| { + let pick = |id: &str| { + entries + .iter() + .find(|(name, _)| name == id) + .map(|(_, file)| file.clone()) + .unwrap_or_default() + }; + (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file"))) + }); + if let Some(found) = from_memo { + notes.push(format!( + "genotypes: '{mode}' treatment reused (ravanan built it for this panel and \ + mode earlier; the mapping workflow takes the same paths, so its own cache \ + still applies)" + )); + found + } else { + let run = gemma::ArtifactWorkflow { + label: "prepare", + ccwl_cmd: &config.ccwl_cmd, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_prepare_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &[ + "mode", + "prepare_script", + "impute_script", + "genotype_file", + "snps_file", + "cross", + "individuals_file", + ], + &inputs, + &["genotype_file", "snps_file", "individuals_file"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let pick = |id: &str| { + outputs + .iter() + .find(|(name, _)| name == id) + .and_then(|(_, paths)| paths.first().cloned()) + .unwrap_or_default() + }; + artifact_memo_save(&memo, &outputs); + built = true; + notes.push(format!( + "genotypes: '{mode}' treatment applied by the prepare workflow (ravanan + the \ + cluster), cached by ravanan on (script, inputs)" + )); + (pick("genotype_file"), pick("snps_file"), Some(pick("individuals_file"))) + } + }; + + let store = if engine == gemma::GemmaEngine::Pangemma { + let memo = std::path::Path::new(cache_dir) + .join("artifacts") + .join(format!( + "{}.txt", + artifact_memo_key( + "store", + &[ + artifact_input_stamp(&genotype_file), + artifact_input_stamp(&snps_file), + ], + ) + )); + if let Some(entries) = artifact_memo_load(&memo) { + notes.push( + "genotypes: pangemma's lmdb store reused (ravanan built it for these genotypes \ + earlier)" + .to_string(), + ); + Some( + entries + .iter() + .find(|(name, _)| name == "store") + .map(|(_, file)| file.clone()) + .unwrap_or_default(), + ) + } else { + // No converter script: geno2mdb comes from the job's profile + // (gemma-wrapper's bin/geno2mdb, an Odin binary), and ccwl appends + // every declared input to the command line -- a staged copy of the + // binary arrived as argv[1] and was read as the BIMBAM file. + let inputs = format!( + "genotype_file: {{class: File, path: {genotype_file}}}\n\ + snps_file: {{class: File, path: {snps_file}}}\n" + ); + let run = gemma::ArtifactWorkflow { + label: "store", + ccwl_cmd: &config.ccwl_cmd, + ravanan_cmd: &config.ravanan_cmd, + batch: &config.ravanan_batch, + source: &config.gemma_store_workflow, + manifest: &config.gemma_artifacts_manifest, + cache_dir, + scratch_dir: &config.ravanan_scratch, + }; + let outputs = gemma::run_artifact( + &run, + &["genotype_file", "snps_file"], + &inputs, + &["store"], + ) + .await + .map_err(|error| gemma_error_to_api_error(error, rid.clone()))?; + let path = outputs + .iter() + .find(|(name, _)| name == "store") + .and_then(|(_, paths)| paths.first().cloned()); + artifact_memo_save(&memo, &outputs); + built = true; + notes.push( + "genotypes: pangemma's lmdb store built by the store workflow (ravanan + the \ + cluster), cached by ravanan on (script, inputs)" + .to_string(), + ); + path + } + } else { + None + }; + + let needed = mode != "none" || engine == gemma::GemmaEngine::Pangemma; + Ok(Artifacts { + genotype_file, + snps_file, + store, + individuals_file, + ms: artifacts_started.elapsed().as_millis() as u64, + state: if !needed { + "none".to_string() + } else if built { + "built".to_string() + } else { + "reused".to_string() + }, + notes, + }) +} + +/// What [`ravanan_artifacts`] produced. +struct Artifacts { + genotype_file: String, + snps_file: String, + store: Option<String>, + /// Milliseconds spent producing the artifacts, and whether any of them was + /// built by this request (`built`), all came from ravanan's store + /// (`reused`), or the request needed none (`none`). + ms: u64, + state: String, + /// The individual order of the prepared genotypes, when the treatment + /// changed it (`hmm` takes its order from the cross). + individuals_file: Option<String>, + notes: Vec<String>, +} + /// Resolve a request's genotype input and trait values. /// /// `endpoint` names this endpoint in errors ("compute_gemma" or @@ -301,6 +864,9 @@ pub(crate) async fn resolve_inputs( }) .unwrap_or_default(); let supplied_values = request.trait_values.clone(); + // Whether the caller named its values: `named` moves into the alignment + // closure below, and the note after it still has to say which it was. + let had_named_values = !named.is_empty(); match (request.genotype_file.clone(), request.snps_file.clone(), group) { (Some(genotype_file), Some(snps_file), None) => { @@ -320,7 +886,15 @@ pub(crate) async fn resolve_inputs( } else { let path = std::path::PathBuf::from(&genotype_file); let aligned = tokio::task::spawn_blocking(move || { - genotypes::align_to_file(&path, &named) + // A `.geno` names its individuals in the header; a BIMBAM + // does not, so its names come from the `.geno` beside it + // (see `names_for_bimbam`). Without that, named values on + // a file request aligned against nothing and every value + // was dropped. + match genotypes::names_for_bimbam(&path) { + Some(names_source) => genotypes::align_to_columns_of(&names_source, &named), + None => genotypes::align_to_file(&path, &named), + } }) .await .map_err(|error| { @@ -337,8 +911,15 @@ pub(crate) async fn resolve_inputs( aligned }; notes.push(format!( - "Genotype: given file and SNP map; {} values used.", - trait_values.iter().filter(|value| value.is_some()).count() + // Name the order the values ended up in, so a caller can check + // it without knowing the file by heart. + "Genotype: given file and SNP map; {} values used{}.", + trait_values.iter().filter(|value| value.is_some()).count(), + if had_named_values { + ", aligned by name onto the genotype file's individuals" + } else { + "" + } )); Ok(ResolvedInputs { individuals: trait_values.len(), @@ -392,7 +973,21 @@ pub(crate) async fn resolve_inputs( None => keep, }; let dropped_empty = (resolved.panel.len() - parents_f1s) - keep.len(); - let (aligned, matched) = genotypes::align(&resolved.panel, &keep, &named); + // Pad the phenotype over *the genotype file's* individuals + // instead of narrowing the genotypes to the ones that have + // values. Both files must describe the same animals in the + // same order, and padding is the side that cannot drift: an + // excluded animal is a row of NA, which GEMMA drops from the + // fit (and from -gk, where `-p` only names who is analysed), + // while a narrowed genotype file has to be written correctly + // for every delimiter a panel might use -- which is how this + // went wrong: write_subset_bimbam splits on ',' and HSNIH's + // BIMBAM is whitespace-separated, so the "subset" was a byte + // copy of all 6147 columns against a 6111-row phenotype, and + // GEMMA failed every marker (6147 != 6111). + let all_individuals: Vec<usize> = (0..resolved.panel.len()).collect(); + let (aligned, matched) = + genotypes::align(&resolved.panel, &all_individuals, &named); let kept_names: Vec<String> = keep .iter() .filter_map(|index| resolved.panel.get(*index).cloned()) @@ -401,7 +996,7 @@ pub(crate) async fn resolve_inputs( &directory, &resolved, genotypes::Engine::Gemma, - &keep, + &all_individuals, &cache_dir, )?; Ok::<_, genotypes::GenotypeError>(( @@ -560,6 +1155,79 @@ pub async fn compute_gemma( Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this request ran on, for the access log (see crate::usage). + record_usage(ctx.clone(), &request, params.id.as_deref(), "gemma"); + + // Which engine answers: Slurm by default (GEMMA_ENGINE=slurm), the same + // per-chromosome workflow /compute/gemma/ravanan runs; the in-process + // gemma-wrapper run below is then only a fallback, and only for an + // infrastructure failure -- Slurm or ravanan unreachable, the engine + // exiting non-zero, i.e. a 5xx from that path. A 4xx is the caller's + // error and is returned as such, and a numerical disagreement is never a + // reason to fall back: that would hide a regression behind an answer from + // the other engine. + let engine_config = Config::load(); + // pangemma has no in-process counterpart: the wrapper runs gemma on + // BIMBAM, so falling back would answer a different question under the + // requested engine's name. It therefore forces the Slurm route even when + // GEMMA_ENGINE=local, and its failures are returned as they are. + let pangemma = matches!( + request.engine.as_deref(), + Some(value) if crate::gemma::GemmaEngine::parse(value) == Some(crate::gemma::GemmaEngine::Pangemma) + ); + // A treatment the request asked for and the wrapper cannot apply: the + // in-process run reads the panel's genotypes as they stand, so falling back + // to it on `impute: hmm` answered 21,055 rows where the request meant the + // HMM's 20,453 -- a wrong answer wearing a "degraded" note. Treated + // requests therefore fail rather than fall back. + let treated = pangemma + || !request + .impute + .as_deref() + .unwrap_or("none") + .eq_ignore_ascii_case("none"); + let mut fallback_note: Option<String> = None; + if treated || !engine_config.gemma_engine.eq_ignore_ascii_case("local") { + match gemma_via_ravanan( + ctx.clone(), + token.clone(), + params.clone(), + request.clone(), + __gn4_claim, + "compute_gemma", + ) + .await + { + Ok(answer) => return Ok(answer), + Err(error) if error.status >= 500 && !treated => { + eprintln!( + "compute_gemma: slurm route failed ({} {}); falling back to the local gemma-wrapper run", + error.status, error.code + ); + // The claim went with the slurm attempt; a light claim is by + // design cheap and reserves nothing, so take a fresh one for + // the fallback rather than plumbing it back. + __gn4_claim = crate::compute_gate::gemma().claim_light( + &token.sub, + params.id.as_deref(), + "compute_gemma", + "compute_gemma", + "/compute/gemma/status", + ); + fallback_note = Some(format!( + concat!( + "Engine: the Slurm route was unavailable ({} {}), so this answer ", + "comes from the local gemma-wrapper run instead -- same GEMMA, ", + "per-chromosome LOCO computed in process rather than as cluster jobs." + ), + error.status, error.code + )); + } + Err(error) => return Err(error), + } + } + let lmm = request.lmm.unwrap_or(9); // Only the values actually run against this GEMMA build (see the // `lmm` field doc above) are allowed; 5-8 are stock-invalid and @@ -746,6 +1414,9 @@ pub async fn compute_gemma( let rid_for_job = rid.clone(); let trait_values_for_job = trait_values.clone(); let covariates_for_job = covariate_list.clone(); + // The in-process run: one phase, because one process did the whole thing + // (the wrapper's own JSON record carries its internal figures). + let wrapper_started = std::time::Instant::now(); compute_gate::gemma() .run(__gn4_claim, async move { gemma::compute( @@ -800,6 +1471,9 @@ pub async fn compute_gemma( for note in &covariate_notes { envelope = envelope.with_note(note); } + if let Some(note) = &fallback_note { + envelope = envelope.with_note(note); + } for note in &extra_notes { envelope = envelope.with_note(note); } @@ -904,10 +1578,50 @@ pub async fn compute_gemma( body: Some(serde_json::Value::Object(body)), }); } - Json(envelope) + let timing = crate::response::Timing { + engine: "gemma".to_string(), + phases: vec![crate::response::PhaseTiming { + name: "wrapper".to_string(), + state: None, + ms: wrapper_started.elapsed().as_millis() as u64, + }], + cluster: None, + steps: Vec::new(), + steps_summary: None, + }; + Json(envelope.with_timing(timing)) }) } + + +/// Re-order trait values to the individual order of a prepared genotype file. +/// +/// `hmm` genotypes come from the qtl2 cross, whose individuals are the whole +/// panel -- 235 for BXD.8 against the 198 that have trait values. Passing the +/// panel's positional values against those columns makes every individual +/// missing, which GEMMA reports as "no individuals in common" and ravanan as +/// "no association output files"; the fix is to write the phenotype by name in +/// the genotype file's order. +fn align_to_individuals( + individuals_path: &str, + names: &[String], + values: &[Option<f64>], +) -> Result<Vec<Option<f64>>, std::io::Error> { + let by_name: std::collections::HashMap<&str, Option<f64>> = names + .iter() + .map(String::as_str) + .zip(values.iter().copied()) + .collect(); + let text = std::fs::read_to_string(individuals_path)?; + Ok(text + .lines() + .map(str::trim) + .filter(|name| !name.is_empty()) + .map(|name| by_name.get(name).copied().flatten()) + .collect()) +} + #[utoipa::path(post, path = "/compute/gemma/ravanan", summary = "Map a QTL with GEMMA, run via ravanan instead of gemma-wrapper directly", description = "Same computation and request/response shape as POST \ @@ -941,7 +1655,263 @@ pub async fn compute_gemma_ravanan( Query(params): Query<ComputeGemmaParams>, Json(mut request): Json<GemmaRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + record_usage(ctx.clone(), &request, params.id.as_deref(), "ravanan"); + gemma_via_ravanan(ctx, token, params, request, __gn4_claim, "compute_gemma_ravanan").await +} +/// `POST /compute/gemma/async` -- start the same mapping a blocking call would, +/// and answer `202` at once with an id to poll. +/// +/// The blocking endpoints stay the default: this is for a run that cannot fit +/// in a client's patience, which on a large panel is any cold one (a cold +/// HSNIH-Palmer_true scan is ~20 minutes of wall clock; a 5-minute client +/// cutoff could never have returned an answer, and its connection closing used +/// to take the result with it). +#[utoipa::path(post, path = "/compute/gemma/async", + summary = "Start a mapping in the background and return an id to poll", + description = "Same request body as /compute/gemma. Answers 202 with the \ +run's id and the URL of /compute/gemma/result/{id}, which reports progress and \ +then the finished reply. Use it when the run may outlast the client: a cold \ +fit on a large panel takes tens of minutes, and a closed connection would \ +otherwise lose the answer.", + params(ComputeGemmaParams), + request_body = GemmaRequest, + responses( + (status = 202, description = "Run started; poll its id", + body = crate::response::Envelope<serde_json::Value>), + (status = 409, description = "id already in use", body = ApiError) + ) +)] +pub async fn compute_gemma_async( + ctx: Ctx, + token: AuthToken, + Query(params): Query<ComputeGemmaParams>, + Json(request): Json<GemmaRequest>, +) -> Result<(StatusCode, Json<Envelope<serde_json::Value>>), ApiError> { + let rid = ctx.request_info(); + let id = params + .id + .clone() + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| { + // The request id is already a uuid (tower-http's MakeRequestUuid), + // and it is the natural name for a run started by this request. + let rid = ctx.request_info(); + format!( + "run-{}", + rid.id().unwrap_or_else(|| "anonymous".to_string()) + ) + }); + if !streaming::is_valid_run_id(&id) { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_run_id", + "Invalid id", + "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + let engine = match request.engine.as_deref() { + None => crate::gemma::GemmaEngine::Gemma, + Some(value) => crate::gemma::GemmaEngine::parse(value).ok_or_else(|| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_engine", + "Invalid engine", + format!("'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)."), + "compute_gemma_async", + ) + .with_request_id(rid.clone()) + })?, + }; + // The run id is the join key a later result fetch carries in its path, + // so recording it here is what makes "computed and never fetched" + // measurable (see crate::usage). + record_usage(ctx.clone(), &request, Some(&id), engine.as_str()); + if !crate::runs::global().begin(&id, engine.as_str()) { + return Err(ApiError::new( + StatusCode::CONFLICT, + "run_id_in_use", + "Run id already in use", + format!("id '{id}' is already in use by another background run; pick a different id."), + "compute_gemma_async", + ) + .with_request_id(rid)); + } + + let job_id = id.clone(); + // A handle for the 202 body: `ctx` itself moves into the task below. + let reply_ctx = ctx.clone(); + let job_subject = token.sub.clone(); + let mut job_params = params.clone(); + job_params.id = Some(id.clone()); + tokio::spawn(async move { + let claim = crate::compute_gate::ravanan().claim_light( + &job_subject, + Some(&job_id), + "compute_gemma_async", + "compute_gemma_async", + "/compute/gemma/result", + ); + let outcome = gemma_via_ravanan( + ctx, + token, + job_params, + request, + claim, + "compute_gemma_async", + ) + .await; + match outcome { + Ok(Json(envelope)) => { + let body = serde_json::to_value(&envelope).unwrap_or(serde_json::Value::Null); + crate::runs::global().finish(&job_id, body); + } + Err(error) => { + let status = error.status; + let body = serde_json::to_value(&error).unwrap_or(serde_json::Value::Null); + crate::runs::global().fail(&job_id, status, body); + } + } + }); + + let envelope = reply_ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": engine.as_str(), + "status": format!("/compute/gemma/result/{id}"), + })) + .with_note( + "The run is in flight. Poll `status`: it reports how long the run has been going \ + and what the cluster is doing, and returns the finished reply once it completes.", + ); + Ok((StatusCode::ACCEPTED, Json(envelope))) +} + +/// `GET /compute/gemma/result/{id}` -- progress while a background run is in +/// flight, its reply once it finishes, its error if it failed. +#[utoipa::path(get, path = "/compute/gemma/result/{id}", + summary = "Progress or the finished reply of a background mapping", + description = "While the run is in flight: its state, how long it has been \ +running and the cluster's job counts. Afterwards: exactly the body the blocking \ +endpoint would have returned (or the error it would have raised).", + params(("id" = String, Path, description = "The run id given to /compute/gemma/async")), + responses( + (status = 200, description = "Progress, or the finished reply", + body = crate::response::Envelope<serde_json::Value>), + (status = 404, description = "No such run in this process", body = ApiError) + ) +)] +pub async fn gemma_result( + ctx: Ctx, + Path(id): Path<String>, +) -> Result<axum::response::Response, ApiError> { + use axum::response::IntoResponse; let rid = ctx.request_info(); + let Some(run) = crate::runs::global().get(&id) else { + return Err(ApiError::new( + StatusCode::NOT_FOUND, + "unknown_run", + "No such run", + format!( + "no background run '{id}' in this process; it may have finished before a \ + restart, in which case re-post the request (ravanan's store answers the \ + steps it already ran)." + ), + "compute_gemma_result", + ) + .with_request_id(rid)); + }; + match run.state.as_str() { + "finished" => { + let body = run.result.unwrap_or(serde_json::Value::Null); + Ok((StatusCode::OK, Json(body)).into_response()) + } + "failed" => { + let (status, body) = run.error.unwrap_or(( + 500, + serde_json::json!({"code": "internal_error", "detail": "no error recorded"}), + )); + let status = StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + Ok((status, Json(body)).into_response()) + } + _ => { + // Still running: what we can measure from outside the run -- the + // clock, and the cluster's view of the jobs this request submitted. + let since_epoch = run + .started_at + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs()) + .unwrap_or(0); + let config = Config::load(); + let (cluster, steps) = crate::gemma::cluster_timing( + &config.ravanan_batch, + since_epoch, + &format!("{}/ravanan-store", config.ravanan_cache_dir), + ) + .await; + let envelope = ctx + .envelope(serde_json::json!({ + "id": id, + "state": "running", + "engine": run.engine, + "elapsed_ms": run.elapsed_ms(), + "cluster": cluster, + "steps_recorded": steps.len(), + })) + .with_note( + "Still running. elapsed_ms is this process's clock for the run, \ + meta.timing.cluster counts the jobs Slurm accepted for it, and \ + steps_recorded counts the step logs already in the store.", + ); + Ok((StatusCode::OK, Json(envelope)).into_response()) + } + } +} + +/// The Slurm path, callable from either GEMMA endpoint. +/// +/// `/compute/gemma/ravanan` is this and nothing else, and `/compute/gemma` +/// uses it as its *default* engine when `GEMMA_ENGINE=slurm` (the default), +/// falling back to its own in-process gemma-wrapper run when this answers +/// 5xx -- i.e. when Slurm, ravanan or the engine is unavailable. A 4xx is a +/// caller error and is returned as such; a numerical disagreement is never a +/// reason to fall back, because it would hide a regression behind an answer +/// from the other engine. +#[allow(clippy::too_many_arguments)] +pub(crate) async fn gemma_via_ravanan( + ctx: Ctx, + token: AuthToken, + params: ComputeGemmaParams, + mut request: GemmaRequest, + mut __gn4_claim: crate::compute_gate::Claim<'static>, + endpoint: &'static str, +) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { + let rid = ctx.request_info(); + let mut genotypes_ms: u64 = 0; + // Before anything else runs, for two reasons: the cluster query has to know + // which jobs belong to *this* request, and each step log's mtime is + // compared against it to tell a step that ran from one ravanan reused. + let request_started = std::time::SystemTime::now(); + let engine = match request.engine.as_deref() { + None => crate::gemma::GemmaEngine::Gemma, + Some(value) => match crate::gemma::GemmaEngine::parse(value) { + Some(engine) => engine, + None => { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_engine", + "Invalid engine", + format!( + "'{value}' is not an engine; use gemma (BIMBAM) or pangemma (lmdb store)." + ), + endpoint, + ) + .with_request_id(rid)) + } + }, + }; let lmm = request.lmm.unwrap_or(9); if !matches!(lmm, 1 | 2 | 3 | 4 | 9) { return Err(ApiError::new( @@ -951,7 +1921,7 @@ pub async fn compute_gemma_ravanan( format!( "lmm must be one of 1, 2, 3, 4, 9 (got {lmm}); 1=Wald, 2=LRT, 3=score, 4=all three, 9=GeneNetwork's convention (observed to behave like LRT)." ), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -962,7 +1932,7 @@ pub async fn compute_gemma_ravanan( "invalid_run_id", "Invalid id", "id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -979,12 +1949,22 @@ pub async fn compute_gemma_ravanan( let ResolvedInputs { genotype_file, snps_file, - trait_values, + mut trait_values, individuals: panel_individuals, - names: _, - group: _, + names: resolved_names, + group: resolved_group, notes: input_notes, - } = resolve_inputs(&config, &mut request, &token, "compute_gemma_ravanan", rid.clone()).await?; + } = { + // Reading the panel is a phase of its own: `resolve_inputs` opens the + // genotype file (a 134,918-marker BIMBAM is a multi-GB read), works out + // which individuals have genotypes, and writes the prepared subset. On + // HSNIH-Palmer_true that is ~29 s of a 46 s request -- the largest + // single cost, and invisible until it is named. + let started = std::time::Instant::now(); + let resolved = resolve_inputs(&config, &mut request, &token, endpoint, rid.clone()).await?; + genotypes_ms = started.elapsed().as_millis() as u64; + resolved + }; if genotype_file.is_empty() || snps_file.is_empty() || trait_values.is_empty() { return Err(ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, @@ -993,7 +1973,7 @@ pub async fn compute_gemma_ravanan( "ravanan needs a genotype file and a SNP map (a group whose version has a BIMBAM \ pair, an upload, or genotype_file + snps_file) and at least one trait value." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1010,7 +1990,7 @@ pub async fn compute_gemma_ravanan( step, so `covariates` cannot be fitted on this path. Use POST /compute/gemma \ for a covariate fit, or drop the covariates." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } @@ -1022,11 +2002,81 @@ pub async fn compute_gemma_ravanan( "send the values already normalized, or use POST /compute/gemma, which applies \ its normalization pipeline before the run." .to_string(), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(rid)); } + // Genotypes as the caller asked for them: `impute` decides what happens to + // a missing call, and both non-default answers produce a complete file. + // Doing it here rather than inside the workflow keeps one implementation + // (`scripts/prepare-genotypes.sh`) for every engine, which is the point -- + // the same trait can then be mapped with `mean` and with `hmm` and the two + // answers compared. + let impute = request + .impute + .clone() + .unwrap_or_else(|| "none".to_string()) + .to_ascii_lowercase(); + if !matches!(impute.as_str(), "none" | "mean" | "hmm") { + return Err(ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_impute", + "Invalid impute mode", + format!("'{}' is not a mode; use none, mean or hmm.", impute), + endpoint, + ) + .with_request_id(rid)); + } + // The genotypes as the caller asked for them, built on the cluster: the + // `hmm`/`mean` treatment and pangemma's lmdb store are workflows of their + // own (see ravanan_artifacts), so what arrives here are paths in ravanan's + // store. + let artifacts = ravanan_artifacts( + &config, + engine, + &impute, + &genotype_file, + &snps_file, + &Some(resolved_group.clone()), + request.genotype_version.as_deref(), + resolved_names.as_ref(), + endpoint, + rid.clone(), + ) + .await?; + let mut impute_notes = artifacts.notes; + let (artifacts_ms, artifacts_state) = (artifacts.ms, artifacts.state.clone()); + let (genotype_file, snps_file) = (artifacts.genotype_file, artifacts.snps_file); + if impute == "hmm" { + if let (Some(individuals), Some(names)) = + (artifacts.individuals_file.as_deref(), resolved_names.as_deref()) + { + match align_to_individuals(individuals, names, &trait_values) { + Ok(aligned) => { + impute_notes.push(format!( + "genotypes: trait values aligned by name to the {} individuals of the \ + HMM calls ({} had a value in the panel)", + aligned.len(), + trait_values.iter().filter(|v| v.is_some()).count() + )); + trait_values = aligned; + } + Err(error) => { + return Err(ApiError::new( + StatusCode::INTERNAL_SERVER_ERROR, + "internal_error", + "Could not align individuals", + format!("reading {individuals} failed: {error}"), + endpoint, + ) + .with_request_id(rid)); + } + } + } + } + let store = artifacts.store; + // Gated like the direct GEMMA run and by the same size rule, now with the // real panel size: a samples-only request used to be sized 0 and took no // slot at all. @@ -1036,14 +2086,38 @@ pub async fn compute_gemma_ravanan( let run_id = params.id.clone(); let job_rid = rid.clone(); + let since_epoch = request_started + .duration_since(std::time::UNIX_EPOCH) + .map(|since| since.as_secs()) + .unwrap_or(0); compute_gate::ravanan() .run(__gn4_claim, async move { - gemma::compute_ravanan( + // The workflow pair follows the engine: gemma-gn2 on BIMBAM, or + // pangemma on an lmdb store, each with the manifest that resolves + // its own step commands. Both are pinned by the deployment, so a + // checkout that lacks one fails here by name rather than producing + // a workflow that cannot find its binary. + let (workflow_source, manifest_source) = match engine { + gemma::GemmaEngine::Gemma => { + (&config.gemma_ravanan_workflow, &config.gemma_ravanan_manifest) + } + gemma::GemmaEngine::Pangemma => ( + &config.gemma_ravanan_workflow_mdb, + &config.gemma_ravanan_manifest_mdb, + ), + }; + let ravanan_workflow = gemma::RavananWorkflow { + engine, + source: workflow_source, + manifest: manifest_source, + }; + let output = gemma::compute_ravanan( &config.ravanan_cmd, &config.ravanan_batch, &config.ccwl_cmd, - &config.gemma_ravanan_workflow, - &config.gemma_ravanan_manifest, + &ravanan_workflow, + store.as_deref(), + request_started, &config.ravanan_cache_dir, &config.ravanan_scratch, &genotype_file, @@ -1059,14 +2133,24 @@ pub async fn compute_gemma_ravanan( "run_id_in_use", "Run id already in use", format!("id '{id}' is already in use; pick a different id."), - "compute_gemma_ravanan", + endpoint, ) .with_request_id(job_rid.clone()), other => gemma_error_to_api_error(other, job_rid.clone()), - }) + })?; + // Asked here, inside the async block: the reply closure below is a + // plain `map`, and this is the last moment the jobs of *this* + // request can be told from every other request's. + let (cluster, ran_steps) = gemma::cluster_timing( + &config.ravanan_batch, + since_epoch, + &format!("{}/ravanan-store", config.ravanan_cache_dir), + ) + .await; + Ok::<_, ApiError>((output, cluster, ran_steps)) }) .await - .map(|output| { + .map(|(output, cluster, ran_steps)| { let num_rows = output.rows.as_array().map(Vec::len).unwrap_or(0); let mut envelope = ctx .envelope(output.rows) @@ -1075,14 +2159,75 @@ pub async fn compute_gemma_ravanan( "Rows come from GEMMA's own .assoc.txt output, positional (see meta.columns for names); column names depend on the lmm value used.", ); // What the request resolved to first (which genotype version, how many - // values aligned, what was dropped), then the run's own notes. + // values aligned, what was dropped), how the genotypes were treated if + // the caller asked for imputation, then the run's own notes. for note in &input_notes { envelope = envelope.with_note(note); } + for note in &impute_notes { + envelope = envelope.with_note(note); + } for note in &output.notes { envelope = envelope.with_note(note); } - Json(envelope) + // Where the time went, beside `took_ms`: the phases this request paid + // for, what the cluster did, and each step's own figure with its state. + let mut phases = vec![crate::response::PhaseTiming { + name: "genotypes".to_string(), + state: None, + ms: genotypes_ms, + }]; + phases.push(crate::response::PhaseTiming { + name: "artifacts".to_string(), + state: Some(artifacts_state.clone()), + ms: artifacts_ms, + }); + phases.push(crate::response::PhaseTiming { + name: "workflow".to_string(), + state: None, + ms: output.workflow_ms, + }); + phases.push(crate::response::PhaseTiming { + name: "parse".to_string(), + state: None, + ms: output.parse_ms, + }); + // Steps located through the jobs of this request (kinship's logs are + // not a workflow output) join the ones read from the returned logs; + // a step present in both keeps the "ran" entry. + let mut steps = output.steps.clone(); + for step in ran_steps { + let duplicate = steps.iter().any(|existing| { + existing.step == step.step && existing.chr == step.chr && existing.state == "ran" + }); + if !duplicate { + steps.push(step); + } + } + steps.sort_by(|a, b| { + (a.step.as_str(), a.chr.as_deref().unwrap_or("")) + .cmp(&(b.step.as_str(), b.chr.as_deref().unwrap_or(""))) + }); + let cached = steps.iter().filter(|s| s.state == "cached").count(); + let compute: Vec<u64> = steps.iter().filter_map(|s| s.compute_ms).collect(); + let summary = crate::response::StepsSummary { + n: steps.len(), + compute_ms_sum: if compute.is_empty() { + None + } else { + Some(compute.iter().sum()) + }, + compute_ms_max: compute.iter().copied().max(), + cached, + }; + let timing = crate::response::Timing { + engine: engine.as_str().to_string(), + phases, + cluster, + steps, + steps_summary: Some(summary), + }; + Json(envelope.with_timing(timing)) }) } diff --git a/src/routes/genoupload.rs b/src/routes/genoupload.rs index bd12018..d6d688b 100644 --- a/src/routes/genoupload.rs +++ b/src/routes/genoupload.rs @@ -55,6 +55,14 @@ fn map_error(error: BasketError, rid: RequestInfo, operation: &'static str) -> A operation, ) .with_request_id(rid), + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Name already in use", + message, + operation, + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_genotype_upload", diff --git a/src/routes/groups.rs b/src/routes/groups.rs index dd59165..28e9c03 100644 --- a/src/routes/groups.rs +++ b/src/routes/groups.rs @@ -30,6 +30,16 @@ pub struct GroupsParams { /// Keep groups whose name, display name or full name contains this /// text, case-insensitively, e.g. "alzheimer". pub q: Option<String>, + /// Keep only these ids or names, comma-separated. Values that match nothing + /// are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per group instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per group instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } fn contains_ci(field: &Option<String>, needle: &str) -> bool { @@ -39,7 +49,8 @@ fn contains_ci(field: &Option<String>, needle: &str) -> bool { } #[utoipa::path(get, path = "/groups", summary = "List all groups (populations; InbredSet rows), optionally filtered", params(GroupsParams), responses( - (status = 200, description = "The groups (InbredSet rows), with family and species name", body = Envelope<Vec<db::Group>>), + (status = 200, description = "The groups (InbredSet rows), with family and species name; \ +`ids_only`/`names_only` answer one value per group instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 500, description = "Database error", body = ApiError) ))] @@ -48,8 +59,24 @@ pub async fn groups( ctx: Ctx, _token: AuthToken, Query(params): Query<GroupsParams>, -) -> Result<Json<Envelope<Vec<db::Group>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "groups", + ) + .with_request_id(rid.clone()) + })?; + let listing_rid = rid.clone(); tokio::task::spawn_blocking(db::get_all_groups) .await .map_err(|e| { @@ -86,10 +113,24 @@ pub async fn groups( }) }) .collect(); - Json(ctx.envelope(groups).with_next( + let rows: Vec<serde_json::Value> = groups + .iter() + .map(|group| serde_json::to_value(group).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let _ = &listing_rid; + let mut envelope = ctx.envelope(shaped).with_next( "/species", "The species the groups belong to (filter groups with ?species=<name>)", - )) + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no group: {}", + missing.len(), + missing.join(", ") + )); + } + Json(envelope) }) .map_err(|e| ApiError::from_db(e, "groups").with_request_id(rid)) } @@ -210,6 +251,16 @@ pub async fn group_by_name( #[derive(serde::Deserialize)] pub struct GroupStrainsParams { used_for_mapping: Option<bool>, + /// Keep only these ids or names, comma-separated. Values that match nothing + /// are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per strain instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per strain instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } #[utoipa::path(get, path = "/groups/{group}/parents-and-f1s", @@ -327,7 +378,8 @@ pub async fn group_parental_design( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), ("used_for_mapping" = Option<bool>, Query, description = "Only strains/samples used for mapping") ), responses( - (status = 200, description = "The strains/samples belonging to the group", body = Envelope<Vec<db::Strain>>), + (status = 200, description = "The strains/samples belonging to the group; \ +`ids_only`/`names_only` answer one value per strain instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -338,8 +390,24 @@ pub async fn group_strains( Path(group): Path<String>, Query(params): Query<GroupStrainsParams>, _token: AuthToken, -) -> Result<Json<Envelope<Vec<db::Strain>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_strains", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); let used_for_mapping = params.used_for_mapping; tokio::task::spawn_blocking(move || { @@ -362,18 +430,30 @@ pub async fn group_strains( .map_err(|e| ApiError::from_db(e, "group_strains").with_request_id(rid.clone()))? .map(|strains| { let group = path_segment(¬_found_name); - Json( - ctx.envelope(strains) - .with_next( - &format!("/groups/{group}"), - "The group these strains belong to", - ) - .with_links(crate::suggest::group_links(¬_found_name)) - .with_next( - &format!("/groups/{group}/case-attributes"), - "Case-attribute names and per-strain values", - ), - ) + let rows: Vec<serde_json::Value> = strains + .iter() + .map(|strain| serde_json::to_value(strain).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) + .with_next( + &format!("/groups/{group}"), + "The group these strains belong to", + ) + .with_links(crate::suggest::group_links(¬_found_name)) + .with_next( + &format!("/groups/{group}/case-attributes"), + "Case-attribute names and per-strain values", + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no strain: {}", + missing.len(), + missing.join(", ") + )); + } + Json(envelope) }) .ok_or_else(|| { ApiError::new( @@ -727,6 +807,16 @@ pub struct GroupTraitsParams { /// Only the traits with this short name (abbreviation), e.g. /// "5HT_MB_M" or "3NP_Tox". pub abbreviation: Option<String>, + /// Keep only these ids or trait names, comma-separated. Values that match + /// nothing are named in the reply's note. + #[serde(default)] + pub limit_to: Option<String>, + /// Answer with one id per trait instead of objects. + #[serde(default)] + pub ids_only: Option<bool>, + /// Answer with one name per trait instead of objects. + #[serde(default)] + pub names_only: Option<bool>, } enum GroupTraitsLookup { @@ -764,7 +854,8 @@ fn get_group_traits_result( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id"), GroupTraitsParams ), responses( - (status = 200, description = "The published traits belonging to the group", body = Envelope<Vec<db::TraitInfo>>), + (status = 200, description = "The published traits belonging to the group; \ +`ids_only`/`names_only` answer one value per trait instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 403, description = "The group's published data isn't public, and the caller isn't authorized for it", body = ApiError), (status = 404, description = "No matching group", body = ApiError), @@ -776,8 +867,24 @@ pub async fn group_traits( Path(group): Path<String>, token: AuthToken, Query(params): Query<GroupTraitsParams>, -) -> Result<Json<Envelope<Vec<db::TraitInfo>>>, ApiError> { +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(&crate::listing::ListingParams { + limit_to: params.limit_to.clone(), + ids_only: params.ids_only, + names_only: params.names_only, + }) + .map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_traits", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); let auth_server_url = Config::load().auth_server_url.clone(); tokio::task::spawn_blocking(move || { @@ -813,15 +920,27 @@ pub async fn group_traits( .and_then(|lookup| match lookup { GroupTraitsLookup::Found(traits) => { let group = path_segment(¬_found_name); - Ok(Json( - ctx.envelope(traits) - .with_note(db::LOD_NOTE) - .with_links(crate::suggest::root_links()) - .with_next( + let rows: Vec<serde_json::Value> = traits + .iter() + .map(|trait_info| serde_json::to_value(trait_info).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); + let mut envelope = ctx + .envelope(shaped) + .with_note(db::LOD_NOTE) + .with_links(crate::suggest::root_links()) + .with_next( &format!("/groups/{group}"), "The group these traits belong to", - ), - )) + ); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no trait: {}", + missing.len(), + missing.join(", ") + )); + } + Ok(Json(envelope)) } GroupTraitsLookup::Forbidden => Err(ApiError::new( StatusCode::FORBIDDEN, @@ -1060,7 +1179,8 @@ pub async fn group_trait_case_attribute( #[utoipa::path(get, path = "/groups/{group}/datasets", summary = "List the expression (ProbeSet) datasets belonging to a group", params( ("group" = String, Path, description = "Group InbredSetName, Name, FullName or numeric Id") ), responses( - (status = 200, description = "The expression (ProbeSet) datasets belonging to the group", body = Envelope<Vec<db::Dataset>>), + (status = 200, description = "The expression (ProbeSet) datasets belonging to the group; \ +`ids_only`/`names_only` answer one value per dataset instead", body = Envelope<crate::listing::Rows>), Unauthorized, (status = 404, description = "No matching group", body = ApiError), (status = 500, description = "Database error", body = ApiError) @@ -1070,8 +1190,20 @@ pub async fn group_datasets( ctx: Ctx, Path(group): Path<String>, _token: AuthToken, -) -> Result<Json<Envelope<Vec<db::Dataset>>>, ApiError> { + Query(params): Query<crate::listing::ListingParams>, +) -> Result<Json<Envelope<crate::listing::Rows>>, ApiError> { let rid = ctx.request_info(); + // No listing parameters means the old answer: `Rows::Objects`. + let listing = crate::listing::Listing::parse(¶ms).map_err(|detail| { + ApiError::new( + StatusCode::UNPROCESSABLE_ENTITY, + "invalid_listing", + "Invalid listing parameters", + detail, + "group_datasets", + ) + .with_request_id(rid.clone()) + })?; let not_found_name = group.clone(); tokio::task::spawn_blocking(move || { db::get_group_by_name(&group).and_then(|group| match group { @@ -1106,13 +1238,25 @@ pub async fn group_datasets( ), ) }); + let rows: Vec<serde_json::Value> = datasets + .iter() + .map(|dataset| serde_json::to_value(dataset).unwrap_or(serde_json::Value::Null)) + .collect(); + let (shaped, missing) = listing.shape(rows, params.limit_to.as_deref()); let mut envelope = ctx - .envelope(datasets) + .envelope(shaped) .with_next( &format!("/groups/{}", path_segment(¬_found_name)), "The group these datasets belong to", ) .with_links(crate::suggest::group_links(¬_found_name)); + if !missing.is_empty() { + envelope = envelope.with_note(&format!( + "limit_to named {} value(s) that matched no dataset: {}", + missing.len(), + missing.join(", ") + )); + } if let Some((href, description)) = example { envelope = envelope.with_next(&href, &description); } diff --git a/src/routes/matrices.rs b/src/routes/matrices.rs index b8b3967..a392456 100644 --- a/src/routes/matrices.rs +++ b/src/routes/matrices.rs @@ -67,6 +67,14 @@ fn map_error(error: BasketError, rid: RequestInfo) -> ApiError { "matrices", ) .with_request_id(rid), + BasketError::NameInUse(message) => ApiError::new( + StatusCode::CONFLICT, + "basket_name_in_use", + "Name already in use", + message, + "matrices", + ) + .with_request_id(rid), BasketError::Invalid(message) => ApiError::new( StatusCode::UNPROCESSABLE_ENTITY, "invalid_matrix", diff --git a/src/routes/mod.rs b/src/routes/mod.rs index 0461165..0da2eaa 100644 --- a/src/routes/mod.rs +++ b/src/routes/mod.rs @@ -7,6 +7,7 @@ pub mod accessions; pub mod baskets; pub mod bnw; pub mod bulklmm; +pub mod compare; pub mod correlation; pub mod correlation_matrix; pub mod datasets; diff --git a/src/routes/plot.rs b/src/routes/plot.rs index 2b4c043..0f698be 100644 --- a/src/routes/plot.rs +++ b/src/routes/plot.rs @@ -158,11 +158,16 @@ fn check_gemma_result(posted: &serde_json::Value) -> Result<(), String> { /// What `/plot/rqtl` validates in a posted R/qtl result: `data.markers`, /// each row `[name, chr, pos, lod, ...]`. fn check_rqtl_result(result: &serde_json::Value) -> Result<(), String> { - let rows = result["data"]["markers"] - .as_array() - .ok_or("`data.markers` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; + // `data` is the marker array; a reply from a build before that change kept + // it under `data.markers`, and a caller may still be holding one. + let rows = if result["data"].is_array() { + result["data"].as_array() + } else { + result["data"]["markers"].as_array() + } + .ok_or("`data` must be the R/qtl marker array from /compute/rqtl -- post that response back, not a request")?; if rows.is_empty() { - return Err("`data.markers` is empty: nothing to plot".to_string()); + return Err("`data` is empty: nothing to plot".to_string()); } let first = rows[0] .as_array() @@ -346,7 +351,7 @@ pub async fn plot_gemma( } /// The SVG, with the plotter's summary alongside it. -fn svg_response(rendered: plot::Plot) -> Response { +pub(crate) fn svg_response(rendered: plot::Plot) -> Response { let mut response = rendered.svg.into_response(); let headers = response.headers_mut(); headers.insert( diff --git a/src/routes/qtl2.rs b/src/routes/qtl2.rs index 896c0e9..46ce90d 100644 --- a/src/routes/qtl2.rs +++ b/src/routes/qtl2.rs @@ -174,6 +174,27 @@ pub async fn compute_qtl2( Json(mut request): Json<Qtl2Request>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on: the body names the panel or the trait, the path + // cannot (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + if let Some(trait_name) = request.trait_name.as_deref() { + crate::usage!(ctx, trait = trait_name); + } + crate::usage!(ctx, engine = "qtl2"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } // An uploaded genotype is just another `.geno`: materialise it and let the // path branch below do the rest. if let Some(upload) = request.genotype_upload.clone() { @@ -675,10 +696,14 @@ pub async fn compute_qtl2( let genotype_root = config.genotype_files_dir.clone(); let cache_dir_for_cross = cache_dir.clone(); let het_for_cross = het; + let convert_for_cross = config.qtl2_convert_script.clone(); let cross = tokio::task::spawn_blocking(move || match source_for_cross { - Source::Convert(resolved) => { - qtl2::prepare_cross(&resolved, std::path::Path::new(&cache_dir_for_cross), het_for_cross) - } + Source::Convert(resolved) => qtl2::prepare_cross( + &resolved, + std::path::Path::new(&cache_dir_for_cross), + het_for_cross, + std::path::Path::new(&convert_for_cross), + ), Source::Control(name) => { qtl2::prepare_control_cross(std::path::Path::new(&genotype_root), &name) } diff --git a/src/routes/rqtl.rs b/src/routes/rqtl.rs index c02adbe..1b9607e 100644 --- a/src/routes/rqtl.rs +++ b/src/routes/rqtl.rs @@ -137,6 +137,24 @@ pub async fn compute_rqtl( Json(mut request): Json<RqtlRequest>, ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> { let rid = ctx.request_info(); + + // What this scan ran on (see crate::usage). + if let Some((source, name)) = crate::usage::source( + request.group.as_deref(), + request.genotype_upload.as_deref(), + request.genotype_file.as_deref(), + request.basket.as_deref(), + ) { + crate::usage!(ctx, dataset = name, source = source); + } + if let Some(group) = request.group.as_deref() { + crate::usage!(ctx, group = group); + } + crate::usage!(ctx, trait = request.trait_name.as_str()); + crate::usage!(ctx, engine = "rqtl"); + if let Some(run) = params.id.as_deref() { + crate::usage!(ctx, run = run); + } if let Some(upload) = request.genotype_upload.clone() { if request.genotype_file.is_some() || request.group.is_some() { return Err(ApiError::new( @@ -546,12 +564,30 @@ pub async fn compute_rqtl( // responses from the same panel apart, and `/plot/rqtl` reads it // for the title. let mut envelope = ctx - .envelope(rqtl::to_json(output)) + // `data` is the marker rows, like every other compute endpoint: + // the permutation null is qualifier information and goes to + // meta.extra, so a caller can write one script for all of them + // (measured: Rob Williams's test-drive read data.markers here and + // data itself on GEMMA, and had to special-case both). + .envelope(rqtl::marker_rows(&output)) .with_columns(rqtl::MARKER_COLUMNS.iter().map(|s| s.to_string()).collect(), num_rows) .with_note(&format!("Trait: {}", request.trait_name)) .with_note( - "markers come from R/qtl's scanone output, positional (see meta.columns for names); permutation is null unless nperm > 0 was requested.", + "markers come from R/qtl's scanone output, positional (see meta.columns for names); the permutation null, when nperm > 0 was requested, is meta.permutation.", + ) + // The conversion is not silent in the status log, but it was + // silent here: every heterozygous call is dropped and X becomes an + // autosome, while GEMMA keeps a heterozygote as 0.5. A caller + // comparing the two engines has to know that. + .with_note( + "R/qtl reads this panel as a riself cross: heterozygous calls are dropped (the \ + run log counts them) and X is treated as an autosome. GEMMA models the same \ + panel with heterozygotes at 0.5, so the two are different models, not two \ + implementations of one.", ); + if let Some(permutation) = rqtl::permutation_json(&output) { + envelope = envelope.with_extra("permutation", permutation); + } for note in ¬es { envelope = envelope.with_note(note); } diff --git a/src/routes/search.rs b/src/routes/search.rs index 20f9712..22ce169 100644 --- a/src/routes/search.rs +++ b/src/routes/search.rs @@ -216,10 +216,23 @@ pub async fn search( (limit, page) }; + // The query itself goes in the line here, and only here: the access log + // drops query strings on purpose (one can carry a credential), so `?q=` + // is otherwise invisible -- and "what people search for" is the most + // useful behavioural signal the API has. Bounded, and sanitised only by + // being text: see crate::usage. + crate::usage!(ctx, q = q); + crate::usage!(ctx, type = search_type); + crate::usage!( + ctx, + engine = crate::config::Config::load().search_engine.clone() + ); + let mut hits = search::search(q, search_type, fetch_limit, gn3_page) .await .map_err(|e| engine_error(e, rid))?; let fetched = hits.len() as u64; + crate::usage!(ctx, hits = fetched); for hit in &mut hits { hit.lod = hit.lrs.map(db::lod); } diff --git a/src/rqtl.rs b/src/rqtl.rs index 2bf6de3..7dd608d 100644 --- a/src/rqtl.rs +++ b/src/rqtl.rs @@ -495,32 +495,39 @@ pub const MARKER_COLUMNS: [&str; 4] = ["name", "chr", "pos", "lod"]; /// is what utoipa needs here. `markers` rows are positional (see /// `MARKER_COLUMNS`), the same space-saving shape `crate::gemma::compute` /// uses for its own (much larger) marker rows. -pub fn to_json(output: RqtlOutput) -> Value { - let markers: Vec<Value> = output - .markers - .into_iter() - .map(|m| { - let mut row = vec![ - Value::String(m.name), - Value::String(m.chr), - serde_json::json!(m.pos), - serde_json::json!(m.lod), - ]; - row.extend(m.extra.into_iter().map(Value::String)); - Value::Array(row) - }) - .collect(); - serde_json::json!({ - "markers": markers, - "permutation": output.permutation, - }) +pub fn marker_rows(output: &RqtlOutput) -> Value { + Value::Array( + output + .markers + .iter() + .map(|m| { + let mut row = vec![ + Value::String(m.name.clone()), + Value::String(m.chr.clone()), + serde_json::json!(m.pos), + serde_json::json!(m.lod), + ]; + row.extend(m.extra.iter().cloned().map(Value::String)); + Value::Array(row) + }) + .collect(), + ) +} + +/// The permutation null, for `meta.extra` beside the rows -- it qualifies the +/// scan rather than being one of its rows, which is why it is not in `data` +/// (that is where every other compute endpoint keeps its rows). +pub fn permutation_json(output: &RqtlOutput) -> Option<Value> { + output + .permutation + .as_ref() + .and_then(|permutation| serde_json::to_value(permutation).ok()) } /// The marker with the strongest LOD in a `to_json` result, if there is /// one: the QTL's peak, which is what a PheWAS wants to be centred on. pub fn peak_marker(data: &Value) -> Option<String> { - data.get("markers")? - .as_array()? + data.as_array()? .iter() .filter_map(|row| { let row = row.as_array()?; @@ -661,16 +668,14 @@ mod tests { #[test] fn the_peak_marker_is_the_strongest_lod() { - let data = serde_json::json!({ - "markers": [ - ["rs1", "1", 3.0, 0.5], - ["rs2", "3", 9.0, 4.2], - ["rs3", "5", 12.0, 1.1] - ], - "permutation": null - }); + // `data` is the rows themselves; the permutation null is in meta. + let data = serde_json::json!([ + ["rs1", "1", 3.0, 0.5], + ["rs2", "3", 9.0, 4.2], + ["rs3", "5", 12.0, 1.1] + ]); assert_eq!(peak_marker(&data).as_deref(), Some("rs2")); - assert_eq!(peak_marker(&serde_json::json!({"markers": []})), None); + assert_eq!(peak_marker(&serde_json::json!([])), None); assert_eq!(peak_marker(&serde_json::json!({})), None); } diff --git a/src/runs.rs b/src/runs.rs new file mode 100644 index 0000000..d62333f --- /dev/null +++ b/src/runs.rs @@ -0,0 +1,126 @@ +//! Compute runs started in the background, so a caller that cannot wait for a +//! long one -- a cold LOCO scan of a large panel is ~20 minutes here -- can +//! still collect its result. +//! +//! `POST /compute/gemma/async` registers an id, spawns the work and returns +//! `202` at once; `GET /compute/gemma/result/{id}` reports progress while it +//! runs and the finished reply afterwards. The blocking endpoints are +//! unchanged, so nothing that fits in a client's patience starts using this. +//! +//! In-process and unbounded on purpose: results live for the life of the +//! process (a finished reply, not a cache), so a restart forgets them -- the +//! same lifetime as the run itself, and the caller can always re-post, which +//! ravanan's store answers from its cache. +use std::collections::HashMap; +use std::sync::{Arc, Mutex, OnceLock}; +use std::time::{Instant, SystemTime}; + +/// One background run. +#[derive(Clone)] +pub struct Run { + pub engine: String, + pub started: Instant, + pub started_at: SystemTime, + /// `running`, `finished` or `failed`. + pub state: String, + /// The finished reply's body, exactly as the blocking endpoint would have + /// answered it. + pub result: Option<serde_json::Value>, + /// The failure body, with the status code the blocking endpoint would have + /// used, so a caller can tell a 4xx from a 5xx. + pub error: Option<(u16, serde_json::Value)>, +} + +impl Run { + pub fn elapsed_ms(&self) -> u64 { + self.started.elapsed().as_millis() as u64 + } +} + +#[derive(Clone, Default)] +pub struct Registry { + runs: Arc<Mutex<HashMap<String, Run>>>, +} + +fn registry() -> &'static Registry { + static REGISTRY: OnceLock<Registry> = OnceLock::new(); + REGISTRY.get_or_init(Registry::default) +} + +/// What the handlers use. +pub fn global() -> &'static Registry { + registry() +} + +impl Registry { + /// Registers `id` as running. Returns false when it is already known, so a + /// caller cannot silently take over another run's id. + pub fn begin(&self, id: &str, engine: &str) -> bool { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if runs.contains_key(id) { + return false; + } + runs.insert( + id.to_string(), + Run { + engine: engine.to_string(), + started: Instant::now(), + started_at: SystemTime::now(), + state: "running".to_string(), + result: None, + error: None, + }, + ); + true + } + + pub fn finish(&self, id: &str, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "finished".to_string(); + run.result = Some(body); + } + } + + pub fn fail(&self, id: &str, status: u16, body: serde_json::Value) { + let mut runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(run) = runs.get_mut(id) { + run.state = "failed".to_string(); + run.error = Some((status, body)); + } + } + + pub fn get(&self, id: &str) -> Option<Run> { + let runs = self.runs.lock().unwrap_or_else(|e| e.into_inner()); + runs.get(id).cloned() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_run_is_registered_once_and_remembers_its_outcome() { + let registry = Registry::default(); + assert!(registry.begin("r1", "pangemma")); + assert!(!registry.begin("r1", "gemma"), "ids are not taken over"); + let run = registry.get("r1").expect("registered"); + assert_eq!(run.state, "running"); + assert_eq!(run.engine, "pangemma"); + registry.finish("r1", serde_json::json!({"data": []})); + let run = registry.get("r1").expect("still there"); + assert_eq!(run.state, "finished"); + assert_eq!(run.result.unwrap()["data"], serde_json::json!([])); + } + + #[test] + fn a_failure_keeps_the_status_the_blocking_endpoint_would_have_used() { + let registry = Registry::default(); + registry.begin("r2", "gemma"); + registry.fail("r2", 422, serde_json::json!({"code": "no_samples_aligned"})); + let run = registry.get("r2").expect("registered"); + assert_eq!(run.state, "failed"); + assert_eq!(run.error.unwrap().0, 422); + } +} diff --git a/src/usage.rs b/src/usage.rs new file mode 100644 index 0000000..2f18613 --- /dev/null +++ b/src/usage.rs @@ -0,0 +1,333 @@ +//! What the *work* was, for the access log — the half a path cannot say. +//! +//! The access line (`request_log_line`, src/lib.rs) is built by middleware +//! that never sees a request body, so on its own it can say which endpoint +//! ran but not which data it ran on: `/compute/gemma` names its panel in +//! the body (`group`, `genotype_file`, `genotype_upload`), and +//! `/compute/bulklmm` names its traits there too. Measured on the week to +//! 2026-11-27, that is 706 of 2 272 requests whose dataset could only be +//! *guessed* from whatever the same user had read a minute earlier. +//! +//! So a handler that knows the answer says it, once, and the line grows +//! those fields: +//! +//! ```ignore +//! usage!(ctx, dataset = &group, engine = "pangemma", run = &run_id); +//! // {"event":"request", …, "dataset":"HSNIH-Palmer","engine":"pangemma","run":"t42"} +//! ``` +//! +//! Deliberately **not** every route: a read route already carries the +//! dataset (`/traits/{dataset}/{trait}/values`) or the group +//! (`/groups/{group}/…`) in its path, so instrumenting it would only +//! duplicate the path into the line. The tracked set is the compute +//! family, listed in [`TRACKED`], plus `/search` — whose query string the +//! line drops on purpose (a query string can carry a credential), which +//! is why `q` is recorded here instead, by the handler, sanitised. +//! +//! Two rules for a value: it is **not a secret** (never a token, a hash or +//! a file's contents), and it is **bounded** — [`MAX_VALUE`] characters, +//! truncated by `note`, because a field a caller controls must not become +//! a way to write megabytes into the log. + +use std::sync::{Arc, Mutex}; + +/// The longest value a field may carry. `q` on `/search` is caller text, +/// and a query can be long: the line stays readable and bounded. +pub const MAX_VALUE: usize = 200; + +/// Keys the line already owns. A handler must not write one of these: it +/// would overwrite the request's own record (`status`, `user`) or invent a +/// second `path`. Checked by [`tests::no_tracked_field_shadows_the_line`]. +pub const RESERVED: &[&str] = &[ + "event", + "method", + "path", + "status", + "took_ms", + "ts", + "request_id", + "user", + "scheme", + "token", +]; + +/// The handlers that must report what they ran on, and the fields each is +/// expected to add. This is documentation *and* the guard: a test walks +/// [`TRACKED`] against the source (see [`tests::every_tracked_handler_reports`]), +/// so a handler edited later without its `usage!` call fails a test rather +/// than silently going dark. +/// +/// Field meanings, shared across handlers so the log stays joinable: +/// +/// - `dataset`: a GeneNetwork dataset name (`UTHSC_BXD_Cochlea_0225`), or a +/// panel name when the request named a group. Use `group` for the second +/// case; both is best (`dataset = group` when they are the same). +/// - `group`: an `InbredSet` name (`BXD`, `HSNIH-Palmer`). +/// - `trait`: the trait id or name the request named, when it named one. +/// - `traits`: how many, for the multi-trait routes (`bulklmm`, `bnw`). +/// - `source`: where the data came from: `group`, `file`, `upload`, +/// `basket`, `values`. +/// - `engine`: `gemma` | `pangemma` | `ravanan` | `rqtl` | `qtl2` | +/// `bulklmm` | `bnw` | `native` | `gn3`. +/// - `cached`: `true` when the answer came from a cache instead of a run. +/// - `run`: the run id the caller can poll or fetch. +/// - `q`: the sanitised `/search` query. +pub const TRACKED: &[(&str, &[&str])] = &[ + ("compute_gemma", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_ravanan", &["dataset", "group", "source", "engine", "run"]), + ("compute_gemma_async", &["dataset", "group", "source", "engine"]), + ("compute_qtl2", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_rqtl", &["dataset", "group", "source", "trait", "engine", "run"]), + ("compute_fitqtl", &["dataset", "group", "source", "trait", "engine"]), + ("compute_bulklmm", &["group", "source", "trait", "engine"]), + ("compute_bnw", &["group", "traits", "engine"]), + ("compute_bnw_features", &["group", "traits", "engine"]), + ("search", &["q", "type", "engine", "hits"]), +]; + +/// Where a compute request's data came from: the `dataset`/`source` +/// pair every compute handler reports. +/// +/// Order matters and is the order a request may name them: a `group` is +/// the common case and names a panel (`HSNIH-Palmer`), then an upload (by +/// its handle, `Arabid.thaliana.genotypes.171126`), then a file on the +/// server -- logged by its stem, because the directory is an +/// implementation detail and `BXD.geno` says the same thing -- and last a +/// basket. `None` when the request gave only inline values, which is +/// honest: there is no dataset to name. +pub fn source<'a>( + group: Option<&'a str>, + upload: Option<&'a str>, + file: Option<&'a str>, + basket: Option<&'a str>, +) -> Option<(&'static str, String)> { + if let Some(group) = group.map(str::trim).filter(|group| !group.is_empty()) { + return Some(("group", group.to_string())); + } + if let Some(upload) = upload.map(str::trim).filter(|upload| !upload.is_empty()) { + return Some(("upload", upload.to_string())); + } + if let Some(file) = file.map(str::trim).filter(|file| !file.is_empty()) { + let stem = std::path::Path::new(file) + .file_stem() + .map(|stem| stem.to_string_lossy().to_string()) + .unwrap_or_else(|| file.to_string()); + return Some(("file", stem)); + } + if let Some(basket) = basket.map(str::trim).filter(|basket| !basket.is_empty()) { + return Some(("basket", basket.to_string())); + } + None +} + +/// The `engine` field: what the request asked for, else what the +/// deployment defaults to. Lower-cased, because the value is compared and +/// counted, not read. +pub fn engine(requested: Option<&str>, default: &str) -> String { + let engine = requested + .map(str::trim) + .filter(|engine| !engine.is_empty()) + .unwrap_or(default); + engine.to_ascii_lowercase() +} + +/// The per-request slot a handler writes its fields into. +/// +/// An `Arc` behind a mutex, exactly like [`crate::auth::CallerSlot`], for +/// the same reason: the handler is not the only holder of the request's +/// [`crate::response::Ctx`] (compute clones it for the fallback path), and +/// every handle must land in the one line. The lock is taken once per +/// note on an instrumented route and never otherwise. +#[derive(Clone, Debug, Default)] +pub struct UsageSlot(Arc<Mutex<Vec<(&'static str, serde_json::Value)>>>); + +impl UsageSlot { + /// Record fields for the line. A later note with the same key replaces + /// the earlier one, so a handler can say what was asked at the top and + /// add `cached` once it knows. + pub fn note(&self, pairs: &[(&'static str, serde_json::Value)]) { + if pairs.is_empty() { + return; + } + let mut guard = match self.0.lock() { + Ok(guard) => guard, + // A poisoned slot must not fail a request: an access-log field + // is not worth a 500, and the line is still written without it. + Err(poisoned) => poisoned.into_inner(), + }; + for (key, value) in pairs { + debug_assert!( + !RESERVED.contains(key), + "{key} is a field of the line itself, not a usage field" + ); + debug_assert!( + !matches!(value, serde_json::Value::String(text) if text.len() > MAX_VALUE), + "note() should have truncated {key}" + ); + match guard.iter_mut().find(|(name, _)| name == key) { + Some(slot) => slot.1 = value.clone(), + None => guard.push((key, value.clone())), + } + } + } + + /// The fields noted so far, in the order they were first noted. + pub fn entries(&self) -> Vec<(&'static str, serde_json::Value)> { + match self.0.lock() { + Ok(guard) => guard.clone(), + Err(poisoned) => poisoned.into_inner().clone(), + } + } + + /// A value as the line will carry it: a string is bounded to + /// [`MAX_VALUE`] characters; a number or a bool stays one, so a reader + /// can count `hits` or test `cached` without parsing text back. + pub fn json<T: Into<serde_json::Value>>(value: T) -> serde_json::Value { + match value.into() { + serde_json::Value::String(text) => serde_json::Value::String(Self::bounded(&text)), + other => other, + } + } + + /// Truncate to [`MAX_VALUE`] characters, on a character boundary (the + /// query is caller text and may be multi-byte). + pub fn bounded(value: &str) -> String { + if value.len() <= MAX_VALUE { + return value.to_string(); + } + let mut end = MAX_VALUE; + while end > 0 && !value.is_char_boundary(end) { + end -= 1; + } + let mut truncated = value[..end].to_string(); + truncated.push('…'); + truncated + } +} + +/// Record usage fields for this request; see the module docs. Values are +/// anything `ToString` (`&str`, `String`, `bool`, numbers), so a handler +/// writes what it has without converting first. +/// +/// ```ignore +/// usage!(ctx, dataset = &group, source = "group", engine = "gemma"); +/// ``` +/// The key is `stringify!`ed, so it is written bare (`group = …`) and may be +/// a keyword (`type = …` on `/search`); it ends up a `&'static str` in the +/// line, which is what keeps a field name from being built at runtime. +#[macro_export] +macro_rules! usage { + ($ctx:expr $(, $key:tt = $value:expr )* $(,)?) => {{ + $ctx.note(&[ $( (stringify!($key), $crate::usage::UsageSlot::json($value)) ),* ]) + }}; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_note_is_read_back_in_order() { + let slot = UsageSlot::default(); + slot.note(&[ + ("dataset", "BXD".into()), + ("group", "BXD".into()), + ("cached", false.into()), + ("hits", 3.into()), + ]); + assert_eq!( + slot.entries(), + vec![ + ("dataset", serde_json::json!("BXD")), + ("group", serde_json::json!("BXD")), + ("cached", serde_json::json!(false)), + ("hits", serde_json::json!(3)), + ], + "a bool stays a bool and a number stays a number" + ); + } + + /// The handler may say what was asked at the top (`engine`) and add + /// what happened later (`cached`) without the line growing a duplicate. + #[test] + fn a_second_note_with_the_same_key_replaces_it() { + let slot = UsageSlot::default(); + slot.note(&[("cached", false.into())]); + slot.note(&[("cached", true.into())]); + assert_eq!(slot.entries(), vec![("cached", serde_json::json!(true))]); + } + + #[test] + fn an_empty_note_is_a_no_op() { + let slot = UsageSlot::default(); + slot.note(&[]); + assert!(slot.entries().is_empty()); + } + + /// `q` is caller text: bounded, and still valid UTF-8 after truncation. + #[test] + fn a_long_value_is_bounded_on_a_character_boundary() { + let long = "é".repeat(MAX_VALUE); + let bounded = UsageSlot::bounded(&long); + assert!(bounded.len() <= MAX_VALUE + '…'.len_utf8()); + assert!(bounded.ends_with('…')); + assert!(bounded.chars().all(|c| c == 'é' || c == '…')); + assert_eq!(UsageSlot::bounded("bxd"), "bxd"); + } + + /// A clone is another handle on the same line, not a second line: the + /// compute handlers clone `Ctx` for the fallback path. + #[test] + fn a_clone_writes_into_the_same_slot() { + let slot = UsageSlot::default(); + let clone = slot.clone(); + clone.note(&[("dataset", "HXB".into())]); + assert_eq!(slot.entries(), vec![("dataset", serde_json::json!("HXB"))]); + } + + #[test] + fn no_tracked_field_shadows_the_line() { + for (handler, fields) in TRACKED { + for field in *fields { + assert!( + !RESERVED.contains(field), + "{handler} would overwrite the line's own {field}" + ); + } + } + } + + /// The guard for a handler edited later without its `usage!` call: each + /// tracked handler's source must contain one. Crude on purpose — it + /// greps the file the handler lives in, so it costs nothing and cannot + /// pass by accident. + #[test] + fn every_tracked_handler_reports() { + let sources = [ + ("compute_gemma", include_str!("routes/gemma.rs")), + ("compute_gemma_ravanan", include_str!("routes/gemma.rs")), + ("compute_gemma_async", include_str!("routes/gemma.rs")), + ("compute_qtl2", include_str!("routes/qtl2.rs")), + ("compute_rqtl", include_str!("routes/rqtl.rs")), + ("compute_fitqtl", include_str!("routes/fitqtl.rs")), + ("compute_bulklmm", include_str!("routes/bulklmm.rs")), + ("compute_bnw", include_str!("routes/bnw.rs")), + ("compute_bnw_features", include_str!("routes/bnw.rs")), + ("search", include_str!("routes/search.rs")), + ]; + for (handler, source) in sources { + let start = source + .find(&format!("pub async fn {handler}(")) + .unwrap_or_else(|| panic!("{handler} is not in the source it should be")); + let rest = &source[start..]; + let end = rest.find("\npub async fn ").unwrap_or(rest.len()); + let body = &rest[..end]; + // `record_usage` is the shared helper the GEMMA handlers call; + // everything else writes the macro out. + assert!( + body.contains("usage!(") || body.contains("record_usage("), + "{handler} is in usage::TRACKED but records nothing" + ); + } + } +} diff --git a/tests/fitqtl.rs b/tests/fitqtl.rs index 0bc7ae8..08e2a9c 100644 --- a/tests/fitqtl.rs +++ b/tests/fitqtl.rs @@ -140,7 +140,7 @@ async fn the_lod_agrees_with_the_scan_at_the_same_marker() { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let scan: Value = serde_json::from_slice(&bytes).unwrap(); - let mut rows = scan["data"]["markers"].as_array().unwrap().clone(); + let mut rows = scan["data"].as_array().unwrap().clone(); rows.sort_by(|left, right| { right[3] .as_f64() diff --git a/tests/genoupload.rs b/tests/genoupload.rs index 9f8a8a5..4797376 100644 --- a/tests/genoupload.rs +++ b/tests/genoupload.rs @@ -335,9 +335,8 @@ async fn every_engine_maps_an_uploaded_genotype() { let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{endpoint}: {}", String::from_utf8_lossy(&bytes)); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - // /compute/rqtl wraps its rows in data.markers; /compute/qtl2 returns - // them as the array itself. - let rows = envelope["data"]["markers"] + // Both /compute/rqtl and /compute/qtl2 return their rows as `data`. + let rows = envelope["data"] .as_array() .or_else(|| envelope["data"].as_array()) .unwrap_or_else(|| panic!("{endpoint}: no rows in {envelope}")); diff --git a/tests/links.rs b/tests/links.rs index 5291008..d36e5a7 100644 --- a/tests/links.rs +++ b/tests/links.rs @@ -221,8 +221,8 @@ async fn a_scan_points_at_the_class_counts_behind_its_peak() { "the trait id is the caller's to fill in: {hint}" ); // And the marker it names is the peak the reply reported. - // /compute/rqtl's rows live under data.markers. - let rows = envelope["data"]["markers"].as_array().unwrap(); + // /compute/rqtl's rows are `data` itself, like every compute endpoint's. + let rows = envelope["data"].as_array().unwrap(); let peak = rows .iter() .max_by(|left, right| { diff --git a/tests/peakgenotypes.rs b/tests/peakgenotypes.rs index 56461f8..132cfca 100644 --- a/tests/peakgenotypes.rs +++ b/tests/peakgenotypes.rs @@ -34,7 +34,7 @@ async fn scan_peak(token: &str, values: &Value) -> Value { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - envelope["data"]["markers"] + envelope["data"] .as_array() .unwrap() .iter() @@ -148,7 +148,7 @@ async fn a_marker_away_from_the_peak_is_refused() { .await; let bytes = response.into_body().collect().await.unwrap().to_bytes(); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - let rows = envelope["data"]["markers"].as_array().unwrap(); + let rows = envelope["data"].as_array().unwrap(); let distant = rows .iter() .find(|row| row[1] != peak[1]) diff --git a/tests/qtl2.rs b/tests/qtl2.rs index dbf6c1d..958c7c3 100644 --- a/tests/qtl2.rs +++ b/tests/qtl2.rs @@ -140,7 +140,7 @@ async fn a_group_panel_scans_and_agrees_with_the_haley_knott_scan() { assert_eq!(response.status(), StatusCode::OK); let bytes = response.into_body().collect().await.unwrap().to_bytes(); let scan: Value = serde_json::from_slice(&bytes).unwrap(); - let hk_peak = scan["data"]["markers"] + let hk_peak = scan["data"] .as_array() .unwrap() .iter() diff --git a/tests/rqtl.rs b/tests/rqtl.rs index ae0e280..5eeaef4 100644 --- a/tests/rqtl.rs +++ b/tests/rqtl.rs @@ -115,7 +115,7 @@ async fn compute_rqtl_maps_a_qtl_from_the_bxd_riset_fixture() { ); let data: Value = common::data(&bytes); - let markers = data["markers"].as_array().unwrap(); + let markers = data.as_array().unwrap(); // The fixture has 6 markers (3 per chromosome, 2 chromosomes). assert_eq!(markers.len(), 6); // Rows are positional (name, chr, pos, lod); see meta.columns. @@ -179,8 +179,11 @@ async fn compute_rqtl_with_permutations_returns_thresholds() { ); let data: Value = common::data(&bytes); - let perm = &data["permutation"]; - assert!(!perm.is_null(), "{data}"); + // The permutation null is qualifier information, so it lives in + // meta.permutation beside the rows rather than in data. + let envelope: Value = serde_json::from_slice(&bytes).unwrap(); + let perm = &envelope["meta"]["permutation"]; + assert!(!perm.is_null(), "{envelope}"); assert_eq!(perm["values"].as_array().unwrap().len(), 20); let suggestive = perm["suggestive"].as_f64().unwrap(); let significant = perm["significant"].as_f64().unwrap(); @@ -432,7 +435,7 @@ async fn compute_rqtl_fits_a_case_attribute_as_a_covariate() { String::from_utf8_lossy(&bytes) ); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - assert!(!envelope["data"]["markers"].as_array().unwrap().is_empty()); + assert!(!envelope["data"].as_array().unwrap().is_empty()); let notes: Vec<&str> = envelope["notes"] .as_array() @@ -514,7 +517,7 @@ async fn a_cm_only_genotype_file_maps() { let bytes = response.into_body().collect().await.unwrap().to_bytes(); assert_eq!(status, StatusCode::OK, "{}", String::from_utf8_lossy(&bytes)); let envelope: Value = serde_json::from_slice(&bytes).unwrap(); - let markers = envelope["data"]["markers"].as_array().unwrap(); + let markers = envelope["data"].as_array().unwrap(); assert_eq!( markers.len(), 6, |
