diff --git a/CHANGELOG.d/analysis-run-idempotency-lookup-http.md b/CHANGELOG.d/analysis-run-idempotency-lookup-http.md new file mode 100644 index 000000000..44ff84a6f --- /dev/null +++ b/CHANGELOG.d/analysis-run-idempotency-lookup-http.md @@ -0,0 +1 @@ +- `tepp_api` loopback `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` returns the metric-free identity of the unique run that used that key so operators can jump from a 202 receipt or retry child key without scanning collection pages (ADR 0037). GET-by-id remains refused. Not lifecycle POST, not cancel, not collection GET, not retry POST, not stored-request GET, not retry-lineage GET, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 5a3a59cc0..ac5014a51 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -18,6 +18,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | 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) | +| Analysis-run idempotency-key lookup HTTP doctoring | [`docs/research/analysis-run-idempotency-lookup-http.md`](docs/research/analysis-run-idempotency-lookup-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_idempotency_lookup_http.rs b/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs new file mode 100644 index 000000000..6ee79d802 --- /dev/null +++ b/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs @@ -0,0 +1,543 @@ +//! Provider-owned analysis-run idempotency-key lookup GET contracts. +//! +//! GAP-003A eleventh slice: `GET /v1/analysis-runs/by-idempotency/{key}` +//! returns the metric-free identity of the unique run that used that +//! idempotency key. Collection GET is cursor-paginated. Stored-request GET +//! and retry-lineage GET require a `run_id`. Retry HTTP mints a new key. +//! Operators with a 202 receipt or log key cannot jump to that run without +//! scanning pages. 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), retry-lineage GET +//! (#379), 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 idempotency key in the lookup path. +pub const ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN: usize = 128; + +/// Supported analysis-run idempotency-lookup contract version. +pub const ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION: u16 = 1; + +/// Reserved collection-relative prefix that names the lookup resource. +pub const ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX: &str = "by-idempotency"; + +const FORBIDDEN_IDEMPOTENCY_LOOKUP_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", +]; + +/// Metric-free identity of one analysis run found by idempotency key. +/// +/// Operators jump from a 202 receipt or log key to the durable `run_id` +/// without scanning a cursor-paginated collection. The payload never carries +/// a terminal result, snapshot, or scientific-acceptance artifact. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisRunIdempotencyLookup { + /// Semantic contract version for this payload family. + pub contract_version: u16, + /// Opaque server-assigned run identity. + pub run_id: String, + /// Current lifecycle state. + pub run_state: AnalysisRunStatusState, + /// Exact request idempotency key that selected this run. + pub idempotency_key: String, +} + +impl AnalysisRunIdempotencyLookup { + /// Construct a validated metric-free idempotency-lookup payload. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities, an oversized + /// identity, or an unsupported contract version. + pub fn new( + run_id: impl Into, + run_state: AnalysisRunStatusState, + idempotency_key: impl Into, + ) -> Result { + let lookup = Self { + contract_version: ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION, + run_id: run_id.into(), + run_state, + idempotency_key: idempotency_key.into(), + }; + lookup.validate()?; + Ok(lookup) + } + + /// Parse and validate an idempotency-lookup 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 an idempotency-lookup 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_idempotency_lookup_payload(payload)?; + let lookup: Self = from_json(payload)?; + lookup.validate()?; + Ok(lookup) + } + + /// Serialize this idempotency-lookup 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_idempotency_lookup_payload(&payload)?; + Ok(payload) + } + + fn validate(&self) -> Result<(), ApiError> { + require_contract_version( + self.contract_version, + ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION, + )?; + require_nonempty(&self.run_id)?; + require_nonempty(&self.idempotency_key)?; + if self.run_id.len() > ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + || self.idempotency_key.len() > ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + { + return Err(ApiError::LimitExceeded); + } + Ok(()) + } +} + +/// Refuse idempotency-lookup 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_idempotency_lookup_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_IDEMPOTENCY_LOOKUP_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) +} + +/// Extract the opaque idempotency key from +/// `GET /v1/analysis-runs/by-idempotency/{key}`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a collection path, GET-by-id, +/// extra segments, a missing `by-idempotency` prefix, cancel/retry/request/ +/// retries/running/terminal suffixes, or a hostile encoding, and +/// [`ApiError::LimitExceeded`] when the decoded key exceeds +/// [`ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN`]. +pub(crate) fn analysis_run_idempotency_lookup_path_key(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_prefix(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX) + .ok_or(ApiError::InvalidWirePayload)?; + let encoded = encoded + .strip_prefix('/') + .ok_or(ApiError::InvalidWirePayload)?; + if encoded.is_empty() || encoded.contains('/') { + return Err(ApiError::InvalidWirePayload); + } + let key = decode_path_segment(encoded)?; + if key == ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX { + return Err(ApiError::InvalidWirePayload); + } + if key.len() > ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(key) +} + +/// Build a provider-owned `GET` analysis-run idempotency-lookup exchange. +/// +/// The builder refuses non-`https` origins and empty or oversized keys. It +/// does not inject credentials. The GET body is empty. The key travels in +/// the path; the builder does not send an `idempotency-key` header. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a non-`https` origin or empty +/// key, and [`ApiError::LimitExceeded`] when the key exceeds +/// [`ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN`] bytes. +pub fn naruon_analysis_run_idempotency_lookup_exchange( + origin: &str, + idempotency_key: &str, +) -> Result { + require_nonempty(idempotency_key)?; + if idempotency_key.len() > ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + let encoded_key = encode_path_segment(idempotency_key); + let target_path = format!( + "{ANALYSIS_RUN_STATUS_PATH}/{ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX}/{encoded_key}" + ); + 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_lookup() -> AnalysisRunIdempotencyLookup { + AnalysisRunIdempotencyLookup::new("tepp-run-1", AnalysisRunStatusState::Failed, "idem-1") + .expect("lookup") + } + + #[test] + fn idempotency_lookup_round_trips_and_refuses_hostile_shapes() { + let lookup = sample_lookup(); + let json = lookup.to_json().expect("json"); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json(&json).expect("decode"), + lookup + ); + 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!(!json.contains("retried_from")); + + assert_eq!( + AnalysisRunIdempotencyLookup::new("", AnalysisRunStatusState::Failed, "idem-1",), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::new("tepp-run-1", AnalysisRunStatusState::Failed, "",), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::new( + "a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1), + AnalysisRunStatusState::Failed, + "idem-1", + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1), + ), + Err(ApiError::LimitExceeded) + ); + + let mut unsupported = lookup.clone(); + unsupported.contract_version = 9; + assert_eq!( + unsupported.to_json(), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json( + r#"{"contract_version":9,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1"}"# + ), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json( + r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1","extra":true}"# + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json_with_limit(&json, 8), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json("[1,2,3]"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn idempotency_lookup_payloads_refuse_scientific_metric_keys() { + assert_eq!(refuse_metrics_on_idempotency_lookup_payload(""), Ok(())); + assert_eq!(refuse_metrics_on_idempotency_lookup_payload(" "), Ok(())); + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload(r#"{"run_id":"r"}"#), + Ok(()) + ); + for key in FORBIDDEN_IDEMPOTENCY_LOOKUP_KEYS { + let payload = format!(r#"{{"{key}":1,"run_id":"r"}}"#); + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload(&payload), + Err(ApiError::InvalidWirePayload), + "key={key}" + ); + } + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload("[true]"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload("null"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn idempotency_lookup_path_decodes_keys_and_refuses_hostile_segments() { + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/idem-1") + .expect("plain"), + "idem-1" + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/key%2dabc") + .expect("lower"), + "key-abc" + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/key%2Dabc") + .expect("upper"), + "key-abc" + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/retries"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/running"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/tepp-run-1/terminal"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/other/by-idempotency/idem-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/a/b"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/%2F"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key("/v1/analysis-runs/by-idempotency/%00"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key( + "/v1/analysis-runs/by-idempotency/by-idempotency" + ), + Err(ApiError::InvalidWirePayload) + ); + let oversized = format!( + "/v1/analysis-runs/by-idempotency/{}", + "a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1) + ); + assert_eq!( + analysis_run_idempotency_lookup_path_key(&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 idempotency_lookup_exchange_gets_https_path_without_credentials() { + let exchange = + naruon_analysis_run_idempotency_lookup_exchange("https://tepp.example.com", "idem-1") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert_eq!( + exchange.target_url, + "https://tepp.example.com/v1/analysis-runs/by-idempotency/idem-1" + ); + 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_idempotency_lookup_exchange( + "https://tepp.example.com", + "key/../../etc", + ) + .expect("encoded"); + assert!( + encoded + .target_url + .contains("by-idempotency/key%2F..%2F..%2Fetc") + ); + + assert_eq!( + naruon_analysis_run_idempotency_lookup_exchange("http://tepp.example.com", "idem-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_idempotency_lookup_exchange("https://tepp.example.com", ""), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_idempotency_lookup_exchange( + "https://tepp.example.com", + &"a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + } +} diff --git a/crates/tepp_api/src/analysis_run_live.rs b/crates/tepp_api/src/analysis_run_live.rs index f1b270f5a..b7fc005c7 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -12,8 +12,9 @@ //! `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 /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. +//! retry children of a listed parent. `GET /v1/analysis-runs/by-idempotency/{key}` +//! returns the metric-free identity of the unique run that used that key. +//! GET-by-id and running/terminal POST transitions remain later slices. use std::collections::HashMap; use std::io::Write; @@ -27,6 +28,10 @@ use crate::analysis_run_collection_http::{ parse_collection_page_cursor, parse_collection_page_limit, refuse_metrics_on_collection_payload, }; +use crate::analysis_run_idempotency_lookup_http::{ + AnalysisRunIdempotencyLookup, analysis_run_idempotency_lookup_path_key, + refuse_metrics_on_idempotency_lookup_payload, +}; use crate::analysis_run_retry_http::{ AnalysisRunRetryRequest, analysis_run_retry_path_run_id, refuse_metrics_on_retry_payload, }; @@ -198,6 +203,12 @@ impl AnalysisRunLiveService { ) { return self.read_analysis_run_stored_request(path, &headers, body); } + if matches!( + analysis_run_idempotency_lookup_path_key(path), + Ok(_) | Err(ApiError::LimitExceeded) + ) { + return self.lookup_analysis_run_by_idempotency(path, &headers, body); + } return self.list_analysis_runs(path, &headers, body); } if method != "POST" { @@ -500,6 +511,39 @@ impl AnalysisRunLiveService { Ok(json_response(200, "OK", response_body)) } + fn lookup_analysis_run_by_idempotency( + &self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + let idempotency_key = analysis_run_idempotency_lookup_path_key(path)?; + if !body.trim().is_empty() { + return Err(ApiError::InvalidWirePayload); + } + let consumer = require_headers(headers, self.bound_addr, false)?; + refuse_metrics_on_idempotency_lookup_payload(body)?; + let mut matches: Vec<&LiveAnalysisRun> = self + .accepted_runs + .values() + .filter(|stored| { + stored.consumer == consumer && stored.accepted.idempotency_key == idempotency_key + }) + .collect(); + if matches.len() != 1 { + return Err(ApiError::InvalidWirePayload); + } + let stored = matches.remove(0); + let payload = AnalysisRunIdempotencyLookup::new( + stored.accepted.run_id.clone(), + stored.run_state, + stored.accepted.idempotency_key.clone(), + )?; + let response_body = payload.to_json()?; + refuse_metrics_on_idempotency_lookup_payload(&response_body)?; + Ok(json_response(200, "OK", response_body)) + } + fn list_analysis_runs( &self, path: &str, @@ -561,9 +605,10 @@ impl AnalysisRunLiveService { /// Test-only seam that records a non-accepted loopback state. /// - /// 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. + /// Used to prove cancel, collection, retry, stored-request inspect, + /// retry-lineage inspect, and idempotency-key lookup 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, @@ -2084,6 +2129,170 @@ mod tests { assert!(!stored.body.contains("retries")); } + fn idempotency_lookup_http(key: &str, consumer: &str, extra: &[(&str, &str)]) -> String { + let mut request = + format!("GET {NARUON_ANALYSIS_RUN_PATH}/by-idempotency/{key} 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("idempotency-lookup 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_idempotency_lookup_get() { + use crate::{ + AnalysisRunIdempotencyLookup, 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 looked_up = service.handle_http_request(&idempotency_lookup_http( + &run.idempotency_key, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(looked_up.status_code, 200); + let lookup = AnalysisRunIdempotencyLookup::from_json(&looked_up.body).expect("lookup"); + assert_eq!(lookup.run_id, parent_id); + assert_eq!(lookup.run_state, AnalysisRunStatusState::Accepted); + assert_eq!(lookup.idempotency_key, run.idempotency_key); + assert!(!looked_up.body.contains("rmse")); + assert!(!looked_up.body.contains("scientific_acceptance")); + assert!(!looked_up.body.contains("snapshot_id")); + assert!(!looked_up.body.contains("tenant_workspace_id")); + assert!(!looked_up.body.contains("retried_from")); + + service + .force_loopback_run_state(&parent_id, AnalysisRunStatusState::Failed) + .expect("force failed"); + let failed = service.handle_http_request(&idempotency_lookup_http( + &run.idempotency_key, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(failed.status_code, 200); + assert_eq!( + AnalysisRunIdempotencyLookup::from_json(&failed.body) + .expect("failed lookup") + .run_state, + AnalysisRunStatusState::Failed + ); + + let retry_key = "analysis-live-idem-lookup-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_id = serde_json::from_str::(&retried.body) + .expect("child json")["run_id"] + .as_str() + .expect("child id") + .to_owned(); + let child_lookup = service.handle_http_request(&idempotency_lookup_http( + retry_key, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(child_lookup.status_code, 200); + let child = AnalysisRunIdempotencyLookup::from_json(&child_lookup.body).expect("child"); + assert_eq!(child.run_id, child_id); + assert_eq!(child.idempotency_key, retry_key); + assert_eq!(child.run_state, AnalysisRunStatusState::Accepted); + + assert_eq!( + service + .handle_http_request(&idempotency_lookup_http( + &run.idempotency_key, + LINEAGEWEAVE_CONSUMER_CODE, + &[], + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&idempotency_lookup_http( + "missing-key", + 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}/by-idempotency/{key} 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", + key = run.idempotency_key + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_ANALYSIS_RUN_PATH}/by-idempotency/{key} 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{{}}", + key = run.idempotency_key + )) + .status_code, + 400 + ); + let oversized = "a".repeat(129); + assert_eq!( + service + .handle_http_request(&idempotency_lookup_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("by-idempotency")); + let stored = service.handle_http_request(&stored_request_http( + &parent_id, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(stored.status_code, 200); + let lineage = + service.handle_http_request(&retry_lineage_http(&parent_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(lineage.status_code, 200); + } + #[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 index 803d5b000..eee2c1da0 100644 --- a/crates/tepp_api/src/analysis_run_retry_lineage_http.rs +++ b/crates/tepp_api/src/analysis_run_retry_lineage_http.rs @@ -517,6 +517,10 @@ mod tests { 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/by-idempotency/idem-1"), + Err(ApiError::InvalidWirePayload) + ); assert_eq!( analysis_run_retry_lineage_path_run_id("/v1/analysis-runs/tepp-run-1/running"), Err(ApiError::InvalidWirePayload) 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 c94fb7021..998b57307 100644 --- a/crates/tepp_api/src/analysis_run_stored_request_http.rs +++ b/crates/tepp_api/src/analysis_run_stored_request_http.rs @@ -450,6 +450,10 @@ mod tests { 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/by-idempotency/idem-1"), + 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 8dcc16038..5a61ab94a 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -15,6 +15,7 @@ mod analysis_result; mod analysis_run; mod analysis_run_cancel_http; mod analysis_run_collection_http; +mod analysis_run_idempotency_lookup_http; mod analysis_run_live; mod analysis_run_retry_http; mod analysis_run_retry_lineage_http; @@ -106,6 +107,18 @@ pub use analysis_run_collection_http::parse_collection_page_cursor; pub use analysis_run_collection_http::parse_collection_page_limit; /// Refuse scientific-metric keys on a collection payload. pub use analysis_run_collection_http::refuse_metrics_on_collection_payload; +/// Analysis-run idempotency-lookup contract version constant. +pub use analysis_run_idempotency_lookup_http::ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION; +/// Maximum opaque idempotency-key length on the lookup path. +pub use analysis_run_idempotency_lookup_http::ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN; +/// Reserved collection-relative prefix for idempotency-key lookup. +pub use analysis_run_idempotency_lookup_http::ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX; +/// Versioned metric-free identity of one analysis run found by idempotency key. +pub use analysis_run_idempotency_lookup_http::AnalysisRunIdempotencyLookup; +/// Build a Naruon analysis-run idempotency-lookup GET exchange. +pub use analysis_run_idempotency_lookup_http::naruon_analysis_run_idempotency_lookup_exchange; +/// Refuse scientific-metric keys on an idempotency-lookup payload. +pub use analysis_run_idempotency_lookup_http::refuse_metrics_on_idempotency_lookup_payload; /// Consumer-neutral loopback analysis-run service. pub use analysis_run_live::AnalysisRunLiveService; /// Analysis-run retry contract version constant. diff --git a/crates/tepp_api/tests/analysis_run_idempotency_lookup_http_contract.rs b/crates/tepp_api/tests/analysis_run_idempotency_lookup_http_contract.rs new file mode 100644 index 000000000..136efe432 --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_idempotency_lookup_http_contract.rs @@ -0,0 +1,77 @@ +//! Contract tests for the analysis-run idempotency-key lookup GET exchange. + +use tepp_api::{ + ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION, ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN, + AnalysisRunIdempotencyLookup, AnalysisRunStatusState, ApiError, + naruon_analysis_run_idempotency_lookup_exchange, refuse_metrics_on_idempotency_lookup_payload, +}; + +#[test] +fn idempotency_lookup_exchange_is_https_get_without_credentials_or_metrics() { + let exchange = + naruon_analysis_run_idempotency_lookup_exchange("https://tepp.example.test", "idem-9") + .expect("exchange"); + assert_eq!(exchange.method, "GET"); + assert_eq!( + exchange.target_url, + "https://tepp.example.test/v1/analysis-runs/by-idempotency/idem-9" + ); + 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 lookup = + AnalysisRunIdempotencyLookup::new("tepp-run-9", AnalysisRunStatusState::Failed, "idem-9") + .expect("lookup"); + assert_eq!( + lookup.contract_version, + ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_CONTRACT_VERSION + ); + let json = lookup.to_json().expect("json"); + assert_eq!(refuse_metrics_on_idempotency_lookup_payload(&json), Ok(())); + assert!(!json.contains("scientific_acceptance")); + assert!(!json.contains("tenant_workspace_id")); + assert!(!json.contains("snapshot_id")); +} + +#[test] +fn idempotency_lookup_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_idempotency_lookup_exchange(origin, "idem-9"), + Err(ApiError::InvalidWirePayload), + "origin={origin}" + ); + } + assert_eq!( + naruon_analysis_run_idempotency_lookup_exchange( + "https://tepp.example.test", + &"a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_idempotency_lookup_payload(r#"{"scientific_acceptance":{}}"#), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 7a40b9d1b..dc8620c74 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, 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. +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, and `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` for metric-free resolve of a 202 receipt or retry child key to a durable run identity. `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 @@ -71,6 +71,7 @@ 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/analysis-runs/by-idempotency/{idempotency_key} GET /v1/model-artifacts/{artifact_id} GET /v1/exports/{export_id} ``` @@ -96,8 +97,11 @@ returns metric-free stored create fields (`snapshot_id`, `knowledge_cutoff`, 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. +parent was never retried. `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` +on the loopback listener returns the metric-free identity of the unique run +that used that key so operators can jump from a 202 receipt or retry child +key without scanning collection pages. 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 1ba90ed29..ec5ddfc26 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -58,6 +58,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | 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 | +| loopback analysis-run idempotency-key lookup GET | ADR 0037; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` on `AnalysisRunLiveService`: metric-free resolve of a 202 receipt or retry child key to a durable `run_id`; 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/0037-analysis-run-idempotency-lookup-get.md b/docs/adr/0037-analysis-run-idempotency-lookup-get.md new file mode 100644 index 000000000..b31c329b1 --- /dev/null +++ b/docs/adr/0037-analysis-run-idempotency-lookup-get.md @@ -0,0 +1,82 @@ +# ADR 0037 — Analysis-run idempotency-key lookup GET path + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0018, ADR 0031, ADR 0032, ADR 0034, and ADR 0035 for the operator-visible jump from an idempotency key to a durable run identity. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0036 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, retry-lineage, ESEM/DSEM, and cancel-CLI slices. + +## Context + +Collection GET enumerates runs as cursor-paginated identity rows. Stored-request GET and retry-lineage GET require a `run_id`. Retry HTTP clones a failed or cancelled run under a **new** idempotency key. Operators who hold a 202 receipt or a log key therefore cannot jump to that run without scanning pages. Returning RMSE, bias, coverage, SE-gate, or `tepp.scientific_acceptance.v1` on the lookup body would treat key resolution as measurement evidence. GET-by-id (#359) is status/terminal by `run_id` on another stack and remains 400 here. + +## Decision + +`AnalysisRunLiveService` serves `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` on loopback: + +- The payload is metric-free: `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. +- Lookup is consumer-scoped. Zero matches and more than one match fail closed (no tenant oracle). +- Empty GET bodies only. Query strings, GET-by-id, POST `/by-idempotency`, GET `/request`, GET `/retries`, and nonempty bodies fail closed. +- The key travels in the path. The NARUON exchange does not send an `idempotency-key` header or credentials. +- Unknown keys 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, GET retry-lineage, loopback CLI, or cancel CLI. +- LineageWeave/Naruon stored-request consumer-parity (mirrors #373; remains a later unique slice). + +## Alternatives considered + +1. **Ask operators to scan collection pages** — rejected because collection GET (#368) is cursor-bounded and retry mints a new key the operator already holds. +2. **Return `tepp.scientific_acceptance.v1` on succeeded lookup** — rejected because lookup bodies must stay metric-free. +3. **Reuse GET-by-id with the key as `{run_id}`** — rejected because GET-by-id (#359) owns status/terminal by server-assigned identity on another stack. +4. **Metric-free idempotency-key lookup GET on loopback** — accepted. + +## Consequences + +- Operators can resolve a 202 receipt or retry child key to a durable `run_id` without scanning the collection. +- Lookup pages cannot be mistaken for a succeeded scientific-acceptance result. +- GET-by-id may later return a digest-bound artifact without changing these lookup gates. + +## Failure and recovery + +Unknown keys, extra path segments, GET-by-id, query strings, nonempty bodies, metric keys, unpublished consumers, consumer mismatch, ambiguous multi-tenant matches, and non-loopback hosts return a redacted `400` envelope. Oversized keys 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 lookup payload. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Idempotency-key lookup remains loopback-only, size-bounded, consumer-scoped, and content-redacting. +- HTTP `200` on a lookup payload is not measurement evidence and is not release evidence. +- Ambiguous matches fail closed so lookup cannot become a tenant-count oracle. + +## Compatibility and migration + +Create POST, cancel POST, retry POST, collection GET, stored-request GET, retry-lineage 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 lookup fields and the artifact refusal. + +## Verification + +Falsifiable evidence: + +- GET lookup JSON has no RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result`/`tenant_workspace_id`/`snapshot_id` keys; +- GET of a create key and of a retry child key each return the matching `run_id`; +- GET does not leak another consumer's run; +- GET-by-id, query strings, nonempty bodies, POST `/by-idempotency`, unknown keys, and reserved `by-idempotency` as a key fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes idempotency-lookup GET dispatch; POST create receipts, cancel, collection GET, retry, stored-request GET, and retry-lineage GET remain valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on lookup, 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 0035 owns loopback retry-lineage 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. diff --git a/docs/adr/README.md b/docs/adr/README.md index c0a9d4eab..a206d0df7 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -35,6 +35,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [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. | +| [0037](0037-analysis-run-idempotency-lookup-get.md) | Loopback GET analysis-run idempotency-key lookup is metric-free identity resolve | Accepted | active-PR | Complements ADR 0018/0031/0032/0034/0035; does not supersede ADR 0014. ADR 0026–0036 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. | @@ -150,6 +151,7 @@ Use the narrowest owning ADR when decisions overlap: - **analysis-run retry HTTP:** ADR 0032. - **analysis-run stored-request GET:** ADR 0034. - **analysis-run retry-lineage GET:** ADR 0035. +- **analysis-run idempotency-key lookup GET:** ADR 0037. ## Change and supersession rule diff --git a/docs/research/analysis-run-idempotency-lookup-http.md b/docs/research/analysis-run-idempotency-lookup-http.md new file mode 100644 index 000000000..ac6ce84f3 --- /dev/null +++ b/docs/research/analysis-run-idempotency-lookup-http.md @@ -0,0 +1,56 @@ +# Analysis-run idempotency-key lookup HTTP (doctoring) + +## Scope + +`AnalysisRunLiveService` serves +`GET /v1/analysis-runs/by-idempotency/{idempotency_key}` 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 0037), not an RFC inference rule. + +Lookup responses are metric-free `AnalysisRunIdempotencyLookup` JSON. Each +payload carries `run_id`, `run_state`, and `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 +resolution of an idempotency key to a durable run identity. The RFC does not +define psychometric acceptance, RMSE, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0037-analysis-run-idempotency-lookup-get.md` — lookup + authority and metric-free identity fields +- `docs/adr/0035-analysis-run-retry-lineage-get.md` — retry-lineage inspect +- `docs/adr/0034-analysis-run-stored-request-get.md` — stored-request inspect +- `docs/adr/0032-analysis-run-retry-http.md` — retry mints a new key +- `docs/adr/0031-analysis-run-collection-get.md` — collection is + cursor-paginated identity only +- `docs/adr/0018-consumer-scoped-analysis-run-ingress.md` — closed consumer + registry and metric-free `202 Accepted` +- `docs/API_CONTRACT.md` — documented idempotency-lookup resource +- `crates/tepp_api/tests/analysis_run_idempotency_lookup_http_contract.rs` — + fail-closed lookup exchange proofs + +## Operator-visible behaviour + +- loopback `GET /v1/analysis-runs/by-idempotency/{key}` of a create key + returns the metric-free `run_id` of that accepted, failed, or cancelled run +- the same path of a retry child key returns the cloned attempt +- collection GET still lists identity rows and does not become a key index +- stored-request GET still inspects snapshot/cutoff/model/profile +- retry-lineage GET still lists direct children of a parent `run_id` +- GET-by-id remains refused on this stack +- consumer mismatch, unknown keys, nonempty bodies, and metric keys fail + closed diff --git a/schemas/analysis_run_idempotency_lookup_v1.json b/schemas/analysis_run_idempotency_lookup_v1.json new file mode 100644 index 000000000..4e7ce2c34 --- /dev/null +++ b/schemas/analysis_run_idempotency_lookup_v1.json @@ -0,0 +1,22 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://tepp.local/schemas/analysis_run_idempotency_lookup_v1.json", + "title": "AnalysisRunIdempotencyLookupV1", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "run_id", + "run_state", + "idempotency_key" + ], + "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, "maxLength": 128, "pattern": ".*\\S.*" } + } +}