From 2040a763505aba35daca131a73924f268d60344d Mon Sep 17 00:00:00 2001 From: Seongho Bae <8172694+seonghobae@users.noreply.github.com> Date: Mon, 31 Aug 2026 12:33:36 +0000 Subject: [PATCH] feat(api): inspect analysis-run retry children on loopback GAP-003A GET /v1/analysis-runs/{run_id}/retries returns metric-free direct retry children of a listed parent so operators can inspect lineage after retry. Empty retries is 200 when the parent was never retried. Stacked on stored-request GET. ADR 0035. --- .../analysis-run-retry-lineage-http.md | 1 + DOCUMENTATION.md | 1 + crates/tepp_api/src/analysis_run_live.rs | 261 +++++++- .../src/analysis_run_retry_lineage_http.rs | 609 ++++++++++++++++++ .../src/analysis_run_stored_request_http.rs | 4 + crates/tepp_api/src/lib.rs | 15 + ...nalysis_run_retry_lineage_http_contract.rs | 88 +++ docs/API_CONTRACT.md | 8 +- docs/TRACEABILITY.md | 1 + .../0035-analysis-run-retry-lineage-get.md | 81 +++ docs/adr/README.md | 2 + .../analysis-run-retry-lineage-http.md | 57 ++ schemas/analysis_run_retry_lineage_v1.json | 40 ++ 13 files changed, 1162 insertions(+), 6 deletions(-) create mode 100644 CHANGELOG.d/analysis-run-retry-lineage-http.md create mode 100644 crates/tepp_api/src/analysis_run_retry_lineage_http.rs create mode 100644 crates/tepp_api/tests/analysis_run_retry_lineage_http_contract.rs create mode 100644 docs/adr/0035-analysis-run-retry-lineage-get.md create mode 100644 docs/research/analysis-run-retry-lineage-http.md create mode 100644 schemas/analysis_run_retry_lineage_v1.json diff --git a/CHANGELOG.d/analysis-run-retry-lineage-http.md b/CHANGELOG.d/analysis-run-retry-lineage-http.md new file mode 100644 index 000000000..532b7a2d0 --- /dev/null +++ b/CHANGELOG.d/analysis-run-retry-lineage-http.md @@ -0,0 +1 @@ +- `tepp_api` loopback `GET /v1/analysis-runs/{run_id}/retries` returns metric-free direct retry children of a listed parent so operators can inspect lineage after retry (ADR 0035). Empty `retries` is `200` when the parent was never retried. GET-by-id remains refused. Not lifecycle POST, not cancel, not collection GET, not retry POST, not stored-request GET, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index cbf933eef..5a3a59cc0 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -17,6 +17,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | 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) | | Analysis-run stored-request HTTP doctoring | [`docs/research/analysis-run-stored-request-http.md`](docs/research/analysis-run-stored-request-http.md) | +| Analysis-run retry-lineage HTTP doctoring | [`docs/research/analysis-run-retry-lineage-http.md`](docs/research/analysis-run-retry-lineage-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 7d6e8e5c1..f1b270f5a 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -11,7 +11,9 @@ //! clones a failed or cancelled run into a new metric-free `202 Accepted`. //! `GET /v1/analysis-runs/{run_id}/request` returns metric-free stored create //! fields so operators can inspect snapshot, cutoff, model, and profile before -//! retry. GET-by-id and running/terminal POST transitions remain later slices. +//! retry. `GET /v1/analysis-runs/{run_id}/retries` returns metric-free direct +//! retry children of a listed parent. GET-by-id and running/terminal POST +//! transitions remain later slices. use std::collections::HashMap; use std::io::Write; @@ -28,6 +30,10 @@ use crate::analysis_run_collection_http::{ use crate::analysis_run_retry_http::{ AnalysisRunRetryRequest, analysis_run_retry_path_run_id, refuse_metrics_on_retry_payload, }; +use crate::analysis_run_retry_lineage_http::{ + AnalysisRunRetryLineage, AnalysisRunRetryLineageItem, analysis_run_retry_lineage_path_run_id, + refuse_metrics_on_retry_lineage_payload, +}; use crate::analysis_run_stored_request_http::{ AnalysisRunStoredRequest, analysis_run_stored_request_path_run_id, refuse_metrics_on_stored_request_payload, @@ -58,6 +64,7 @@ struct LiveAnalysisRun { request: AnalysisRunRequest, accepted: AnalysisRunAccepted, run_state: AnalysisRunStatusState, + retried_from_run_id: Option, } /// Loopback HTTP/1.1 analysis-run service shared by published CWL consumers. @@ -179,6 +186,12 @@ impl AnalysisRunLiveService { let (method, path) = parse_request_line(lines.next().unwrap_or(""))?; let headers = parse_headers(&mut lines)?; if method == "GET" { + if matches!( + analysis_run_retry_lineage_path_run_id(path), + Ok(_) | Err(ApiError::LimitExceeded) + ) { + return self.list_analysis_run_retries(path, &headers, body); + } if matches!( analysis_run_stored_request_path_run_id(path), Ok(_) | Err(ApiError::LimitExceeded) @@ -263,6 +276,7 @@ impl AnalysisRunLiveService { request, accepted, run_state: AnalysisRunStatusState::Accepted, + retried_from_run_id: None, }, ); Ok(json_response(202, "Accepted", response_body)) @@ -390,6 +404,7 @@ impl AnalysisRunLiveService { request: cloned_request, accepted, run_state: AnalysisRunStatusState::Accepted, + retried_from_run_id: Some(run_id), }, ); Ok(json_response(202, "Accepted", response_body)) @@ -433,6 +448,58 @@ impl AnalysisRunLiveService { Ok(json_response(200, "OK", response_body)) } + fn list_analysis_run_retries( + &self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + let run_id = analysis_run_retry_lineage_path_run_id(path)?; + if !body.trim().is_empty() { + return Err(ApiError::InvalidWirePayload); + } + let consumer = require_headers(headers, self.bound_addr, false)?; + refuse_metrics_on_retry_lineage_payload(body)?; + let replay_key = self + .runs_by_id + .get(&run_id) + .cloned() + .ok_or(ApiError::InvalidWirePayload)?; + let parent = self + .accepted_runs + .get(&replay_key) + .ok_or(ApiError::InvalidWirePayload)?; + if parent.consumer != consumer { + return Err(ApiError::InvalidWirePayload); + } + let mut children: Vec<&LiveAnalysisRun> = self + .accepted_runs + .values() + .filter(|stored| { + stored.consumer == consumer + && stored.retried_from_run_id.as_deref() == Some(run_id.as_str()) + }) + .collect(); + children.sort_by(|left, right| left.accepted.run_id.cmp(&right.accepted.run_id)); + let mut retries = Vec::with_capacity(children.len()); + for stored in children { + retries.push(AnalysisRunRetryLineageItem::new( + stored.accepted.run_id.clone(), + stored.run_state, + stored.accepted.idempotency_key.clone(), + )?); + } + let lineage = AnalysisRunRetryLineage::new( + parent.accepted.run_id.clone(), + parent.run_state, + parent.accepted.idempotency_key.clone(), + retries, + )?; + let response_body = lineage.to_json()?; + refuse_metrics_on_retry_lineage_payload(&response_body)?; + Ok(json_response(200, "OK", response_body)) + } + fn list_analysis_runs( &self, path: &str, @@ -494,9 +561,9 @@ impl AnalysisRunLiveService { /// Test-only seam that records a non-accepted loopback state. /// - /// Used to prove cancel, collection, retry, and stored-request inspect of - /// running, succeeded, failed, and cancelled runs without duplicating the - /// live POST running/terminal lifecycle slice. + /// Used to prove cancel, collection, retry, stored-request inspect, and + /// retry-lineage inspect 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, @@ -1831,6 +1898,192 @@ mod tests { assert!(!listed.body.contains("snapshot_id")); } + fn retry_lineage_http(run_id: &str, consumer: &str, extra: &[(&str, &str)]) -> String { + let mut request = format!("GET {NARUON_ANALYSIS_RUN_PATH}/{run_id}/retries 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\n" + ) + .expect("retry-lineage headers"); + for (name, value) in extra { + write!(request, "{name}: {value}\r\n").expect("extra header"); + } + request.push_str("content-length: 0\r\n\r\n"); + request + } + + #[test] + #[allow(clippy::too_many_lines)] + fn handler_covers_metric_free_retry_lineage_get() { + use crate::{AnalysisRunRetryLineage, 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(); + + let empty = + service.handle_http_request(&retry_lineage_http(&parent_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(empty.status_code, 200); + let empty_lineage = AnalysisRunRetryLineage::from_json(&empty.body).expect("empty"); + assert_eq!(empty_lineage.run_id, parent_id); + assert_eq!(empty_lineage.run_state, AnalysisRunStatusState::Accepted); + assert!(empty_lineage.retries.is_empty()); + assert!(!empty.body.contains("rmse")); + assert!(!empty.body.contains("scientific_acceptance")); + assert!(!empty.body.contains("snapshot_id")); + assert!(!empty.body.contains("tenant_workspace_id")); + + service + .force_loopback_run_state(&parent_id, AnalysisRunStatusState::Failed) + .expect("force failed"); + let retry_key = "analysis-live-retry-lineage-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_id = serde_json::from_str::(&retried.body) + .expect("child json")["run_id"] + .as_str() + .expect("child id") + .to_owned(); + + let lineage_response = + service.handle_http_request(&retry_lineage_http(&parent_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(lineage_response.status_code, 200); + let lineage = AnalysisRunRetryLineage::from_json(&lineage_response.body).expect("lineage"); + assert_eq!(lineage.run_id, parent_id); + assert_eq!(lineage.run_state, AnalysisRunStatusState::Failed); + assert_eq!(lineage.retries.len(), 1); + assert_eq!(lineage.retries[0].run_id, child_id); + assert_eq!( + lineage.retries[0].run_state, + AnalysisRunStatusState::Accepted + ); + assert_eq!(lineage.retries[0].idempotency_key, retry_key); + assert!(!lineage_response.body.contains("scientific_acceptance")); + assert!(!lineage_response.body.contains("snapshot_id")); + + let child_lineage = + service.handle_http_request(&retry_lineage_http(&child_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(child_lineage.status_code, 200); + assert!( + AnalysisRunRetryLineage::from_json(&child_lineage.body) + .expect("child lineage") + .retries + .is_empty() + ); + + let mut cancelled_run = run.clone(); + cancelled_run.idempotency_key = "analysis-live-idem-lineage-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-lineage-002", + )); + assert_eq!(cancelled_retry.status_code, 202); + let cancelled_lineage = service.handle_http_request(&retry_lineage_http( + &cancelled_id, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(cancelled_lineage.status_code, 200); + let cancelled = + AnalysisRunRetryLineage::from_json(&cancelled_lineage.body).expect("cancelled"); + assert_eq!(cancelled.run_state, AnalysisRunStatusState::Cancelled); + assert_eq!(cancelled.retries.len(), 1); + + assert_eq!( + service + .handle_http_request(&retry_lineage_http( + &parent_id, + LINEAGEWEAVE_CONSUMER_CODE, + &[], + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&retry_lineage_http( + "missing-run", + NARUON_CONSUMER_CODE, + &[], + )) + .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}/retries 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!( + "GET {NARUON_ANALYSIS_RUN_PATH}/{parent_id}/retries 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: 2\r\n\r\n{{}}" + )) + .status_code, + 400 + ); + let oversized = "a".repeat(129); + assert_eq!( + service + .handle_http_request(&retry_lineage_http(&oversized, NARUON_CONSUMER_CODE, &[],)) + .status_code, + 413 + ); + let listed = service.handle_http_request(&collection_http(NARUON_CONSUMER_CODE, &[])); + assert_eq!(listed.status_code, 200); + assert!(!listed.body.contains("retried_from")); + assert!(!listed.body.contains("snapshot_id")); + let stored = service.handle_http_request(&stored_request_http( + &parent_id, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(stored.status_code, 200); + assert!(!stored.body.contains("retries")); + } + #[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_lineage_http.rs b/crates/tepp_api/src/analysis_run_retry_lineage_http.rs new file mode 100644 index 000000000..803d5b000 --- /dev/null +++ b/crates/tepp_api/src/analysis_run_retry_lineage_http.rs @@ -0,0 +1,609 @@ +//! Provider-owned analysis-run retry-lineage GET contracts. +//! +//! GAP-003A tenth slice: `GET /v1/analysis-runs/{run_id}/retries` returns the +//! metric-free direct retry children of a listed run. Collection GET lists +//! parent and child independently. Retry HTTP clones without exposing +//! parent/child linkage. Stored-request GET inspects create fields, not +//! lineage. This module does not serve GET-by-id (#359), lifecycle POST +//! (#360), cancel HTTP (#361), loopback CLI (#362), collection GET (#368), +//! retry POST (#369), stored-request GET (#377), or cancel CLI (#378). +//! Persistence remains GAP-003B. + +use crate::naruon_http::{NaruonHttpExchange, compose_https_target}; +use crate::wire::{ + from_json, require_byte_limit, require_contract_version, require_nonempty, to_json, +}; +use crate::{ + ANALYSIS_RUN_STATUS_PATH, AnalysisRunStatusState, ApiError, DEFAULT_ANALYSIS_RUN_BYTE_LIMIT, +}; +use serde::{Deserialize, Serialize}; + +/// Maximum length accepted for an opaque run identity in the retry-lineage path. +pub const ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN: usize = 128; + +/// Maximum number of direct retry children returned for one parent. +pub const ANALYSIS_RUN_RETRY_LINEAGE_MAX_RETRIES: usize = 64; + +/// Supported analysis-run retry-lineage contract version. +pub const ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION: u16 = 1; + +const FORBIDDEN_RETRY_LINEAGE_KEYS: [&str; 14] = [ + "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", + "terminal_result", + "tenant_workspace_id", +]; + +/// One metric-free direct retry child of a parent analysis run. +/// +/// The row names the cloned attempt. It never carries a terminal result, +/// snapshot, or scientific-acceptance artifact. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisRunRetryLineageItem { + /// Opaque server-assigned child run identity. + pub run_id: String, + /// Current lifecycle state of the child. + pub run_state: AnalysisRunStatusState, + /// Exact request idempotency key of the child. + pub idempotency_key: String, +} + +impl AnalysisRunRetryLineageItem { + /// Construct a validated metric-free retry-lineage child row. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities or an oversized run + /// identity. + pub fn new( + run_id: impl Into, + run_state: AnalysisRunStatusState, + idempotency_key: impl Into, + ) -> Result { + let item = Self { + run_id: run_id.into(), + run_state, + idempotency_key: idempotency_key.into(), + }; + item.validate()?; + Ok(item) + } + + fn validate(&self) -> Result<(), ApiError> { + require_nonempty(&self.run_id)?; + require_nonempty(&self.idempotency_key)?; + if self.run_id.len() > ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(()) + } +} + +/// Metric-free retry lineage for one parent analysis run. +/// +/// Operators inspect which cloned attempts exist for a failed or cancelled +/// parent. An empty `retries` array means the parent was never retried. +/// The payload never carries a terminal result or scientific-acceptance +/// artifact. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisRunRetryLineage { + /// Semantic contract version for this payload family. + pub contract_version: u16, + /// Opaque server-assigned parent run identity. + pub run_id: String, + /// Current lifecycle state of the parent. + pub run_state: AnalysisRunStatusState, + /// Exact request idempotency key of the parent. + pub idempotency_key: String, + /// Direct retry children, sorted by `run_id`. + pub retries: Vec, +} + +impl AnalysisRunRetryLineage { + /// Construct a validated metric-free retry-lineage payload. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities, an oversized run + /// identity, too many children, or an unsupported contract version. + pub fn new( + run_id: impl Into, + run_state: AnalysisRunStatusState, + idempotency_key: impl Into, + retries: Vec, + ) -> Result { + let lineage = Self { + contract_version: ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION, + run_id: run_id.into(), + run_state, + idempotency_key: idempotency_key.into(), + retries, + }; + lineage.validate()?; + Ok(lineage) + } + + /// Parse and validate a retry-lineage payload 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-lineage payload 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_lineage_payload(payload)?; + let lineage: Self = from_json(payload)?; + lineage.validate()?; + Ok(lineage) + } + + /// Serialize this retry-lineage payload 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_lineage_payload(&payload)?; + Ok(payload) + } + + fn validate(&self) -> Result<(), ApiError> { + require_contract_version( + self.contract_version, + ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION, + )?; + require_nonempty(&self.run_id)?; + require_nonempty(&self.idempotency_key)?; + if self.run_id.len() > ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + if self.retries.len() > ANALYSIS_RUN_RETRY_LINEAGE_MAX_RETRIES { + return Err(ApiError::LimitExceeded); + } + for item in &self.retries { + item.validate()?; + } + Ok(()) + } +} + +/// Refuse retry-lineage JSON that already carries scientific-metric keys. +/// +/// Empty payloads are admitted for the GET request body. 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_lineage_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_LINEAGE_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) +} + +/// Extract the opaque parent identity from `GET /v1/analysis-runs/{run_id}/retries`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a collection path, extra +/// segments, a missing `/retries` suffix, cancel/retry/request/running/terminal +/// suffixes, or a hostile encoding, and [`ApiError::LimitExceeded`] when the +/// decoded identity exceeds [`ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN`]. +pub(crate) fn analysis_run_retry_lineage_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("/retries") + .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_LINEAGE_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(run_id) +} + +/// Build a provider-owned `GET` analysis-run retry-lineage exchange. +/// +/// The builder refuses non-`https` origins and empty or oversized run +/// identifiers. It does not inject credentials. The GET body is empty. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a non-`https` origin or empty +/// identity, and [`ApiError::LimitExceeded`] when the run identity exceeds +/// [`ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN`] bytes. +pub fn naruon_analysis_run_retry_lineage_exchange( + origin: &str, + run_id: &str, +) -> Result { + require_nonempty(run_id)?; + if run_id.len() > ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + let encoded_run_id = encode_path_segment(run_id); + let target_path = format!("{ANALYSIS_RUN_STATUS_PATH}/{encoded_run_id}/retries"); + let target_url = compose_https_target(origin, &target_path)?; + Ok(NaruonHttpExchange { + method: "GET", + target_url, + headers: vec![ + ("content-type".into(), "application/json".into()), + ("tepp-consumer".into(), "naruon".into()), + ("tepp-contract-version".into(), "1".into()), + ], + body: String::new(), + }) +} + +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::*; + + fn sample_lineage() -> AnalysisRunRetryLineage { + AnalysisRunRetryLineage::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "idem-1", + vec![ + AnalysisRunRetryLineageItem::new( + "tepp-run-2", + AnalysisRunStatusState::Accepted, + "idem-retry-1", + ) + .expect("child"), + ], + ) + .expect("lineage") + } + + #[test] + fn retry_lineage_round_trips_and_refuses_hostile_shapes() { + let lineage = sample_lineage(); + let json = lineage.to_json().expect("json"); + assert_eq!( + AnalysisRunRetryLineage::from_json(&json).expect("decode"), + lineage + ); + assert!(!json.contains("rmse")); + assert!(!json.contains("scientific_acceptance")); + assert!(!json.contains("terminal_result")); + assert!(!json.contains("tenant_workspace_id")); + assert!(!json.contains("snapshot_id")); + + assert_eq!( + AnalysisRunRetryLineage::new("", AnalysisRunStatusState::Failed, "idem-1", Vec::new(),), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryLineage::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "", + Vec::new(), + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryLineage::new( + "a".repeat(ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN + 1), + AnalysisRunStatusState::Failed, + "idem-1", + Vec::new(), + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + AnalysisRunRetryLineageItem::new( + "a".repeat(ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN + 1), + AnalysisRunStatusState::Accepted, + "idem-retry-1", + ), + Err(ApiError::LimitExceeded) + ); + + let mut unsupported = lineage.clone(); + unsupported.contract_version = 9; + assert_eq!( + unsupported.to_json(), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunRetryLineage::from_json( + r#"{"contract_version":9,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1","retries":[]}"# + ), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunRetryLineage::from_json( + r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1","retries":[],"extra":true}"# + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunRetryLineage::from_json_with_limit(&json, 8), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + AnalysisRunRetryLineage::from_json("[1,2,3]"), + Err(ApiError::InvalidWirePayload) + ); + let too_many = vec![ + AnalysisRunRetryLineageItem::new( + "tepp-run-x", + AnalysisRunStatusState::Accepted, + "idem-x", + ) + .expect("row"); + ANALYSIS_RUN_RETRY_LINEAGE_MAX_RETRIES + 1 + ]; + assert_eq!( + AnalysisRunRetryLineage::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "idem-1", + too_many, + ), + Err(ApiError::LimitExceeded) + ); + let empty = AnalysisRunRetryLineage::new( + "tepp-run-1", + AnalysisRunStatusState::Accepted, + "idem-1", + Vec::new(), + ) + .expect("empty"); + assert!(empty.retries.is_empty()); + } + + #[test] + fn retry_lineage_payloads_refuse_scientific_metric_keys() { + assert_eq!(refuse_metrics_on_retry_lineage_payload(""), Ok(())); + assert_eq!(refuse_metrics_on_retry_lineage_payload(" "), Ok(())); + assert_eq!( + refuse_metrics_on_retry_lineage_payload(r#"{"run_id":"r"}"#), + Ok(()) + ); + for key in FORBIDDEN_RETRY_LINEAGE_KEYS { + let payload = format!(r#"{{"{key}":1,"run_id":"r"}}"#); + assert_eq!( + refuse_metrics_on_retry_lineage_payload(&payload), + Err(ApiError::InvalidWirePayload), + "key={key}" + ); + } + assert_eq!( + refuse_metrics_on_retry_lineage_payload("[true]"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_retry_lineage_payload("null"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn retry_lineage_path_decodes_identities_and_refuses_hostile_segments() { + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/retries") + .expect("plain"), + "tepp-run-1" + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/run%2dabc/retries") + .expect("lower"), + "run-abc" + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/run%2Dabc/retries") + .expect("upper"), + "run-abc" + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/running"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/terminal"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/other/tepp-run-1/retries"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs//retries"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/a/b/retries"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/%2F/retries"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/%00/retries"), + Err(ApiError::InvalidWirePayload) + ); + let oversized = format!( + "/v1/analysis-runs/{}/retries", + "a".repeat(ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN + 1) + ); + assert_eq!( + analysis_run_retry_lineage_path_run_id(&oversized), + Err(ApiError::LimitExceeded) + ); + assert_eq!(decode_path_segment(""), 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_lineage_exchange_gets_https_path_without_credentials() { + let exchange = + naruon_analysis_run_retry_lineage_exchange("https://tepp.example.com", "tepp-run-1") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert_eq!( + exchange.target_url, + "https://tepp.example.com/v1/analysis-runs/tepp-run-1/retries" + ); + assert!(exchange.body.is_empty()); + assert!( + exchange + .headers + .iter() + .any(|(name, value)| name == "tepp-consumer" && value == "naruon") + ); + assert!( + !exchange + .headers + .iter() + .any(|(name, _)| name.contains("authorization") + || name.contains("copilot") + || name.contains("idempotency")) + ); + + let encoded = + naruon_analysis_run_retry_lineage_exchange("https://tepp.example.com", "run/../../etc") + .expect("encoded"); + assert!(encoded.target_url.contains("run%2F..%2F..%2Fetc/retries")); + + assert_eq!( + naruon_analysis_run_retry_lineage_exchange("http://tepp.example.com", "tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_retry_lineage_exchange("https://tepp.example.com", ""), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_retry_lineage_exchange( + "https://tepp.example.com", + &"a".repeat(ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + } +} diff --git a/crates/tepp_api/src/analysis_run_stored_request_http.rs b/crates/tepp_api/src/analysis_run_stored_request_http.rs index 653a12665..c94fb7021 100644 --- a/crates/tepp_api/src/analysis_run_stored_request_http.rs +++ b/crates/tepp_api/src/analysis_run_stored_request_http.rs @@ -446,6 +446,10 @@ mod tests { analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/retry"), Err(ApiError::InvalidWirePayload) ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/retries"), + Err(ApiError::InvalidWirePayload) + ); assert_eq!( analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/running"), Err(ApiError::InvalidWirePayload) diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index ac10fc472..8dcc16038 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -17,6 +17,7 @@ mod analysis_run_cancel_http; mod analysis_run_collection_http; mod analysis_run_live; mod analysis_run_retry_http; +mod analysis_run_retry_lineage_http; mod analysis_run_status_http; mod analysis_run_stored_request_http; mod authorization; @@ -117,6 +118,20 @@ pub use analysis_run_retry_http::AnalysisRunRetryRequest; 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 retry-lineage contract version constant. +pub use analysis_run_retry_lineage_http::ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION; +/// Maximum opaque run identity length on the retry-lineage path. +pub use analysis_run_retry_lineage_http::ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN; +/// Maximum number of direct retry children on one lineage page. +pub use analysis_run_retry_lineage_http::ANALYSIS_RUN_RETRY_LINEAGE_MAX_RETRIES; +/// Versioned metric-free retry lineage of one parent analysis run. +pub use analysis_run_retry_lineage_http::AnalysisRunRetryLineage; +/// One metric-free retry-lineage child row. +pub use analysis_run_retry_lineage_http::AnalysisRunRetryLineageItem; +/// Build a Naruon analysis-run retry-lineage GET exchange. +pub use analysis_run_retry_lineage_http::naruon_analysis_run_retry_lineage_exchange; +/// Refuse scientific-metric keys on a retry-lineage payload. +pub use analysis_run_retry_lineage_http::refuse_metrics_on_retry_lineage_payload; /// Analysis-run status HTTP exchange re-exports. pub use analysis_run_status_http::{ANALYSIS_RUN_ID_MAX_LEN, naruon_analysis_run_status_exchange}; /// Analysis-run stored-request contract version constant. diff --git a/crates/tepp_api/tests/analysis_run_retry_lineage_http_contract.rs b/crates/tepp_api/tests/analysis_run_retry_lineage_http_contract.rs new file mode 100644 index 000000000..aef3b7c0c --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_retry_lineage_http_contract.rs @@ -0,0 +1,88 @@ +//! Contract tests for the analysis-run retry-lineage GET exchange. + +use tepp_api::{ + ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION, ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN, + AnalysisRunRetryLineage, AnalysisRunRetryLineageItem, AnalysisRunStatusState, ApiError, + naruon_analysis_run_retry_lineage_exchange, refuse_metrics_on_retry_lineage_payload, +}; + +#[test] +fn retry_lineage_exchange_is_https_get_without_credentials_or_metrics() { + let exchange = + naruon_analysis_run_retry_lineage_exchange("https://tepp.example.test", "tepp-run-9") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert_eq!( + exchange.target_url, + "https://tepp.example.test/v1/analysis-runs/tepp-run-9/retries" + ); + assert!(exchange.body.is_empty()); + assert!( + exchange + .headers + .iter() + .any(|(name, value)| name == "tepp-consumer" && value == "naruon") + ); + assert!( + !exchange + .headers + .iter() + .any(|(name, _)| name.contains("authorization") + || name.contains("token") + || name.contains("copilot") + || name.contains("idempotency")) + ); + let lineage = AnalysisRunRetryLineage::new( + "tepp-run-9", + AnalysisRunStatusState::Failed, + "idem-9", + vec![ + AnalysisRunRetryLineageItem::new( + "tepp-run-10", + AnalysisRunStatusState::Accepted, + "idem-retry-9", + ) + .expect("child"), + ], + ) + .expect("lineage"); + assert_eq!( + lineage.contract_version, + ANALYSIS_RUN_RETRY_LINEAGE_CONTRACT_VERSION + ); + let json = lineage.to_json().expect("json"); + assert_eq!(refuse_metrics_on_retry_lineage_payload(&json), Ok(())); + assert!(!json.contains("scientific_acceptance")); + assert!(!json.contains("tenant_workspace_id")); + assert!(!json.contains("snapshot_id")); +} + +#[test] +fn retry_lineage_contract_refuses_table_access_and_metric_keys() { + for origin in [ + "http://tepp.example.test", + "https://db.postgres.example", + "https://jdbc.example", + ] { + assert_eq!( + naruon_analysis_run_retry_lineage_exchange(origin, "tepp-run-9"), + Err(ApiError::InvalidWirePayload), + "origin={origin}" + ); + } + assert_eq!( + naruon_analysis_run_retry_lineage_exchange( + "https://tepp.example.test", + &"a".repeat(ANALYSIS_RUN_RETRY_LINEAGE_ID_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + refuse_metrics_on_retry_lineage_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_retry_lineage_payload(r#"{"scientific_acceptance":{}}"#), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 41e52cb68..7a40b9d1b 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, `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`, and `GET /v1/analysis-runs/{run_id}/request` for metric-free inspect of stored create fields. `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`, and `GET /v1/analysis-runs/{run_id}/request` for metric-free inspect of stored create fields, and `GET /v1/analysis-runs/{run_id}/retries` for metric-free inspect of direct retry children. `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 @@ -70,6 +70,7 @@ GET /v1/analysis-runs/{run_id} POST /v1/analysis-runs/{run_id}/cancel POST /v1/analysis-runs/{run_id}/retry GET /v1/analysis-runs/{run_id}/request +GET /v1/analysis-runs/{run_id}/retries GET /v1/model-artifacts/{artifact_id} GET /v1/exports/{export_id} ``` @@ -92,7 +93,10 @@ new idempotency key; accepted, running, succeeded, and unknown runs fail closed. `GET /v1/analysis-runs/{run_id}/request` on the loopback listener returns metric-free stored create fields (`snapshot_id`, `knowledge_cutoff`, `model_contract_version`, `output_profile`) so operators can inspect a listed -run before retry. GET-by-id remains a later slice on this protected-main +run before retry. `GET /v1/analysis-runs/{run_id}/retries` on the loopback +listener returns metric-free direct retry children of that parent so operators +can inspect lineage after retry. An empty `retries` array is `200` when the +parent was never retried. GET-by-id remains a later slice on this protected-main lineage. The stacked `analysis_engine` slice provides the first executable service-side diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index 3dd7d658a..1ba90ed29 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -57,6 +57,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | 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 | | loopback analysis-run stored-request GET | ADR 0034; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs/{run_id}/request` on `AnalysisRunLiveService`: metric-free inspect of snapshot/cutoff/model/profile; collection GET lists identity only; GET-by-id remains a later slice | active-PR | +| loopback analysis-run retry-lineage GET | ADR 0035; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs/{run_id}/retries` on `AnalysisRunLiveService`: metric-free direct retry children of a listed parent; empty `retries` when never retried; 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/0035-analysis-run-retry-lineage-get.md b/docs/adr/0035-analysis-run-retry-lineage-get.md new file mode 100644 index 000000000..fe4d57f11 --- /dev/null +++ b/docs/adr/0035-analysis-run-retry-lineage-get.md @@ -0,0 +1,81 @@ +# ADR 0035 — Analysis-run retry-lineage GET path + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0018, ADR 0031, ADR 0032, and ADR 0034 for the operator-visible retry parent/child inspect. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0034 remain on live GAP-003A engine-library, terminal-wire DTO, GET-by-id, lifecycle-POST, cancel, loopback-CLI, collection-GET, retry, collection-CLI, engine-execute, loopback-binary, CWC, cancel-consumer-parity, Rubin, stored-request, ESEM/DSEM, and cancel-CLI slices. + +## Context + +Retry HTTP clones a failed or cancelled run into a new metric-free `202 Accepted`. Collection GET lists parent and child as independent rows. Stored-request GET returns snapshot/cutoff/model/profile of one run. Operators therefore cannot see which cloned attempts belong to a listed failed or cancelled parent. Returning RMSE, bias, coverage, SE-gate, or `tepp.scientific_acceptance.v1` on the lineage body would treat parent/child enumeration as measurement evidence. + +## Decision + +`AnalysisRunLiveService` serves `GET /v1/analysis-runs/{run_id}/retries` on loopback: + +- The payload is metric-free: parent `run_id`, `run_state`, `idempotency_key`, and a `retries` array of direct children (`run_id`, `run_state`, `idempotency_key`). +- `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, report, `terminal_result`, `tenant_workspace_id`, and `snapshot_id` never appear. +- Direct children only. Grandchildren are listed on their own parent. An empty `retries` array is `200` when the parent exists and was never retried. +- Empty GET bodies only. Query strings, GET-by-id, POST `/retries`, POST `/retry`, GET `/request`, and nonempty bodies fail closed. +- Consumer isolation: another consumer cannot read the first consumer's retry lineage. +- Unknown identities fail closed. Persistence remains GAP-003B. + +## Non-goals + +- Production TLS, public bind, or durable request 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, POST retry, GET stored-request, loopback CLI, or cancel CLI. + +## Alternatives considered + +1. **Add `retried_from` to collection GET rows** — rejected because collection GET (#368) already owns identity-only enumeration and a parallel field would duplicate that head. +2. **Return `tepp.scientific_acceptance.v1` on succeeded children** — rejected because lineage bodies must stay metric-free. +3. **Ask operators to correlate parent and child from local notes** — rejected because retry already cloned the parent and collection lists both without linkage. +4. **Metric-free retry-lineage GET on loopback** — accepted. + +## Consequences + +- Operators can inspect direct retry children of a listed run after retry. +- Lineage pages cannot be mistaken for a succeeded scientific-acceptance result. +- GET-by-id may later return a digest-bound artifact without changing these lineage gates. + +## Failure and recovery + +Unknown identities, extra path segments, GET-by-id, query strings, nonempty bodies, metric keys, unpublished consumers, consumer mismatch, and non-loopback hosts return a redacted `400` envelope. Oversized run identities and more than 64 direct children return `413`. Credential headers remain `403`. The in-memory registry is not durable; a restart requires re-POSTing the original metric-free create and retry requests. Callers must not fabricate a succeeded scientific-acceptance artifact from a retry-lineage payload. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Retry-lineage GET remains loopback-only, size-bounded, consumer-scoped, and content-redacting. +- HTTP `200` on a retry-lineage payload is not measurement evidence and is not release evidence. + +## Compatibility and migration + +Create POST, cancel POST, retry POST, collection GET, stored-request 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 lineage fields and the artifact refusal. + +## Verification + +Falsifiable evidence: + +- GET retry-lineage JSON has no RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result`/`tenant_workspace_id`/`snapshot_id` keys; +- GET returns direct children after retry of failed and cancelled parents; +- GET of a never-retried parent returns an empty `retries` array; +- GET does not leak another consumer's retry lineage; +- GET-by-id, query strings, nonempty bodies, POST `/retries`, and unknown identities fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes retry-lineage GET dispatch; POST create receipts, cancel, collection GET, retry, and stored-request GET remain valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on lineage, or treat HTTP success as an ADR 0014 claim. + +## Related authority + +- ADR 0018 owns consumer-scoped ingress and metric-free `202 Accepted`. +- ADR 0031 owns loopback collection GET. +- ADR 0032 owns loopback retry HTTP on this stack. +- ADR 0034 owns loopback stored-request GET on this stack. +- ADR 0027 owns GET-by-id status (live on another PR). +- ADR 0014 owns scientific claim promotion. +- ADR 0011 owns standalone/modular HTTP boundaries. +- RFC 9110 owns GET semantics (Fielding, Nottingham, & Reschke, 2022). It does not authorize scientific claims. diff --git a/docs/adr/README.md b/docs/adr/README.md index 4a23e5b42..c0a9d4eab 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -34,6 +34,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [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. | | [0034](0034-analysis-run-stored-request-get.md) | Loopback GET analysis-run stored-request is metric-free inspect | Accepted | active-PR | Complements ADR 0018/0031/0032; does not supersede ADR 0014. ADR 0026–0033 live on other GAP-003A PRs. | +| [0035](0035-analysis-run-retry-lineage-get.md) | Loopback GET analysis-run retry-lineage is metric-free parent/child inspect | Accepted | active-PR | Complements ADR 0018/0031/0032/0034; does not supersede ADR 0014. ADR 0026–0034 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. | @@ -148,6 +149,7 @@ Use the narrowest owning ADR when decisions overlap: - **analysis-run collection GET:** ADR 0031. - **analysis-run retry HTTP:** ADR 0032. - **analysis-run stored-request GET:** ADR 0034. +- **analysis-run retry-lineage GET:** ADR 0035. ## Change and supersession rule diff --git a/docs/research/analysis-run-retry-lineage-http.md b/docs/research/analysis-run-retry-lineage-http.md new file mode 100644 index 000000000..37b4545b9 --- /dev/null +++ b/docs/research/analysis-run-retry-lineage-http.md @@ -0,0 +1,57 @@ +# Analysis-run retry-lineage HTTP (doctoring) + +## Scope + +`AnalysisRunLiveService` serves `GET /v1/analysis-runs/{run_id}/retries` 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 0035), not an RFC +inference rule. + +Retry-lineage responses are metric-free `AnalysisRunRetryLineage` JSON. +Each payload carries parent `run_id`, `run_state`, `idempotency_key`, and a +`retries` array of direct children (`run_id`, `run_state`, `idempotency_key`) +only. HTTP `200` is not a completed temporal model, calibrated score, theta +estimate, uncertainty statement, or scientific claim. +`tepp.scientific_acceptance.v1` never appears. + +## 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.1 describes GET as a method for retrieving the target resource's +current state. TEPP maps that retrieval onto a bounded, consumer-scoped +inspect of direct retry children. The RFC does not define psychometric +acceptance, RMSE, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0035-analysis-run-retry-lineage-get.md` — retry-lineage + authority and metric-free parent/child fields +- `docs/adr/0034-analysis-run-stored-request-get.md` — stored-request inspect +- `docs/adr/0032-analysis-run-retry-http.md` — retry clones without linkage +- `docs/adr/0031-analysis-run-collection-get.md` — collection lists identity + only +- `docs/adr/0018-consumer-scoped-analysis-run-ingress.md` — closed consumer + registry and metric-free `202 Accepted` +- `docs/API_CONTRACT.md` — documented retry-lineage resource +- `crates/tepp_api/tests/analysis_run_retry_lineage_http_contract.rs` — + fail-closed retry-lineage exchange proofs + +## Operator-visible behaviour + +- loopback `GET /v1/analysis-runs/{run_id}/retries` of a failed or cancelled + parent returns metric-free direct children after retry +- a never-retried parent returns `200` with an empty `retries` array +- collection GET still lists parent and child independently and does not + leak `retried_from` +- stored-request GET still inspects snapshot/cutoff/model/profile and does + not list children +- GET-by-id remains refused on this stack +- consumer mismatch, unknown identities, nonempty bodies, and metric keys + fail closed diff --git a/schemas/analysis_run_retry_lineage_v1.json b/schemas/analysis_run_retry_lineage_v1.json new file mode 100644 index 000000000..65e135964 --- /dev/null +++ b/schemas/analysis_run_retry_lineage_v1.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://tepp.local/schemas/analysis_run_retry_lineage_v1.json", + "title": "AnalysisRunRetryLineageV1", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "run_id", + "run_state", + "idempotency_key", + "retries" + ], + "properties": { + "contract_version": { "type": "integer", "const": 1 }, + "run_id": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": ".*\\S.*" }, + "run_state": { + "type": "string", + "enum": ["accepted", "running", "succeeded", "failed", "cancelled"] + }, + "idempotency_key": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" }, + "retries": { + "type": "array", + "maxItems": 64, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["run_id", "run_state", "idempotency_key"], + "properties": { + "run_id": { "type": "string", "minLength": 1, "maxLength": 128, "pattern": ".*\\S.*" }, + "run_state": { + "type": "string", + "enum": ["accepted", "running", "succeeded", "failed", "cancelled"] + }, + "idempotency_key": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" } + } + } + } + } +}