about summary refs log tree commit diff
path: root/src
diff options
context:
space:
mode:
authorPjotr <wrk@bosa.lan>2026-10-12 12:19:12 +0000
committerPjotr <wrk@bosa.lan>2026-10-12 12:19:12 +0000
commitb04db9ea05a73074afcf88300f8b6aa8c6e28e64 (patch)
tree747b1472d5c5ae304c8c4265de144de7fbdeb4a8 /src
parenta60d3a1bc21e355b5342747be0ede3654d2cce41 (diff)
downloadgenenetwork4-b04db9ea05a73074afcf88300f8b6aa8c6e28e64.tar.gz
gemma: stream gemma-wrapper's progress; add GET /compute/gemma/status
/compute/gemma can genuinely take minutes (see the README's ~100K
marker caveat), and until now gave no visibility into a run already
in flight. Same shape GeneNetwork2/3 use for R/qtl
(gn3/computations/streaming.py, gn3/api/streaming.py): the caller
picks a run id, passes it as POST /compute/gemma?id=<id>, and polls
GET /compute/gemma/status/{id}?peak=<offset> on a second connection
while the first is still blocked.

What's actually tailed is gemma-wrapper's stderr, not stdout: under
--json, all of its human-readable progress (banner, chromosome list,
"Executing: ...", per-step info) goes to stderr, and stdout carries
only the one final JSON record, printed once at the very end -- so
there is nothing to stream on stdout. run_streaming() replaces the
old buffered Command::output() call with one that reads stderr line
by line as the process runs, appending each line to a log file if one
was given, across both the kinship and GWA steps into a single
continuous log; stdout is still read in full (unchanged, one JSON
blob). A completion marker ("GN4: computation complete") is appended
once the whole request finishes, the same convention GeneNetwork3
uses ("Done with GN3 Computation" in gn3/api/rqtl2.py) under this
project's own name.

run_id is validated (1-64 ASCII letters/digits/-/_) before it's ever
joined into a path, on both the POST's ?id= and the status endpoint's
path segment -- GeneNetwork3's own /api/stream/{run_id} does no such
check on its equivalent id, which is not knowingly replicated here.

Verified end to end, not just unit tested: the integration test spawns
the POST on its own task and polls the status endpoint from this one
while the ~19s real computation is still running, asserting it
actually observed non-empty progress lines mid-run (not merely after
the fact), then checks the finished log for both real gemma-wrapper
progress text and the completion marker. cargo test passes in full.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'src')
-rw-r--r--src/gemma.rs182
-rw-r--r--src/lib.rs3
-rw-r--r--src/routes/gemma.rs122
3 files changed, 288 insertions, 19 deletions
diff --git a/src/gemma.rs b/src/gemma.rs
index 9c74b30..a42c201 100644
--- a/src/gemma.rs
+++ b/src/gemma.rs
@@ -12,10 +12,12 @@
 //! and `compute` below.
 
 use std::io;
+use std::io::{Read, Seek, SeekFrom, Write};
 use std::path::Path;
-use std::process::Output;
+use std::process::{Output, Stdio};
 
 use serde_json::Value;
+use tokio::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
 use tokio::process::Command;
 
 /// One phenotype value per strain (genotype-file order), or `None` for
@@ -72,8 +74,54 @@ pub fn write_pheno_file(path: &Path, values: &TraitValues) -> io::Result<()> {
     std::fs::write(path, contents)
 }
 
-async fn run(cmd: &str, args: &[&str]) -> io::Result<Output> {
-    Command::new(cmd).args(args).output().await
+/// Run `cmd`, optionally tailing its stderr into `log_path` one line at
+/// a time as it runs, and return the same `Output` shape
+/// `Command::output()` would have (full stdout, full stderr, exit
+/// status) -- callers that don't pass `log_path` see identical
+/// behaviour to the plain, non-streaming call it replaces.
+///
+/// stderr, not stdout, is what's tailed: gemma-wrapper's own `--json`
+/// mode sends all of its human-readable progress (banner, chromosome
+/// list, "Executing: ...", per-step info/debug lines) to stderr, and
+/// reserves stdout for the one final JSON record, printed once at
+/// the very end (`OUTPUT = (options[:json] ? $stderr : $stdout)` in
+/// bin/gemma-wrapper) -- so stdout has nothing to stream.
+async fn run_streaming(cmd: &str, args: &[&str], log_path: Option<&Path>) -> io::Result<Output> {
+    let mut child = Command::new(cmd)
+        .args(args)
+        .stdout(Stdio::piped())
+        .stderr(Stdio::piped())
+        .spawn()?;
+    let stdout_handle = child.stdout.take().expect("stdout was piped");
+    let stderr_handle = child.stderr.take().expect("stderr was piped");
+
+    let stdout_task = tokio::spawn(async move {
+        let mut buf = Vec::new();
+        let mut reader = stdout_handle;
+        let _ = reader.read_to_end(&mut buf).await;
+        buf
+    });
+
+    let log_path = log_path.map(Path::to_path_buf);
+    let stderr_task = tokio::spawn(async move {
+        let mut buf = Vec::new();
+        let mut lines = BufReader::new(stderr_handle).lines();
+        while let Ok(Some(line)) = lines.next_line().await {
+            if let Some(path) = &log_path {
+                if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
+                    let _ = writeln!(f, "{line}");
+                }
+            }
+            buf.extend_from_slice(line.as_bytes());
+            buf.push(b'\n');
+        }
+        buf
+    });
+
+    let status = child.wait().await?;
+    let stdout = stdout_task.await.unwrap_or_default();
+    let stderr = stderr_task.await.unwrap_or_default();
+    Ok(Output { status, stdout, stderr })
 }
 
 fn parse_wrapper_output(step: &'static str, output: Output) -> Result<Value, GemmaError> {
@@ -121,9 +169,10 @@ async fn compute_kinship(
     genotype_file: &str,
     pheno_file: &str,
     snps_file: &str,
+    log_path: Option<&Path>,
 ) -> Result<Value, GemmaError> {
     let args = kinship_args(cache_dir, genotype_file, pheno_file, snps_file);
-    let output = run(gemma_wrapper_cmd, &args)
+    let output = run_streaming(gemma_wrapper_cmd, &args, log_path)
         .await
         .map_err(GemmaError::Io)?;
     parse_wrapper_output("kinship", output)
@@ -155,6 +204,7 @@ async fn compute_gwa(
     snps_file: &str,
     lmm: u8,
     k_json_path: &str,
+    log_path: Option<&Path>,
 ) -> Result<Value, GemmaError> {
     let lmm_str = lmm.to_string();
     let args = gwa_args(
@@ -165,7 +215,7 @@ async fn compute_gwa(
         &lmm_str,
         k_json_path,
     );
-    let output = run(gemma_wrapper_cmd, &args)
+    let output = run_streaming(gemma_wrapper_cmd, &args, log_path)
         .await
         .map_err(GemmaError::Io)?;
     parse_wrapper_output("gwa", output)
@@ -229,14 +279,10 @@ fn parse_assoc_file(contents: &str) -> Vec<AssocRow> {
 /// about this between the two steps).
 async fn extract_archive(cache_dir: &str, archive: &str, dest_dir: &str) -> Result<(), GemmaError> {
     let archive_path = Path::new(cache_dir).join(archive);
-    let output = run(
+    let output = run_streaming(
         "tar",
-        &[
-            "xJf",
-            &archive_path.to_string_lossy(),
-            "-C",
-            dest_dir,
-        ],
+        &["xJf", &archive_path.to_string_lossy(), "-C", dest_dir],
+        None,
     )
     .await
     .map_err(GemmaError::Io)?;
@@ -327,6 +373,27 @@ fn gwa_args<'a>(
 /// schema) implements `ToSchema` for `serde_json::Value` itself, but
 /// `Vec<serde_json::Value>` needs `Value: ComposeSchema`, which it does
 /// not implement in this utoipa version.
+/// `run_id` must be a short token of ASCII letters, digits, `-` or `_`
+/// (no path separators or `.`): it is joined straight onto `cache_dir`
+/// to name the log file `status` reads back, so an unchecked value
+/// would let a caller write/read outside `cache_dir` (the same
+/// unchecked-`run_id`-as-path-component GeneNetwork3 does for its own
+/// `/api/stream/{run_id}` -- not knowingly replicated here).
+pub fn is_valid_run_id(run_id: &str) -> bool {
+    !run_id.is_empty()
+        && run_id.len() <= 64
+        && run_id
+            .chars()
+            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
+}
+
+/// The line `compute` appends to the log file once it finishes
+/// successfully, so a `status` poller can tell "still running" apart
+/// from "done" without needing a separate field -- same convention
+/// GeneNetwork3 uses ("Done with GN3 Computation" in gn3/api/rqtl2.py),
+/// under this project's own name.
+pub const COMPLETION_MARKER: &str = "GN4: computation complete";
+
 pub async fn compute(
     gemma_wrapper_cmd: &str,
     cache_dir: &str,
@@ -334,6 +401,7 @@ pub async fn compute(
     snps_file: &str,
     trait_values: &TraitValues,
     lmm: u8,
+    run_id: Option<&str>,
 ) -> Result<GemmaOutput, GemmaError> {
     std::fs::create_dir_all(cache_dir).map_err(GemmaError::Io)?;
     let unique = format!("{}-{}", std::process::id(), nanos_since_epoch());
@@ -341,6 +409,14 @@ pub async fn compute(
     write_pheno_file(&pheno_path, trait_values).map_err(GemmaError::Io)?;
     let pheno_file = pheno_path.to_string_lossy().into_owned();
 
+    // One log file for the whole request (both steps), truncated fresh
+    // at the start of each run so re-using an id doesn't append stale
+    // lines from a previous request ahead of this one's.
+    let log_path = run_id.map(|id| Path::new(cache_dir).join(format!("{id}.log")));
+    if let Some(path) = &log_path {
+        std::fs::write(path, "").map_err(GemmaError::Io)?;
+    }
+
     let kinship_note = format!(
         "Kinship: {gemma_wrapper_cmd} {}",
         kinship_args(cache_dir, genotype_file, &pheno_file, snps_file).join(" ")
@@ -351,6 +427,7 @@ pub async fn compute(
         genotype_file,
         &pheno_file,
         snps_file,
+        log_path.as_deref(),
     )
     .await?;
     let k_json_path = Path::new(cache_dir).join(format!("{unique}-k.json"));
@@ -377,6 +454,7 @@ pub async fn compute(
         snps_file,
         lmm,
         &k_json_path.to_string_lossy(),
+        log_path.as_deref(),
     )
     .await?;
 
@@ -402,12 +480,50 @@ pub async fn compute(
         rows.extend(parse_assoc_file(&contents).into_iter().map(Value::Object));
     }
     let _ = std::fs::remove_dir_all(&extract_dir); // best effort; a leftover scratch dir is harmless
+
+    if let Some(path) = &log_path {
+        if let Ok(mut f) = std::fs::OpenOptions::new().append(true).open(path) {
+            let _ = writeln!(f, "{COMPLETION_MARKER}");
+        }
+    }
+
     Ok(GemmaOutput {
         rows: Value::Array(rows),
         notes: vec![kinship_note, gwa_note],
     })
 }
 
+/// Why `status` (below) couldn't read a run's log.
+#[derive(Debug)]
+pub enum StatusError {
+    /// No log file for this `run_id` (unknown id, or the run hasn't
+    /// written anything yet -- `compute` creates the file before its
+    /// first subprocess call, but there is a brief window before that).
+    NotFound,
+    Io(io::Error),
+}
+
+/// Lines appended to `run_id`'s log since byte offset `peak`, and the
+/// new offset to pass as `peak` next time. Mirrors GeneNetwork3's
+/// `GET /api/stream/{run_id}?peak=` (gn3/api/streaming.py), stateless
+/// in the same way: the caller tracks `peak`, not the server.
+pub fn status(cache_dir: &str, run_id: &str, peak: u64) -> Result<(Vec<String>, u64), StatusError> {
+    let path = Path::new(cache_dir).join(format!("{run_id}.log"));
+    let mut file = std::fs::File::open(&path).map_err(|e| {
+        if e.kind() == io::ErrorKind::NotFound {
+            StatusError::NotFound
+        } else {
+            StatusError::Io(e)
+        }
+    })?;
+    file.seek(SeekFrom::Start(peak)).map_err(StatusError::Io)?;
+    let mut buf = String::new();
+    file.read_to_string(&mut buf).map_err(StatusError::Io)?;
+    let pointer = peak + buf.len() as u64;
+    let lines = buf.lines().map(str::to_string).collect();
+    Ok((lines, pointer))
+}
+
 #[cfg(test)]
 mod tests {
     use super::*;
@@ -487,4 +603,46 @@ mod tests {
         );
         assert!(!args.contains(&"-gk"), "the GWA step must never carry -gk alongside -lmm");
     }
+
+    #[test]
+    fn is_valid_run_id_accepts_alnum_dash_underscore() {
+        for ok in ["abc123", "a-b_c", "A1", "x"] {
+            assert!(is_valid_run_id(ok), "{ok}");
+        }
+    }
+
+    #[test]
+    fn is_valid_run_id_rejects_path_separators_and_empty() {
+        for bad in ["", "../etc/passwd", "a/b", "a.b", "a b", &"x".repeat(65)] {
+            assert!(!is_valid_run_id(bad), "{bad}");
+        }
+    }
+
+    #[test]
+    fn status_reads_from_peak_and_returns_a_new_pointer() {
+        let path = std::env::temp_dir().join(format!("gn4-gemma-status-test-{}", std::process::id()));
+        let cache_dir = path.to_str().unwrap();
+        std::fs::create_dir_all(cache_dir).unwrap();
+        std::fs::write(Path::new(cache_dir).join("run1.log"), "line one\nline two\n").unwrap();
+
+        let (lines, pointer) = status(cache_dir, "run1", 0).unwrap();
+        assert_eq!(lines, vec!["line one", "line two"]);
+
+        std::fs::OpenOptions::new()
+            .append(true)
+            .open(Path::new(cache_dir).join("run1.log"))
+            .unwrap()
+            .write_all(b"line three\n")
+            .unwrap();
+        let (more, _) = status(cache_dir, "run1", pointer).unwrap();
+        assert_eq!(more, vec!["line three"]);
+
+        std::fs::remove_dir_all(cache_dir).unwrap();
+    }
+
+    #[test]
+    fn status_unknown_run_id_is_not_found() {
+        let err = status("/tmp", "no-such-gn4-gemma-run-id", 0).unwrap_err();
+        assert!(matches!(err, StatusError::NotFound));
+    }
 }
diff --git a/src/lib.rs b/src/lib.rs
index ab88fff..4d90785 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -78,7 +78,8 @@ pub fn app() -> Router {
         .routes(routes!(routes::publications::publication_traits))
         .routes(routes!(routes::search::search))
         .routes(routes!(routes::correlation::correlation))
-        .routes(routes!(routes::gemma::compute_gemma));
+        .routes(routes!(routes::gemma::compute_gemma))
+        .routes(routes!(routes::gemma::gemma_status));
     // Registered -- and so reachable and listed in /openapi.json -- unless
     // GENENETWORK4_TEST_TOKEN switches it off; when registered it decides
     // per request whether the caller is local. See src/routes/dev.rs.
diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs
index 3df86a7..18423b1 100644
--- a/src/routes/gemma.rs
+++ b/src/routes/gemma.rs
@@ -1,18 +1,51 @@
 //! Compute domain: /compute/gemma invokes gemma-wrapper (and the real
 //! GEMMA binary it wraps) to map a QTL from a genotype file, a SNP
-//! annotation file and a list of trait values. See `crate::gemma` for
-//! the invocation itself.
+//! annotation file and a list of trait values. `GET
+//! /compute/gemma/status/{run_id}` tails that run's progress while it
+//! is (or was) in flight, the same shape GeneNetwork2/3 use for R/qtl
+//! (gn3/computations/streaming.py, gn3/api/streaming.py): the caller
+//! picks a `run_id`, passes it as `?id=` on the POST, and polls the
+//! status endpoint with `?peak=` (the byte offset already read) on a
+//! second connection while the first is still blocked on the POST. See
+//! `crate::gemma` for the invocation and log-writing itself.
 
 use axum::Json;
+use axum::extract::{Path, Query};
 use axum::http::StatusCode;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
 
 use crate::auth::AuthToken;
 use crate::config::Config;
 use crate::error::{ApiError, Unauthorized};
-use crate::gemma::{self, GemmaError};
+use crate::gemma::{self, GemmaError, StatusError};
 use crate::response::{Ctx, Envelope, RequestInfo};
 
+/// `?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.
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct ComputeGemmaParams {
+    pub id: Option<String>,
+}
+
+#[derive(Deserialize, utoipa::IntoParams)]
+pub struct GemmaStatusParams {
+    /// Byte offset already read; 0 to read from the start. Echoed back
+    /// (grown) as `pointer` in the response -- pass that next time.
+    pub peak: Option<u64>,
+}
+
+#[derive(Serialize, utoipa::ToSchema)]
+pub struct GemmaStatus {
+    pub run_id: String,
+    /// New lines of gemma-wrapper's stderr (its progress output under
+    /// --json) since `peak`. The last line, once the run has finished,
+    /// is the completion marker (`gemma::COMPLETION_MARKER`).
+    pub lines: Vec<String>,
+    /// The new byte offset; pass this back as `peak` next poll.
+    pub pointer: u64,
+}
+
 #[derive(Deserialize, utoipa::ToSchema)]
 pub struct GemmaRequest {
     /// Path to a BIMBAM genotype file (plain text or gzipped), passed
@@ -41,17 +74,20 @@ pub struct GemmaRequest {
     description = "Runs gemma-wrapper's K-matrix step, then its LMM \
 association step, over the given genotype and SNP annotation files and \
 trait values, and returns the resulting rows of GEMMA's own \
-.assoc.txt output.",
+.assoc.txt output. Pass ?id= to log progress for GET \
+/compute/gemma/status/{id} to poll concurrently.",
+    params(ComputeGemmaParams),
     request_body = GemmaRequest,
     responses(
         (status = 200, description = "Mapped QTL rows from GEMMA's .assoc.txt output, as a JSON array of row objects", body = Envelope<serde_json::Value>),
         Unauthorized,
-        (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9)", body = ApiError),
+        (status = 422, description = "lmm not one of the known-working values (1, 2, 3, 4, 9), or id not alnum/-/_ (max 64 chars)", body = ApiError),
         (status = 502, description = "gemma-wrapper or GEMMA failed", body = ApiError)
     ))]
 pub async fn compute_gemma(
     ctx: Ctx,
     _token: AuthToken,
+    Query(params): Query<ComputeGemmaParams>,
     Json(request): Json<GemmaRequest>,
 ) -> Result<Json<Envelope<serde_json::Value>>, ApiError> {
     let rid = ctx.request_info();
@@ -71,6 +107,18 @@ pub async fn compute_gemma(
         )
         .with_request_id(rid));
     }
+    if let Some(id) = &params.id {
+        if !gemma::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",
+            )
+            .with_request_id(rid));
+        }
+    }
 
     let config = Config::load();
     gemma::compute(
@@ -80,6 +128,7 @@ pub async fn compute_gemma(
         &request.snps_file,
         &request.trait_values,
         lmm,
+        params.id.as_deref(),
     )
     .await
     .map(|output| {
@@ -94,6 +143,67 @@ pub async fn compute_gemma(
     .map_err(|e| gemma_error_to_api_error(e, rid))
 }
 
+#[utoipa::path(get, path = "/compute/gemma/status/{run_id}",
+    summary = "Poll a running (or finished) /compute/gemma call's progress",
+    description = "Returns the lines gemma-wrapper has written to stderr \
+for this run_id since byte offset `peak`, and a new `pointer` to pass as \
+`peak` next time. Call this on a second connection while the POST is \
+still in flight, the same tail-the-log-file shape GeneNetwork2/3 use for \
+R/qtl.",
+    params(("run_id" = String, Path, description = "The id passed as ?id= on the POST"), GemmaStatusParams),
+    responses(
+        (status = 200, description = "New log lines and the new pointer", body = Envelope<GemmaStatus>),
+        Unauthorized,
+        (status = 404, description = "No run with this id (unknown, or not started yet)", body = ApiError),
+        (status = 422, description = "run_id not alnum/-/_ (max 64 chars)", body = ApiError)
+    ))]
+pub async fn gemma_status(
+    ctx: Ctx,
+    _token: AuthToken,
+    Path(run_id): Path<String>,
+    Query(params): Query<GemmaStatusParams>,
+) -> Result<Json<Envelope<GemmaStatus>>, ApiError> {
+    let rid = ctx.request_info();
+    if !gemma::is_valid_run_id(&run_id) {
+        return Err(ApiError::new(
+            StatusCode::UNPROCESSABLE_ENTITY,
+            "invalid_run_id",
+            "Invalid run_id",
+            "run_id must be 1-64 ASCII letters, digits, '-' or '_'.".to_string(),
+            "gemma_status",
+        )
+        .with_request_id(rid));
+    }
+    let config = Config::load();
+    let peak = params.peak.unwrap_or(0);
+    gemma::status(&config.gemma_cache_dir, &run_id, peak)
+        .map(|(lines, pointer)| {
+            Json(ctx.envelope(GemmaStatus {
+                run_id: run_id.clone(),
+                lines,
+                pointer,
+            }))
+        })
+        .map_err(|e| match e {
+            StatusError::NotFound => ApiError::new(
+                StatusCode::NOT_FOUND,
+                "run_not_found",
+                "Run not found",
+                format!("No run with id '{run_id}' (unknown, or not started yet)."),
+                "gemma_status",
+            )
+            .with_request_id(rid),
+            StatusError::Io(err) => ApiError::new(
+                StatusCode::INTERNAL_SERVER_ERROR,
+                "internal_error",
+                "Internal error",
+                err.to_string(),
+                "gemma_status",
+            )
+            .with_request_id(rid),
+        })
+}
+
 fn gemma_error_to_api_error(error: GemmaError, rid: RequestInfo) -> ApiError {
     ApiError::new(
         StatusCode::BAD_GATEWAY,