about summary refs log tree commit diff
path: root/tests/plot.rs
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-07 18:23:36 +0000
committerPjotr <wrk@bosa.lan>2026-11-07 18:23:36 +0000
commitc087e4186874921f48caefa2d8630f5bf05b3c0d (patch)
treedf827dd62afdb72476f89f31fa69cac5b5d4c92a /tests/plot.rs
parentf9ba0f12e3bf52919fc363c037fbf0a0deda8c17 (diff)
downloadgenenetwork4-c087e4186874921f48caefa2d8630f5bf05b3c0d.tar.gz
plot: take a posted result, and never re-run the mapping
The plot endpoints ran the mapping themselves, which meant the picture
could come from a different run than the one the caller was looking at,
and cost a scan to draw. They now take the mapping's own response -- the
JSON /compute/{rqtl,gemma} returned, posted back -- and hand it straight
to the plotter, which is what the scripts were written for
(`python3 plot-rqtl.py result.json -o out.svg --trait …`).

Validation replaces the run: `/plot/rqtl` needs `data.markers` with
positional 4+ column rows, `/plot/gemma` needs `data` rows *and*
`meta.columns` (its plotter reads the column names to find `p_lrt`), and
anything else is a 422 saying "post that response back". `/plot/rqtl`
also accepts just the `data` member; GEMMA cannot, and says why.

The mapping's `actions` suggestion now describes posting its own response
and carries no body -- duplicating a 21 000-row response into a
suggestion would double the envelope for nothing, and the caller already
holds it.

* src/routes/plot.rs: posted result, shape validation, `?trait`/`?title`
and `?bonferroni=false` passthrough to the scripts; no compute imports.
* src/routes/{rqtl,gemma}.rs: the plot suggestion loses its body.
* tests/plot.rs: canned results instead of real mappings -- the tests now
  need only the plotter, no Rscript or gemma; covers both engines, the
  bare-`data` form, and the 422 for a body that is a request.
* README.md, docs/www/ai-instruction.md (4a), docs/www/operator-checklist.md:
  "post the response back", and why GEMMA needs `meta.columns`.
Diffstat (limited to 'tests/plot.rs')
-rw-r--r--tests/plot.rs160
1 files changed, 116 insertions, 44 deletions
diff --git a/tests/plot.rs b/tests/plot.rs
index 012dc84..848ae49 100644
--- a/tests/plot.rs
+++ b/tests/plot.rs
@@ -1,8 +1,9 @@
 //! `POST /plot/rqtl` and `POST /plot/gemma`: an SVG back, not an envelope.
 //!
-//! These run a real mapping, so they need the engines -- and the plotter
-//! scripts, which are configured (`RQTL_PLOTTER`, `GEMMA_PLOTTER`,
-//! `PLOT_PYTHON`). Skips when a piece is missing, like the mapping tests.
+//! They take a **posted mapping result**, so they need no engine at all:
+//! the plotter scripts (`RQTL_PLOTTER`, `GEMMA_PLOTTER`, run by
+//! `PLOT_PYTHON`) are the only requirement, and a canned result exercises
+//! the whole path.
 
 use axum::http::StatusCode;
 use http_body_util::BodyExt;
@@ -39,59 +40,117 @@ fn plotter_present(which: &str) -> bool {
     std::path::Path::new(&path).is_file() && tool_available(&config.plot_python, &["--version"])
 }
 
+fn canned_rqtl_result() -> Value {
+    serde_json::json!({
+        "data": {
+            "markers": [
+                ["rs1", "1", 3.1, 2.4],
+                ["rs2", "1", 8.2, 1.1],
+                ["rs3", "2", 12.0, 4.2],
+                ["rs4", "2", 19.5, 0.3],
+                ["rs5", "X", 30.0, 1.8]
+            ],
+            "permutation": {"values": [1.0, 1.2], "suggestive": 2.5, "significant": 3.5}
+        },
+        "notes": ["Genotype: prepared panel subset x (version BXD.8, 198 individuals, 0 parents/F1s dropped); 5 of 5 supplied values aligned onto it by name."]
+    })
+}
+
+fn canned_gemma_result() -> Value {
+    serde_json::json!({
+        "meta": {"state": "complete", "took_ms": 12, "request_id": "canned",
+                 "columns": ["chr", "rs", "ps", "n_miss", "allele1", "allele0", "af",
+                             "beta", "se", "l_mle", "p_lrt"],
+                 "num_rows": 3, "num_cols": 11},
+        "data": [
+            [1.0, "rs1", 3.1, 0.0, "X", "Y", 0.2, 1.0, 2.0, 3.0, 0.5],
+            [1.0, "rs2", 8.2, 0.0, "X", "Y", 0.2, 1.0, 2.0, 3.0, 0.001],
+            [2.0, "rs3", 12.0, 0.0, "X", "Y", 0.2, 1.0, 2.0, 3.0, 0.3]
+        ],
+        "notes": []
+    })
+}
+
 #[tokio::test]
-async fn an_rqtl_mapping_can_be_plotted_and_the_suggestion_resolves() {
-    if !genotype_dir_present() || !rscript_available() || !plotter_present("rqtl") {
+async fn a_posted_rqtl_result_is_drawn_and_the_suggestion_says_so() {
+    if !plotter_present("rqtl") {
         eprintln!(
-            "skipping an_rqtl_mapping_can_be_plotted_and_the_suggestion_resolves: needs \
-             genotype files, Rscript and the plotter script"
+            "skipping a_posted_rqtl_result_is_drawn_and_the_suggestion_says_so: needs the \
+             plotter script (RQTL_PLOTTER) and PLOT_PYTHON"
         );
         return;
     }
     let Some(token) = auth_token().await else {
-        eprintln!("skipping an_rqtl_mapping_can_be_plotted_and_the_suggestion_resolves: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
+        eprintln!("skipping a_posted_rqtl_result_is_drawn_and_the_suggestion_says_so: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
         return;
     };
 
-    let samples: Vec<Value> = ["BXD1", "BXD2", "BXD5", "BXD6", "BXD8", "BXD9", "BXD11", "BXD12"]
-        .iter()
-        .enumerate()
-        .map(|(index, name)| serde_json::json!({"name": name, "value": index as f64 + 1.0}))
-        .collect();
-    let body = serde_json::json!({"group": "BXD", "trait_name": "plot-check", "samples": samples});
-
-    // The mapping suggests the plot; the suggestion is runnable as it stands.
     let response = post_json_with_token(
-        "POST /compute/rqtl",
-        "/compute/rqtl",
+        "POST /plot/rqtl",
+        "/plot/rqtl?trait=BXDPublish::10001",
         &token,
-        &body,
+        &canned_rqtl_result(),
     )
     .await;
     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();
-    let plot_action = envelope["actions"]
-        .as_array()
+    assert_eq!(
+        response.headers().get("content-type").unwrap(),
+        "image/svg+xml; charset=utf-8"
+    );
+    let summary = response
+        .headers()
+        .get("x-plot-summary")
+        .expect("x-plot-summary")
+        .to_str()
         .unwrap()
-        .iter()
-        .find(|action| action["href"] == "/plot/rqtl")
-        .expect("a plot suggestion")
-        .clone();
+        .to_string();
+    assert!(summary.contains("peak rs3"), "the peak is the strongest LOD: {summary}");
+    let svg = response.into_body().collect().await.unwrap().to_bytes();
+    let text = String::from_utf8_lossy(&svg);
+    assert!(text.starts_with("<svg"), "an SVG document");
+    assert!(text.trim_end().ends_with("</svg>"), "a complete SVG");
+    assert!(text.contains("BXDPublish::10001"), "the title carries the trait label");
 
+    // Just the `data` member works too.
     let response = post_json_with_token(
         "POST /plot/rqtl",
         "/plot/rqtl",
         &token,
-        &plot_action["body"],
+        &canned_rqtl_result()["data"],
+    )
+    .await;
+    assert_eq!(response.status(), StatusCode::OK);
+
+    // GEMMA's plotter reads `meta.columns`, so a bare `data` is refused
+    // with a message saying to post the whole response.
+    let response = post_json_with_token(
+        "POST /plot/gemma",
+        "/plot/gemma",
+        &token,
+        &canned_gemma_result()["data"],
+    )
+    .await;
+    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+}
+
+#[tokio::test]
+async fn a_posted_gemma_result_is_drawn() {
+    if !plotter_present("gemma") {
+        eprintln!("skipping a_posted_gemma_result_is_drawn: needs the plotter script (GEMMA_PLOTTER) and PLOT_PYTHON");
+        return;
+    }
+    let Some(token) = auth_token().await else {
+        eprintln!("skipping a_posted_gemma_result_is_drawn: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
+        return;
+    };
+    let response = post_json_with_token(
+        "POST /plot/gemma",
+        "/plot/gemma?trait=BXDPublish::10001",
+        &token,
+        &canned_gemma_result(),
     )
     .await;
     assert_eq!(response.status(), StatusCode::OK);
-    assert_eq!(
-        response.headers().get("content-type").unwrap(),
-        "image/svg+xml; charset=utf-8"
-    );
-    // The plotter's one-line peak summary rides along as a header.
     let summary = response
         .headers()
         .get("x-plot-summary")
@@ -99,25 +158,38 @@ async fn an_rqtl_mapping_can_be_plotted_and_the_suggestion_resolves() {
         .to_str()
         .unwrap()
         .to_string();
-    assert!(summary.contains("peak"), "{summary}");
+    assert!(summary.contains("rs2"), "the smallest p_lrt: {summary}");
     let svg = response.into_body().collect().await.unwrap().to_bytes();
-    let text = String::from_utf8_lossy(&svg);
-    assert!(text.starts_with("<svg"), "an SVG document: {}", &text[..40.min(text.len())]);
-    assert!(text.trim_end().ends_with("</svg>"), "a complete SVG");
+    assert!(String::from_utf8_lossy(&svg).starts_with("<svg"));
 }
 
 #[tokio::test]
-async fn plotting_refuses_an_invalid_mapping_request_like_the_mapping_does() {
+async fn a_body_that_is_not_a_mapping_result_is_a_422() {
     let Some(token) = auth_token().await else {
-        eprintln!("skipping plotting_refuses_an_invalid_mapping_request_like_the_mapping_does: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
+        eprintln!("skipping a_body_that_is_not_a_mapping_result_is_a_422: set GN4_TEST_AUTH_TOKEN (see docs/gn-auth.md)");
         return;
     };
-    // No group and no genotype_file: the mapping handler's own 422, before
-    // any plotting happens.
-    let body = serde_json::json!({"trait_name": "t", "samples": []});
-    let response = post_json_with_token("POST /plot/rqtl", "/plot/rqtl", &token, &body).await;
+    // A compute *request* is what this used to take; it is not a result.
+    let request = serde_json::json!({"group": "BXD", "trait_name": "t", "samples": []});
+    let response = post_json_with_token("POST /plot/rqtl", "/plot/rqtl", &token, &request).await;
     assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
     let bytes = response.into_body().collect().await.unwrap().to_bytes();
     let error: Value = serde_json::from_slice(&bytes).unwrap();
-    assert_eq!(error["code"], "missing_genotype");
+    assert_eq!(error["code"], "not_an_rqtl_result");
+    assert!(
+        error["detail"]
+            .as_str()
+            .unwrap()
+            .contains("post that response back"),
+        "{error}"
+    );
+
+    let response = post_json_with_token(
+        "POST /plot/gemma",
+        "/plot/gemma",
+        &token,
+        &serde_json::json!({"markers": []}),
+    )
+    .await;
+    assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
 }