Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(admin): log the failures the server owns instead of only returning them (#692)

Igor Sant'Ana807d188e5c1a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fa333692..03c80d3f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,6 +17,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
now uses the import instead of a prose pointer (#680).
### Fixed
+- Admin requests that fail for a reason the server owns are now logged
+ server-side instead of existing only in the response body. `POST
+ /admin/bootstrap` and the auto-improve routes serialized the error into JSON
+ and told the log nothing, so an upstream provider failure could break every
+ bootstrap while the log showed only the run starting — and a scheduled
+ auto-improve tick, which has no client to print the body, failed with no
+ operator-visible trace at all. A 5xx now emits a `warn!` naming the status,
+ the operation, and the error. A 4xx stays quiet: the caller was told and the
+ caller was at fault, so logging those would let any client fill the log at
+ will (#692).
- The from-source AUR `PKGBUILD` now builds and tests on constrained AUR
builders. Release LTO was disabled (`options=('!debug' '!lto')`) so the
final link no longer gets OOM-killed on low-memory build hosts, and the
diff --git a/Cargo.lock b/Cargo.lock
index f8549b79..861518ec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -225,6 +225,7 @@ dependencies = [
"tokio-util",
"tower",
"tracing",
+ "tracing-subscriber",
]
[[package]]
diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.toml
index 6547f9e4..515dcddb 100644
--- a/crates/ai-memory-mcp/Cargo.toml
+++ b/crates/ai-memory-mcp/Cargo.toml
@@ -51,6 +51,7 @@ flate2.workspace = true
tar.workspace = true
tempfile.workspace = true
tower.workspace = true
+tracing-subscriber.workspace = true
[lints]
workspace = true
diff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rs
index bdd5bb76..579cf167 100644
--- a/crates/ai-memory-mcp/src/admin.rs
+++ b/crates/ai-memory-mcp/src/admin.rs
@@ -1830,9 +1830,24 @@ fn bootstrap_error_response(
BootstrapError::Llm(_) => StatusCode::BAD_GATEWAY,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
+ log_server_error(status, "bootstrap", &e);
(status, Json(serde_json::json!({ "error": e.to_string() })))
}
+/// Record a failure the server owns.
+///
+/// A 5xx says the request was fine and *we* could not serve it, so the reason
+/// belongs in the server's log: the response body reaches one client once and
+/// is gone when its process exits, which is how an upstream provider 404
+/// managed to fail every bootstrap while the log showed only the run starting
+/// (#692). A 4xx stays quiet — the caller was told, and the caller was at
+/// fault.
+fn log_server_error(status: StatusCode, operation: &str, error: &dyn std::fmt::Display) {
+ if status.is_server_error() {
+ warn!(%status, operation, %error, "admin request failed");
+ }
+}
+
/// Build a dry-run [`BootstrapOutcome`] without an LLM by applying the
/// same budget-pruning logic that `Bootstrap::process_sources` would use.
fn dry_run_outcome(
@@ -2290,6 +2305,7 @@ fn auto_improve_error_response(
AutoImproveError::Memory(_) => StatusCode::BAD_REQUEST,
AutoImproveError::Store(_) => StatusCode::INTERNAL_SERVER_ERROR,
};
+ log_server_error(status, "auto-improve", &e);
(status, Json(serde_json::json!({ "error": e.to_string() })))
}
diff --git a/crates/ai-memory-mcp/tests/suite/admin_provider_error_logging.rs b/crates/ai-memory-mcp/tests/suite/admin_provider_error_logging.rs
new file mode 100644
index 00000000..12717403
--- /dev/null
+++ b/crates/ai-memory-mcp/tests/suite/admin_provider_error_logging.rs
@@ -0,0 +1,220 @@
+//! #692: a 5xx built from an upstream provider failure must also reach the
+//! server's own log.
+//!
+//! The failure that motivated this reached the operator as
+//! `502 Bad Gateway: {"error":"provider error 404: 404 page not found"}` and
+//! nowhere else: the server logged the bootstrap starting, then nothing. The
+//! response body is the client's copy of the diagnosis; the log is the
+//! operator's, and only the log survives the CLI process exiting.
+
+use std::io;
+use std::sync::{Arc, Mutex};
+
+use ai_memory_consolidate::{BootstrapSource, SourceKind};
+use ai_memory_llm::{ChatRequest, ChatResponse, LlmError, LlmProvider, LlmResult};
+use ai_memory_mcp::{AdminState, admin_router};
+use ai_memory_store::{DecayParams, Store};
+use ai_memory_wiki::Wiki;
+use axum::body::Body;
+use axum::http::{Request, StatusCode};
+use serde_json::json;
+use tempfile::TempDir;
+use tower::ServiceExt;
+use tracing::Level;
+use tracing_subscriber::fmt::MakeWriter;
+
+/// A provider that fails the way a misdirected base URL does: a real HTTP
+/// 404 whose body is Ollama's plain-text `404 page not found` rather than the
+/// vendor's structured error.
+struct FourOhFourProvider;
+
+#[async_trait::async_trait]
+impl LlmProvider for FourOhFourProvider {
+ fn name(&self) -> &'static str {
+ "gemini"
+ }
+
+ fn model(&self) -> &str {
+ "gemini-3.5-flash-lite"
+ }
+
+ async fn complete(&self, _request: ChatRequest) -> LlmResult<ChatResponse> {
+ Err(provider_404())
+ }
+
+ async fn complete_structured_raw(
+ &self,
+ _request: ChatRequest,
+ _schema: serde_json::Value,
+ ) -> LlmResult<serde_json::Value> {
+ Err(provider_404())
+ }
+}
+
+fn provider_404() -> LlmError {
+ LlmError::Provider {
+ status: 404,
+ body: "404 page not found".into(),
+ }
+}
+
+/// Collects everything a subscriber writes so a test can assert on it.
+#[derive(Clone, Default)]
+struct CapturedLog(Arc<Mutex<Vec<u8>>>);
+
+impl CapturedLog {
+ fn text(&self) -> String {
+ String::from_utf8_lossy(&self.0.lock().unwrap()).into_owned()
+ }
+}
+
+impl io::Write for CapturedLog {
+ fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
+ self.0.lock().unwrap().extend_from_slice(buf);
+ Ok(buf.len())
+ }
+
+ fn flush(&mut self) -> io::Result<()> {
+ Ok(())
+ }
+}
+
+impl<'a> MakeWriter<'a> for CapturedLog {
+ type Writer = Self;
+
+ fn make_writer(&'a self) -> Self::Writer {
+ self.clone()
+ }
+}
+
+async fn make_admin_state(tmp: &TempDir, llm: Option<Arc<dyn LlmProvider>>) -> AdminState {
+ let store = Store::open(tmp.path()).unwrap();
+ let wiki = Wiki::new(tmp.path(), store.writer.clone()).unwrap();
+ let db_path = store.db_path().to_path_buf();
+ AdminState {
+ ingest_metrics: Arc::new(ai_memory_core::IngestMetrics::default()),
+ writer: store.writer.clone(),
+ reader: store.reader.clone(),
+ wiki,
+ llm,
+ auto_improve_require_approval: false,
+ auto_improve_review_config: Default::default(),
+ embedder: None,
+ provider_health: ai_memory_llm::ProviderHealth::default(),
+ decay_params: DecayParams::default(),
+ data_dir: tmp.path().to_path_buf(),
+ db_path,
+ bind: "127.0.0.1:0".to_string(),
+ home_dir: None,
+ bootstrap_lock: Arc::new(tokio::sync::Mutex::new(())),
+ token_pepper: None,
+ active_project: ai_memory_core::ActiveProject::new(),
+ scope_invalidator: None,
+ trusted_proxy_identity: false,
+ }
+}
+
+fn synthetic_sources() -> Vec<BootstrapSource> {
+ vec![BootstrapSource {
+ kind: SourceKind::Readme,
+ label: "README (README.md)".into(),
+ text: "# my-project\n\nA toy project used for testing bootstrap ingestion.".into(),
+ }]
+}
+
+/// The operator's only durable record of *why* bootstrap returned 502 is the
+/// server log, so the provider status and body must appear there — not just in
+/// the response the CLI prints once and forgets.
+#[tokio::test]
+async fn a_bootstrap_provider_failure_is_logged_and_not_only_returned() {
+ let captured = CapturedLog::default();
+ let subscriber = tracing_subscriber::fmt()
+ .with_writer(captured.clone())
+ .with_max_level(Level::WARN)
+ .with_ansi(false)
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp, Some(Arc::new(FourOhFourProvider))).await;
+
+ let body = json!({
+ "workspace": "test-ws",
+ "project": "test-proj",
+ "sources": synthetic_sources(),
+ "max_input_tokens": 50_000,
+ "dry_run": false,
+ "force": false,
+ });
+
+ let resp = admin_router(state)
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/bootstrap")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(resp.status(), StatusCode::BAD_GATEWAY);
+
+ let logged = captured.text();
+ assert!(
+ logged.contains("404 page not found"),
+ "the provider error must reach the server log, not only the response body; \
+ captured log was: {logged:?}"
+ );
+}
+
+/// The converse, and the reason the rule is "server error" rather than "any
+/// error": a rejected request is the caller's problem and was answered in the
+/// response. Logging those too would bury the 5xx this file exists to surface
+/// under noise any client can generate at will.
+#[tokio::test]
+async fn a_rejected_request_is_answered_without_a_server_log_line() {
+ let captured = CapturedLog::default();
+ let subscriber = tracing_subscriber::fmt()
+ .with_writer(captured.clone())
+ .with_max_level(Level::WARN)
+ .with_ansi(false)
+ .finish();
+ let _guard = tracing::subscriber::set_default(subscriber);
+
+ let tmp = TempDir::new().unwrap();
+ let state = make_admin_state(&tmp, Some(Arc::new(FourOhFourProvider))).await;
+
+ let body = json!({
+ "workspace": "test-ws",
+ "project": "test-proj",
+ "sources": Vec::<BootstrapSource>::new(),
+ "max_input_tokens": 50_000,
+ "dry_run": false,
+ "force": false,
+ });
+
+ let resp = admin_router(state)
+ .oneshot(
+ Request::builder()
+ .method("POST")
+ .uri("/admin/bootstrap")
+ .header("content-type", "application/json")
+ .body(Body::from(serde_json::to_vec(&body).unwrap()))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+
+ assert!(
+ resp.status().is_client_error(),
+ "no sources is a validation failure, got {}",
+ resp.status()
+ );
+ assert_eq!(
+ captured.text(),
+ "",
+ "a 4xx must not write to the server log"
+ );
+}
diff --git a/crates/ai-memory-mcp/tests/suite/mod.rs b/crates/ai-memory-mcp/tests/suite/mod.rs
index 82784111..421af735 100644
--- a/crates/ai-memory-mcp/tests/suite/mod.rs
+++ b/crates/ai-memory-mcp/tests/suite/mod.rs
@@ -10,6 +10,7 @@ mod admin_bootstrap;
mod admin_move;
mod admin_move_session;
mod admin_phase3;
+mod admin_provider_error_logging;
mod admin_purge;
mod admin_read_page;
mod admin_rename;