about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-11-07 15:25:48 +0000
committerPjotr <wrk@bosa.lan>2026-11-07 15:25:48 +0000
commite5c333959af6675a0d80934c8cf76275d5571ef8 (patch)
treedbd56c23ccca7b92f2f122b88fd99aff16d46c8c /src
parent4831e5aebb81e7280d017bc57145aa1a7453e661 (diff)
downloadgenenetwork4-e5c333959af6675a0d80934c8cf76275d5571ef8.tar.gz
values: suggest R/qtl and GEMMA in the envelope's `actions`
Fetching one trait's value per strain is usually the step before mapping
that trait, and the API can do the mapping. Those calls are POSTs with a
body, so they cannot go in `next` -- a `next` link is a GET that returns
200, which is what makes `next` safe to follow blindly and what
tests/envelope.rs relies on. Hence a fifth envelope member, `actions`,
holding method + href + description + body, and omitted entirely when
there is nothing to suggest (most responses keep the four-member shape).

The three per-trait values endpoints now carry a `POST /compute/rqtl`
and a `POST /compute/gemma` suggestion with the values already in the
body, in the response's own sample order. Genotype/SNP paths stay
bracketed placeholders: they must exist on the server, which the server
cannot know on the caller's behalf.

The instruction page says, in the same breath, never to run R/qtl or
GEMMA locally -- a local scan would use genotypes that are not the
panel's and would disagree with GeneNetwork's own results -- and that
results are cached, so repeat calls are cheap (measured: ~2 s cached
against ~20 s cold on the BXD fixtures).

Also fixes a flake the new test exposed rather than caused:
config::tests read and write process-global env vars and Config::load()
reads all of them, so the RAVANAN_* tests could fail
search_engine_keys_follow_env_over_default_layering on an unrelated
assertion. One module-level lock serialises them.

* src/response.rs (SuggestedCall, Envelope::actions/with_action/
with_actions): the new member, omitted when empty; unit tests for both.
* src/suggest.rs: new. Builds the two suggestions for either value type
(db::TraitValue, db::ProbeSetValue), with its own unit tests.
* src/routes/{traits,groups,datasets}.rs: the three values handlers.
* tests/compute_suggestions.rs: new. Suggestions present with values in
order, on all three routes; absent elsewhere; `next` still GET-only and
still returns 200.
* src/config.rs (tests): env_guard, taken by the 11 config tests.
* README.md (Success responses): the `actions` member, with an example.
* docs/www/ai-instruction.md (4a): never compute locally, why, caching,
and how to use the suggested bodies.
* docs/www/operator-checklist.md: the caching numbers.
Diffstat (limited to 'src')
-rw-r--r--src/config.rs23
-rw-r--r--src/lib.rs1
-rw-r--r--src/response.rs62
-rw-r--r--src/routes/datasets.rs25
-rw-r--r--src/routes/groups.rs15
-rw-r--r--src/routes/traits.rs25
-rw-r--r--src/suggest.rs150
7 files changed, 281 insertions, 20 deletions
diff --git a/src/config.rs b/src/config.rs
index 9d06c4f..661f012 100644
--- a/src/config.rs
+++ b/src/config.rs
@@ -478,12 +478,25 @@ fn load_file(path: &str) -> HashMap<String, String> {
 #[cfg(test)]
 mod tests {
     use super::*;
+    use std::sync::{Mutex, MutexGuard};
+
+    /// These tests read and write process-global environment variables,
+    /// and `Config::load()` reads *all* of them: a test that sets
+    /// `RAVANAN_*` while another loads the config makes that other one
+    /// fail on an unrelated assertion (the file's own warning about
+    /// env-var mutation, one level up). This serialises the module.
+    /// Poisoning is ignored: one failing test should not cascade.
+    fn env_guard() -> MutexGuard<'static, ()> {
+        static LOCK: Mutex<()> = Mutex::new(());
+        LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+    }
 
     /// Defaults apply when nothing overrides them. Skips (rather than
     /// flakes) if the surrounding environment happens to set any of the
     /// knobs this test asserts on.
     #[test]
     fn defaults_apply_with_no_files_or_env() {
+        let _env = env_guard();
         for key in [
             "SQL_URI",
             "GN4_DB_MODE",
@@ -551,6 +564,7 @@ mod tests {
 
     #[test]
     fn db_mode_accepts_only_dev_and_production() {
+        let _env = env_guard();
         assert_eq!(parse_db_mode("dev"), DbMode::Dev);
         assert_eq!(parse_db_mode(" DEV "), DbMode::Dev);
         assert_eq!(parse_db_mode("production"), DbMode::Production);
@@ -564,6 +578,7 @@ mod tests {
 
     #[test]
     fn a_switch_is_on_only_for_a_clearly_affirmative_value() {
+        let _env = env_guard();
         for on in ["true", "TRUE", "True", "1", "yes", "ON", " on "] {
             assert!(parse_switch(on), "{on:?}");
         }
@@ -612,6 +627,7 @@ mod tests {
     /// per the rule documented in tests/search_engine.rs.
     #[test]
     fn search_engine_keys_follow_env_over_default_layering() {
+        let _env = env_guard();
         let restore = |key: &str, previous: Option<String>| unsafe {
             match previous {
                 Some(value) => std::env::set_var(key, value),
@@ -661,6 +677,7 @@ mod tests {
     /// single-machine adds no switches of its own beyond --scratch.
     #[test]
     fn ravanan_batch_defaults_to_single_machine() {
+        let _env = env_guard();
         let mut values = HashMap::new();
         values.insert("RAVANAN_BATCH_SYSTEM".to_string(), String::new());
         assert_eq!(parse_ravanan_batch(&values), RavananBatch::SingleMachine);
@@ -678,6 +695,7 @@ mod tests {
     /// backend needs, and nothing when they are optional and unset.
     #[test]
     fn ravanan_batch_slurm_args() {
+        let _env = env_guard();
         let mut values = HashMap::new();
         values.insert("RAVANAN_BATCH_SYSTEM".to_string(), " Slurm-API ".to_string());
         values.insert(
@@ -730,30 +748,35 @@ mod tests {
     #[test]
     #[should_panic(expected = "RAVANAN_BATCH_SYSTEM must be")]
     fn ravanan_batch_rejects_unknown_backend() {
+        let _env = env_guard();
         parse_ravanan_batch(&ravanan_values("slrum-api", "http://h:6820", "/jwt", ""));
     }
 
     #[test]
     #[should_panic(expected = "RAVANAN_SLURM_API_ENDPOINT")]
     fn ravanan_batch_slurm_requires_endpoint() {
+        let _env = env_guard();
         parse_ravanan_batch(&ravanan_values("slurm-api", "", "/jwt", ""));
     }
 
     #[test]
     #[should_panic(expected = "RAVANAN_SLURM_JWT")]
     fn ravanan_batch_slurm_requires_jwt_file() {
+        let _env = env_guard();
         parse_ravanan_batch(&ravanan_values("slurm-api", "http://127.0.0.1:6820", "", ""));
     }
 
     #[test]
     #[should_panic(expected = "RAVANAN_SLURM_NICE must be an integer")]
     fn ravanan_batch_rejects_non_integer_nice() {
+        let _env = env_guard();
         parse_ravanan_batch(&ravanan_values("slurm-api", "http://127.0.0.1:6820", "/jwt", "high"));
     }
 
     /// The new keys layer like the rest: environment beats the default.
     #[test]
     fn ravanan_batch_keys_follow_env_over_default_layering() {
+        let _env = env_guard();
         let keys = [
             "RAVANAN_BATCH_SYSTEM",
             "RAVANAN_SLURM_API_ENDPOINT",
diff --git a/src/lib.rs b/src/lib.rs
index b7407ea..ac63977 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -18,6 +18,7 @@ mod routes;
 mod rqtl;
 pub mod search;
 mod streaming;
+pub mod suggest;
 
 use error::ApiError;
 use response::{Ctx, Envelope};
diff --git a/src/response.rs b/src/response.rs
index e85362a..fd37e21 100644
--- a/src/response.rs
+++ b/src/response.rs
@@ -65,6 +65,12 @@ pub struct Envelope<T: Serialize + utoipa::ToSchema> {
     /// missing). Never derived from database content or request input.
     pub notes: Vec<String>,
     pub next: Vec<NextAction>,
+    /// Calls the server suggests that are not plain `GET`s (see
+    /// [`SuggestedCall`]). Present only when there is something to
+    /// suggest, e.g. on the per-trait values endpoints, where a QTL
+    /// mapping run is the obvious next step.
+    #[serde(skip_serializing_if = "Vec::is_empty")]
+    pub actions: Vec<SuggestedCall>,
 }
 
 /// One suggested follow-up call.
@@ -76,6 +82,27 @@ pub struct NextAction {
     pub description: String,
 }
 
+/// 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
+/// suite relies on). This carries the method, and a ready-to-edit body
+/// where the server can build one.
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct SuggestedCall {
+    /// HTTP method, e.g. "POST".
+    pub method: String,
+    /// Endpoint, relative to the API root, e.g. "/compute/rqtl".
+    pub href: String,
+    /// What this call does, and what the caller must fill in first.
+    pub description: String,
+    /// A body to send, with placeholders where the server cannot know
+    /// the value (e.g. a path that has to exist on the server's own
+    /// filesystem).
+    #[serde(skip_serializing_if = "Option::is_none")]
+    #[schema(value_type = Object)]
+    pub body: Option<serde_json::Value>,
+}
+
 impl<T: Serialize + utoipa::ToSchema> Envelope<T> {
     pub fn with_next(mut self, href: &str, description: &str) -> Self {
         self.next.push(NextAction {
@@ -85,6 +112,19 @@ impl<T: Serialize + utoipa::ToSchema> Envelope<T> {
         self
     }
 
+    /// Adds one suggested non-`GET` call (see [`SuggestedCall`]).
+    pub fn with_action(mut self, action: SuggestedCall) -> Self {
+        self.actions.push(action);
+        self
+    }
+
+    /// Adds several, e.g. everything `suggest::mapping_actions_for`
+    /// offers for a trait's values.
+    pub fn with_actions(mut self, actions: Vec<SuggestedCall>) -> Self {
+        self.actions.extend(actions);
+        self
+    }
+
     pub fn with_note(mut self, note: &str) -> Self {
         self.notes.push(note.to_string());
         self
@@ -179,6 +219,7 @@ impl Ctx {
             },
             notes: Vec::new(),
             next: Vec::new(),
+            actions: Vec::new(),
         }
     }
 }
@@ -247,6 +288,27 @@ mod tests {
         assert_eq!(json["meta"]["state"], "complete");
         assert_eq!(json["notes"], serde_json::json!([]));
         assert_eq!(json["next"], serde_json::json!([]));
+        // `actions` is omitted entirely when the server has nothing to
+        // suggest, so most responses keep the four-member shape.
+        assert!(json.get("actions").is_none(), "{json}");
+    }
+
+    #[test]
+    fn a_suggested_action_carries_its_method_and_body() {
+        let json = serde_json::to_value(
+            ctx().envelope(42).with_action(SuggestedCall {
+                method: "POST".to_string(),
+                href: "/compute/rqtl".to_string(),
+                description: "Map it".to_string(),
+                body: Some(serde_json::json!({"trait_name": "mytrait"})),
+            }),
+        )
+        .unwrap();
+        assert_eq!(json["actions"][0]["method"], "POST");
+        assert_eq!(json["actions"][0]["href"], "/compute/rqtl");
+        assert_eq!(json["actions"][0]["body"]["trait_name"], "mytrait");
+        // ... and `next` stays the GET-only list it was.
+        assert_eq!(json["next"], serde_json::json!([]));
     }
 
     #[test]
diff --git a/src/routes/datasets.rs b/src/routes/datasets.rs
index 34a2b09..71aae52 100644
--- a/src/routes/datasets.rs
+++ b/src/routes/datasets.rs
@@ -12,6 +12,7 @@ use crate::config::Config;
 use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::response::{Ctx, Envelope, path_segment};
+use crate::suggest;
 
 #[utoipa::path(get, path = "/datasets/{dataset}", summary = "Get one expression dataset's full record by name or numeric id", params(
     ("dataset" = String, Path, description = "Dataset Name, Name2, FullName, ShortName or numeric Id")
@@ -401,14 +402,22 @@ pub async fn dataset_probeset_values(
     .and_then(|lookup| match lookup {
         DatasetProbesetLookup::Found(authorized, values) => {
             let _: Authorized = authorized;
-            Ok(Json(ctx.envelope(values).with_next(
-                &format!(
-                    "/datasets/{}/probesets/{}",
-                    path_segment(&not_found_dataset),
-                    path_segment(&not_found_probeset)
-                ),
-                "The probeset's metadata",
-            )))
+            let actions = suggest::mapping_actions_for(
+                &values,
+                &format!("{}::{}", not_found_dataset, not_found_probeset),
+            );
+            Ok(Json(
+                ctx.envelope(values)
+                    .with_actions(actions)
+                    .with_next(
+                        &format!(
+                            "/datasets/{}/probesets/{}",
+                            path_segment(&not_found_dataset),
+                            path_segment(&not_found_probeset)
+                        ),
+                        "The probeset's metadata",
+                    ),
+            ))
         }
         DatasetProbesetLookup::Forbidden => Err(ApiError::new(
             StatusCode::FORBIDDEN,
diff --git a/src/routes/groups.rs b/src/routes/groups.rs
index 48778f6..860e588 100644
--- a/src/routes/groups.rs
+++ b/src/routes/groups.rs
@@ -13,6 +13,7 @@ use crate::config::Config;
 use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::response::{Ctx, Envelope, path_segment};
+use crate::suggest;
 
 /// Query parameters for `GET /groups`; all optional, combined with AND.
 #[derive(Deserialize, utoipa::IntoParams)]
@@ -351,10 +352,16 @@ pub async fn group_trait_values(
         GroupTraitLookup::Found(authorized, values) => {
             let _: Authorized = authorized;
             let group = path_segment(&not_found_group);
-            Ok(Json(ctx.envelope(values).with_next(
-                &format!("/groups/{group}/traits/{trait_id}"),
-                "The trait's metadata",
-            )))
+            let actions = suggest::mapping_actions_for(
+                &values,
+                &format!("{}::{trait_id}", not_found_group),
+            );
+            Ok(Json(
+                ctx.envelope(values).with_actions(actions).with_next(
+                    &format!("/groups/{group}/traits/{trait_id}"),
+                    "The trait's metadata",
+                ),
+            ))
         }
         GroupTraitLookup::Forbidden => Err(ApiError::new(
             StatusCode::FORBIDDEN,
diff --git a/src/routes/traits.rs b/src/routes/traits.rs
index b4013c3..28ff6ba 100644
--- a/src/routes/traits.rs
+++ b/src/routes/traits.rs
@@ -24,6 +24,7 @@ use crate::config::Config;
 use crate::db;
 use crate::error::{ApiError, Unauthorized};
 use crate::response::{Ctx, Envelope, path_segment};
+use crate::suggest;
 
 /// One trait's metadata, tagged by which category its dataset resolved
 /// to (db::resolve_trait_dataset). ProbeSetInfo and TraitInfo share
@@ -474,14 +475,22 @@ pub async fn trait_values(
     .and_then(|lookup| match lookup {
         TraitValuesLookup::Found(authorized, values) => {
             let _: Authorized = authorized;
-            Ok(Json(ctx.envelope(values).with_next(
-                &format!(
-                    "/traits/{}/{}",
-                    path_segment(&not_found_dataset),
-                    path_segment(&not_found_trait)
-                ),
-                "The trait's metadata",
-            )))
+            let actions = suggest::mapping_actions_for(
+                &values,
+                &format!("{}::{}", not_found_dataset, not_found_trait),
+            );
+            Ok(Json(
+                ctx.envelope(values)
+                    .with_actions(actions)
+                    .with_next(
+                        &format!(
+                            "/traits/{}/{}",
+                            path_segment(&not_found_dataset),
+                            path_segment(&not_found_trait)
+                        ),
+                        "The trait's metadata",
+                    ),
+            ))
         }
         TraitValuesLookup::Forbidden => Err(ApiError::new(
             StatusCode::FORBIDDEN,
diff --git a/src/suggest.rs b/src/suggest.rs
new file mode 100644
index 0000000..615cffe
--- /dev/null
+++ b/src/suggest.rs
@@ -0,0 +1,150 @@
+//! QTL-mapping suggestions for the per-trait values endpoints.
+//!
+//! Fetching one trait's value per strain is usually the step before
+//! mapping that trait, and the API can do the mapping itself
+//! (`/compute/rqtl`, `/compute/gemma`). Those are `POST`s with a body, so
+//! they cannot go in `next` -- following a `next` link is a `GET` that
+//! returns 200, which is what makes `next` safe to follow blindly -- hence
+//! [`SuggestedCall`] in the envelope's `actions`.
+//!
+//! What the server can fill in, it does: the values themselves, in the
+//! sample order of the response they came from. What it cannot know is
+//! where the genotype files live on its own filesystem, so those stay
+//! bracketed placeholders: a caller that posts the body unchanged gets a
+//! clear "no such file" error rather than a wrong answer.
+
+use crate::response::SuggestedCall;
+
+/// The two per-strain value types (`db::TraitValue`, `db::ProbeSetValue`)
+/// are both `{name, value}`; this is what lets one suggestion builder
+/// serve both.
+pub trait NamedValue {
+    fn name(&self) -> &str;
+    fn value(&self) -> Option<f64>;
+}
+
+impl NamedValue for crate::db::TraitValue {
+    fn name(&self) -> &str {
+        &self.name
+    }
+    fn value(&self) -> Option<f64> {
+        self.value
+    }
+}
+
+impl NamedValue for crate::db::ProbeSetValue {
+    fn name(&self) -> &str {
+        &self.name
+    }
+    fn value(&self) -> Option<f64> {
+        self.value
+    }
+}
+
+/// [`mapping_actions`] for one of the two value types.
+pub fn mapping_actions_for<T: NamedValue>(values: &[T], trait_name: &str) -> Vec<SuggestedCall> {
+    let samples: Vec<(String, Option<f64>)> = values
+        .iter()
+        .map(|value| (value.name().to_string(), value.value()))
+        .collect();
+    mapping_actions(&samples, trait_name)
+}
+
+/// Placeholder for a path that must already exist on the server.
+const SERVER_PATH: &str = "<path on the server, e.g. a genotype file it already holds>";
+
+/// `POST /compute/rqtl` and `POST /compute/gemma` for one trait's
+/// values, in the response's own sample order.
+///
+/// `samples` is `(strain name, value)`; `trait_name` labels the trait in
+/// the R/qtl request (R/qtl has no other use for it, but a run should be
+/// identifiable).
+pub fn mapping_actions(samples: &[(String, Option<f64>)], trait_name: &str) -> Vec<SuggestedCall> {
+    let values: Vec<Option<f64>> = samples.iter().map(|(_, value)| *value).collect();
+    let named: Vec<serde_json::Value> = samples
+        .iter()
+        .map(|(name, value)| serde_json::json!({"name": name, "value": value}))
+        .collect();
+
+    vec![
+        SuggestedCall {
+            method: "POST".to_string(),
+            href: "/compute/rqtl".to_string(),
+            description: format!(
+                "Map '{trait_name}' with R/qtl (scanone): this body carries the {n} values \
+                 above as `samples`, in the same order. Replace the `genotype_file` \
+                 placeholder with a path that exists on the server. Synchronous: seconds to \
+                 minutes.",
+                n = samples.len()
+            ),
+            body: Some(serde_json::json!({
+                "genotype_file": SERVER_PATH,
+                "trait_name": trait_name,
+                "samples": named,
+            })),
+        },
+        SuggestedCall {
+            method: "POST".to_string(),
+            href: "/compute/gemma".to_string(),
+            description: format!(
+                "Run GEMMA's LOCO GWAS on '{trait_name}': this body carries the {n} values \
+                 above as `trait_values` (null for missing). Replace the `genotype_file` and \
+                 `snps_file` placeholders with paths that exist on the server. Synchronous: \
+                 tens of seconds to minutes, so pass `?id=` and poll its status endpoint.",
+                n = samples.len()
+            ),
+            body: Some(serde_json::json!({
+                "genotype_file": SERVER_PATH,
+                "snps_file": SERVER_PATH,
+                "trait_values": values,
+            })),
+        },
+    ]
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn samples() -> Vec<(String, Option<f64>)> {
+        vec![
+            ("BXD1".to_string(), Some(9.5)),
+            ("BXD2".to_string(), None),
+        ]
+    }
+
+    #[test]
+    fn both_mapping_endpoints_are_suggested_with_the_values_in_order() {
+        let actions = mapping_actions(&samples(), "mytrait");
+        assert_eq!(actions.len(), 2);
+        assert_eq!(actions[0].method, "POST");
+        assert_eq!(actions[0].href, "/compute/rqtl");
+        assert_eq!(actions[1].href, "/compute/gemma");
+
+        let rqtl = actions[0].body.as_ref().unwrap();
+        assert_eq!(rqtl["trait_name"], "mytrait");
+        assert_eq!(rqtl["samples"][0]["name"], "BXD1");
+        assert_eq!(rqtl["samples"][0]["value"], 9.5);
+        assert_eq!(rqtl["samples"][1]["value"], serde_json::Value::Null);
+
+        let gemma = actions[1].body.as_ref().unwrap();
+        assert_eq!(gemma["trait_values"], serde_json::json!([9.5, null]));
+        // The paths are placeholders, deliberately: the server does not
+        // know where a genotype file it may read lives.
+        assert!(gemma["genotype_file"].as_str().unwrap().starts_with('<'));
+        assert!(rqtl["genotype_file"].as_str().unwrap().starts_with('<'));
+    }
+
+    #[test]
+    fn the_description_says_what_must_be_replaced() {
+        let actions = mapping_actions(&samples(), "mytrait");
+        for action in &actions {
+            assert!(
+                action.description.to_lowercase().contains("replace"),
+                "{}",
+                action.description
+            );
+            assert!(action.description.contains("2 values"), "{}", action.description);
+        }
+    }
+}