From a3410d42d82c09dd3eb7978a54e6c46513179695 Mon Sep 17 00:00:00 2001 From: Seongho Bae <8172694+seonghobae@users.noreply.github.com> Date: Mon, 31 Aug 2026 16:41:07 +0000 Subject: [PATCH] feat(api): resolve analysis-run identity via loopback lookup CLI GAP-003A / issue #166: operators can jump from a 202 receipt or retry child key to a durable run_id through `tepp-analysis-runs lookup` without writing raw HTTP. Metric-free run_id/run_state/idempotency_key only. tepp.scientific_acceptance.v1 never appears. Stacked on lookup GET (#380). Does not duplicate stored-request/retry/retry-parent/cancel/create/status CLIs. --- .../analysis-run-idempotency-lookup-cli.md | 1 + DOCUMENTATION.md | 1 + crates/tepp_api/Cargo.toml | 6 + .../analysis_run_idempotency_lookup_cli.rs | 842 ++++++++++++++++++ .../analysis_run_idempotency_lookup_http.rs | 2 +- crates/tepp_api/src/bin/tepp_analysis_runs.rs | 39 + crates/tepp_api/src/lib.rs | 15 + ...sis_run_idempotency_lookup_cli_contract.rs | 67 ++ docs/API_CONTRACT.md | 5 +- docs/TRACEABILITY.md | 1 + ...038-analysis-run-idempotency-lookup-cli.md | 70 ++ docs/adr/README.md | 2 + docs/connectors/naruon-artifact-consumer.md | 1 + .../analysis-run-idempotency-lookup-cli.md | 58 ++ 14 files changed, 1108 insertions(+), 2 deletions(-) create mode 100644 CHANGELOG.d/analysis-run-idempotency-lookup-cli.md create mode 100644 crates/tepp_api/src/analysis_run_idempotency_lookup_cli.rs create mode 100644 crates/tepp_api/src/bin/tepp_analysis_runs.rs create mode 100644 crates/tepp_api/tests/analysis_run_idempotency_lookup_cli_contract.rs create mode 100644 docs/adr/0038-analysis-run-idempotency-lookup-cli.md create mode 100644 docs/research/analysis-run-idempotency-lookup-cli.md diff --git a/CHANGELOG.d/analysis-run-idempotency-lookup-cli.md b/CHANGELOG.d/analysis-run-idempotency-lookup-cli.md new file mode 100644 index 000000000..d92c80bd8 --- /dev/null +++ b/CHANGELOG.d/analysis-run-idempotency-lookup-cli.md @@ -0,0 +1 @@ +- `tepp_api` loopback `tepp-analysis-runs lookup` resolves a metric-free run identity by idempotency key (ADR 0038). `run_id`/`run_state`/`idempotency_key` only. Refuses RMSE/bias/coverage/SE-gate keys and `tepp.scientific_acceptance.v1`. Not lookup HTTP, not stored-request CLI, not GET-by-id, not persistence. diff --git a/DOCUMENTATION.md b/DOCUMENTATION.md index ac5014a51..36c956487 100644 --- a/DOCUMENTATION.md +++ b/DOCUMENTATION.md @@ -19,6 +19,7 @@ TEPP's approved PRD v0.4 and implementation plan are the primary product baselin | 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) | +| Analysis-run idempotency-key lookup CLI doctoring | [`docs/research/analysis-run-idempotency-lookup-cli.md`](docs/research/analysis-run-idempotency-lookup-cli.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/Cargo.toml b/crates/tepp_api/Cargo.toml index 47ad7c433..b3c3d43f4 100644 --- a/crates/tepp_api/Cargo.toml +++ b/crates/tepp_api/Cargo.toml @@ -29,5 +29,11 @@ path = "src/bin/tepp_loopback.rs" test = false bench = false +[[bin]] +name = "tepp-analysis-runs" +path = "src/bin/tepp_analysis_runs.rs" +test = false +bench = false + [lints] workspace = true diff --git a/crates/tepp_api/src/analysis_run_idempotency_lookup_cli.rs b/crates/tepp_api/src/analysis_run_idempotency_lookup_cli.rs new file mode 100644 index 000000000..453b77e09 --- /dev/null +++ b/crates/tepp_api/src/analysis_run_idempotency_lookup_cli.rs @@ -0,0 +1,842 @@ +//! Operator loopback CLI for analysis-run idempotency-key lookup GET. +//! +//! GAP-003A operator-visible client of +//! `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` (ADR 0037 / live +//! #380). Operators run `tepp-analysis-runs lookup` to resolve a 202 receipt +//! or retry child key to a durable `run_id` without writing raw HTTP. +//! `tepp.scientific_acceptance.v1` never appears. This module does not +//! duplicate lookup HTTP, stored-request CLI, retry CLI, retry-parent CLI, +//! collection/cancel/create/status CLIs, or GET-by-id. Persistence remains +//! GAP-003B. + +use std::io::{Read, Write}; +use std::net::{SocketAddr, TcpStream}; + +use crate::analysis_run_idempotency_lookup_http::{ + ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN, ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX, + encode_path_segment, refuse_metrics_on_idempotency_lookup_payload, +}; +use crate::lineageweave_http::consumer_is_supported; +use crate::live_http::map_io_error; +use crate::naruon_http::{NARUON_ANALYSIS_RUN_PATH, header_is_credential}; +use crate::wire::require_nonempty; +use crate::{ + AnalysisRunIdempotencyLookup, AnalysisRunLiveService, ApiError, NARUON_LIVE_IO_TIMEOUT, + NaruonLiveResponse, +}; + +const SCIENTIFIC_ACCEPTANCE_SCHEMA: &str = "tepp.scientific_acceptance.v1"; + +/// Supported operator verbs for the loopback idempotency-lookup CLI. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AnalysisRunIdempotencyLookupCliVerb { + /// `GET /v1/analysis-runs/by-idempotency/{idempotency_key}`. + Lookup, +} + +impl AnalysisRunIdempotencyLookupCliVerb { + /// Parse one exact lowercase verb token. + /// + /// # Errors + /// + /// Returns [`ApiError::InvalidWirePayload`] for an unknown token. + pub fn parse(token: &str) -> Result { + match token { + "lookup" => Ok(Self::Lookup), + _ => Err(ApiError::InvalidWirePayload), + } + } + + /// Return the canonical lowercase verb token. + #[must_use] + pub const fn as_str(self) -> &'static str { + match self { + Self::Lookup => "lookup", + } + } +} + +/// One operator CLI invocation against a loopback idempotency-lookup GET listener. +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct AnalysisRunIdempotencyLookupCliInvocation { + /// CLI verb to execute. + pub verb: AnalysisRunIdempotencyLookupCliVerb, + /// Loopback `host:port` of `tepp-loopback`. + pub host: String, + /// Published modular consumer (`naruon` or `lineageweave`). + pub consumer: String, + /// Exact request idempotency key to resolve. + pub idempotency_key: String, + /// JSON body. Lookup GET requires empty. + pub body: String, +} + +impl AnalysisRunIdempotencyLookupCliInvocation { + /// Parse argv plus stdin body into a validated loopback lookup invocation. + /// + /// # Errors + /// + /// Returns a fail-closed error for unknown verbs, missing required flags, a + /// non-loopback host, an unpublished consumer, credential-shaped flags, + /// hostile identities, or a nonempty body. + pub fn from_args(args: I, body: impl Into) -> Result + where + I: IntoIterator, + S: AsRef, + { + let tokens: Vec = args + .into_iter() + .map(|token| token.as_ref().to_owned()) + .collect(); + let (verb_token, rest) = tokens.split_first().ok_or(ApiError::InvalidWirePayload)?; + let verb = AnalysisRunIdempotencyLookupCliVerb::parse(verb_token)?; + let flags = parse_flags(rest)?; + assemble_invocation(verb, flags, body.into()) + } + + /// Reject a non-loopback host, unpublished consumer, or hostile lookup body. + /// + /// # Errors + /// + /// Returns [`ApiError::AuthorizationDenied`] for a non-loopback host and + /// [`ApiError::InvalidWirePayload`] or [`ApiError::LimitExceeded`] for + /// empty, unpublished, oversized, or nonempty-body fields. + pub fn validate(&self) -> Result<(), ApiError> { + require_loopback_host(&self.host)?; + require_nonempty(&self.consumer)?; + if !consumer_is_supported(&self.consumer) { + return Err(ApiError::InvalidWirePayload); + } + require_nonempty(&self.idempotency_key)?; + if self.idempotency_key.len() > ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN { + return Err(ApiError::LimitExceeded); + } + if !self.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance(&self.body)?; + refuse_metrics_on_idempotency_lookup_payload(&self.body)?; + Ok(()) + } +} + +struct ParsedFlags { + host: Option, + consumer: Option, + idempotency_key: Option, +} + +fn parse_flags(rest: &[String]) -> Result { + let mut flags = ParsedFlags { + host: None, + consumer: None, + idempotency_key: None, + }; + let mut index = 0; + while index < rest.len() { + let flag = rest[index].as_str(); + if !flag.starts_with("--") { + return Err(ApiError::InvalidWirePayload); + } + let name = &flag[2..]; + if header_is_credential(name) { + return Err(ApiError::AuthorizationDenied); + } + let slot = match name { + "host" => &mut flags.host, + "consumer" => &mut flags.consumer, + "idempotency-key" => &mut flags.idempotency_key, + _ => return Err(ApiError::InvalidWirePayload), + }; + if slot.is_some() || index + 1 >= rest.len() { + return Err(ApiError::InvalidWirePayload); + } + let value = rest[index + 1].as_str(); + require_nonempty(value)?; + *slot = Some(value.to_owned()); + index += 2; + } + Ok(flags) +} + +fn assemble_invocation( + verb: AnalysisRunIdempotencyLookupCliVerb, + flags: ParsedFlags, + body: String, +) -> Result { + let invocation = AnalysisRunIdempotencyLookupCliInvocation { + verb, + host: flags.host.ok_or(ApiError::InvalidWirePayload)?, + consumer: flags + .consumer + .unwrap_or_else(|| crate::NARUON_CONSUMER_CODE.to_owned()), + idempotency_key: flags.idempotency_key.ok_or(ApiError::InvalidWirePayload)?, + body, + }; + invocation.validate()?; + Ok(invocation) +} + +fn require_loopback_host(host: &str) -> Result { + let addr: SocketAddr = host.parse().map_err(|_| ApiError::InvalidWirePayload)?; + if addr.ip().is_loopback() { + Ok(addr) + } else { + Err(ApiError::AuthorizationDenied) + } +} + +/// Compose one HTTP/1.1 idempotency-lookup GET for a validated CLI invocation. +/// +/// # Errors +/// +/// Returns the same fail-closed errors as +/// [`AnalysisRunIdempotencyLookupCliInvocation::validate`]. +pub fn compose_analysis_run_idempotency_lookup_cli_http( + invocation: &AnalysisRunIdempotencyLookupCliInvocation, +) -> Result { + invocation.validate()?; + let encoded_key = encode_path_segment(&invocation.idempotency_key); + let path = format!( + "{NARUON_ANALYSIS_RUN_PATH}/{ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_PREFIX}/{encoded_key}" + ); + Ok(format!( + "GET {path} HTTP/1.1\r\nHost: {}\r\ncontent-type: application/json\r\ntepp-consumer: {}\r\ntepp-contract-version: 1\r\ncontent-length: 0\r\n\r\n", + invocation.host, invocation.consumer + )) +} + +/// Dispatch one lookup CLI invocation against an in-process loopback service. +/// +/// # Errors +/// +/// Returns fail-closed validation errors before the HTTP handler runs. +pub fn dispatch_analysis_run_idempotency_lookup_cli( + service: &mut AnalysisRunLiveService, + invocation: &AnalysisRunIdempotencyLookupCliInvocation, +) -> Result { + let request = compose_analysis_run_idempotency_lookup_cli_http(invocation)?; + Ok(service.handle_http_request(&request)) +} + +/// Execute one lookup CLI invocation over loopback TCP against `tepp-loopback`. +/// +/// # Errors +/// +/// Returns fail-closed validation, transport, or response-framing errors. +pub fn execute_analysis_run_idempotency_lookup_cli( + invocation: &AnalysisRunIdempotencyLookupCliInvocation, +) -> Result { + let addr = require_loopback_host(&invocation.host)?; + let request = compose_analysis_run_idempotency_lookup_cli_http(invocation)?; + let mut stream = TcpStream::connect(addr).map_err(|error| map_io_error(&error))?; + stream + .set_read_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .set_write_timeout(Some(NARUON_LIVE_IO_TIMEOUT)) + .map_err(|error| map_io_error(&error))?; + stream + .write_all(request.as_bytes()) + .map_err(|error| map_io_error(&error))?; + stream.flush().map_err(|error| map_io_error(&error))?; + let mut bytes = Vec::new(); + stream + .read_to_end(&mut bytes) + .map_err(|error| map_io_error(&error))?; + parse_http_response(&bytes) +} + +/// Filter CLI stdout so lookup never prints scientific acceptance. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when the body is empty, carries +/// metric keys or the scientific-acceptance schema, or identities do not match +/// the invocation. +pub fn render_analysis_run_idempotency_lookup_cli_stdout( + invocation: &AnalysisRunIdempotencyLookupCliInvocation, + response: &NaruonLiveResponse, +) -> Result { + invocation.validate()?; + if response.body.is_empty() { + return Err(ApiError::InvalidWirePayload); + } + refuse_scientific_acceptance(&response.body)?; + refuse_metrics_on_idempotency_lookup_payload(&response.body)?; + if !(200..300).contains(&response.status_code) { + return Ok(response.body.clone()); + } + let lookup = AnalysisRunIdempotencyLookup::from_json(&response.body)?; + if lookup.idempotency_key != invocation.idempotency_key { + return Err(ApiError::InvalidWirePayload); + } + lookup.to_json() +} + +fn refuse_scientific_acceptance(body: &str) -> Result<(), ApiError> { + if body.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA) { + Err(ApiError::InvalidWirePayload) + } else { + Ok(()) + } +} + +fn parse_http_response(bytes: &[u8]) -> Result { + let text = std::str::from_utf8(bytes).map_err(|_| ApiError::InvalidWirePayload)?; + let (header_block, body) = text + .split_once("\r\n\r\n") + .ok_or(ApiError::InvalidWirePayload)?; + let mut lines = header_block.split("\r\n"); + let status_line = lines.next().ok_or(ApiError::InvalidWirePayload)?; + let mut parts = status_line.split(' '); + if parts.next() != Some("HTTP/1.1") { + return Err(ApiError::InvalidWirePayload); + } + let code = parts + .next() + .ok_or(ApiError::InvalidWirePayload)? + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?; + let reason_phrase = static_reason(code)?; + let mut content_length = None; + for line in lines { + let (name, value) = line.split_once(':').ok_or(ApiError::InvalidWirePayload)?; + if name.eq_ignore_ascii_case("content-length") { + if content_length.is_some() { + return Err(ApiError::InvalidWirePayload); + } + content_length = Some( + value + .trim() + .parse::() + .map_err(|_| ApiError::InvalidWirePayload)?, + ); + } + } + let declared = content_length.ok_or(ApiError::InvalidWirePayload)?; + if declared != body.len() { + return Err(ApiError::InvalidWirePayload); + } + Ok(NaruonLiveResponse { + status_code: code, + reason_phrase, + body: body.to_owned(), + }) +} + +fn static_reason(code: u16) -> Result<&'static str, ApiError> { + match code { + 200 => Ok("OK"), + 202 => Ok("Accepted"), + 400 => Ok("Bad Request"), + 403 => Ok("Forbidden"), + 413 => Ok("Payload Too Large"), + 422 => Ok("Unprocessable Entity"), + _ => Err(ApiError::InvalidWirePayload), + } +} + +/// Read stdin leftover bytes on a non-terminal; lookup GET refuses a body. +/// +/// # Errors +/// +/// Returns [`ApiError::InvalidWirePayload`] when stdin cannot be read. +pub fn read_analysis_run_idempotency_lookup_cli_stdin( + stdin_is_terminal: bool, + mut stdin: impl Read, +) -> Result { + if stdin_is_terminal { + Ok(String::new()) + } else { + let mut body = String::new(); + stdin + .read_to_string(&mut body) + .map_err(|_| ApiError::InvalidWirePayload)?; + Ok(body) + } +} + +#[cfg(test)] +#[allow(clippy::too_many_lines)] +mod tests { + use super::{ + AnalysisRunIdempotencyLookupCliInvocation, AnalysisRunIdempotencyLookupCliVerb, + SCIENTIFIC_ACCEPTANCE_SCHEMA, compose_analysis_run_idempotency_lookup_cli_http, + dispatch_analysis_run_idempotency_lookup_cli, execute_analysis_run_idempotency_lookup_cli, + parse_http_response, read_analysis_run_idempotency_lookup_cli_stdin, + render_analysis_run_idempotency_lookup_cli_stdout, static_reason, + }; + use crate::{ + ANALYSIS_RUN_CONTRACT_VERSION, ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN, + AnalysisRunAccepted, AnalysisRunIdempotencyLookup, AnalysisRunLiveService, + AnalysisRunRequest, AnalysisRunStatusState, ApiError, LINEAGEWEAVE_CONSUMER_CODE, + NARUON_CONSUMER_CODE, NaruonLiveResponse, + }; + + fn request(idempotency_key: &str) -> AnalysisRunRequest { + AnalysisRunRequest { + contract_version: ANALYSIS_RUN_CONTRACT_VERSION, + idempotency_key: idempotency_key.into(), + tenant_workspace_id: "cli-lookup-tenant".into(), + snapshot_id: "cli-lookup-snapshot".into(), + knowledge_cutoff: "2026-08-01T00:00:00Z".into(), + model_contract_version: "tepp-analysis-run-v1".into(), + output_profile: "calibrated_event_measurement".into(), + } + } + + fn create_http(run: &AnalysisRunRequest, consumer: &str, host: &str) -> String { + let body = run.to_json().expect("json"); + format!( + "POST /v1/analysis-runs HTTP/1.1\r\nHost: {host}\r\ncontent-type: application/json\r\ntepp-consumer: {consumer}\r\ntepp-contract-version: 1\r\nidempotency-key: {}\r\ncontent-length: {}\r\n\r\n{body}", + run.idempotency_key, + body.len() + ) + } + + fn lookup_invocation(key: &str) -> AnalysisRunIdempotencyLookupCliInvocation { + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + key, + ], + "", + ) + .expect("lookup") + } + + #[test] + fn verbs_parse_and_reject_unknown_tokens() { + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("lookup").expect("verb"), + AnalysisRunIdempotencyLookupCliVerb::Lookup + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::Lookup.as_str(), + "lookup" + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("LOOKUP"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("stored-request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("retry"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("list"), + Err(ApiError::InvalidWirePayload) + ); + } + + #[test] + fn from_args_refuses_empty_unknown_host_and_credential_flags() { + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args(Vec::::new(), "") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args(["lookup"], "").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "8.8.8.8:80", + "--idempotency-key", + "idem-1" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--authorization", + "secret" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--github-token", + "secret" + ], + "" + ) + .unwrap_err(), + ApiError::AuthorizationDenied + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + "{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--consumer", + "other" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + &"a".repeat(ANALYSIS_RUN_IDEMPOTENCY_LOOKUP_KEY_MAX_LEN + 1) + ], + "" + ) + .unwrap_err(), + ApiError::LimitExceeded + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--run-id", + "tepp-run-1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + "--page-limit", + "1" + ], + "" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn lookup_assembles_default_consumer_and_encoded_path() { + let lookup = lookup_invocation("idem-1"); + assert_eq!(lookup.verb, AnalysisRunIdempotencyLookupCliVerb::Lookup); + assert_eq!(lookup.consumer, NARUON_CONSUMER_CODE); + let http = compose_analysis_run_idempotency_lookup_cli_http(&lookup).expect("http"); + assert!(http.starts_with("GET /v1/analysis-runs/by-idempotency/idem-1 HTTP/1.1")); + assert!(http.contains("tepp-consumer: naruon")); + assert!(http.contains("content-length: 0")); + assert!(!http.contains("authorization")); + assert!(!http.contains("idempotency-key:")); + assert!(!http.contains("/cancel")); + assert!(!http.contains("/retry")); + assert!(!http.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + + let encoded = lookup_invocation("key/../../etc"); + let encoded_http = + compose_analysis_run_idempotency_lookup_cli_http(&encoded).expect("encoded"); + assert!( + encoded_http + .contains("GET /v1/analysis-runs/by-idempotency/key%2F..%2F..%2Fetc HTTP/1.1") + ); + + let lw = AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + "idem-1", + ], + "", + ) + .expect("lw"); + let lw_http = compose_analysis_run_idempotency_lookup_cli_http(&lw).expect("lw http"); + assert!(lw_http.contains("tepp-consumer: lineageweave")); + } + + #[test] + fn dispatch_resolves_accepted_without_leaking_metrics_or_other_consumers() { + let mut service = AnalysisRunLiveService::new(); + let first = request("cli-lookup-idem-1"); + let created = service.handle_http_request(&create_http( + &first, + NARUON_CONSUMER_CODE, + "127.0.0.1:18081", + )); + assert_eq!(created.status_code, 202); + let accepted = AnalysisRunAccepted::from_json(&created.body).expect("accepted"); + let invocation = lookup_invocation("cli-lookup-idem-1"); + let got = dispatch_analysis_run_idempotency_lookup_cli(&mut service, &invocation) + .expect("lookup"); + assert_eq!(got.status_code, 200); + let stdout = + render_analysis_run_idempotency_lookup_cli_stdout(&invocation, &got).expect("stdout"); + assert!(!stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!stdout.contains("rmse")); + assert!(!stdout.contains("terminal_result")); + assert!(!stdout.contains("tenant_workspace_id")); + assert!(!stdout.contains("snapshot_id")); + let lookup = AnalysisRunIdempotencyLookup::from_json(&stdout).expect("lookup"); + assert_eq!(lookup.run_id, accepted.run_id); + assert_eq!(lookup.run_state, AnalysisRunStatusState::Accepted); + assert_eq!(lookup.idempotency_key, first.idempotency_key); + + let other = AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--consumer", + LINEAGEWEAVE_CONSUMER_CODE, + "--idempotency-key", + "cli-lookup-idem-1", + ], + "", + ) + .expect("other"); + let isolated = + dispatch_analysis_run_idempotency_lookup_cli(&mut service, &other).expect("isolated"); + assert_eq!(isolated.status_code, 400); + let isolated_stdout = + render_analysis_run_idempotency_lookup_cli_stdout(&other, &isolated).expect("out"); + assert!(!isolated_stdout.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert!(!isolated_stdout.contains(&accepted.run_id)); + } + + #[test] + fn render_refuses_metrics_schema_and_empty_bodies() { + let lookup = lookup_invocation("idem-1"); + assert_eq!( + render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: String::new(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"idem-1","rmse":1.0}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: format!(r#"{{"schema_version":"{SCIENTIFIC_ACCEPTANCE_SCHEMA}"}}"#), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + let error_stdout = render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 400, + reason_phrase: "Bad Request", + body: r#"{"error_code":"invalid_wire_payload"}"#.into(), + }, + ) + .expect("error"); + assert!(error_stdout.contains("invalid_wire_payload")); + let ok = render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"idem-1"}"#.into(), + }, + ) + .expect("ok"); + assert!(ok.contains("\"run_id\":\"tepp-run-1\"")); + assert!(!ok.contains(SCIENTIFIC_ACCEPTANCE_SCHEMA)); + assert_eq!( + render_analysis_run_idempotency_lookup_cli_stdout( + &lookup, + &NaruonLiveResponse { + status_code: 200, + reason_phrase: "OK", + body: r#"{"contract_version":1,"run_id":"tepp-run-1","run_state":"accepted","idempotency_key":"other"}"#.into(), + } + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn execute_over_tcp_and_parse_response_failures() { + let mut service = AnalysisRunLiveService::bind_loopback().expect("bind"); + let addr = service.local_addr().expect("addr"); + let created = service.handle_http_request(&create_http( + &request("cli-lookup-tcp"), + NARUON_CONSUMER_CODE, + &addr.to_string(), + )); + assert_eq!(created.status_code, 202); + let handle = std::thread::spawn(move || { + drop(service.serve_one()); + }); + let mut invocation = lookup_invocation("cli-lookup-tcp"); + invocation.host = addr.to_string(); + let response = execute_analysis_run_idempotency_lookup_cli(&invocation).expect("tcp"); + assert_eq!(response.status_code, 200); + handle.join().expect("join"); + + invocation.host = "127.0.0.1:1".into(); + assert_eq!( + execute_analysis_run_idempotency_lookup_cli(&invocation).unwrap_err(), + ApiError::InvalidWirePayload + ); + + let parsed = + parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\n{}").expect("parse"); + assert_eq!(parsed.status_code, 200); + assert_eq!( + parse_http_response(b"not-http").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.0 200 OK\r\ncontent-length: 2\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 299 Mystery\r\ncontent-length: 2\r\n\r\n{}") + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response( + b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\ncontent-length: 2\r\n\r\n{}" + ) + .unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-length: 9\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\nbad-header\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(&[0xff, 0xfe]).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!(static_reason(200).expect("200"), "OK"); + assert_eq!(static_reason(202).expect("202"), "Accepted"); + assert_eq!(static_reason(400).expect("400"), "Bad Request"); + assert_eq!(static_reason(403).expect("403"), "Forbidden"); + assert_eq!(static_reason(413).expect("413"), "Payload Too Large"); + assert_eq!(static_reason(422).expect("422"), "Unprocessable Entity"); + assert_eq!( + static_reason(500).unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1\r\ncontent-length: 0\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 abc OK\r\ncontent-length: 0\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\ncontent-length: x\r\n\r\n").unwrap_err(), + ApiError::InvalidWirePayload + ); + assert_eq!( + parse_http_response(b"HTTP/1.1 200 OK\r\nhost: 127.0.0.1\r\n\r\n{}").unwrap_err(), + ApiError::InvalidWirePayload + ); + } + + #[test] + fn stdin_reader_skips_terminal_and_reads_otherwise() { + let empty = + read_analysis_run_idempotency_lookup_cli_stdin(true, std::io::empty()).expect("tty"); + assert!(empty.is_empty()); + let piped = read_analysis_run_idempotency_lookup_cli_stdin( + false, + std::io::Cursor::new(b"leftover"), + ) + .expect("piped"); + assert_eq!(piped, "leftover"); + let piped_empty = + read_analysis_run_idempotency_lookup_cli_stdin(false, std::io::Cursor::new(b"")) + .expect("empty"); + assert!(piped_empty.is_empty()); + } +} diff --git a/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs b/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs index 6ee79d802..6ce29fc5b 100644 --- a/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs +++ b/crates/tepp_api/src/analysis_run_idempotency_lookup_http.rs @@ -235,7 +235,7 @@ pub fn naruon_analysis_run_idempotency_lookup_exchange( }) } -fn encode_path_segment(value: &str) -> String { +pub(crate) 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() { diff --git a/crates/tepp_api/src/bin/tepp_analysis_runs.rs b/crates/tepp_api/src/bin/tepp_analysis_runs.rs new file mode 100644 index 000000000..a292b0d3d --- /dev/null +++ b/crates/tepp_api/src/bin/tepp_analysis_runs.rs @@ -0,0 +1,39 @@ +//! Operator CLI for loopback analysis-run idempotency-key lookup GET. + +use std::io::{self, IsTerminal}; +use std::process::ExitCode; + +use tepp_api::{ + AnalysisRunIdempotencyLookupCliInvocation, ApiError, + execute_analysis_run_idempotency_lookup_cli, read_analysis_run_idempotency_lookup_cli_stdin, + render_analysis_run_idempotency_lookup_cli_stdout, +}; + +fn main() -> ExitCode { + match run() { + Ok(()) => ExitCode::SUCCESS, + Err(_) => ExitCode::FAILURE, + } +} + +fn run() -> Result<(), ApiError> { + let args: Vec = std::env::args().skip(1).collect(); + match args.first().map(String::as_str) { + Some("lookup") => run_lookup(&args), + _ => Err(ApiError::InvalidWirePayload), + } +} + +fn run_lookup(args: &[String]) -> Result<(), ApiError> { + let body = + read_analysis_run_idempotency_lookup_cli_stdin(io::stdin().is_terminal(), io::stdin())?; + let invocation = AnalysisRunIdempotencyLookupCliInvocation::from_args(args, body)?; + let response = execute_analysis_run_idempotency_lookup_cli(&invocation)?; + let stdout = render_analysis_run_idempotency_lookup_cli_stdout(&invocation, &response)?; + println!("{stdout}"); + if (200..300).contains(&response.status_code) { + Ok(()) + } else { + Err(ApiError::InvalidWirePayload) + } +} diff --git a/crates/tepp_api/src/lib.rs b/crates/tepp_api/src/lib.rs index 5a61ab94a..ef78a0a9d 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_cli; mod analysis_run_idempotency_lookup_http; mod analysis_run_live; mod analysis_run_retry_http; @@ -107,6 +108,20 @@ 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; +/// One validated idempotency-lookup CLI invocation. +pub use analysis_run_idempotency_lookup_cli::AnalysisRunIdempotencyLookupCliInvocation; +/// Loopback idempotency-lookup CLI verb. +pub use analysis_run_idempotency_lookup_cli::AnalysisRunIdempotencyLookupCliVerb; +/// Compose loopback lookup GET bytes for a CLI invocation. +pub use analysis_run_idempotency_lookup_cli::compose_analysis_run_idempotency_lookup_cli_http; +/// Dispatch a lookup CLI invocation against an in-process listener. +pub use analysis_run_idempotency_lookup_cli::dispatch_analysis_run_idempotency_lookup_cli; +/// Execute a lookup CLI invocation over loopback TCP. +pub use analysis_run_idempotency_lookup_cli::execute_analysis_run_idempotency_lookup_cli; +/// Read leftover stdin for the lookup CLI. +pub use analysis_run_idempotency_lookup_cli::read_analysis_run_idempotency_lookup_cli_stdin; +/// Render lookup CLI stdout with metric-free gates. +pub use analysis_run_idempotency_lookup_cli::render_analysis_run_idempotency_lookup_cli_stdout; /// 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. diff --git a/crates/tepp_api/tests/analysis_run_idempotency_lookup_cli_contract.rs b/crates/tepp_api/tests/analysis_run_idempotency_lookup_cli_contract.rs new file mode 100644 index 000000000..95b273a36 --- /dev/null +++ b/crates/tepp_api/tests/analysis_run_idempotency_lookup_cli_contract.rs @@ -0,0 +1,67 @@ +//! Contract tests for the analysis-run idempotency-lookup loopback CLI. + +use tepp_api::{ + AnalysisRunIdempotencyLookupCliInvocation, AnalysisRunIdempotencyLookupCliVerb, ApiError, + NARUON_CONSUMER_CODE, compose_analysis_run_idempotency_lookup_cli_http, +}; + +#[test] +fn lookup_cli_is_metric_free_get_without_credentials() { + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("lookup").expect("verb"), + AnalysisRunIdempotencyLookupCliVerb::Lookup + ); + let invocation = AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1", + ], + "", + ) + .expect("invocation"); + assert_eq!(invocation.consumer, NARUON_CONSUMER_CODE); + let http = compose_analysis_run_idempotency_lookup_cli_http(&invocation).expect("http"); + assert!(http.starts_with("GET /v1/analysis-runs/by-idempotency/idem-1 HTTP/1.1")); + assert!(!http.contains("authorization")); + assert!(!http.contains("idempotency-key:")); + assert!(!http.contains("tepp.scientific_acceptance.v1")); + assert!(!http.contains("/cancel")); + assert!(!http.contains("/retry")); +} + +#[test] +fn lookup_cli_refuses_non_loopback_unknown_verbs_and_bodies() { + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "8.8.8.8:80", + "--idempotency-key", + "idem-1" + ], + "" + ), + Err(ApiError::AuthorizationDenied) + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliVerb::parse("stored-request"), + Err(ApiError::InvalidWirePayload) + ); + assert_eq!( + AnalysisRunIdempotencyLookupCliInvocation::from_args( + [ + "lookup", + "--host", + "127.0.0.1:18081", + "--idempotency-key", + "idem-1" + ], + r#"{"rmse":1.0}"# + ), + Err(ApiError::InvalidWirePayload) + ); +} diff --git a/docs/API_CONTRACT.md b/docs/API_CONTRACT.md index dc8620c74..768508ded 100644 --- a/docs/API_CONTRACT.md +++ b/docs/API_CONTRACT.md @@ -100,7 +100,10 @@ can inspect lineage after retry. An empty `retries` array is `200` when the 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 +key without scanning collection pages. The loopback +`tepp-analysis-runs lookup` CLI is the operator-visible client for that GET; +stdout stays metric-free and `tepp.scientific_acceptance.v1` never appears. +GET-by-id remains a later slice on this protected-main lineage. The stacked `analysis_engine` slice provides the first executable service-side diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index ec5ddfc26..729aeb7ab 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -59,6 +59,7 @@ The full APA 7th standards/literature register remains `docs/research/standards- | 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 | +| loopback analysis-run idempotency-key lookup CLI | ADR 0038; API contract; RFC 9110 | `tepp_api` `tepp-analysis-runs lookup` CLI: operator-visible client of `GET /v1/analysis-runs/by-idempotency/{idempotency_key}`; metric-free `run_id`/`run_state`/`idempotency_key`; `tepp.scientific_acceptance.v1` never appears | 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/0038-analysis-run-idempotency-lookup-cli.md b/docs/adr/0038-analysis-run-idempotency-lookup-cli.md new file mode 100644 index 000000000..6d7f07cc6 --- /dev/null +++ b/docs/adr/0038-analysis-run-idempotency-lookup-cli.md @@ -0,0 +1,70 @@ +# ADR 0038 — Analysis-run idempotency-key lookup loopback CLI + +**Decision status:** Accepted +**Implementation maturity:** active-PR +**Date:** 2026-08-31 +**Supersedes:** None; complements ADR 0037 for the operator-visible lookup client. Does not supersede ADR 0014 claim-promotion authority. This ADR number is unique on the lookup lineage; other live PRs may reuse 0038 on unrelated stacks (retry-parent GET). + +## Context + +ADR 0037 serves `GET /v1/analysis-runs/by-idempotency/{idempotency_key}`, but operators still had to write raw HTTP/1.1 to jump from a 202 receipt or retry child key to a durable `run_id`. Duplicating lookup HTTP, stored-request CLI (#395), retry CLI (#394), retry-parent CLI (#400), lifecycle CLI (#397), collection/cancel/create/status CLIs, or GET-by-id would collide with live PRs. + +## Decision + +`tepp_api` publishes a loopback-only `tepp-analysis-runs` CLI on this lookup lineage: + +- `lookup` GETs `/v1/analysis-runs/by-idempotency/{idempotency_key}` with `--idempotency-key`. +- The key travels in the path. The CLI does not send an `idempotency-key` header. +- Empty stdin is required. A nonempty body fails closed. +- Stdout is metric-free `AnalysisRunIdempotencyLookup` JSON. `tepp.scientific_acceptance.v1`, RMSE, bias, coverage, SE-gate, `terminal_result`, `tenant_workspace_id`, and `snapshot_id` never appear. +- Non-loopback hosts, unpublished consumers, credential-shaped flags, `--run-id`, collection pagination flags, unknown verbs, hostile identities, and metric keys on stdout fail closed. +- This slice does not implement lookup HTTP (ADR 0037). +- Persistence, Compose recovery, and psychometric execution remain GAP-003B. + +## Alternatives considered + +1. **Keep raw HTTP as the only lookup path** — rejected because operators still guess framing after ADR 0037. +2. **Add `lookup` onto the live stored-request CLI (#395)** — rejected because that head already owns inspect-by-`run_id`. +3. **Return scientific-acceptance on succeeded lookup** — rejected because lookup bodies must stay metric-free. +4. **Loopback lookup CLI stacked on ADR 0037** — accepted. + +## Consequences + +- Operators can resolve a 202 receipt or retry child key to a durable `run_id` without writing HTTP. +- Lookup stdout cannot be mistaken for a succeeded scientific-acceptance result. +- CLI success is not release evidence. + +## Failure and recovery + +Non-loopback hosts return authorization denied. Unknown verbs, nonempty stdin, unpublished consumers, credential flags, oversized keys, `--run-id`, and collection flags fail closed. Unknown keys and consumer mismatch remain refused by ADR 0037. The in-memory registry is not durable. + +## Security, privacy, scientific-integrity, and governance impact + +- No credential headers cross the consumer boundary. +- The CLI remains loopback-only and size-bounded. +- Process exit 0 on a lookup is not measurement evidence and is not an ADR 0014 claim. + +## Compatibility and migration + +Lookup GET HTTP, create POST, cancel POST, retry POST, collection GET, stored-request GET, retry-lineage GET, temporal-context, and project-history paths are unchanged. The collection/cancel/create `tepp-analysis-runs` verbs live on a parallel stack and merge by combining verbs. + +## Verification + +Falsifiable evidence: + +- CLI lookup of an accepted run returns `run_id`/`run_state`/`idempotency_key` with no RMSE/bias/coverage/SE-gate/`tepp.scientific_acceptance.v1` keys; +- another consumer cannot resolve the first consumer's key; +- non-loopback host, credential flags, `--run-id`, nonempty stdin, and unknown verbs fail closed; +- Clippy `-D warnings`, `tepp_api` tests, rustdoc, and exact-head review remain required. + +## Rollback and supersession + +Rollback removes the lookup verb and `tepp-analysis-runs` binary from this lineage; lookup GET HTTP remains valid. A superseding ADR is required to persist the registry, bind a public address, emit scientific-acceptance on lookup, or treat CLI success as an ADR 0014 claim. + +## Related authority + +- ADR 0037 owns loopback idempotency-key lookup GET. +- ADR 0018 owns consumer-scoped ingress and metric-free `202 Accepted`. +- 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 a206d0df7..a75e5d07a 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -36,6 +36,7 @@ Read [`ADR_POLICY.md`](ADR_POLICY.md) first. **Decision status and implementatio | [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. | +| [0038](0038-analysis-run-idempotency-lookup-cli.md) | Loopback `tepp-analysis-runs lookup` is idempotency-key lookup GET client | Accepted | active-PR | Complements ADR 0037; does not supersede ADR 0014. Unique on lookup lineage. | | [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. | @@ -152,6 +153,7 @@ Use the narrowest owning ADR when decisions overlap: - **analysis-run stored-request GET:** ADR 0034. - **analysis-run retry-lineage GET:** ADR 0035. - **analysis-run idempotency-key lookup GET:** ADR 0037. +- **analysis-run idempotency-key lookup CLI:** ADR 0038. ## Change and supersession rule diff --git a/docs/connectors/naruon-artifact-consumer.md b/docs/connectors/naruon-artifact-consumer.md index 5bdc328a1..0544c78b9 100644 --- a/docs/connectors/naruon-artifact-consumer.md +++ b/docs/connectors/naruon-artifact-consumer.md @@ -28,6 +28,7 @@ TEPP remains the scientific authority for estimation, recovery metrics, temporal | HTTP analysis-run create | `tepp_api` `naruon_analysis_run_exchange` → `POST /v1/analysis-runs` | naruon → TEPP | | HTTP analysis-run collection | `tepp_api` `naruon_analysis_run_collection_exchange` → `GET /v1/analysis-runs` | naruon → TEPP | | HTTP analysis-run cancel | `tepp_api` `naruon_analysis_run_cancel_exchange` → `POST /v1/analysis-runs/{run_id}/cancel` | naruon → TEPP | +| CLI analysis-run idempotency lookup | `tepp_api` `tepp-analysis-runs lookup` → loopback `GET /v1/analysis-runs/by-idempotency/{idempotency_key}` | naruon → TEPP | | HTTP export authorize | `tepp_api` `naruon_export_exchange` → `POST /v1/exports` | naruon → TEPP | | Live loopback POST | `tepp_api` `NaruonLiveService` → `POST /v1/analysis-runs` and `/v1/exports` | naruon → TEPP | diff --git a/docs/research/analysis-run-idempotency-lookup-cli.md b/docs/research/analysis-run-idempotency-lookup-cli.md new file mode 100644 index 000000000..f58133cc1 --- /dev/null +++ b/docs/research/analysis-run-idempotency-lookup-cli.md @@ -0,0 +1,58 @@ +# Analysis-run idempotency-lookup CLI (doctoring) + +## Scope + +`tepp-analysis-runs lookup` is the operator-visible client of loopback +`GET /v1/analysis-runs/by-idempotency/{idempotency_key}`. HTTP method, path, +and header semantics follow current HTTP semantics (Fielding, Nottingham, & +Reschke, 2022). Fail-closed refusal of non-loopback hosts, unpublished +consumers, review/Copilot/GitHub credential flags, and scientific-authority +promotion is repository contract authority (ADR 0038; ADR 0037; ADR 0018; +ADR 0011), not an RFC inference rule. + +CLI stdout is metric-free `AnalysisRunIdempotencyLookup` JSON. `run_id`, +`run_state`, and `idempotency_key` are inspectable. +`tepp.scientific_acceptance.v1` never appears. Process exit 0 is not a +completed temporal model, calibrated score, theta estimate, uncertainty +statement, or scientific claim. + +## Authority + +### External standards (HTTP only) + +Fielding, R., Nottingham, M., & Reschke, J. (Eds.). (2022). *HTTP semantics* +(RFC 9110). IETF. https://doi.org/10.17487/RFC9110 + +RFC 9110 §9.3.1 describes GET as a method for retrieving a representation of +the target resource. TEPP maps that retrieval onto a bounded, consumer-scoped +resolve 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/0038-analysis-run-idempotency-lookup-cli.md` — this client +- `docs/adr/0037-analysis-run-idempotency-lookup-get.md` — lookup GET listener +- `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` — CLI + success is not a scientific claim +- `docs/API_CONTRACT.md` — documented lookup resource +- `crates/tepp_api/tests/analysis_run_idempotency_lookup_cli_contract.rs` — + fail-closed lookup CLI proofs + +## Verification + +- `tepp-analysis-runs lookup` of an accepted run returns metric-free + `run_id`/`run_state`/`idempotency_key` without RMSE/bias/coverage/SE-gate + keys or `tepp.scientific_acceptance.v1`; +- another consumer cannot resolve the first consumer's key; +- non-loopback hosts, credential flags, `--run-id`, collection pagination + flags, nonempty stdin, and unknown verbs fail closed; +- review, Copilot, GitHub, and bearer flags remain `AuthorizationDenied`. + +## Non-claims + +This slice does not implement lookup GET HTTP, stored-request CLI, retry CLI, +retry-parent CLI, collection GET, collection CLI list, cancel HTTP, cancel +CLI, create CLI, status CLI, GET-by-id, persistence, production TLS, Leiden +consensus, or an ADR 0014 scientific claim-promotion package.