Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(api): explain a document-style write to /_memory (#1683)

xerj-org662e7418a142
diff --git a/engine/crates/xerj-api/src/memory_api.rs b/engine/crates/xerj-api/src/memory_api.rs
index 6dbc8e9e2..6751714b2 100644
--- a/engine/crates/xerj-api/src/memory_api.rs
+++ b/engine/crates/xerj-api/src/memory_api.rs
@@ -15,6 +15,11 @@
//! DELETE /_memory/{namespace} drop — drop the whole namespace
//! ```
//!
+//! `POST /_memory/{namespace}/_doc` and `PUT /_memory/{namespace}/_doc/{id}`
+//! are the Elasticsearch document routes, not this API. They answer `405`
+//! with a JSON body that names the store and recall calls, instead of an
+//! empty method-not-allowed.
+//!
//! ## Pagination (item 12)
//!
//! `GET /_memory/{namespace}` pages the namespace with `from` (offset, default
@@ -55,7 +60,7 @@
use axum::{
extract::{Path, State},
- http::StatusCode,
+ http::{header, HeaderValue, StatusCode},
response::{IntoResponse, Response},
Json,
};
@@ -1345,6 +1350,46 @@ pub async fn list(
// Forget
// ─────────────────────────────────────────────────────────────────────────────
+/// JSON `405` for a memory path that is not a write or a read.
+///
+/// The Elasticsearch document routes (`POST /{index}/_doc`,
+/// `PUT /{index}/_doc/{id}`, `POST /{index}/_search`) land here when an agent
+/// copies them onto `/_memory`. An empty `405` costs a round trip; the body
+/// names the four calls this API actually has.
+///
+/// `allow` is the `Allow` header for the path that was hit: `DELETE` on
+/// `/_memory/{namespace}/{id}` (forget), empty on `/_memory/{namespace}/_doc/{id}`,
+/// where no method is served.
+fn memory_method_not_allowed(namespace: &str, allow: &'static str) -> Response {
+ let reason = format!(
+ "/_memory/{namespace} is the agent-memory API, not the document API. \
+ Store with POST /_memory/{namespace} and a JSON body {{\"text\":\"...\"}}. \
+ Recall with POST /_memory/{namespace}/_recall and {{\"query\":\"...\"}}. \
+ List with GET /_memory/{namespace}. \
+ Forget one entry with DELETE /_memory/{namespace}/{{id}}."
+ );
+ (
+ StatusCode::METHOD_NOT_ALLOWED,
+ [(header::ALLOW, HeaderValue::from_static(allow))],
+ Json(json!({
+ "error": { "type": "memory_error", "reason": reason },
+ "status": 405,
+ })),
+ )
+ .into_response()
+}
+
+/// `GET`/`POST`/`PUT /_memory/{namespace}/{id}` — that path only forgets.
+pub async fn unsupported_memory_verb(Path((namespace, _id)): Path<(String, String)>) -> Response {
+ memory_method_not_allowed(&namespace, "DELETE")
+}
+
+/// `PUT`/`POST`/`GET`/`DELETE /_memory/{namespace}/_doc/{id}` — the document
+/// route with an id. No memory id lives at this path.
+pub async fn unsupported_memory_doc_id(Path((namespace, _id)): Path<(String, String)>) -> Response {
+ memory_method_not_allowed(&namespace, "")
+}
+
/// `DELETE /_memory/{namespace}/{id}` — forget a single memory entry.
pub async fn forget_one(
State(state): State<AppState>,
@@ -2303,4 +2348,93 @@ mod tests {
"recency_weight=0.9 must surface the most recent memory first"
);
}
+
+ /// Copying the Elasticsearch document routes onto `/_memory` used to
+ /// return an empty 405/404. The body has to name the real calls.
+ #[tokio::test]
+ async fn document_routes_on_memory_name_the_real_calls() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let path = dir.keep();
+ let mut config = Config::default();
+ config.server.data_dir = path.to_str().unwrap().to_string();
+ config.auth.enabled = false;
+ let metrics = Metrics::new().expect("metrics");
+ let engine = Engine::new(config.clone()).expect("engine");
+ let app = crate::router::build_es_compat_router(AppState::new(config, engine, metrics));
+
+ for (method, uri) in [
+ ("POST", "/_memory/notes/_doc"),
+ ("GET", "/_memory/notes/_search"),
+ ("PUT", "/_memory/notes/_doc/abc"),
+ ("POST", "/_memory/notes/some-id"),
+ ] {
+ let req = axum::http::Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(
+ r#"{"text":"via the document route"}"#,
+ ))
+ .unwrap();
+ let resp = tower::ServiceExt::oneshot(app.clone(), req).await.unwrap();
+ assert_eq!(
+ resp.status(),
+ StatusCode::METHOD_NOT_ALLOWED,
+ "{method} {uri}"
+ );
+ // `/_memory/{ns}/{id}` serves DELETE (forget); the `_doc/{id}`
+ // spelling serves nothing, so its `Allow` is empty.
+ let expected_allow = if uri.starts_with("/_memory/notes/_doc/") {
+ ""
+ } else {
+ "DELETE"
+ };
+ assert_eq!(
+ resp.headers()
+ .get(header::ALLOW)
+ .and_then(|v| v.to_str().ok()),
+ Some(expected_allow),
+ "{method} {uri}"
+ );
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&bytes).unwrap();
+ let reason = body["error"]["reason"].as_str().unwrap_or("");
+ assert!(
+ reason.contains("POST /_memory/notes") && reason.contains("\"text\""),
+ "{method} {uri} reason must name the store call: {reason}"
+ );
+ assert!(
+ reason.contains("POST /_memory/notes/_recall"),
+ "{method} {uri} reason must name recall: {reason}"
+ );
+ assert!(!bytes.is_empty(), "{method} {uri} body was empty");
+ }
+
+ // The real store route is unchanged.
+ let req = axum::http::Request::builder()
+ .method("POST")
+ .uri("/_memory/notes")
+ .header("content-type", "application/json")
+ .body(axum::body::Body::from(r#"{"text":"kept"}"#))
+ .unwrap();
+ let resp = tower::ServiceExt::oneshot(app.clone(), req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::CREATED);
+
+ // DELETE of one id is still forget, including an id spelled `_doc`.
+ let req = axum::http::Request::builder()
+ .method("DELETE")
+ .uri("/_memory/notes/_doc")
+ .body(axum::body::Body::empty())
+ .unwrap();
+ let resp = tower::ServiceExt::oneshot(app, req).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::NOT_FOUND);
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
+ .await
+ .unwrap();
+ let body: Value = serde_json::from_slice(&bytes).unwrap();
+ assert_eq!(body["forgotten"], false);
+ assert_eq!(body["id"], "_doc");
+ }
}
diff --git a/engine/crates/xerj-api/src/router.rs b/engine/crates/xerj-api/src/router.rs
index f5a2264f8..a2372042a 100644
--- a/engine/crates/xerj-api/src/router.rs
+++ b/engine/crates/xerj-api/src/router.rs
@@ -933,7 +933,24 @@ pub fn build_es_compat_router_with_hub(
.delete(memory_api::forget_namespace),
)
.route("/_memory/:namespace/_recall", post(memory_api::recall))
- .route("/_memory/:namespace/:id", delete(memory_api::forget_one))
+ // The document-API spellings an agent copies from `POST /{index}/_doc`.
+ // More specific than `/:id`, so they explain themselves instead of
+ // falling through to an empty 404. DELETE of a memory whose id is the
+ // literal `_doc` stays on the `/:id` route below.
+ .route(
+ "/_memory/:namespace/_doc/:doc_id",
+ get(memory_api::unsupported_memory_doc_id)
+ .post(memory_api::unsupported_memory_doc_id)
+ .put(memory_api::unsupported_memory_doc_id)
+ .delete(memory_api::unsupported_memory_doc_id),
+ )
+ .route(
+ "/_memory/:namespace/:id",
+ delete(memory_api::forget_one)
+ .get(memory_api::unsupported_memory_verb)
+ .post(memory_api::unsupported_memory_verb)
+ .put(memory_api::unsupported_memory_verb),
+ )
// ── Corpus Hub hosted endpoints ───────────────────────────────────────
// Four read-only GET routes that answer from the packs restored on this
// node (`hub_api.rs`; plan §6). Always mounted and keyed like every