diff --git a/CHANGELOG.d/analysis-run-stored-request-http.md b/CHANGELOG.d/analysis-run-stored-request-http.md new file mode 100644 index 000000000..2db64ee7b --- /dev/null +++ b/CHANGELOG.d/analysis-run-stored-request-http.md @@ -0,0 +1 @@ +- `tepp_api` loopback `GET /v1/analysis-runs/{run_id}/request` returns metric-free stored create fields (snapshot, cutoff, model contract, output profile) so operators can inspect a listed run before retry (ADR 0034). GET-by-id remains refused. Not lifecycle POST, not cancel, not collection GET, not retry, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index 7bfb61f00..cbf933eef 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -16,6 +16,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | Analysis-run cancel HTTP doctoring | [`docs/research/analysis-run-cancel-http.md`](docs/research/analysis-run-cancel-http.md) | | Analysis-run collection HTTP doctoring | [`docs/research/analysis-run-collection-http.md`](docs/research/analysis-run-collection-http.md) | | Analysis-run retry HTTP doctoring | [`docs/research/analysis-run-retry-http.md`](docs/research/analysis-run-retry-http.md) | +| Analysis-run stored-request HTTP doctoring | [`docs/research/analysis-run-stored-request-http.md`](docs/research/analysis-run-stored-request-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 ecb356958..7d6e8e5c1 100644 --- a/crates/tepp_api/src/analysis_run_live.rs +++ b/crates/tepp_api/src/analysis_run_live.rs @@ -9,7 +9,9 @@ //! metric-free `cancelled` status. `GET /v1/analysis-runs` enumerates those //! runs without guessing identities. `POST /v1/analysis-runs/{run_id}/retry` //! clones a failed or cancelled run into a new metric-free `202 Accepted`. -//! GET-by-id and running/terminal POST transitions remain later slices. +//! `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. use std::collections::HashMap; use std::io::Write; @@ -26,6 +28,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_stored_request_http::{ + AnalysisRunStoredRequest, analysis_run_stored_request_path_run_id, + refuse_metrics_on_stored_request_payload, +}; use crate::lineageweave_http::{LINEAGEWEAVE_CONSUMER_CODE, consumer_is_supported}; use crate::live_http::{ header_value, map_io_error, parse_headers, parse_request_line, read_http_request_with_limit, @@ -173,6 +179,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_stored_request_path_run_id(path), + Ok(_) | Err(ApiError::LimitExceeded) + ) { + return self.read_analysis_run_stored_request(path, &headers, body); + } return self.list_analysis_runs(path, &headers, body); } if method != "POST" { @@ -383,6 +395,44 @@ impl AnalysisRunLiveService { Ok(json_response(202, "Accepted", response_body)) } + fn read_analysis_run_stored_request( + &self, + path: &str, + headers: &HashMap, + body: &str, + ) -> Result { + let run_id = analysis_run_stored_request_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_stored_request_payload(body)?; + let replay_key = self + .runs_by_id + .get(&run_id) + .cloned() + .ok_or(ApiError::InvalidWirePayload)?; + let stored = self + .accepted_runs + .get(&replay_key) + .ok_or(ApiError::InvalidWirePayload)?; + if stored.consumer != consumer { + return Err(ApiError::InvalidWirePayload); + } + let payload = AnalysisRunStoredRequest::new( + stored.accepted.run_id.clone(), + stored.run_state, + stored.accepted.idempotency_key.clone(), + stored.request.snapshot_id.clone(), + stored.request.knowledge_cutoff.clone(), + stored.request.model_contract_version.clone(), + stored.request.output_profile.clone(), + )?; + let response_body = payload.to_json()?; + refuse_metrics_on_stored_request_payload(&response_body)?; + Ok(json_response(200, "OK", response_body)) + } + fn list_analysis_runs( &self, path: &str, @@ -444,9 +494,9 @@ impl AnalysisRunLiveService { /// Test-only seam that records a non-accepted loopback state. /// - /// Used to prove cancel, collection, and retry of running, succeeded, - /// failed, and cancelled runs without duplicating the live POST - /// running/terminal lifecycle slice. + /// 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. #[cfg(test)] fn force_loopback_run_state( &mut self, @@ -1636,6 +1686,151 @@ mod tests { assert!(!listed.body.contains("rmse")); } + fn stored_request_http(run_id: &str, consumer: &str, extra: &[(&str, &str)]) -> String { + let mut request = format!("GET {NARUON_ANALYSIS_RUN_PATH}/{run_id}/request 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("stored-request 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_stored_request_get() { + use crate::{AnalysisRunStatusState, AnalysisRunStoredRequest}; + + 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 run_id = serde_json::from_str::(&accepted.body) + .expect("accepted json")["run_id"] + .as_str() + .expect("run_id") + .to_owned(); + + let inspected = + service.handle_http_request(&stored_request_http(&run_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(inspected.status_code, 200); + let stored = AnalysisRunStoredRequest::from_json(&inspected.body).expect("stored"); + assert_eq!(stored.run_id, run_id); + assert_eq!(stored.run_state, AnalysisRunStatusState::Accepted); + assert_eq!(stored.idempotency_key, run.idempotency_key); + assert_eq!(stored.snapshot_id, run.snapshot_id); + assert_eq!(stored.knowledge_cutoff, run.knowledge_cutoff); + assert_eq!(stored.model_contract_version, run.model_contract_version); + assert_eq!(stored.output_profile, run.output_profile); + assert!(!inspected.body.contains("rmse")); + assert!(!inspected.body.contains("scientific_acceptance")); + assert!(!inspected.body.contains("terminal_result")); + assert!(!inspected.body.contains("tenant_workspace_id")); + + service + .force_loopback_run_state(&run_id, AnalysisRunStatusState::Failed) + .expect("force failed"); + let failed = + service.handle_http_request(&stored_request_http(&run_id, NARUON_CONSUMER_CODE, &[])); + assert_eq!(failed.status_code, 200); + assert_eq!( + AnalysisRunStoredRequest::from_json(&failed.body) + .expect("failed stored") + .run_state, + AnalysisRunStatusState::Failed + ); + + let mut cancelled_run = run.clone(); + cancelled_run.idempotency_key = "analysis-live-idem-002".into(); + let cancelled_accepted = service.handle_http_request(&valid_request( + &cancelled_run, + NARUON_CONSUMER_CODE, + "127.0.0.1", + )); + let cancelled_id = serde_json::from_str::(&cancelled_accepted.body) + .expect("cancelled accepted")["run_id"] + .as_str() + .expect("id") + .to_owned(); + service + .force_loopback_run_state(&cancelled_id, AnalysisRunStatusState::Cancelled) + .expect("force cancelled"); + let cancelled = service.handle_http_request(&stored_request_http( + &cancelled_id, + NARUON_CONSUMER_CODE, + &[], + )); + assert_eq!(cancelled.status_code, 200); + let cancelled_stored = + AnalysisRunStoredRequest::from_json(&cancelled.body).expect("cancelled stored"); + assert_eq!( + cancelled_stored.run_state, + AnalysisRunStatusState::Cancelled + ); + assert_eq!(cancelled_stored.snapshot_id, run.snapshot_id); + assert_eq!(cancelled_stored.output_profile, run.output_profile); + + assert_eq!( + service + .handle_http_request(&stored_request_http( + &run_id, + LINEAGEWEAVE_CONSUMER_CODE, + &[], + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&stored_request_http( + "missing-run", + NARUON_CONSUMER_CODE, + &[], + )) + .status_code, + 400 + ); + assert_eq!( + service + .handle_http_request(&format!( + "GET {NARUON_ANALYSIS_RUN_PATH}/{run_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}/{run_id}/request 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}/{run_id}/request 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(&stored_request_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("snapshot_id")); + } + #[test] fn temporal_read_headers_and_defensive_write_edges_are_covered() { let run = sample_run(); diff --git a/crates/tepp_api/src/analysis_run_stored_request_http.rs b/crates/tepp_api/src/analysis_run_stored_request_http.rs new file mode 100644 index 000000000..653a12665 --- /dev/null +++ b/crates/tepp_api/src/analysis_run_stored_request_http.rs @@ -0,0 +1,540 @@ +//! Provider-owned analysis-run stored-request GET contracts. +//! +//! GAP-003A ninth slice: `GET /v1/analysis-runs/{run_id}/request` returns the +//! metric-free stored create fields operators need before retry — snapshot, +//! cutoff, model contract, and output profile. Collection GET lists identity +//! only. GET-by-id (#359) remains a later slice on this stack. Retry HTTP +//! (#369) clones blindly. This module does not serve lifecycle POST, cancel, +//! collection GET, retry POST, or loopback CLI. 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 stored-request path. +pub const ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN: usize = 128; + +/// Supported analysis-run stored-request contract version. +pub const ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION: u16 = 1; + +const FORBIDDEN_STORED_REQUEST_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 stored create fields for one analysis run. +/// +/// Operators inspect snapshot, cutoff, model contract, and output profile +/// before retry. The payload never carries a terminal result or +/// scientific-acceptance artifact. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AnalysisRunStoredRequest { + /// 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 of this run. + pub idempotency_key: String, + /// Immutable corpus/evidence snapshot identity. + pub snapshot_id: String, + /// Knowledge cutoff instant as an ISO-8601 / RFC 3339 string. + pub knowledge_cutoff: String, + /// Versioned model/backend contract identity. + pub model_contract_version: String, + /// Requested output profile name. + pub output_profile: String, +} + +impl AnalysisRunStoredRequest { + /// Construct a validated metric-free stored-request payload. + /// + /// # Errors + /// + /// Returns a fail-closed error for empty identities, an oversized run + /// identity, or an unsupported contract version. + pub fn new( + run_id: impl Into, + run_state: AnalysisRunStatusState, + idempotency_key: impl Into, + snapshot_id: impl Into, + knowledge_cutoff: impl Into, + model_contract_version: impl Into, + output_profile: impl Into, + ) -> Result { + let stored = Self { + contract_version: ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION, + run_id: run_id.into(), + run_state, + idempotency_key: idempotency_key.into(), + snapshot_id: snapshot_id.into(), + knowledge_cutoff: knowledge_cutoff.into(), + model_contract_version: model_contract_version.into(), + output_profile: output_profile.into(), + }; + stored.validate()?; + Ok(stored) + } + + /// Parse and validate a stored-request 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 stored-request 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_stored_request_payload(payload)?; + let stored: Self = from_json(payload)?; + stored.validate()?; + Ok(stored) + } + + /// Serialize this stored-request 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_stored_request_payload(&payload)?; + Ok(payload) + } + + fn validate(&self) -> Result<(), ApiError> { + require_contract_version( + self.contract_version, + ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION, + )?; + require_nonempty(&self.run_id)?; + require_nonempty(&self.idempotency_key)?; + require_nonempty(&self.snapshot_id)?; + require_nonempty(&self.knowledge_cutoff)?; + require_nonempty(&self.model_contract_version)?; + require_nonempty(&self.output_profile)?; + if self.run_id.len() > ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(()) + } +} + +/// Refuse stored-request 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_stored_request_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_STORED_REQUEST_KEYS + .iter() + .any(|key| object.contains_key(*key)) + { + return Err(ApiError::InvalidWirePayload); + } + Ok(()) +} + +/// Extract the opaque run identity from `GET /v1/analysis-runs/{run_id}/request`. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] for a collection path, extra +/// segments, a missing `/request` suffix, cancel/retry/running/terminal +/// suffixes, or a hostile encoding, and [`ApiError::LimitExceeded`] when the +/// decoded identity exceeds [`ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN`]. +pub(crate) fn analysis_run_stored_request_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("/request") + .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_STORED_REQUEST_ID_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + Ok(run_id) +} + +/// Build a provider-owned `GET` analysis-run stored-request 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_STORED_REQUEST_ID_MAX_LEN`] bytes. +pub fn naruon_analysis_run_stored_request_exchange( + origin: &str, + run_id: &str, +) -> Result { + require_nonempty(run_id)?; + if run_id.len() > ANALYSIS_RUN_STORED_REQUEST_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}/request"); + 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_stored() -> AnalysisRunStoredRequest { + AnalysisRunStoredRequest::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "idem-1", + "snapshot-1", + "2026-08-01T00:00:00Z", + "tepp-analysis-run-v1", + "calibrated_event_measurement", + ) + .expect("stored") + } + + #[test] + fn stored_request_round_trips_and_refuses_hostile_shapes() { + let stored = sample_stored(); + let json = stored.to_json().expect("json"); + assert_eq!( + AnalysisRunStoredRequest::from_json(&json).expect("decode"), + stored + ); + assert!(!json.contains("rmse")); + assert!(!json.contains("scientific_acceptance")); + assert!(!json.contains("terminal_result")); + assert!(!json.contains("tenant_workspace_id")); + + assert_eq!( + AnalysisRunStoredRequest::new( + "", + AnalysisRunStatusState::Failed, + "idem-1", + "snapshot-1", + "2026-08-01T00:00:00Z", + "tepp-analysis-run-v1", + "calibrated_event_measurement", + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunStoredRequest::new( + "tepp-run-1", + AnalysisRunStatusState::Failed, + "", + "snapshot-1", + "2026-08-01T00:00:00Z", + "tepp-analysis-run-v1", + "calibrated_event_measurement", + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunStoredRequest::new( + "a".repeat(ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN + 1), + AnalysisRunStatusState::Failed, + "idem-1", + "snapshot-1", + "2026-08-01T00:00:00Z", + "tepp-analysis-run-v1", + "calibrated_event_measurement", + ), + Err(ApiError::LimitExceeded) + ); + + let mut unsupported = stored.clone(); + unsupported.contract_version = 9; + assert_eq!( + unsupported.to_json(), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunStoredRequest::from_json( + r#"{"contract_version":9,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1","snapshot_id":"snapshot-1","knowledge_cutoff":"2026-08-01T00:00:00Z","model_contract_version":"tepp-analysis-run-v1","output_profile":"calibrated_event_measurement"}"# + ), + Err(ApiError::UnsupportedContractVersion) + ); + assert_eq!( + AnalysisRunStoredRequest::from_json( + r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"failed","idempotency_key":"idem-1","snapshot_id":"snapshot-1","knowledge_cutoff":"2026-08-01T00:00:00Z","model_contract_version":"tepp-analysis-run-v1","output_profile":"calibrated_event_measurement","extra":true}"# + ), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunStoredRequest::from_json_with_limit(&json, 8), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + AnalysisRunStoredRequest::from_json("[1,2,3]"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn stored_request_payloads_refuse_scientific_metric_keys() { + assert_eq!(refuse_metrics_on_stored_request_payload(""), Ok(())); + assert_eq!(refuse_metrics_on_stored_request_payload(" "), Ok(())); + assert_eq!( + refuse_metrics_on_stored_request_payload(r#"{"run_id":"r"}"#), + Ok(()) + ); + for key in FORBIDDEN_STORED_REQUEST_KEYS { + let payload = format!(r#"{{"{key}":1,"run_id":"r"}}"#); + assert_eq!( + refuse_metrics_on_stored_request_payload(&payload), + Err(ApiError::InvalidWirePayload), + "key={key}" + ); + } + assert_eq!( + refuse_metrics_on_stored_request_payload("[true]"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_stored_request_payload("null"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn stored_request_path_decodes_identities_and_refuses_hostile_segments() { + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/request") + .expect("plain"), + "tepp-run-1" + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/run%2dabc/request") + .expect("lower"), + "run-abc" + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/run%2Dabc/request") + .expect("upper"), + "run-abc" + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/cancel"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + 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/running"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/tepp-run-1/terminal"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/other/tepp-run-1/request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs//request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/a/b/request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/%2F/request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + analysis_run_stored_request_path_run_id("/v1/analysis-runs/%00/request"), + Err(ApiError::InvalidWirePayload) + ); + let oversized = format!( + "/v1/analysis-runs/{}/request", + "a".repeat(ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN + 1) + ); + assert_eq!( + analysis_run_stored_request_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 stored_request_exchange_gets_https_path_without_credentials() { + let exchange = + naruon_analysis_run_stored_request_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/request" + ); + 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_stored_request_exchange( + "https://tepp.example.com", + "run/../../etc", + ) + .expect("encoded"); + assert!(encoded.target_url.contains("run%2F..%2F..%2Fetc/request")); + + assert_eq!( + naruon_analysis_run_stored_request_exchange("http://tepp.example.com", "tepp-run-1"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_stored_request_exchange("https://tepp.example.com", ""), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + naruon_analysis_run_stored_request_exchange( + "https://tepp.example.com", + &"a".repeat(ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 227dbd4ec..ac10fc472 100644 --- a/crates/tepp_api/src/lib.rs +++ b/crates/tepp_api/src/lib.rs @@ -18,6 +18,7 @@ mod analysis_run_collection_http; mod analysis_run_live; mod analysis_run_retry_http; mod analysis_run_status_http; +mod analysis_run_stored_request_http; mod authorization; mod corpus_split_manifest; mod envelope; @@ -118,6 +119,16 @@ pub use analysis_run_retry_http::naruon_analysis_run_retry_exchange; pub use analysis_run_retry_http::refuse_metrics_on_retry_payload; /// Analysis-run status HTTP exchange re-exports. pub use analysis_run_status_http::{ANALYSIS_RUN_ID_MAX_LEN, naruon_analysis_run_status_exchange}; +/// Analysis-run stored-request contract version constant. +pub use analysis_run_stored_request_http::ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION; +/// Maximum opaque run identity length on the stored-request path. +pub use analysis_run_stored_request_http::ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN; +/// Versioned metric-free stored analysis-run create fields. +pub use analysis_run_stored_request_http::AnalysisRunStoredRequest; +/// Build a Naruon analysis-run stored-request GET exchange. +pub use analysis_run_stored_request_http::naruon_analysis_run_stored_request_exchange; +/// Refuse scientific-metric keys on a stored-request payload. +pub use analysis_run_stored_request_http::refuse_metrics_on_stored_request_payload; /// Corpus-split leakage-audit contract version. pub use corpus_split_manifest::CORPUS_SPLIT_MANIFEST_CONTRACT_VERSION; /// Versioned corpus-split leakage-audit manifest. diff --git a/crates/tepp_api/tests/analysis_run_stored_request_http_contract.rs b/crates/tepp_api/tests/analysis_run_stored_request_http_contract.rs new file mode 100644 index 000000000..439c6415f --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_stored_request_http_contract.rs @@ -0,0 +1,83 @@ +//! Contract tests for the analysis-run stored-request GET exchange. + +use tepp_api::{ + ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION, ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN, + AnalysisRunStatusState, AnalysisRunStoredRequest, ApiError, + naruon_analysis_run_stored_request_exchange, refuse_metrics_on_stored_request_payload, +}; + +#[test] +fn stored_request_exchange_is_https_get_without_credentials_or_metrics() { + let exchange = + naruon_analysis_run_stored_request_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/request" + ); + 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 stored = AnalysisRunStoredRequest::new( + "tepp-run-9", + AnalysisRunStatusState::Failed, + "idem-9", + "snapshot-9", + "2026-08-01T00:00:00Z", + "tepp-analysis-run-v1", + "calibrated_event_measurement", + ) + .expect("stored"); + assert_eq!( + stored.contract_version, + ANALYSIS_RUN_STORED_REQUEST_CONTRACT_VERSION + ); + let json = stored.to_json().expect("json"); + assert_eq!(refuse_metrics_on_stored_request_payload(&json), Ok(())); + assert!(!json.contains("scientific_acceptance")); + assert!(!json.contains("tenant_workspace_id")); +} + +#[test] +fn stored_request_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_stored_request_exchange(origin, "tepp-run-9"), + Err(ApiError::InvalidWirePayload), + "origin={origin}" + ); + } + assert_eq!( + naruon_analysis_run_stored_request_exchange( + "https://tepp.example.test", + &"a".repeat(ANALYSIS_RUN_STORED_REQUEST_ID_MAX_LEN + 1) + ), + Err(ApiError::LimitExceeded) + ); + assert_eq!( + refuse_metrics_on_stored_request_payload(r#"{"rmse":1.0}"#), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + refuse_metrics_on_stored_request_payload(r#"{"scientific_acceptance":{}}"#), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index 4cc2e63e4..41e52cb68 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`. `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. `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 @@ -69,6 +69,7 @@ POST /v1/temporal-context GET /v1/analysis-runs/{run_id} POST /v1/analysis-runs/{run_id}/cancel POST /v1/analysis-runs/{run_id}/retry +GET /v1/analysis-runs/{run_id}/request GET /v1/model-artifacts/{artifact_id} GET /v1/exports/{export_id} ``` @@ -88,7 +89,11 @@ operators do not guess run identities. Collection bodies never carry `tepp.scientific_acceptance.v1`. `POST /v1/analysis-runs/{run_id}/retry` clones a failed or cancelled run into a new metric-free `202 Accepted` with a new idempotency key; accepted, running, succeeded, and unknown runs fail -closed. GET-by-id remains a later slice on this protected-main lineage. +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 +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 3937c14b5..3dd7d658a 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -56,6 +56,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | loopback analysis-run cancel HTTP | ADR 0029; API contract; RFC 9110 | `tepp_api` `POST /v1/analysis-runs/{run_id}/cancel` on `AnalysisRunLiveService`: metric-free cancelled status for accepted/running runs; succeeded/failed/unknown refuse; GET status remains a later slice | active-PR | | loopback analysis-run collection GET | ADR 0031; API contract; RFC 9110 | `tepp_api` `GET /v1/analysis-runs` on `AnalysisRunLiveService`: metric-free enumeration of accepted/running/cancelled/terminal runs; collection bodies refuse scientific-acceptance and RMSE keys; GET-by-id remains a later slice | active-PR | | loopback analysis-run retry HTTP | ADR 0032; API contract; RFC 9110 | `tepp_api` `POST /v1/analysis-runs/{run_id}/retry` on `AnalysisRunLiveService`: clones failed/cancelled into a new metric-free `202 Accepted` with a new idempotency key; accepted/running/succeeded/unknown refuse; GET-by-id remains a later slice | active-PR | +| 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 | | 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/0034-analysis-run-stored-request-get.md b/docs/adr/0034-analysis-run-stored-request-get.md new file mode 100644 index 000000000..b9f207847 --- /dev/null +++ b/docs/adr/0034-analysis-run-stored-request-get.md @@ -0,0 +1,79 @@ +# ADR 0034 — Analysis-run stored-request GET path + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0018, ADR 0031, and ADR 0032 for the operator-visible stored-request inspect. Does not supersede ADR 0014 claim-promotion authority. ADR 0026–0033 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, and loopback-binary slices. + +## Context + +Collection GET lists `run_id`, `run_state`, and `idempotency_key` only. Retry HTTP clones a failed or cancelled run blindly. Operators therefore cannot inspect `snapshot_id`, `knowledge_cutoff`, `model_contract_version`, or `output_profile` of a listed run before retry. GET-by-id (#359) returns status/terminal on a different stack and would duplicate that head if stacked here. Returning RMSE, bias, coverage, SE-gate, or `tepp.scientific_acceptance.v1` on the inspect body would treat enumeration of stored create fields as measurement evidence. + +## Decision + +`AnalysisRunLiveService` serves `GET /v1/analysis-runs/{run_id}/request` on loopback: + +- The payload is metric-free: `run_id`, `run_state`, `idempotency_key`, `snapshot_id`, `knowledge_cutoff`, `model_contract_version`, and `output_profile`. +- `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, report, `terminal_result`, and `tenant_workspace_id` never appear. +- Accepted, running, cancelled, succeeded, and failed runs are readable. Succeeded rows still omit the artifact. +- Empty GET bodies only. Query strings, GET-by-id, POST `/request`, and nonempty bodies fail closed. +- Consumer isolation: another consumer cannot read the first consumer's stored request. +- 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, or loopback CLI. + +## Alternatives considered + +1. **Stack inspect onto the live GET-by-id PR** — rejected because that head already owns single-run status and a parallel stack would duplicate it. +2. **Return `tepp.scientific_acceptance.v1` on succeeded inspect** — rejected because stored-request bodies must stay metric-free. +3. **Ask operators to reconstruct snapshot/cutoff/profile from local notes** — rejected because collection GET already identified the run and retry clones blindly. +4. **Metric-free stored-request GET on loopback** — accepted. + +## Consequences + +- Operators can inspect stored create fields of a listed run before retry. +- Inspect pages cannot be mistaken for a succeeded scientific-acceptance result. +- GET-by-id may later return a digest-bound artifact without changing these inspect 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 return `413`. Credential headers remain `403`. The in-memory registry is not durable; a restart requires re-POSTing the original metric-free create requests. Callers must not fabricate a succeeded scientific-acceptance artifact from a stored-request payload. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- Stored-request GET remains loopback-only, size-bounded, consumer-scoped, and content-redacting. +- HTTP `200` on a stored-request payload is not measurement evidence and is not release evidence. + +## Compatibility and migration + +Create POST, cancel POST, retry POST, collection GET, temporal-context, and project-history paths are unchanged. GET-by-id remains refused on this slice. Production adapters may replace loopback while preserving metric-free stored-request fields and the artifact refusal. + +## Verification + +Falsifiable evidence: + +- GET stored-request JSON has no RMSE/bias/coverage/SE-gate/scientific-acceptance/`terminal_result`/`tenant_workspace_id` keys; +- GET returns snapshot, cutoff, model contract, and output profile for failed and cancelled runs; +- GET does not leak another consumer's stored request; +- GET-by-id, query strings, nonempty bodies, and unknown identities fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes stored-request GET dispatch; POST create receipts, cancel, collection GET, and retry remain valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on inspect, 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 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 12683d65a..4a23e5b42 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -33,6 +33,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [0029](0029-analysis-run-cancel-http.md) | Loopback POST analysis-run cancel is metric-free cancelled status | Accepted | active-PR | Complements ADR 0018; does not supersede ADR 0014. ADR 0026–0028 live on other GAP-003A PRs. | | [0031](0031-analysis-run-collection-get.md) | Loopback GET analysis-run collection is metric-free enumeration | Accepted | active-PR | Complements ADR 0018/0029; does not supersede ADR 0014. ADR 0026–0030 live on other GAP-003A PRs. | | [0032](0032-analysis-run-retry-http.md) | Loopback POST analysis-run retry clones failed/cancelled into a new metric-free 202 | Accepted | active-PR | Complements ADR 0018/0029/0031; does not supersede ADR 0014. ADR 0026–0031 live on other GAP-003A PRs. | +| [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. | | [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. | @@ -146,6 +147,7 @@ Use the narrowest owning ADR when decisions overlap: - **analysis-run cancel HTTP:** ADR 0029. - **analysis-run collection GET:** ADR 0031. - **analysis-run retry HTTP:** ADR 0032. +- **analysis-run stored-request GET:** ADR 0034. ## Change and supersession rule diff --git a/docs/research/analysis-run-stored-request-http.md b/docs/research/analysis-run-stored-request-http.md new file mode 100644 index 000000000..fc4ff3354 --- /dev/null +++ b/docs/research/analysis-run-stored-request-http.md @@ -0,0 +1,61 @@ +# Analysis-run stored-request HTTP (doctoring) + +## Scope + +`AnalysisRunLiveService` serves `GET /v1/analysis-runs/{run_id}/request` 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 0034), not an RFC +inference rule. + +Stored-request responses are metric-free `AnalysisRunStoredRequest` JSON. +Each payload carries `run_id`, `run_state`, `idempotency_key`, `snapshot_id`, +`knowledge_cutoff`, `model_contract_version`, and `output_profile` 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 stored create fields. The RFC does not define psychometric +acceptance, RMSE, or claim promotion. + +### Internal contract evidence + +- `docs/adr/0034-analysis-run-stored-request-get.md` — stored-request + authority and metric-free inspect fields +- `docs/adr/0032-analysis-run-retry-http.md` — retry clones after inspect +- `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/adr/0014-scientific-claim-promotion-and-release-evidence.md` — HTTP + success is not a scientific claim +- `docs/API_CONTRACT.md` — documented stored-request resource +- `crates/tepp_api/tests/analysis_run_stored_request_http_contract.rs` — + fail-closed stored-request exchange proofs + +## Verification + +- loopback `GET /v1/analysis-runs/{run_id}/request` of failed and cancelled + runs returns snapshot, cutoff, model contract, and output profile without + RMSE/bias/coverage/SE-gate keys or `tepp.scientific_acceptance.v1`; +- another consumer cannot read the first consumer's stored request; +- GET-by-id, query strings, nonempty GET bodies, and unknown identities fail + closed; +- review, Copilot, GitHub, and bearer headers remain `AuthorizationDenied`. + +## Non-claims + +This slice does not implement GET-by-id, running/terminal POST, cancel HTTP, +collection GET, retry HTTP, loopback CLI, persistence, production TLS, Leiden +consensus, or an ADR 0014 scientific claim-promotion package. diff --git a/schemas/analysis_run_stored_request_v1.json b/schemas/analysis_run_stored_request_v1.json new file mode 100644 index 000000000..705a6edb5 --- /dev/null +++ b/schemas/analysis_run_stored_request_v1.json @@ -0,0 +1,30 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://tepp.local/schemas/analysis_run_stored_request_v1.json", + "title": "AnalysisRunStoredRequestV1", + "type": "object", + "additionalProperties": false, + "required": [ + "contract_version", + "run_id", + "run_state", + "idempotency_key", + "snapshot_id", + "knowledge_cutoff", + "model_contract_version", + "output_profile" + ], + "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.*" }, + "snapshot_id": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" }, + "knowledge_cutoff": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" }, + "model_contract_version": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" }, + "output_profile": { "type": "string", "minLength": 1, "pattern": ".*\\S.*" } + } +}