diff options
| author | Pjotr <wrk@bosa.lan> | 2026-10-12 15:57:46 +0000 |
|---|---|---|
| committer | Pjotr <wrk@bosa.lan> | 2026-10-12 15:57:46 +0000 |
| commit | 9cc1631324216d564aca4448cbe71f49dbf2a4af (patch) | |
| tree | c975e39607738065f108dc0577c6fbac7e501a1b /src | |
| parent | b04db9ea05a73074afcf88300f8b6aa8c6e28e64 (diff) | |
| download | genenetwork4-9cc1631324216d564aca4448cbe71f49dbf2a4af.tar.gz | |
gemma: rename peak to peek; reject a reused run id with 409
peak -> peek: the status endpoint's byte-offset query parameter and everywhere it's documented (code comments, the GemmaStatusParams field, tests, README). GeneNetwork3's own equivalent (gn3/api/streaming.py) is spelled "peak"; noted where this now deliberately differs, not touching the unrelated "peak marker" wording elsewhere in the README. Run id uniqueness: the log file is now created with OpenOptions::create_new(true) instead of a plain truncating write, so it fails atomically (no separate check-then-write race) if a log already exists for that id -- another run still in progress, or a finished one never polled/cleaned up. Added GemmaError::RunIdInUse, mapped to 409 Conflict in the route, caught before any subprocess runs. Previously a reused id would have silently truncated whatever was already there. Verified: the new compute_gemma_rejects_a_run_id_already_in_use test pre-seeds a log file for an id and confirms the POST is refused (this needs no gemma-wrapper, since the check runs before any subprocess call). cargo test passes in full. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Diffstat (limited to 'src')
| -rw-r--r-- | src/gemma.rs | 40 | ||||
| -rw-r--r-- | src/routes/gemma.rs | 32 |
2 files changed, 51 insertions, 21 deletions
diff --git a/src/gemma.rs b/src/gemma.rs index a42c201..c855673 100644 --- a/src/gemma.rs +++ b/src/gemma.rs @@ -38,6 +38,11 @@ pub enum GemmaError { AssocFile(io::Error), /// gemma-wrapper's GWA output archive did not list any files. NoAssocFiles, + /// `run_id` already has a log file (a run with that id is in + /// progress, or finished and was never polled/cleaned up). Caught + /// before any subprocess runs, so this never silently truncates + /// another run's in-progress log. + RunIdInUse(String), } impl std::fmt::Display for GemmaError { @@ -54,6 +59,9 @@ impl std::fmt::Display for GemmaError { GemmaError::NoAssocFiles => { write!(f, "gemma-wrapper's response listed no association output files") } + GemmaError::RunIdInUse(id) => { + write!(f, "run id '{id}' is already in use; pick a different id") + } } } } @@ -409,12 +417,19 @@ 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. + // One log file for the whole request (both steps). create_new + // fails if it already exists, atomically: run_id must be unique, + // so a collision errors out here rather than silently truncating + // another run's (possibly still in-progress) log. 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)?; + match std::fs::OpenOptions::new().write(true).create_new(true).open(path) { + Ok(_) => {} + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => { + return Err(GemmaError::RunIdInUse(run_id.unwrap().to_string())); + } + Err(e) => return Err(GemmaError::Io(e)), + } } let kinship_note = format!( @@ -503,11 +518,12 @@ pub enum StatusError { 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> { +/// Lines appended to `run_id`'s log since byte offset `peek`, and the +/// new offset to pass as `peek` next time. Mirrors GeneNetwork3's +/// `GET /api/stream/{run_id}?peak=` (gn3/api/streaming.py, spelled +/// "peak" there), stateless in the same way: the caller tracks `peek`, +/// not the server. +pub fn status(cache_dir: &str, run_id: &str, peek: 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 { @@ -516,10 +532,10 @@ pub fn status(cache_dir: &str, run_id: &str, peak: u64) -> Result<(Vec<String>, StatusError::Io(e) } })?; - file.seek(SeekFrom::Start(peak)).map_err(StatusError::Io)?; + file.seek(SeekFrom::Start(peek)).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 pointer = peek + buf.len() as u64; let lines = buf.lines().map(str::to_string).collect(); Ok((lines, pointer)) } @@ -619,7 +635,7 @@ mod tests { } #[test] - fn status_reads_from_peak_and_returns_a_new_pointer() { + fn status_reads_from_peek_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(); diff --git a/src/routes/gemma.rs b/src/routes/gemma.rs index 18423b1..c79c589 100644 --- a/src/routes/gemma.rs +++ b/src/routes/gemma.rs @@ -5,7 +5,7 @@ //! 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 +//! status endpoint with `?peek=` (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. @@ -23,6 +23,9 @@ 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. +/// 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)] pub struct ComputeGemmaParams { pub id: Option<String>, @@ -32,17 +35,17 @@ pub struct ComputeGemmaParams { 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>, + pub peek: 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, + /// --json) since `peek`. 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. + /// The new byte offset; pass this back as `peek` next poll. pub pointer: u64, } @@ -81,6 +84,7 @@ trait values, and returns the resulting rows of GEMMA's own \ 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 = 409, description = "id is already in use by another run", 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) ))] @@ -140,14 +144,24 @@ pub async fn compute_gemma( } Json(envelope) }) - .map_err(|e| gemma_error_to_api_error(e, rid)) + .map_err(|e| match e { + GemmaError::RunIdInUse(id) => ApiError::new( + StatusCode::CONFLICT, + "run_id_in_use", + "Run id already in use", + format!("id '{id}' is already in use; pick a different id."), + "compute_gemma", + ) + .with_request_id(rid.clone()), + other => gemma_error_to_api_error(other, rid.clone()), + }) } #[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 \ +for this run_id since byte offset `peek`, and a new `pointer` to pass as \ +`peek` 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), @@ -175,8 +189,8 @@ pub async fn 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) + let peek = params.peek.unwrap_or(0); + gemma::status(&config.gemma_cache_dir, &run_id, peek) .map(|(lines, pointer)| { Json(ctx.envelope(GemmaStatus { run_id: run_id.clone(), |
