From 4c7371a618173f8f66ac24f50cd5abb529fe1764 Mon Sep 17 00:00:00 2001 From: Alex <47092487+ooodummy@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:09:07 -0500 Subject: [PATCH 1/2] fix(client): preserve structured read failures and retry hints - Decode native JSON and paginated failures without requiring success data or page fields. - Preserve native error codes, full diagnostics and Retry-After through fallback and forbidden response paths. - Add seven offline regressions covering MCP guidance, unchanged success shapes and no extra retries. --- README.md | 8 ++ src/client/failure.rs | 13 +-- src/client/failure/tests.rs | 154 +++++++++++++++++++++++++++++++++++- src/client/mod.rs | 16 ++-- src/client/retry.rs | 2 + src/client/retry/tests.rs | 24 ++++++ 6 files changed, 202 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index fb7185a..7a19167 100644 --- a/README.md +++ b/README.md @@ -151,6 +151,14 @@ most 5 seconds for a first index before it reports that the index is still running. The edit actions have no deadline: a limit that fired after the files changed would report a failed edit that was applied. +Failed reads preserve the server's error code, message, details, and +`Retry-After` delay. This applies to normal error envelopes, bare JSON errors, +and paginated errors without success data or page fields. A typed `409` +`GraphLoading` or `FileLoading` failure gives one delayed retry as the next +step, then local Read/Grep if that call also fails. Other failures keep their +own guidance. This error decoding does not repair the server's graph or add +request retries. + The `index_codebase` tool does not wait for the first index. It registers the codebase, starts the scan and upload in the background, and returns at once with the codebase id and the path. The `sync_status` tool then reports the first-index diff --git a/src/client/failure.rs b/src/client/failure.rs index 470feb2..f922c80 100644 --- a/src/client/failure.rs +++ b/src/client/failure.rs @@ -125,19 +125,20 @@ pub(super) fn summarize_errors(errors: &[serde_json::Value]) -> String { .join("; ") } -/// Preserve a structured JSON denial even when it is not wrapped in the -/// resource server's usual API envelope. Tenant binding failures can be emitted -/// by middleware before controller envelope handling runs. +/// Preserve a structured JSON failure even when it does not match the +/// endpoint's success envelope. Errors can omit success data and page fields, +/// or arrive as bare objects from middleware. pub(super) fn response_body_error( method: &str, url: &str, status: StatusCode, + retry_after: Option, body: &str, ) -> anyhow::Error { let Ok(parsed) = serde_json::from_str::(body) else { - return gateway_error(method, url, status, None, body); + return gateway_error(method, url, status, retry_after, body); }; - // The denial is either the envelope or a bare error object. + // The failure is either the envelope or a bare error object. let errors = parsed .get("errors") .and_then(serde_json::Value::as_array) @@ -145,7 +146,7 @@ pub(super) fn response_body_error( anyhow::Error::new(ApiFailure::new( status, first_error_code(errors), - None, + retry_after, format!("{method} {url} -> {status}: {body}"), )) } diff --git a/src/client/failure/tests.rs b/src/client/failure/tests.rs index 8e10785..4f87eb2 100644 --- a/src/client/failure/tests.rs +++ b/src/client/failure/tests.rs @@ -2,11 +2,13 @@ use std::fmt::Write as _; use std::time::Duration; use reqwest::StatusCode; +use rmcp::handler::server::tool::IntoCallToolResult; use serde_json::json; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use super::{ApiFailure, first_error_code, gateway_error, response_body_error, retry_after}; use crate::client::{unwrap_envelope, unwrap_page}; +use crate::query::ToolError; /// Answer one local request with a fixed HTTP response, and return what a /// client reads from it. The test needs no network beyond the loopback. @@ -208,15 +210,23 @@ fn a_structured_denial_keeps_its_code() { "GET", url, StatusCode::FORBIDDEN, + None, r#"{"success":false,"errors":[{"code":"TenantBindingDenied"}]}"#, ); let bare = response_body_error( "GET", url, StatusCode::FORBIDDEN, + None, r#"{"code":"TenantBindingDenied","message":"denied"}"#, ); - let page = response_body_error("GET", url, StatusCode::FORBIDDEN, "forbidden"); + let page = response_body_error( + "GET", + url, + StatusCode::FORBIDDEN, + None, + "forbidden", + ); assert_eq!( typed(&enveloped).code.as_deref(), @@ -263,3 +273,145 @@ fn only_a_conflict_with_a_loading_code_is_a_loading_state() { assert!(!failure(StatusCode::CONFLICT, None).is_loading()); assert!(!failure(StatusCode::BAD_GATEWAY, Some("GraphLoading")).is_loading()); } + +#[tokio::test] +async fn a_bare_loading_error_keeps_native_details_and_mcp_retry_guidance() { + let body = r#"{"code":"GraphLoading","details":"The native graph of the selected immutable snapshot is not ready.","message":"This code graph is still loading from storage. Retry shortly."}"#; + for paged in [false, true] { + for (headers, seconds) in [(vec![], 1), (vec![("Retry-After", "3")], 3)] { + let (response, url) = answered("409 Conflict", &headers, body).await; + let error = if paged { + unwrap_page::(response, "GET", &url) + .await + .unwrap_err() + } else { + unwrap_envelope::(response, "GET", &url) + .await + .unwrap_err() + }; + + let failure = typed(&error); + assert_eq!(failure.status(), StatusCode::CONFLICT); + assert_eq!(failure.code.as_deref(), Some("GraphLoading")); + assert_eq!( + failure.retry_after(), + (!headers.is_empty()).then_some(Duration::from_secs(seconds)) + ); + let failed: Result = + Err(ToolError::from_client("find_definition", &error)); + let result = failed.into_call_tool_result().unwrap(); + assert_eq!(result.is_error, Some(true)); + assert_eq!(result.content.len(), 1); + assert_eq!( + result.content[0].as_text().unwrap().text, + format!( + "find_definition failed: GET {url} -> 409 Conflict: {body}\n\ + next: retry this call once after {seconds} s. If it fails again, \ + use local Read/Grep for this request." + ) + ); + } + } +} + +#[tokio::test] +async fn a_paged_error_needs_no_success_data_or_page_fields() { + let body = r#"{"success":false,"errors":[{"code":"FileLoading","message":"loading","details":"The selected file is not ready."}]}"#; + let (response, url) = answered("409 Conflict", &[("Retry-After", "2")], body).await; + let error = unwrap_page::(response, "GET", &url) + .await + .unwrap_err(); + + assert_eq!(typed(&error).code.as_deref(), Some("FileLoading")); + assert_eq!(typed(&error).retry_after(), Some(Duration::from_secs(2))); + assert_eq!( + ToolError::from_client("list_files", &error).to_string(), + format!( + "list_files failed: GET {url} -> 409 Conflict: {body}\n\ + next: retry this call once after 2 s. If it fails again, \ + use local Read/Grep for this request." + ) + ); +} + +#[tokio::test] +async fn failure_decoding_does_not_require_the_success_data_type() { + let body = r#"{"success":false,"errors":[{"code":"FileLoading","details":"File not ready."}],"data":{}}"#; + let (response, url) = answered("409 Conflict", &[("Retry-After", "2")], body).await; + let error = unwrap_envelope::>(response, "GET", &url) + .await + .unwrap_err(); + + assert_eq!(typed(&error).code.as_deref(), Some("FileLoading")); + assert_eq!(typed(&error).retry_after(), Some(Duration::from_secs(2))); + assert!( + ToolError::from_client("read_source", &error) + .to_string() + .contains(body) + ); +} + +#[tokio::test] +async fn a_bare_conflict_without_a_loading_code_keeps_local_fallback_guidance() { + for body in [ + r#"{"code":"SnapshotMismatch","message":"GraphLoading is not the cause."}"#, + r#"{"message":"GraphLoading is not a typed code here."}"#, + ] { + let (response, url) = answered("409 Conflict", &[("Retry-After", "2")], body).await; + let error = unwrap_envelope::(response, "GET", &url) + .await + .unwrap_err(); + + assert!(!typed(&error).is_loading()); + assert_eq!(typed(&error).retry_after(), Some(Duration::from_secs(2))); + assert_eq!( + ToolError::from_client("trace", &error).to_string(), + format!( + "trace failed: GET {url} -> 409 Conflict: {body}\n\ + next: use local Read/Grep for this request." + ) + ); + } +} + +#[tokio::test] +async fn a_paged_plain_text_gateway_error_keeps_its_cause_and_delay() { + let (response, url) = answered( + "503 Service Unavailable", + &[("Retry-After", "7")], + "upstream unavailable", + ) + .await; + let error = unwrap_page::(response, "GET", &url) + .await + .unwrap_err(); + + assert_eq!(typed(&error).status(), StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(typed(&error).code, None); + assert_eq!(typed(&error).retry_after(), Some(Duration::from_secs(7))); + let text = ToolError::from_client("list_files", &error).to_string(); + assert!(text.contains("the server is unavailable behind the gateway")); + assert!(text.contains("response was not JSON: \"upstream unavailable\"")); + assert!(text.ends_with("next: use local Read/Grep for this request.")); +} + +#[tokio::test] +async fn success_responses_keep_standard_and_legacy_data_shapes() { + let (response, url) = answered("200 OK", &[], r#"{"success":true,"data":["ok"]}"#).await; + assert_eq!( + unwrap_envelope::>(response, "GET", &url) + .await + .unwrap(), + ["ok"] + ); + for field in ["data", "items"] { + let body = + format!(r#"{{"success":true,"{field}":["ok"],"page":1,"pageSize":25,"total":1}}"#); + let (response, url) = answered("200 OK", &[], &body).await; + let page = unwrap_page::(response, "GET", &url).await.unwrap(); + assert_eq!(page.items, ["ok"]); + assert_eq!(page.number, 1); + assert_eq!(page.size, 25); + assert_eq!(page.total, 1); + } +} diff --git a/src/client/mod.rs b/src/client/mod.rs index b9807ff..7594f0c 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -31,7 +31,7 @@ pub(crate) mod stub; pub(crate) mod transport; mod truncation; -use failure::gateway_error; +use failure::response_body_error; use retry::Idempotency; pub(crate) use failure::ApiFailure; @@ -641,10 +641,10 @@ async fn read_envelope( .text() .await .with_context(|| format!("{method} {url}: read body"))?; - // Not the envelope: attribute it to whatever answered instead of blaming - // the parser. See `gateway_error`. + // A native failure need not have the endpoint's success shape. Preserve + // its code, full JSON body, and delay before considering a gateway error. let Ok(envelope) = serde_json::from_str::>(&body) else { - return Err(gateway_error(method, url, status, retry_after, &body)); + return Err(response_body_error(method, url, status, retry_after, &body)); }; if !status.is_success() || !envelope.success { let errors = envelope.errors.as_deref().unwrap_or_default(); @@ -680,9 +680,8 @@ async fn unwrap_page( .text() .await .with_context(|| format!("{method} {url}: read body"))?; - let env: PageEnvelope = serde_json::from_str(&body).with_context(|| { - format!("{method} {url} -> {status}: parse paginated envelope ({body})") - })?; + let env: PageEnvelope = serde_json::from_str(&body) + .map_err(|_| response_body_error(method, url, status, retry_after, &body))?; if !status.is_success() || !env.success { let errors = env.errors.as_deref().unwrap_or_default(); return Err(ApiFailure::from_errors(method, url, status, retry_after, errors).into()); @@ -797,8 +796,9 @@ mod tests { use serde::Deserialize; + use super::failure::gateway_error; use super::{ - Client, CredentialSource, HttpTransport, PageEnvelope, gateway_error, loading_retry_delay, + Client, CredentialSource, HttpTransport, PageEnvelope, loading_retry_delay, tenant_binding_denied, tenant_selection, }; diff --git a/src/client/retry.rs b/src/client/retry.rs index 4bfdb02..6134f45 100644 --- a/src/client/retry.rs +++ b/src/client/retry.rs @@ -157,6 +157,7 @@ impl Client { return Ok((resp, url)); } + let retry_after = super::failure::retry_after(resp.headers()); let response_body = resp .text() .await @@ -177,6 +178,7 @@ impl Client { method.as_str(), &url, status, + retry_after, &response_body, )); } diff --git a/src/client/retry/tests.rs b/src/client/retry/tests.rs index 70695d3..f96c863 100644 --- a/src/client/retry/tests.rs +++ b/src/client/retry/tests.rs @@ -494,3 +494,27 @@ async fn a_server_that_never_answers_fails_before_the_deadline_and_names_it() { ); assert_eq!(stub.requests(), 1, "a timed-out read is not retried"); } + +#[tokio::test] +async fn a_forbidden_response_keeps_its_delay_without_a_retry() { + let body = + r#"{"code":"AccessDenied","message":"denied","details":"The request is not allowed."}"#; + let stub = Stub::serve(vec![Reply::Answer { + status: "403 Forbidden", + headers: vec![("Retry-After", "7")], + body: body.to_owned(), + }]) + .await; + + let error = client(&stub) + .get::("/v1/probe") + .await + .expect_err("the server refused this request"); + + assert_eq!(failure(&error).status(), reqwest::StatusCode::FORBIDDEN); + assert_eq!(failure(&error).retry_after(), Some(Duration::from_secs(7))); + assert_eq!(stub.requests(), 1); + let text = ToolError::from_client("trace", &error).to_string(); + assert!(text.contains(body)); + assert!(text.ends_with("next: use local Read/Grep for this request.")); +} From 155939b7ba3b0314c94e92e33c4532177ef4b8c4 Mon Sep 17 00:00:00 2001 From: Alex <47092487+ooodummy@users.noreply.github.com> Date: Sun, 15 Nov 2026 14:27:53 -0500 Subject: [PATCH 2/2] fix(ci): satisfy Rust 1.100 Clippy defaults lint - Replace map/unwrap_or_default chains with equivalent lazy map_or_else defaults and borrowed-string map_or values. - Preserve existing behavior and older API compatibility without suppressing warnings or pinning CI to an older compiler. - Verify formatting, Clippy, 585 tests and rustdoc with CI-matching Rust 1.100.0. --- src/auth/mod.rs | 3 +-- src/client/api.rs | 10 ++-------- src/client/mod.rs | 3 +-- src/commands/hook/message.rs | 2 +- src/commands/hook/mod.rs | 6 ++---- src/daemon/client.rs | 2 +- src/query/advanced.rs | 12 ++++++------ src/query/mod.rs | 15 +++++++-------- src/query/render.rs | 6 ++---- tests/sync_uploads.rs | 3 +-- 10 files changed, 24 insertions(+), 38 deletions(-) diff --git a/src/auth/mod.rs b/src/auth/mod.rs index 6272bf2..6f49465 100644 --- a/src/auth/mod.rs +++ b/src/auth/mod.rs @@ -129,8 +129,7 @@ pub async fn fetch_tenants( let envelope: api::TenantsEnvelope = resp.json().await.context("parse tenants response")?; Ok(envelope .data - .map(api::TenantsPage::into_rows) - .unwrap_or_default()) + .map_or_else(Vec::new, api::TenantsPage::into_rows)) } /// Step 1: request a device + user code from identity. Returns the diff --git a/src/client/api.rs b/src/client/api.rs index 07c991d..1149e8d 100644 --- a/src/client/api.rs +++ b/src/client/api.rs @@ -854,10 +854,7 @@ mod tests { ) .expect("the standard envelope must parse"); - let rows = envelope - .data - .map(TenantsPage::into_rows) - .unwrap_or_default(); + let rows = envelope.data.map_or_else(Vec::new, TenantsPage::into_rows); assert_eq!(rows.len(), 1); assert_eq!(rows[0].slug, "napbat"); @@ -874,10 +871,7 @@ mod tests { ) .expect("the older shape must still parse"); - let rows = envelope - .data - .map(TenantsPage::into_rows) - .unwrap_or_default(); + let rows = envelope.data.map_or_else(Vec::new, TenantsPage::into_rows); assert_eq!(rows.len(), 1); assert_eq!(rows[0].slug, "napbat"); diff --git a/src/client/mod.rs b/src/client/mod.rs index 7594f0c..d118556 100644 --- a/src/client/mod.rs +++ b/src/client/mod.rs @@ -422,8 +422,7 @@ impl Client { .get_or_init(|| async { self.get::("/v1/whoami") .await - .map(|whoami| whoami.capabilities) - .unwrap_or_default() + .map_or_else(|_| Vec::new(), |whoami| whoami.capabilities) }) .await; diff --git a/src/commands/hook/message.rs b/src/commands/hook/message.rs index bb857a7..b623a80 100644 --- a/src/commands/hook/message.rs +++ b/src/commands/hook/message.rs @@ -110,7 +110,7 @@ pub fn tier2( ), SearchKind::Content => match classify(pattern) { QueryKind::Symbol => { - let sym = pattern.map(str::trim).unwrap_or_default(); + let sym = pattern.map_or("", str::trim); format!( "For unresolved cross-file evidence about `{sym}`, \ `{prefix}find_definition` / `{prefix}find_references` / \ diff --git a/src/commands/hook/mod.rs b/src/commands/hook/mod.rs index dc19ecc..190c0a6 100644 --- a/src/commands/hook/mod.rs +++ b/src/commands/hook/mod.rs @@ -272,13 +272,11 @@ async fn user_prompt_context(cli: &Cli, input: &HookInput) -> Option { let sym = h .symbol .as_deref() - .map(|s| format!(" {s}")) - .unwrap_or_default(); + .map_or_else(String::new, |s| format!(" {s}")); let lang = h .language .as_deref() - .map(|l| format!(" · {l}")) - .unwrap_or_default(); + .map_or_else(String::new, |l| format!(" · {l}")); writeln!(out, "- {path}{loc}{sym}{lang} ({:.3}){freshness}", h.score) .expect("writing to a String cannot fail"); } diff --git a/src/daemon/client.rs b/src/daemon/client.rs index fb9db3d..32537c7 100644 --- a/src/daemon/client.rs +++ b/src/daemon/client.rs @@ -64,7 +64,7 @@ impl DaemonMode { /// safe for a typo: `auto` serves the session in this process when no /// daemon can serve it. fn parse(raw: Option<&str>) -> Self { - let value = raw.map(str::trim).unwrap_or_default(); + let value = raw.map_or("", str::trim); if value.is_empty() { return Self::Auto; } diff --git a/src/query/advanced.rs b/src/query/advanced.rs index 3118077..c39d084 100644 --- a/src/query/advanced.rs +++ b/src/query/advanced.rs @@ -21,8 +21,10 @@ async fn codebases_for_source(client: &Client, source_id: &str) -> Vec { urlencode(source_id) )) .await - .map(|page| page.items.into_iter().map(|row| row.id).collect()) - .unwrap_or_default() + .map_or_else( + |_| Vec::new(), + |page| page.items.into_iter().map(|row| row.id).collect(), + ) } /// How this codebase's copies relate to the checkout we are standing in. @@ -452,8 +454,7 @@ fn render_type_hierarchy(client: &Client, hierarchy: &api::TypeHierarchy) -> Str hierarchy .caveat .as_deref() - .map(|caveat| format!(" ({caveat})")) - .unwrap_or_default() + .map_or_else(String::new, |caveat| format!(" ({caveat})")) ); writeln!(out, "nodes ({})", hierarchy.nodes.len()).expect("writing to a String cannot fail"); for node in &hierarchy.nodes { @@ -503,8 +504,7 @@ async fn graph_clusters( group .hash .as_deref() - .map(|hash| format!(" hash={hash}")) - .unwrap_or_default() + .map_or_else(String::new, |hash| format!(" hash={hash}")) ) .expect("writing to a String cannot fail"); for hit in &group.chunks { diff --git a/src/query/mod.rs b/src/query/mod.rs index 114ca00..e1dee05 100644 --- a/src/query/mod.rs +++ b/src/query/mod.rs @@ -154,9 +154,9 @@ pub async fn search( .await .map_err(|e| ToolError::from_client("search_codebase", &e))?; // The note leads, so an agent reads it before it reasons from the hits. - let mut out = truncation - .map(|truncation| budget_note(BudgetedResult::Search, &truncation)) - .unwrap_or_default(); + let mut out = truncation.map_or_else(String::new, |truncation| { + budget_note(BudgetedResult::Search, &truncation) + }); if hits.is_empty() { out.push_str("no results"); return Ok(out); @@ -506,9 +506,9 @@ pub async fn grep( .get_budgeted::>(&url) .await .map_err(|e| ToolError::from_client("grep", &e))?; - let mut out = truncation - .map(|truncation| budget_note(BudgetedResult::Grep, &truncation)) - .unwrap_or_default(); + let mut out = truncation.map_or_else(String::new, |truncation| { + budget_note(BudgetedResult::Grep, &truncation) + }); if matches.is_empty() { write!(out, "no matches for `{pattern}`").expect("writing to a String cannot fail"); return Ok(out); @@ -839,8 +839,7 @@ mod tests { let stub = Stub::serve(vec![Reply::Answer { status: "200 OK", headers: value - .map(|value| vec![("X-Semctx-Result-Truncated", value)]) - .unwrap_or_default(), + .map_or_else(Vec::new, |value| vec![("X-Semctx-Result-Truncated", value)]), body: format!(r#"{{"success":true,"data":{data}}}"#), }]) .await; diff --git a/src/query/render.rs b/src/query/render.rs index 9e5edd5..97e3a17 100644 --- a/src/query/render.rs +++ b/src/query/render.rs @@ -289,8 +289,7 @@ pub(super) fn render_hits_inner( let lang = h .language .as_deref() - .map(|l| format!(" {l}")) - .unwrap_or_default(); + .map_or_else(String::new, |l| format!(" {l}")); let score = if show_score { format!(" (score {:.3})", h.score) } else { @@ -312,8 +311,7 @@ pub(super) fn render_hits_inner( let codebase = if show_score { h.codebase_id .as_deref() - .map(|id| format!(" [codebase {id}]")) - .unwrap_or_default() + .map_or_else(String::new, |id| format!(" [codebase {id}]")) } else { String::new() }; diff --git a/tests/sync_uploads.rs b/tests/sync_uploads.rs index 76e03c6..ed0a2fa 100644 --- a/tests/sync_uploads.rs +++ b/tests/sync_uploads.rs @@ -187,8 +187,7 @@ fn respond(stream: &mut TcpStream, request: &Request, reply: &Reply) { } => { let body = "Client Closed Request"; let retry = retry_after - .map(|seconds| format!("Retry-After: {seconds}\r\n")) - .unwrap_or_default(); + .map_or_else(String::new, |seconds| format!("Retry-After: {seconds}\r\n")); write!( stream, "HTTP/1.1 {status} Fixture\r\nContent-Type: text/plain\r\n{retry}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",