Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions src/auth/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 2 additions & 8 deletions src/client/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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");
Expand Down
13 changes: 7 additions & 6 deletions src/client/failure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -125,27 +125,28 @@ 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<Duration>,
body: &str,
) -> anyhow::Error {
let Ok(parsed) = serde_json::from_str::<serde_json::Value>(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)
.map_or(std::slice::from_ref(&parsed), Vec::as_slice);
anyhow::Error::new(ApiFailure::new(
status,
first_error_code(errors),
None,
retry_after,
format!("{method} {url} -> {status}: {body}"),
))
}
Expand Down
154 changes: 153 additions & 1 deletion src/client/failure/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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, "<html>forbidden</html>");
let page = response_body_error(
"GET",
url,
StatusCode::FORBIDDEN,
None,
"<html>forbidden</html>",
);

assert_eq!(
typed(&enveloped).code.as_deref(),
Expand Down Expand Up @@ -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::<serde_json::Value>(response, "GET", &url)
.await
.unwrap_err()
} else {
unwrap_envelope::<serde_json::Value>(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<String, ToolError> =
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::<serde_json::Value>(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::<Vec<String>>(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::<serde_json::Value>(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::<serde_json::Value>(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::<Vec<String>>(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::<String>(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);
}
}
19 changes: 9 additions & 10 deletions src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -422,8 +422,7 @@ impl Client {
.get_or_init(|| async {
self.get::<api::Whoami>("/v1/whoami")
.await
.map(|whoami| whoami.capabilities)
.unwrap_or_default()
.map_or_else(|_| Vec::new(), |whoami| whoami.capabilities)
})
.await;

Expand Down Expand Up @@ -641,10 +640,10 @@ async fn read_envelope<T: DeserializeOwned>(
.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::<ApiEnvelope<T>>(&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();
Expand Down Expand Up @@ -680,9 +679,8 @@ async fn unwrap_page<T: DeserializeOwned>(
.text()
.await
.with_context(|| format!("{method} {url}: read body"))?;
let env: PageEnvelope<T> = serde_json::from_str(&body).with_context(|| {
format!("{method} {url} -> {status}: parse paginated envelope ({body})")
})?;
let env: PageEnvelope<T> = 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());
Expand Down Expand Up @@ -797,8 +795,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,
};

Expand Down
2 changes: 2 additions & 0 deletions src/client/retry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -177,6 +178,7 @@ impl Client {
method.as_str(),
&url,
status,
retry_after,
&response_body,
));
}
Expand Down
24 changes: 24 additions & 0 deletions src/client/retry/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Probe>("/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."));
}
2 changes: 1 addition & 1 deletion src/commands/hook/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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` / \
Expand Down
6 changes: 2 additions & 4 deletions src/commands/hook/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,13 +272,11 @@ async fn user_prompt_context(cli: &Cli, input: &HookInput) -> Option<String> {
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");
}
Expand Down
Loading
Loading