From 58bfc40d1d577042ff4f3913867651c54b26feb8 Mon Sep 17 00:00:00 2001 From: Seongho Bae <8172694+seonghobae@users.noreply.github.com> Date: Mon, 31 Aug 2026 10:24:29 +0000 Subject: [PATCH] feat(api): retry failed and cancelled analysis runs on loopback GAP-003A eighth slice: POST /v1/analysis-runs/{run_id}/retry clones a failed or cancelled run into a new metric-free 202 Accepted with a new idempotency key. Accepted, running, succeeded, and unknown runs fail closed. Stacked on collection GET. ADR 0032. --- CHANGELOG.d/analysis-run-retry-http.md | 1 + DOCUMENTATION.md | 1 + crates/tepp_api/src/analysis_run_live.rs | 356 +++++++++++- .../tepp_api/src/analysis_run_retry_http.rs | 510 ++++++++++++++++++ crates/tepp_api/src/lib.rs | 11 + .../tests/analysis_run_retry_http_contract.rs | 70 +++ docs/API_CONTRACT.md | 9 +- docs/TRACEABILITY.md | 1 + docs/adr/0032-analysis-run-retry-http.md | 84 +++ docs/adr/README.md | 2 + docs/research/analysis-run-retry-http.md | 58 ++ schemas/analysis_run_retry_request_v1.json | 17 + 12 files changed, 1112 insertions(+), 8 deletions(-) create mode 100644 CHANGELOG.d/analysis-run-retry-http.md create mode 100644 crates/tepp_api/src/analysis_run_retry_http.rs create mode 100644 crates/tepp_api/tests/analysis_run_retry_http_contract.rs create mode 100644 docs/adr/0032-analysis-run-retry-http.md create mode 100644 docs/research/analysis-run-retry-http.md create mode 100644 schemas/analysis_run_retry_request_v1.json diff --git a/CHANGELOG.d/analysis-run-retry-http.md b/CHANGELOG.d/analysis-run-retry-http.md new file mode 100644 index 000000000..cb11998e8 --- /dev/null +++ b/CHANGELOG.d/analysis-run-retry-http.md @@ -0,0 +1 @@ +- `tepp_api` loopback `POST /v1/analysis-runs/{run_id}/retry` clones failed or cancelled runs into a metric-free new `202 Accepted` with a new idempotency key (ADR 0032). Accepted/running/succeeded/unknown retry fails closed. Not GET-by-id, not lifecycle POST, not cancel, not collection GET, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index b29d53702..7bfb61f00 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -15,6 +15,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Orchestrator live HTTP doctoring | [`docs/research/orchestrator-live-http.md`](docs/research/orchestrator-live-http.md) | | Analysis-run cancel HTTP doctoring | [`docs/research/analysis-run-cancel-http.md`](docs/research/analysis-run-cancel-http.md) | | Analysis-run collection HTTP doctoring | [`docs/research/analysis-run-collection-http.md`](docs/research/analysis-run-collection-http.md) | +| Analysis-run retry HTTP doctoring | [`docs/research/analysis-run-retry-http.md`](docs/research/analysis-run-retry-http.md) | | UML/runtime/scientific flows | [`docs/UML.md`](docs/UML.md) | | Logical/physical ERD | [`docs/ERD.md`](docs/ERD.md) | | Security policy | [`SECURITY.md`](SECURITY.md) | diff --git a/crates/tepp_api/src/analysis_run_live.rs b/crates/tepp_api/src/analysis_run_live.rs index a59fdb03c..ecb356958 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -7,8 +7,9 @@ //! results remain outside this crate. `POST /v1/analysis-runs/{run_id}/cancel` //! is the operator-visible cancel path: accepted and running runs become //! metric-free `cancelled` status. `GET /v1/analysis-runs` enumerates those -//! runs without guessing identities. GET-by-id and running/terminal POST -//! transitions remain later slices. +//! runs without guessing identities. `POST /v1/analysis-runs/{run_id}/retry` +//! clones a failed or cancelled run into a new metric-free `202 Accepted`. +//! GET-by-id and running/terminal POST transitions remain later slices. use std::collections::HashMap; use std::io::Write; @@ -22,6 +23,9 @@ use crate::analysis_run_collection_http::{ parse_collection_page_cursor, parse_collection_page_limit, refuse_metrics_on_collection_payload, }; +use crate::analysis_run_retry_http::{ + AnalysisRunRetryRequest, analysis_run_retry_path_run_id, refuse_metrics_on_retry_payload, +}; use crate::lineageweave_http::{LINEAGEWEAVE_CONSUMER_CODE, consumer_is_supported}; use crate::live_http::{ header_value, map_io_error, parse_headers, parse_request_line, read_http_request_with_limit, @@ -174,6 +178,12 @@ impl AnalysisRunLiveService { if method != "POST" { return Err(ApiError::InvalidWirePayload); } + if matches!( + analysis_run_retry_path_run_id(path), + Ok(_) | Err(ApiError::LimitExceeded) + ) { + return self.retry_analysis_run(path, &headers, body); + } if matches!( analysis_run_cancel_path_run_id(path), Ok(_) | Err(ApiError::LimitExceeded) @@ -289,6 +299,90 @@ impl AnalysisRunLiveService { Ok(json_response(200, "OK", response_body)) } + fn retry_analysis_run( + &mut self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + let run_id = analysis_run_retry_path_run_id(path)?; + let consumer = require_headers(headers, self.bound_addr, true)?; + refuse_metrics_on_retry_payload(body)?; + let new_idempotency_key = header_value(headers, "idempotency-key")?; + if !body.trim().is_empty() { + let retry = AnalysisRunRetryRequest::from_json(body)?; + if retry.run_id != run_id || retry.idempotency_key != new_idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + } + let parent_replay_key = self + .runs_by_id + .get(&run_id) + .cloned() + .ok_or(ApiError::InvalidWirePayload)?; + let (parent_consumer, mut cloned_request, parent_idempotency_key, parent_state) = { + let stored = self + .accepted_runs + .get(&parent_replay_key) + .ok_or(ApiError::InvalidWirePayload)?; + ( + stored.consumer.clone(), + stored.request.clone(), + stored.accepted.idempotency_key.clone(), + stored.run_state, + ) + }; + if parent_consumer != consumer { + return Err(ApiError::InvalidWirePayload); + } + if new_idempotency_key == parent_idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + match parent_state { + AnalysisRunStatusState::Failed | AnalysisRunStatusState::Cancelled => {} + AnalysisRunStatusState::Accepted + | AnalysisRunStatusState::Running + | AnalysisRunStatusState::Succeeded => { + return Err(ApiError::InvalidWirePayload); + } + } + new_idempotency_key.clone_into(&mut cloned_request.idempotency_key); + cloned_request.validate()?; + let replay_key = consumer_tenant_idempotency_key( + consumer, + &cloned_request.tenant_workspace_id, + new_idempotency_key, + ); + if let Some(stored) = self.accepted_runs.get(&replay_key) { + if requests_are_idempotent_matches(&stored.request, &cloned_request) { + let response_body = stored.accepted.to_json()?; + refuse_metrics_on_retry_payload(&response_body)?; + return Ok(json_response(202, "Accepted", response_body)); + } + return Err(ApiError::InvalidWirePayload); + } + let child_run_id = format!("tepp-run-{}", self.next_run_serial); + self.next_run_serial += 1; + let accepted = AnalysisRunAccepted::new( + child_run_id.clone(), + "accepted", + cloned_request.idempotency_key.clone(), + )?; + let response_body = accepted.to_json()?; + refuse_metrics_on_retry_payload(&response_body)?; + self.runs_by_id.insert(child_run_id, replay_key.clone()); + self.accepted_runs.insert( + replay_key, + LiveAnalysisRun { + consumer: consumer.to_owned(), + request: cloned_request, + accepted, + run_state: AnalysisRunStatusState::Accepted, + }, + ); + Ok(json_response(202, "Accepted", response_body)) + } + fn list_analysis_runs( &self, path: &str, @@ -350,9 +444,9 @@ impl AnalysisRunLiveService { /// Test-only seam that records a non-accepted loopback state. /// - /// Used to prove cancel and collection of running, succeeded, failed, and - /// cancelled runs without duplicating the live POST running/terminal - /// lifecycle slice. + /// Used to prove cancel, collection, and retry of running, succeeded, + /// failed, and cancelled runs without duplicating the live POST + /// running/terminal lifecycle slice. #[cfg(test)] fn force_loopback_run_state( &mut self, @@ -1290,6 +1384,258 @@ mod tests { ); } + fn retry_http(run_id: &str, body: &str, consumer: &str, idempotency_key: &str) -> String { + let mut request = format!("POST {NARUON_ANALYSIS_RUN_PATH}/{run_id}/retry HTTP/1.1\r\n"); + write!( + request, + "Host: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: {consumer}\r\ntepp-contract-version: 1\r\nidempotency-key: {idempotency_key}\r\ncontent-length: {}\r\n\r\n{body}", + body.len() + ) + .expect("retry request"); + request + } + + #[test] + #[allow(clippy::too_many_lines)] + fn handler_covers_metric_free_retry_of_failed_and_cancelled() { + use crate::{ + AnalysisRunAccepted, AnalysisRunCollection, AnalysisRunRetryRequest, + AnalysisRunStatusState, + }; + + let run = sample_run(); + let mut service = AnalysisRunLiveService::new(); + let accepted = + service.handle_http_request(&valid_request(&run, NARUON_CONSUMER_CODE, "127.0.0.1")); + assert_eq!(accepted.status_code, 202); + let parent_id = serde_json::from_str::(&accepted.body) + .expect("accepted json")["run_id"] + .as_str() + .expect("run_id") + .to_owned(); + assert_eq!(parent_id, "tepp-run-1"); + service + .force_loopback_run_state(&parent_id, AnalysisRunStatusState::Failed) + .expect("force failed"); + + let retry_key = "analysis-live-retry-001"; + let retry_body = AnalysisRunRetryRequest::new(&parent_id, retry_key) + .expect("retry dto") + .to_json() + .expect("retry json"); + let retried = service.handle_http_request(&retry_http( + &parent_id, + &retry_body, + NARUON_CONSUMER_CODE, + retry_key, + )); + assert_eq!(retried.status_code, 202); + let child = AnalysisRunAccepted::from_json(&retried.body).expect("child"); + assert_eq!(child.run_id, "tepp-run-2"); + assert_eq!(child.run_state, "accepted"); + assert_eq!(child.idempotency_key, retry_key); + assert!(!retried.body.contains("rmse")); + assert!(!retried.body.contains("scientific_acceptance")); + assert_ne!(child.run_id, parent_id); + + let replay = service.handle_http_request(&retry_http( + &parent_id, + &retry_body, + NARUON_CONSUMER_CODE, + retry_key, + )); + assert_eq!(replay.status_code, 202); + assert_eq!(replay.body, retried.body); + + let empty_body = service.handle_http_request(&retry_http( + &parent_id, + "", + NARUON_CONSUMER_CODE, + retry_key, + )); + assert_eq!(empty_body.status_code, 202); + assert_eq!(empty_body.body, retried.body); + + let mut cancelled_run = run.clone(); + cancelled_run.idempotency_key = "analysis-live-idem-002".into(); + let cancelled_accepted = service.handle_http_request(&valid_request( + &cancelled_run, + NARUON_CONSUMER_CODE, + "127.0.0.1", + )); + let cancelled_id = serde_json::from_str::(&cancelled_accepted.body) + .expect("cancelled accepted")["run_id"] + .as_str() + .expect("id") + .to_owned(); + service + .force_loopback_run_state(&cancelled_id, AnalysisRunStatusState::Cancelled) + .expect("force cancelled"); + let cancelled_retry = service.handle_http_request(&retry_http( + &cancelled_id, + "", + NARUON_CONSUMER_CODE, + "analysis-live-retry-002", + )); + assert_eq!(cancelled_retry.status_code, 202); + let cancelled_child = + AnalysisRunAccepted::from_json(&cancelled_retry.body).expect("cancelled child"); + assert_eq!(cancelled_child.run_id, "tepp-run-4"); + assert_eq!(cancelled_child.idempotency_key, "analysis-live-retry-002"); + + for (state, key_suffix) in [ + (AnalysisRunStatusState::Accepted, "003"), + (AnalysisRunStatusState::Running, "004"), + (AnalysisRunStatusState::Succeeded, "005"), + ] { + let mut blocked = run.clone(); + blocked.idempotency_key = format!("analysis-live-idem-{key_suffix}"); + let blocked_accepted = service.handle_http_request(&valid_request( + &blocked, + NARUON_CONSUMER_CODE, + "127.0.0.1", + )); + let blocked_id = serde_json::from_str::(&blocked_accepted.body) + .expect("blocked accepted")["run_id"] + .as_str() + .expect("id") + .to_owned(); + service + .force_loopback_run_state(&blocked_id, state) + .expect("force blocked"); + assert_eq!( + service + .handle_http_request(&retry_http( + &blocked_id, + "", + NARUON_CONSUMER_CODE, + &format!("analysis-live-retry-{key_suffix}"), + )) + .status_code, + 400, + "state={state:?}" + ); + } + + assert_eq!( + service + .handle_http_request(&retry_http( + "missing-run", + "", + NARUON_CONSUMER_CODE, + retry_key, + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&retry_http( + &parent_id, + &retry_body, + LINEAGEWEAVE_CONSUMER_CODE, + retry_key, + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&retry_http( + &parent_id, + "", + NARUON_CONSUMER_CODE, + run.idempotency_key.as_str(), + )) + .status_code, + 400 + ); + let mismatched = AnalysisRunRetryRequest::new("other-run", retry_key) + .expect("mismatch") + .to_json() + .expect("mismatch json"); + assert_eq!( + service + .handle_http_request(&retry_http( + &parent_id, + &mismatched, + NARUON_CONSUMER_CODE, + retry_key, + )) + .status_code, + 400 + ); + let key_mismatch = AnalysisRunRetryRequest::new(&parent_id, "wrong-retry-key") + .expect("key mismatch") + .to_json() + .expect("key json"); + assert_eq!( + service + .handle_http_request(&retry_http( + &parent_id, + &key_mismatch, + NARUON_CONSUMER_CODE, + retry_key, + )) + .status_code, + 400 + ); + let metric_body = r#"{"contract_version":1,"run_id":"tepp-run-1","idempotency_key":"analysis-live-retry-001","rmse":0.1}"#; + assert_eq!( + service + .handle_http_request(&retry_http( + &parent_id, + metric_body, + NARUON_CONSUMER_CODE, + retry_key, + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_ANALYSIS_RUN_PATH}/{parent_id} HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: naruon\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n" + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "POST {NARUON_ANALYSIS_RUN_PATH}/{parent_id}/cancel HTTP/1.1\r\nHost: 127.0.0.1\r\ncontent-type: application/json\r\ntepp-consumer: naruon\r\ntepp-contract-version: 1\r\nidempotency-key: {retry_key}\r\ncontent-length: 0\r\n\r\n" + )) + .status_code, + 400 + ); + let oversized = "a".repeat(129); + assert_eq!( + service + .handle_http_request(&retry_http(&oversized, "", NARUON_CONSUMER_CODE, retry_key,)) + .status_code, + 413 + ); + + let listed = service.handle_http_request(&collection_http(NARUON_CONSUMER_CODE, &[])); + assert_eq!(listed.status_code, 200); + let page = AnalysisRunCollection::from_json(&listed.body).expect("page"); + let parent_row = page + .runs + .iter() + .find(|row| row.run_id == parent_id) + .expect("parent row"); + assert_eq!(parent_row.run_state, AnalysisRunStatusState::Failed); + let child_row = page + .runs + .iter() + .find(|row| row.run_id == child.run_id) + .expect("child row"); + assert_eq!(child_row.run_state, AnalysisRunStatusState::Accepted); + assert_eq!(child_row.idempotency_key, retry_key); + assert!(!listed.body.contains("scientific_acceptance")); + assert!(!listed.body.contains("rmse")); + } + #[test] fn temporal_read_headers_and_defensive_write_edges_are_covered() { let run = sample_run(); diff --git a/crates/tepp_api/src/analysis_run_retry_http.rs b/crates/tepp_api/src/analysis_run_retry_http.rs new file mode 100644 index 000000000..533ce7f8a --- /dev/null +++ b/crates/tepp_api/src/analysis_run_retry_http.rs @@ -0,0 +1,510 @@ +//! Provider-owned analysis-run retry HTTP contracts. +//! +//! GAP-003A eighth slice: `POST /v1/analysis-runs/{run_id}/retry` clones a +//! failed or cancelled run into a new metric-free `202 Accepted` receipt with +//! a new idempotency key and a new `run_id`. Accepted, running, succeeded, +//! and unknown runs cannot be retried. Retry bodies and accepted receipts +//! refuse RMSE, bias, coverage, SE-gate, scientific-acceptance, and report +//! keys. This module does not serve GET-by-id (#359), lifecycle POST (#360), +//! cancel HTTP (#361), collection GET (#368), or loopback CLI (#362). +//! Persistence remains GAP-003B. + +use crate::naruon_http::{NaruonHttpExchange, compose_https_target, standard_headers}; +use crate::wire::{ + from_json, require_byte_limit, require_contract_version, require_nonempty, to_json, +}; +use crate::{ANALYSIS_RUN_STATUS_PATH, ApiError, DEFAULT_ANALYSIS_RUN_BYTE_LIMIT}; +use serde::{Deserialize, Serialize}; + +/// Maximum length accepted for an opaque run identity in the retry path. +pub const ANALYSIS_RUN_RETRY_ID_MAX_LEN: usize = 128; + +/// Supported analysis-run retry contract version. +pub const ANALYSIS_RUN_RETRY_CONTRACT_VERSION: u16 = 1; + +const FORBIDDEN_RETRY_KEYS: [&str; 12] = [ + "rmse", + "rmse_standard_error", + "mean_bias", + "bias_standard_error", + "interval_coverage", + "coverage_wilson_lower", + "coverage_wilson_upper", + "temporal_order_accuracy", + "se_gate_accepted", + "se_gate_k", + "scientific_acceptance", + "report", +]; + +/// Versioned retry request for one failed or cancelled analysis run. +/// +/// Path `run_id` identifies the parent. Header `idempotency-key` is the **new** +/// retry key and must match `idempotency_key` when a body is present. An empty +/// POST body is also admitted on the loopback listener and uses the path +/// identity plus the new idempotency header. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisRunRetryRequest { + /// Semantic contract version for this payload family. + pub contract_version: u16, + /// Opaque server-assigned parent run identity. + pub run_id: String, + /// New request idempotency key for the cloned attempt. + pub idempotency_key: String, +} + +impl AnalysisRunRetryRequest { + /// Construct a validated retry request. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities or an unsupported + /// contract version. + pub fn new( + run_id: impl Into, + idempotency_key: impl Into, + ) -> Result { + let request = Self { + contract_version: ANALYSIS_RUN_RETRY_CONTRACT_VERSION, + run_id: run_id.into(), + idempotency_key: idempotency_key.into(), + }; + request.validate()?; + Ok(request) + } + + /// Parse and validate a retry request with the default byte limit. + /// + /// # Errors + /// + /// Returns wire, version, limit, metric-key, or field-validation errors. + pub fn from_json(payload: &str) -> Result { + Self::from_json_with_limit(payload, DEFAULT_ANALYSIS_RUN_BYTE_LIMIT) + } + + /// Parse and validate a retry request with a caller-supplied limit. + /// + /// # Errors + /// + /// Returns wire, version, limit, metric-key, or field-validation errors. + pub fn from_json_with_limit(payload: &str, maximum_bytes: usize) -> Result { + require_byte_limit(payload, maximum_bytes)?; + refuse_metrics_on_retry_payload(payload)?; + let request: Self = from_json(payload)?; + request.validate()?; + Ok(request) + } + + /// Serialize this retry request after complete validation. + /// + /// # Errors + /// + /// Returns validation or serialization errors. + pub fn to_json(&self) -> Result { + self.validate()?; + let payload = to_json(self)?; + require_byte_limit(&payload, DEFAULT_ANALYSIS_RUN_BYTE_LIMIT)?; + refuse_metrics_on_retry_payload(&payload)?; + Ok(payload) + } + + pub(crate) fn validate(&self) -> Result<(), ApiError> { + require_contract_version(self.contract_version, ANALYSIS_RUN_RETRY_CONTRACT_VERSION)?; + require_nonempty(&self.run_id)?; + require_nonempty(&self.idempotency_key)?; + if self.run_id.len() > ANALYSIS_RUN_RETRY_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(()) + } +} + +/// Refuse retry JSON that already carries scientific-metric keys. +/// +/// Empty bodies are admitted (the loopback listener treats them as +/// header-and-path retry). Non-object JSON fails closed as invalid wire. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when a forbidden metric key is +/// present or the payload is a non-empty non-object. +pub fn refuse_metrics_on_retry_payload(payload: &str) -> Result<(), ApiError> { + if payload.trim().is_empty() { + return Ok(()); + } + let value: serde_json::Value = + serde_json::from_str(payload).map_err(|_| ApiError::InvalidWirePayload)?; + let Some(object) = value.as_object() else { + return Err(ApiError::InvalidWirePayload); + }; + if FORBIDDEN_RETRY_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) +} + +/// Build a provider-owned `POST` analysis-run retry exchange. +/// +/// The builder refuses non-`https` origins and empty or oversized run +/// identifiers. It does not inject credentials. The idempotency header is the +/// new retry key, not the parent's. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a non-`https` origin or empty +/// identity, and [`ApiError::LimitExceeded`] when the run identity exceeds +/// [`ANALYSIS_RUN_RETRY_ID_MAX_LEN`] bytes. +pub fn naruon_analysis_run_retry_exchange( + origin: &str, + request: &AnalysisRunRetryRequest, +) -> Result { + request.validate()?; + let encoded_run_id = encode_path_segment(&request.run_id); + let target_path = format!("{ANALYSIS_RUN_STATUS_PATH}/{encoded_run_id}/retry"); + let target_url = compose_https_target(origin, &target_path)?; + Ok(NaruonHttpExchange { + method: "POST", + target_url, + headers: standard_headers(&request.idempotency_key), + body: request.to_json()?, + }) +} + +/// Extract the opaque parent identity from `POST /v1/analysis-runs/{run_id}/retry`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a collection path, extra +/// segments, a missing `/retry` suffix, cancel/running/terminal suffixes, or +/// a hostile encoding, and [`ApiError::LimitExceeded`] when the decoded +/// identity exceeds [`ANALYSIS_RUN_RETRY_ID_MAX_LEN`]. +pub(crate) fn analysis_run_retry_path_run_id(path: &str) -> Result { + let remainder = path + .strip_prefix(ANALYSIS_RUN_STATUS_PATH) + .ok_or(ApiError::InvalidWirePayload)?; + let encoded = remainder + .strip_prefix('/') + .ok_or(ApiError::InvalidWirePayload)?; + let encoded = encoded + .strip_suffix("/retry") + .ok_or(ApiError::InvalidWirePayload)?; + if encoded.is_empty() || encoded.contains('/') { + return Err(ApiError::InvalidWirePayload); + } + let run_id = decode_path_segment(encoded)?; + if run_id.len() > ANALYSIS_RUN_RETRY_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(run_id) +} + +fn encode_path_segment(value: &str) -> String { + let mut out = String::with_capacity(value.len() + value.len() / 2); + let hex = b"0123456789ABCDEF"; + for byte in value.bytes() { + match byte { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(byte as char); + } + _ => { + out.push('%'); + out.push(hex[usize::from(byte >> 4)] as char); + out.push(hex[usize::from(byte & 0x0F)] as char); + } + } + } + out +} + +fn decode_path_segment(value: &str) -> Result { + let mut out = Vec::with_capacity(value.len()); + let bytes = value.as_bytes(); + let mut index = 0; + while index < bytes.len() { + match bytes[index] { + b'%' => { + if index + 2 >= bytes.len() { + return Err(ApiError::InvalidWirePayload); + } + let hi = from_hex(bytes[index + 1])?; + let lo = from_hex(bytes[index + 2])?; + out.push((hi << 4) | lo); + index += 3; + } + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => { + out.push(bytes[index]); + index += 1; + } + _ => return Err(ApiError::InvalidWirePayload), + } + } + let decoded = String::from_utf8(out).map_err(|_| ApiError::InvalidWirePayload)?; + if decoded.is_empty() || decoded.contains('/') || decoded.contains('\0') { + return Err(ApiError::InvalidWirePayload); + } + Ok(decoded) +} + +fn from_hex(byte: u8) -> Result { + match byte { + b'0'..=b'9' => Ok(byte - b'0'), + b'a'..=b'f' => Ok(byte - b'a' + 10), + b'A'..=b'F' => Ok(byte - b'A' + 10), + _ => Err(ApiError::InvalidWirePayload), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::DEFAULT_ANALYSIS_RUN_BYTE_LIMIT; + + fn sample_request() -> AnalysisRunRetryRequest { + AnalysisRunRetryRequest::new("tepp-run-1", "idem-retry-1").expect("request") + } + + #[test] + fn retry_request_round_trips_and_refuses_hostile_shapes() { + let request = sample_request(); + let json = request.to_json().expect("json"); + assert_eq!( + AnalysisRunRetryRequest::from_json(&json).expect("decode"), + request + ); + assert!(!json.contains("rmse")); + assert!(!json.contains("scientific_acceptance")); + + assert_eq!( + AnalysisRunRetryRequest::new("", "idem-retry-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryRequest::new("tepp-run-1", ""), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryRequest::new( + "a".repeat(ANALYSIS_RUN_RETRY_ID_MAX_LEN + 1), + "idem-retry-1" + ), + Err(ApiError::LimitExceeded) + ); + + let mut unsupported = request.clone(); + unsupported.contract_version = 9; + assert_eq!( + unsupported.to_json(), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunRetryRequest::from_json( + r#"{"contract_version":9,"run_id":"tepp-run-1","idempotency_key":"idem-retry-1"}"# + ), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunRetryRequest::from_json( + r#"{"contract_version":1,"run_id":"tepp-run-1","idempotency_key":"idem-retry-1","extra":true}"# + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryRequest::from_json_with_limit(&json, 8), + Err(ApiError::LimitExceeded) + ); + let mut oversized_json = request.clone(); + oversized_json.idempotency_key = "x".repeat(DEFAULT_ANALYSIS_RUN_BYTE_LIMIT); + assert_eq!(oversized_json.to_json(), Err(ApiError::LimitExceeded)); + assert_eq!( + AnalysisRunRetryRequest::from_json("[1,2,3]"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryRequest::from_json("not-json"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn retry_payloads_refuse_scientific_metric_keys() { + assert_eq!(refuse_metrics_on_retry_payload(""), Ok(())); + assert_eq!(refuse_metrics_on_retry_payload(" "), Ok(())); + assert_eq!(refuse_metrics_on_retry_payload(r#"{"run_id":"r"}"#), Ok(())); + for key in FORBIDDEN_RETRY_KEYS { + let payload = format!(r#"{{"{key}":1,"run_id":"r"}}"#); + assert_eq!( + refuse_metrics_on_retry_payload(&payload), + Err(ApiError::InvalidWirePayload), + "key={key}" + ); + let with_contract = format!( + r#"{{"contract_version":1,"run_id":"tepp-run-1","idempotency_key":"idem-retry-1","{key}":0}}"# + ); + assert_eq!( + AnalysisRunRetryRequest::from_json(&with_contract), + Err(ApiError::InvalidWirePayload), + "dto key={key}" + ); + } + assert_eq!( + refuse_metrics_on_retry_payload("[true]"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_retry_payload("null"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn retry_path_decodes_identities_and_refuses_hostile_segments() { + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/tepp-run-1/retry").expect("plain"), + "tepp-run-1" + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/run%2dabc/retry").expect("lower"), + "run-abc" + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/run%2Dabc/retry").expect("upper"), + "run-abc" + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/tepp-run-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/tepp-run-1/running"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/tepp-run-1/terminal"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/other/tepp-run-1/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs//retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/a/b/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%2F/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%00/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%2/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%2G/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/run space/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_path_run_id("/v1/analysis-runs/%80/retry"), + Err(ApiError::InvalidWirePayload) + ); + let oversized = format!( + "/v1/analysis-runs/{}/retry", + "a".repeat(ANALYSIS_RUN_RETRY_ID_MAX_LEN + 1) + ); + assert_eq!( + analysis_run_retry_path_run_id(&oversized), + Err(ApiError::LimitExceeded) + ); + assert_eq!(decode_path_segment(""), Err(ApiError::InvalidWirePayload)); + assert_eq!(decode_path_segment("%"), Err(ApiError::InvalidWirePayload)); + assert_eq!(decode_path_segment("%2"), Err(ApiError::InvalidWirePayload)); + assert_eq!( + decode_path_segment("%2g"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!(from_hex(b'g'), Err(ApiError::InvalidWirePayload)); + assert_eq!(from_hex(b'0'), Ok(0)); + assert_eq!(from_hex(b'a'), Ok(10)); + assert_eq!(from_hex(b'F'), Ok(15)); + } + + #[test] + fn retry_exchange_posts_https_path_without_credentials() { + let request = sample_request(); + let exchange = naruon_analysis_run_retry_exchange("https://tepp.example.com", &request) + .expect("exchange"); + assert_eq!(exchange.method, "POST"); + assert_eq!( + exchange.target_url, + "https://tepp.example.com/v1/analysis-runs/tepp-run-1/retry" + ); + assert!(!exchange.body.is_empty()); + assert!( + exchange + .headers + .iter() + .any(|(name, value)| name == "tepp-consumer" && value == "naruon") + ); + assert!( + exchange + .headers + .iter() + .any(|(name, value)| name == "idempotency-key" && value == "idem-retry-1") + ); + assert!( + !exchange + .headers + .iter() + .any(|(name, _)| name.contains("authorization") || name.contains("copilot")) + ); + + let encoded = AnalysisRunRetryRequest::new("run/../../etc", "key").expect("encoded"); + let exchange = naruon_analysis_run_retry_exchange("https://tepp.example.com", &encoded) + .expect("encoded exchange"); + assert!(exchange.target_url.contains("run%2F..%2F..%2Fetc/retry")); + + assert_eq!( + naruon_analysis_run_retry_exchange("http://tepp.example.com", &request), + Err(ApiError::InvalidWirePayload) + ); + let mut empty_id = request.clone(); + empty_id.run_id.clear(); + assert_eq!( + naruon_analysis_run_retry_exchange("https://tepp.example.com", &empty_id), + Err(ApiError::InvalidWirePayload) + ); + let mut oversized = request; + oversized.run_id = "a".repeat(ANALYSIS_RUN_RETRY_ID_MAX_LEN + 1); + assert_eq!( + naruon_analysis_run_retry_exchange("https://tepp.example.com", &oversized), + Err(ApiError::LimitExceeded) + ); + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 2acf87810..227dbd4ec 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -16,6 +16,7 @@ mod analysis_run; mod analysis_run_cancel_http; mod analysis_run_collection_http; mod analysis_run_live; +mod analysis_run_retry_http; mod analysis_run_status_http; mod authorization; mod corpus_split_manifest; @@ -105,6 +106,16 @@ pub use analysis_run_collection_http::parse_collection_page_limit; pub use analysis_run_collection_http::refuse_metrics_on_collection_payload; /// Consumer-neutral loopback analysis-run service. pub use analysis_run_live::AnalysisRunLiveService; +/// Analysis-run retry contract version constant. +pub use analysis_run_retry_http::ANALYSIS_RUN_RETRY_CONTRACT_VERSION; +/// Maximum opaque run identity length on the retry path. +pub use analysis_run_retry_http::ANALYSIS_RUN_RETRY_ID_MAX_LEN; +/// Versioned analysis-run retry request. +pub use analysis_run_retry_http::AnalysisRunRetryRequest; +/// Build a Naruon analysis-run retry exchange. +pub use analysis_run_retry_http::naruon_analysis_run_retry_exchange; +/// Refuse scientific-metric keys on a retry payload. +pub use analysis_run_retry_http::refuse_metrics_on_retry_payload; /// Analysis-run status HTTP exchange re-exports. pub use analysis_run_status_http::{ANALYSIS_RUN_ID_MAX_LEN, naruon_analysis_run_status_exchange}; /// Corpus-split leakage-audit contract version. diff --git a/crates/tepp_api/tests/analysis_run_retry_http_contract.rs b/crates/tepp_api/tests/analysis_run_retry_http_contract.rs new file mode 100644 index 000000000..c352176d4 --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_retry_http_contract.rs @@ -0,0 +1,70 @@ +//! Contract tests for the analysis-run retry HTTP exchange. + +use tepp_api::{ + ANALYSIS_RUN_RETRY_CONTRACT_VERSION, ANALYSIS_RUN_RETRY_ID_MAX_LEN, AnalysisRunRetryRequest, + ApiError, naruon_analysis_run_retry_exchange, refuse_metrics_on_retry_payload, +}; + +#[test] +fn retry_exchange_is_https_post_without_credentials_or_metrics() { + let request = AnalysisRunRetryRequest::new("tepp-run-9", "idem-retry-9").expect("request"); + assert_eq!( + request.contract_version, + ANALYSIS_RUN_RETRY_CONTRACT_VERSION + ); + let exchange = naruon_analysis_run_retry_exchange("https://tepp.example.test", &request) + .expect("exchange"); + assert_eq!(exchange.method, "POST"); + assert_eq!( + exchange.target_url, + "https://tepp.example.test/v1/analysis-runs/tepp-run-9/retry" + ); + assert!( + exchange + .headers + .iter() + .any(|(name, value)| name == "idempotency-key" && value == "idem-retry-9") + ); + assert!( + !exchange + .headers + .iter() + .any(|(name, _)| name.contains("authorization") + || name.contains("token") + || name.contains("copilot")) + ); + let decoded = AnalysisRunRetryRequest::from_json(&exchange.body).expect("body"); + assert_eq!(decoded, request); + assert_eq!(refuse_metrics_on_retry_payload(&exchange.body), Ok(())); +} + +#[test] +fn retry_contract_refuses_table_access_and_metric_keys() { + let request = AnalysisRunRetryRequest::new("tepp-run-9", "idem-retry-9").expect("request"); + for origin in [ + "http://tepp.example.test", + "https://db.postgres.example", + "https://jdbc.example", + ] { + assert_eq!( + naruon_analysis_run_retry_exchange(origin, &request), + Err(ApiError::InvalidWirePayload), + "origin={origin}" + ); + } + assert_eq!( + AnalysisRunRetryRequest::new( + "a".repeat(ANALYSIS_RUN_RETRY_ID_MAX_LEN + 1), + "idem-retry-9" + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + refuse_metrics_on_retry_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_retry_payload(r#"{"scientific_acceptance":{}}"#), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 88782097a..4cc2e63e4 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -8,7 +8,7 @@ TEPP must work both as a standalone product and as a modular CWL component. Integrations with `naruon`, `contextual-orchestrator`, `.github`, or other repositories use explicit versioned API/artifact contracts. Cross-service direct table access is prohibited. -Current protected main exposes Rust library/domain contracts. The active stack adds a loopback HTTP/1.1 listener for naruon analysis-run, LineageWeave temporal-context, and export POSTs, including `POST /v1/project-histories` on the `AnalysisRunLiveService` contract boundary, `POST /v1/analysis-runs/{run_id}/cancel` for metric-free cancellation of accepted or running runs, and `GET /v1/analysis-runs` for metric-free enumeration of accepted, running, cancelled, and terminal runs. `tepp-loopback` runs the shared consumer listener on `127.0.0.1:18081` by default; a caller may pass another loopback socket address and an optional maximum request count as its two arguments. The container is intended for a trusted same-host or shared-network-namespace sidecar, checks readiness through a synthetic bounded temporal-context request, and deliberately cannot bind a public or bridge address. It is not a production TLS/`$PORT` service. Endpoint examples below that are not covered by `NaruonLiveService` or `AnalysisRunLiveService` remain target interface shapes; export retrieval stays a target shape until an executable export route ships. +Current protected main exposes Rust library/domain contracts. The active stack adds a loopback HTTP/1.1 listener for naruon analysis-run, LineageWeave temporal-context, and export POSTs, including `POST /v1/project-histories` on the `AnalysisRunLiveService` contract boundary, `POST /v1/analysis-runs/{run_id}/cancel` for metric-free cancellation of accepted or running runs, `GET /v1/analysis-runs` for metric-free enumeration of accepted, running, cancelled, and terminal runs, and `POST /v1/analysis-runs/{run_id}/retry` for cloning a failed or cancelled run into a new metric-free `202 Accepted`. `tepp-loopback` runs the shared consumer listener on `127.0.0.1:18081` by default; a caller may pass another loopback socket address and an optional maximum request count as its two arguments. The container is intended for a trusted same-host or shared-network-namespace sidecar, checks readiness through a synthetic bounded temporal-context request, and deliberately cannot bind a public or bridge address. It is not a production TLS/`$PORT` service. Endpoint examples below that are not covered by `NaruonLiveService` or `AnalysisRunLiveService` remain target interface shapes; export retrieval stays a target shape until an executable export route ships. ## 2. Contract families @@ -68,6 +68,7 @@ GET /v1/analysis-runs POST /v1/temporal-context GET /v1/analysis-runs/{run_id} POST /v1/analysis-runs/{run_id}/cancel +POST /v1/analysis-runs/{run_id}/retry GET /v1/model-artifacts/{artifact_id} GET /v1/exports/{export_id} ``` @@ -84,8 +85,10 @@ on the loopback listener transitions accepted or running runs to cancelled; succeeded, failed, and unknown runs fail closed. `GET /v1/analysis-runs` on the loopback listener returns a metric-free collection of those states so operators do not guess run identities. Collection bodies never carry -`tepp.scientific_acceptance.v1`. GET-by-id remains a later slice on this -protected-main lineage. +`tepp.scientific_acceptance.v1`. `POST /v1/analysis-runs/{run_id}/retry` +clones a failed or cancelled run into a new metric-free `202 Accepted` with a +new idempotency key; accepted, running, succeeded, and unknown runs fail +closed. GET-by-id remains a later slice on this protected-main lineage. The stacked `analysis_engine` slice provides the first executable service-side path behind these DTOs. It consumes a bounded identity-free snapshot, excludes diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index b4509e6fd..3937c14b5 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -55,6 +55,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); request-bound terminal result active in PR #157; HTTP service remains accepted-target; the `orchestrator_live` loopback interpretation listener is on this PR | partial | | loopback analysis-run cancel HTTP | ADR 0029; API contract; RFC 9110 | `tepp_api` `POST /v1/analysis-runs/{run_id}/cancel` on `AnalysisRunLiveService`: metric-free cancelled status for accepted/running runs; succeeded/failed/unknown refuse; GET status remains a later slice | active-PR | | loopback analysis-run collection GET | ADR 0031; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs` on `AnalysisRunLiveService`: metric-free enumeration of accepted/running/cancelled/terminal runs; collection bodies refuse scientific-acceptance and RMSE keys; GET-by-id remains a later slice | active-PR | +| loopback analysis-run retry HTTP | ADR 0032; API contract; RFC 9110 | `tepp_api` `POST /v1/analysis-runs/{run_id}/retry` on `AnalysisRunLiveService`: clones failed/cancelled into a new metric-free `202 Accepted` with a new idempotency key; accepted/running/succeeded/unknown refuse; GET-by-id remains a later slice | active-PR | | executable cutoff-safe analysis-run readiness | ADR 0021; temporal research; API terminal-result contract | stacked `analysis_engine` PR on #157: availability cutoff, snapshot binding, multiple-membership aggregation, digest-bound artifact, realistic end-to-end tests | active-PR | | delayed-reporting cutoff eligibility in truth corpora | ADR 0002; research | `tepp_simulation` eligible-at-cutoff filter on the active PR | active-PR | | versioned service/API contracts and exports | PRD; API contract; ADR 0011/0013 | `tepp_api` analysis-run/export/JSON-LD/GraphML contracts on protected main (PR #21); HTTP service remaining accepted-target | partial | diff --git a/docs/adr/0032-analysis-run-retry-http.md b/docs/adr/0032-analysis-run-retry-http.md new file mode 100644 index 000000000..797a93941 --- /dev/null +++ b/docs/adr/0032-analysis-run-retry-http.md @@ -0,0 +1,84 @@ +# ADR 0032 — Analysis-run retry HTTP path + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0018 for the operator-visible retry path. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0031 remain on live GAP-003A engine-library, terminal-wire DTO, GET-by-id, lifecycle-POST, cancel, loopback-CLI, and collection-GET slices. + +## Context + +`docs/API_CONTRACT.md` documents the lifecycle `failed → retryable`. Protected main and the live collection GET slice let operators list a failed or cancelled run, but `POST /v1/analysis-runs` with the original idempotency key returns the original failed or cancelled receipt. Operators therefore cannot start a new attempt without reconstructing the original body and inventing a new key. Returning RMSE, bias, coverage, SE-gate, or `tepp.scientific_acceptance.v1` on a retry body would treat a new attempt as measurement evidence. Stacking this slice onto GET-by-id, lifecycle POST, cancel, CLI, or collection GET would duplicate those heads. + +## Decision + +`AnalysisRunLiveService` serves `POST /v1/analysis-runs/{run_id}/retry` on loopback: + +- Failed and cancelled runs clone the stored request into a new metric-free `202 Accepted` receipt with a new `run_id` and a **new** idempotency key. +- The new key comes from the `idempotency-key` header (and matching body field when a body is present). Reusing the parent's key fails closed. +- Already-accepted retry receipts with the same new key are idempotent: the same `202` child is returned. +- Accepted, running, succeeded, and unknown runs cannot be retried. +- Empty POST bodies are admitted and bind path `run_id` plus the new idempotency header. A typed `AnalysisRunRetryRequest` body must match path identity and header key. +- Retry bodies and accepted receipts refuse RMSE, bias, coverage, SE-gate, scientific-acceptance, and report keys. +- The parent remains failed or cancelled. Collection GET lists both parent and child. +- GET-by-id, lifecycle POST, cancel, and CLI remain other live slices. Persistence remains GAP-003B. + +## Non-goals + +- Production TLS, public bind, or durable retry storage. +- Leiden community detection, Driver p.16 std-family restoration, or Figma/export work. +- Promoting an ADR 0014 scientific claim from HTTP success. +- Duplicating GET `/v1/analysis-runs/{run_id}`, POST running/terminal, POST cancel, GET collection, or loopback CLI. + +## Alternatives considered + +1. **Ask operators to POST create with a reconstructed body** — rejected because collection GET already identified the failed run and reconstructing the original snapshot/cutoff/profile is not operator-visible. +2. **Reuse the parent's idempotency key** — rejected because create replay returns the original failed or cancelled receipt. +3. **Carry scientific-acceptance metrics on the retry receipt** — rejected because a new attempt is not measurement evidence until a later succeeded GET-by-id with profile `scientific_acceptance_v1`. +4. **Clone failed/cancelled runs into a new metric-free `202` with a distinct key** — accepted. + +## Consequences + +- Operators can start a new attempt from a listed failed or cancelled run on the same loopback listener. +- Retry receipts cannot be mistaken for a succeeded scientific-acceptance result. +- GET-by-id may later report the child without changing these retry gates. + +## Failure and recovery + +Unknown run identities, extra path segments, truncated percent-encoding, metric keys on retry bodies, accepted/running/succeeded retry, parent-key reuse, consumer mismatch, and path/header/body identity mismatch return a redacted `400` envelope. Oversized run identities return `413`. Credential headers remain `403`. The in-memory registry is not durable; a restart requires re-POSTing the original metric-free create request. Callers must not fabricate a succeeded run from a retry `202`. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Retry remains loopback-only, size-bounded, and content-redacting. +- HTTP `202` on a retried run is not measurement evidence and is not release evidence. + +## Compatibility and migration + +The existing POST analysis-run, cancel, collection GET, temporal-context, and project-history paths are unchanged. GET-by-id remains refused on this slice. Production adapters may replace loopback while preserving metric-free retry receipts and the accepted/running/succeeded retry refusal. + +## Verification + +Falsifiable evidence: + +- POST retry of failed and cancelled returns metric-free `202 Accepted` with a new `run_id` and new idempotency key; +- POST retry of accepted, running, succeeded, and unknown runs fails closed; +- reusing the parent idempotency key fails closed; +- replaying the same new key is idempotent; +- metric keys, consumer mismatch, and identity mismatch fail closed; +- GET `/v1/analysis-runs/{run_id}` remains `400` on this slice; +- collection GET lists both the parent and the child; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes retry dispatch; POST create receipts, cancel, and collection GET remain valid. A superseding ADR is required to persist retry, bind a public address, retry succeeded runs, or treat HTTP success as an ADR 0014 claim. + +## Related authority + +- ADR 0018 owns consumer-scoped ingress and metric-free `202 Accepted`. +- ADR 0029 owns loopback cancel. +- ADR 0031 owns loopback collection GET. +- ADR 0022 owns deterministic execution to a digest-bound terminal result. +- ADR 0014 owns scientific claim promotion. +- ADR 0011 owns standalone/modular HTTP boundaries. +- RFC 9110 owns POST semantics (Fielding, Nottingham, & Reschke, 2022). It does not authorize scientific claims. diff --git a/docs/adr/README.md b/docs/adr/README.md index b4111e69c..12683d65a 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -32,6 +32,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0025](0025-macos-native-rust-mlx-metal-boundary.md) | macOS-native Rust-owned MLX Metal execution | Accepted | accepted-target | Compose authenticates to a native host service; Linux never claims Metal, and actual backend/parity receipts fail closed. | | [0029](0029-analysis-run-cancel-http.md) | Loopback POST analysis-run cancel is metric-free cancelled status | Accepted | active-PR | Complements ADR 0018; does not supersede ADR 0014. ADR 0026–0028 live on other GAP-003A PRs. | | [0031](0031-analysis-run-collection-get.md) | Loopback GET analysis-run collection is metric-free enumeration | Accepted | active-PR | Complements ADR 0018/0029; does not supersede ADR 0014. ADR 0026–0030 live on other GAP-003A PRs. | +| [0032](0032-analysis-run-retry-http.md) | Loopback POST analysis-run retry clones failed/cancelled into a new metric-free 202 | Accepted | active-PR | Complements ADR 0018/0029/0031; does not supersede ADR 0014. ADR 0026–0031 live on other GAP-003A PRs. | | [0023](0023-lineage-criterion-anchor-contract.md) | TEPP-owned Event Lineage criterion anchor | Accepted | active-PR | PR #237 publishes the strict accepted/rejected artifact and identities; estimator execution remains fail-closed future work. | | [0024](0024-independent-topic-importance-anchor.md) | Posterior topic-context producer contract | Accepted | contract-only active-PR | Strict DTO/schema only; the current estimator does not emit it. fast-mlsirm owns case-deletion influence. | | [0001](0001-rust-first-modular-msa.md) | Rust-first numerical core and CPU `f64` reference | Accepted | partial | ADR 0011 owns cross-service/MSA authority; 0001 retains numerical/backend authority. | @@ -144,6 +145,7 @@ Use the narrowest owning ADR when decisions overlap: - **macOS-native Rust-owned MLX Metal execution:** ADR 0024. - **analysis-run cancel HTTP:** ADR 0029. - **analysis-run collection GET:** ADR 0031. +- **analysis-run retry HTTP:** ADR 0032. ## Change and supersession rule diff --git a/docs/research/analysis-run-retry-http.md b/docs/research/analysis-run-retry-http.md new file mode 100644 index 000000000..05c38462e --- /dev/null +++ b/docs/research/analysis-run-retry-http.md @@ -0,0 +1,58 @@ +# Analysis-run retry HTTP (doctoring) + +## Scope + +`AnalysisRunLiveService` serves `POST /v1/analysis-runs/{run_id}/retry` on a +loopback-only HTTP/1.1 listener. HTTP method, path, and header semantics +follow current HTTP semantics (Fielding, Nottingham, & Reschke, 2022). +Fail-closed refusal of non-loopback binds, table-access hosts, +review/Copilot/GitHub credential headers, and scientific-authority promotion +is repository contract authority (ADR 0018; ADR 0011; ADR 0032), not an RFC +inference rule. + +Retry responses are metric-free `AnalysisRunAccepted` JSON with a new `run_id` +and a new idempotency key. HTTP `202` is not a completed temporal model, +calibrated score, theta estimate, uncertainty statement, or scientific claim. + +## Authority + +### External standards (HTTP only) + +Fielding, R., Nottingham, M., & Reschke, J. (Eds.). (2022). *HTTP semantics* +(RFC 9110). IETF. https://doi.org/10.17487/RFC9110 + +RFC 9110 §9.3.3 describes POST as a method for processing the request +according to the resource's own semantics. TEPP maps that processing onto a +clone of a failed or cancelled run into a new accepted receipt. The RFC does +not define psychometric acceptance, RMSE, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0032-analysis-run-retry-http.md` — retry authority and + metric-free new `202 Accepted` +- `docs/adr/0031-analysis-run-collection-get.md` — collection lists parent + and child without scientific-acceptance keys +- `docs/adr/0029-analysis-run-cancel-http.md` — cancelled is retryable +- `docs/adr/0018-consumer-scoped-analysis-run-ingress.md` — closed consumer + registry and metric-free `202 Accepted` +- `docs/adr/0014-scientific-claim-promotion-and-release-evidence.md` — HTTP + success is not a scientific claim +- `docs/API_CONTRACT.md` — documented retry resource +- `crates/tepp_api/tests/analysis_run_retry_http_contract.rs` — fail-closed + retry exchange proofs + +## Verification + +- loopback `POST /v1/analysis-runs/{run_id}/retry` of a failed run returns + `202` accepted JSON without RMSE/bias/coverage/SE-gate keys; +- cancelled runs retry to the same metric-free accepted receipt family; +- replaying the same new idempotency key returns the same child; +- accepted, running, succeeded, and unknown runs fail closed; +- GET `/v1/analysis-runs/{run_id}` remains `400` on this slice; +- review, Copilot, GitHub, and bearer headers remain `AuthorizationDenied`. + +## Non-claims + +This slice does not implement GET-by-id, running/terminal POST, cancel HTTP, +collection GET, loopback CLI, persistence, production TLS, Leiden consensus, +or an ADR 0014 scientific claim-promotion package. diff --git a/schemas/analysis_run_retry_request_v1.json b/schemas/analysis_run_retry_request_v1.json new file mode 100644 index 000000000..0e3f2927e --- /dev/null +++ b/schemas/analysis_run_retry_request_v1.json @@ -0,0 +1,17 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://tepp.local/schemas/analysis_run_retry_request_v1.json", + "title": "AnalysisRunRetryRequestV1", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "run_id", + "idempotency_key" + ], + "properties": { + "contract_version": { "type": "integer", "const": 1 }, + "run_id": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": ".*\\S.*" }, + "idempotency_key": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" } + } +}