Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(admin): rename-project after purge returns 404 instead of false 200
Djalma Júnior591869e3d84a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da6b043f..f5dc1c21 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Fixed+- `POST /admin/rename-project` now returns `404 Not Found` when the project row+ has been deleted (typically by a concurrent `purge-project`) between the+ handler's id lookup and the writer's `UPDATE`. The pre-fix path silently+ responded `200 OK` with `pages: 0` for an operation that affected zero rows,+ which contradicted the concurrent purge's also-`200 OK` destruction of the+ same project and gave operators no signal that the rename had been undone.## [0.10.0] - 2026-06-04### Addeddiff --git a/crates/ai-memory-mcp/src/admin.rs b/crates/ai-memory-mcp/src/admin.rsindex 0e7f606a..5096fb35 100644--- a/crates/ai-memory-mcp/src/admin.rs+++ b/crates/ai-memory-mcp/src/admin.rs@@ -1593,7 +1593,11 @@ async fn handle_rename_project(};// Step 3: execute the rename. The writer validates the name and- // returns ProjectNameTaken / InvalidProjectName on conflicts.+ // returns ProjectNameTaken / InvalidProjectName on conflicts. A+ // `NotFound` here signals a race — typically a concurrent+ // `purge-project` deleted the row between the lookup above and+ // this UPDATE. Map it to 404 so the caller sees an honest failure+ // instead of the previous false-200.if let Err(e) = state.writer.rename_project(ws_id, proj_id, req.to.clone())@@ -1603,6 +1607,7 @@ async fn handle_rename_project(StoreError::ProjectNameTaken(_) | StoreError::InvalidProjectName(_) => {StatusCode::UNPROCESSABLE_ENTITY}+ StoreError::NotFound(_) => StatusCode::NOT_FOUND,_ => StatusCode::INTERNAL_SERVER_ERROR,};return (status, Json(serde_json::json!({ "error": e.to_string() })));diff --git a/crates/ai-memory-mcp/tests/admin_rename.rs b/crates/ai-memory-mcp/tests/admin_rename.rsindex 8436fe4a..ed8e67e6 100644--- a/crates/ai-memory-mcp/tests/admin_rename.rs+++ b/crates/ai-memory-mcp/tests/admin_rename.rs@@ -350,3 +350,79 @@ async fn rename_project_pages_still_searchable() {"page must still be searchable after rename: {hits}");}++/// Regression for the rename-vs-purge race surfaced by live exploration.+///+/// The race shape: admin handler resolves `(ws_id, proj_id)` via the+/// reader pool, then dispatches the rename to the writer actor. A+/// `POST /admin/purge-project` that arrives between those two steps+/// deletes the row. The writer's `UPDATE projects` then affects ZERO+/// rows but `conn.execute` returns `Ok(0)` — the pre-fix code accepted+/// any `Ok` as success and the handler responded `200 OK` for an+/// operation that touched nothing.+///+/// We don't need a concurrent purge to reproduce the symptom: any+/// state where the project row is gone but the admin handler still+/// holds its id triggers the same code path. The test takes the+/// shortcut of purging serially first, then asserting that a rename+/// of the now-vanished project returns `404 Not Found` instead of a+/// false `200 OK`.+#[tokio::test]+async fn rename_project_after_purge_returns_404_not_silent_200() {+ let tmp = TempDir::new().unwrap();+ let (state, store) = make_state(&tmp).await;++ // Seed default/race-victim so the workspace + project rows exist.+ seed_page(&store, &state.wiki, "race-victim").await;++ // Purge the row out from under any in-flight rename.+ let purge_state = AdminState {+ writer: state.writer.clone(),+ reader: state.reader.clone(),+ wiki: state.wiki.clone(),+ llm: state.llm.clone(),+ embedder: state.embedder.clone(),+ provider_health: state.provider_health.clone(),+ decay_params: state.decay_params,+ data_dir: state.data_dir.clone(),+ db_path: state.db_path.clone(),+ bind: state.bind.clone(),+ bootstrap_lock: state.bootstrap_lock.clone(),+ token_pepper: None,+ active_project: state.active_project.clone(),+ on_project_moved: None,+ };+ let purge_resp = post(+ purge_state,+ "/admin/purge-project",+ json!({ "workspace": "default", "project": "race-victim", "confirm": true }),+ )+ .await;+ assert_eq!(+ purge_resp.status(),+ StatusCode::OK,+ "purge step must succeed"+ );++ // Now rename the now-deleted project. Without the fix this returns+ // `200 OK` with `pages: 0` — visibly indistinguishable from a happy+ // path on an empty project. With the fix the writer surfaces+ // `StoreError::NotFound` and the admin handler maps to 404.+ let rename_resp = post(+ state,+ "/admin/rename-project",+ json!({ "workspace": "default", "from": "race-victim", "to": "race-survivor" }),+ )+ .await;++ // The pre-lookup also runs against the missing project; depending+ // on which step trips the absence (handler-level `lookup_ws_proj_no_create`+ // vs writer-side `UPDATE projects ... = 0 rows`), either path must+ // produce a 404. Accept either — the load-bearing invariant is+ // "no false 200 OK".+ assert_eq!(+ rename_resp.status(),+ StatusCode::NOT_FOUND,+ "rename of a vanished project must NOT silently return 200"+ );+}diff --git a/crates/ai-memory-store/src/ops.rs b/crates/ai-memory-store/src/ops.rsindex 9087d55e..172758f8 100644--- a/crates/ai-memory-store/src/ops.rs+++ b/crates/ai-memory-store/src/ops.rs@@ -917,6 +917,17 @@ pub fn rename_project();match rows {+ // Zero rows affected means the project row vanished between the+ // admin handler's `lookup_ws_proj_no_create` and this UPDATE —+ // the classic shape is a concurrent `purge-project` racing the+ // rename. Without this check, the rename would happily return+ // `Ok(())` and the admin handler would respond `200 OK` for an+ // operation that touched nothing, contradicting the purge's+ // (also `200 OK`) destruction of the same row.+ Ok(0) => Err(StoreError::NotFound(format!(+ "project id {project_id} no longer exists in workspace {workspace_id} \+ (race with concurrent purge or delete)",+ ))),Ok(_) => Ok(()),Err(rusqlite::Error::SqliteFailure(err, _))if err.extended_code == rusqlite::ffi::SQLITE_CONSTRAINT_UNIQUE@@ -2221,4 +2232,44 @@ mod tests {};insert_handoff(&mut conn, &good_handoff).unwrap();}++ /// Regression for the rename-vs-purge race that live exploration+ /// caught: a `rename_project` for a row that was deleted between+ /// the admin handler's `lookup_ws_proj_no_create` and the+ /// `UPDATE projects` used to silently return `Ok(())` — the admin+ /// endpoint then responded `200 OK` for an operation that touched+ /// zero rows, contradicting the concurrent purge's (also `200 OK`)+ /// destruction of the same project. After the fix, the writer+ /// returns `StoreError::NotFound`, which the admin handler maps to+ /// `404 Not Found`. Pins both the writer-side semantic and a+ /// concrete recipe for the failure shape so a future refactor+ /// can't quietly downgrade the error back to a silent Ok.+ #[test]+ fn rename_project_after_purge_returns_not_found() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ // Simulate the post-purge state: project row gone.+ // `purge_project` drives the cascading deletes we want here.+ let _ = purge_project(&mut conn, &ws, &proj, "default/scratch")+ .expect("purge of fresh project should succeed");+ // Now try to rename the project that no longer exists. The+ // pre-fix code returned `Ok(())` because `UPDATE` affected+ // zero rows. The fix returns `NotFound` so admin handlers+ // can respond 404 honestly.+ let err = rename_project(&mut conn, &ws, &proj, "renamed")+ .expect_err("rename of purged project must error");+ match err {+ StoreError::NotFound(_) => {}+ other => panic!("expected StoreError::NotFound, got {other:?}"),+ }+ }++ /// Belt-and-suspenders for the common path: rename of an existing+ /// project still succeeds. Without this, a future "always return+ /// NotFound" regression would also pass the test above by accident.+ #[test]+ fn rename_project_of_live_project_succeeds() {+ let (_tmp, mut conn, ws, proj) = fresh_db();+ rename_project(&mut conn, &ws, &proj, "renamed-live")+ .expect("rename of live project must succeed");+ }}