Skip to content

BrainAPI is a knowledge graph–powered AI memory layer that transforms unstructured data into structured knowledge, enabling intelligent search, recommendations, and contextual memory for AI agents and applications.

Implement brain lifecycle clear and delete routes

Christian356e1e668c0e
diff --git a/src/lib/milvus/client.py b/src/lib/milvus/client.py
index 2fbf2df..f232d5a 100644
--- a/src/lib/milvus/client.py
+++ b/src/lib/milvus/client.py
@@ -155,6 +155,29 @@ class MilvusClient(VectorStoreClient):
raise ValueError("Invalid Milvus configuration")
return self._clients[brain_id]
+ def clear_brain_data(self, brain_id: str) -> None:
+ if config.milvus.uri and config.milvus.token:
+ connections.connect(
+ uri=config.milvus.uri,
+ token=config.milvus.token,
+ timeout=30,
+ )
+ elif config.milvus.host and config.milvus.port:
+ uri = f"http://{config.milvus.host}:{config.milvus.port}"
+ connections.connect(
+ uri=uri,
+ token=config.milvus.token if config.milvus.token else None,
+ timeout=30,
+ )
+ else:
+ raise ValueError("Invalid Milvus configuration")
+
+ if brain_id not in db.list_database():
+ return
+ client = self._get_client(brain_id)
+ for collection in client.list_collections():
+ client.drop_collection(collection_name=collection)
+
def _ensure_store(self, store: str, brain_id: str) -> None:
"""
Ensure the store exists and is loaded in the specified database.
diff --git a/src/lib/mongo/client.py b/src/lib/mongo/client.py
index 72335ce..884c518 100644
--- a/src/lib/mongo/client.py
+++ b/src/lib/mongo/client.py
@@ -174,6 +174,22 @@ class MongoClient(DataClient):
for result in result
]
+ def clear_brain_data(self, brain_id: str) -> None:
+ protected = {
+ "admin",
+ "config",
+ "local",
+ config.mongo.system_database,
+ }
+ if brain_id in protected:
+ raise ValueError(f'Refusing to clear protected Mongo database "{brain_id}"')
+ self.client.drop_database(brain_id)
+
+ def delete_brain_registry(self, brain_id: str) -> bool:
+ collection = self.get_collection("brains", config.mongo.system_database)
+ result = collection.delete_one({"name_key": brain_id})
+ return result.deleted_count > 0
+
def save_kg_changes(self, kg_changes: KGChanges, brain_id: str) -> KGChanges:
collection = self.get_collection("kg_changes", database=brain_id)
collection.insert_one(kg_changes.model_dump(mode="json"))
diff --git a/src/lib/neo4j/client.py b/src/lib/neo4j/client.py
index 9079052..8a69c4a 100644
--- a/src/lib/neo4j/client.py
+++ b/src/lib/neo4j/client.py
@@ -89,6 +89,14 @@ class Neo4jClient(GraphClient):
"If using Neo4j Community Edition, you can only use the default 'neo4j' database."
)
+ def clear_brain_data(self, brain_id: str) -> None:
+ if not self._verify_database_accessible(brain_id):
+ return
+ self.driver.execute_query(
+ "MATCH (node) DETACH DELETE node",
+ database_=brain_id,
+ )
+
def _verify_database_accessible(self, database: str) -> bool:
"""
Verify that a database is accessible by executing a simple query.
diff --git a/src/lib/postgresql/_provisioning.py b/src/lib/postgresql/_provisioning.py
index bf4bfcb..6fbe5ca 100644
--- a/src/lib/postgresql/_provisioning.py
+++ b/src/lib/postgresql/_provisioning.py
@@ -211,3 +211,47 @@ def list_brain_database_names() -> list[str]:
for row in cur.fetchall()
if row[0] != system_db
]
+
+
+def clear_brain_database(
+ brain_id: str,
+ *,
+ table_prefixes: tuple[str, ...] | None = None,
+) -> list[str]:
+ """Truncate every application table in one brain database.
+
+ The database and schemas remain in place so API and worker connection pools
+ stay valid. This makes an online clear safe across processes while removing
+ data, graph records, vectors, and plugin-owned tables in the public schema.
+ """
+ dbname = brain_db_name(brain_id)
+ maintenance = _registry.get(_maintenance_dbname())
+ with borrow(maintenance) as conn:
+ with conn.cursor() as cur:
+ cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", (dbname,))
+ if cur.fetchone() is None:
+ return []
+
+ with borrow(get_brain_pool(brain_id)) as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "SELECT tablename FROM pg_tables "
+ "WHERE schemaname = 'public' ORDER BY tablename"
+ )
+ tables = [
+ row[0]
+ for row in cur.fetchall()
+ if table_prefixes is None
+ or row[0].startswith(table_prefixes)
+ ]
+ if tables:
+ identifiers = sql.SQL(", ").join(
+ sql.Identifier(table) for table in tables
+ )
+ cur.execute(
+ sql.SQL("TRUNCATE TABLE {} RESTART IDENTITY CASCADE").format(
+ identifiers
+ )
+ )
+ conn.commit()
+ return tables
diff --git a/src/lib/postgresql/data.py b/src/lib/postgresql/data.py
index 48e83ca..8d76ffc 100644
--- a/src/lib/postgresql/data.py
+++ b/src/lib/postgresql/data.py
@@ -37,6 +37,7 @@ from ._provisioning import (
ensure_database_exists,
get_brain_pool,
get_system_pool,
+ clear_brain_database,
list_brain_database_names,
)
@@ -593,6 +594,20 @@ class PostgreSQLDataClient(DataClient):
return sorted(by_key.values(), key=lambda brain: brain.name_key)
+ def clear_brain_data(self, brain_id: str) -> None:
+ clear_brain_database(brain_id)
+
+ def delete_brain_registry(self, brain_id: str) -> bool:
+ with self._system_connection() as conn:
+ with conn.cursor() as cur:
+ cur.execute(
+ "DELETE FROM data_brains WHERE name_key = %s",
+ (brain_id,),
+ )
+ deleted = cur.rowcount > 0
+ conn.commit()
+ return deleted
+
def save_kg_changes(self, kg_changes: KGChanges, brain_id: str) -> KGChanges:
document = kg_changes.model_dump(mode="json")
type_value = (
diff --git a/src/lib/postgresql/networkx_client.py b/src/lib/postgresql/networkx_client.py
index 8a20c65..8a1e657 100644
--- a/src/lib/postgresql/networkx_client.py
+++ b/src/lib/postgresql/networkx_client.py
@@ -28,6 +28,7 @@ from src.lib.postgresql.graph_store import (
PostgreSQLGraphStore,
_RelationshipProxy,
)
+from src.lib.postgresql._provisioning import clear_brain_database
from src.utils.serialization.data import always_dict
@@ -42,6 +43,10 @@ class NetworkXGraphClient(GraphClient):
def ensure_database(self, database: str) -> None:
self._store.ensure_database(database)
+ def clear_brain_data(self, brain_id: str) -> None:
+ clear_brain_database(brain_id, table_prefixes=("kg_",))
+ self._store.invalidate_brain(brain_id)
+
def execute_operation(self, operation: str, brain_id: str) -> Any:
self._store.ensure_database(brain_id)
return self._store.execute_read_query(brain_id, operation)
diff --git a/src/lib/postgresql/vectors.py b/src/lib/postgresql/vectors.py
index 5e77a32..514f9c2 100644
--- a/src/lib/postgresql/vectors.py
+++ b/src/lib/postgresql/vectors.py
@@ -23,7 +23,12 @@ from src.adapters.interfaces.embeddings import VectorStoreClient
from src.config import config
from src.constants.embeddings import EMBEDDING_STORES_SIZES, Vector
-from ._provisioning import borrow, ensure_brain_database, get_brain_pool
+from ._provisioning import (
+ borrow,
+ clear_brain_database,
+ ensure_brain_database,
+ get_brain_pool,
+)
logger = logging.getLogger(__name__)
@@ -142,6 +147,9 @@ class PostgreSQLVectorStoreClient(VectorStoreClient):
conn.commit()
self._brain_extensions_ready.add(brain_id)
+ def clear_brain_data(self, brain_id: str) -> None:
+ clear_brain_database(brain_id, table_prefixes=("vectors_",))
+
def _ensure_store(self, store: str, brain_id: str) -> None:
if store not in EMBEDDING_STORES_SIZES:
raise ValueError(f"Store {store} not available")
diff --git a/src/lib/redis/client.py b/src/lib/redis/client.py
index f256477..ca600e2 100644
--- a/src/lib/redis/client.py
+++ b/src/lib/redis/client.py
@@ -85,6 +85,27 @@ class RedisClient(CacheClient):
return self.client.hdel(f"{brain_id}:_tasks", task_id)
return self.client.delete(prefixed_key)
+ def clear_brain_data(self, brain_id: str) -> int:
+ """Delete only keys scoped to one brain without flushing shared Redis."""
+ deleted = 0
+ chunk = []
+ for key in self.client.scan_iter(match=f"{brain_id}:*", count=500):
+ chunk.append(key)
+ if len(chunk) == 500:
+ deleted += int(self.client.delete(*chunk))
+ chunk = []
+ if chunk:
+ deleted += int(self.client.delete(*chunk))
+ return deleted
+
+ def clear_brain_registry_cache(self, brain_id: str) -> int:
+ return int(
+ self.client.delete(
+ f"system:brain:{brain_id}",
+ f"system:brainpat:{brain_id}",
+ )
+ )
+
def get_task_keys(self, brain_id: str) -> list[str]:
"""
Get all task keys for a given brain_id.
diff --git a/src/services/api/constants/responses.py b/src/services/api/constants/responses.py
index 4585049..75cb81a 100644
--- a/src/services/api/constants/responses.py
+++ b/src/services/api/constants/responses.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+from typing import Literal
+
from pydantic import BaseModel, ConfigDict, JsonValue, RootModel
from src.constants.data import KGChanges, Observation, StructuredData, TextChunk
@@ -19,6 +21,14 @@ class LoginInfoResponse(BaseModel):
brain_id: str
+class BrainLifecycleResponse(BaseModel):
+ success: bool
+ brain_id: str
+ operation: Literal["clear", "delete"]
+ existed: bool
+ cleared_backends: list[str]
+
+
class StringListResponse(RootModel[list[str]]):
pass
@@ -142,4 +152,3 @@ class TaskStateResponse(BaseModel):
class TaskListResponse(BaseModel):
tasks: list[TaskStateResponse]
-
diff --git a/src/services/api/controllers/system.py b/src/services/api/controllers/system.py
index 25ba1a0..cb87371 100644
--- a/src/services/api/controllers/system.py
+++ b/src/services/api/controllers/system.py
@@ -10,8 +10,8 @@ Modified By: Christian Nonis <[email protected]>
import asyncio
-from pydantic import BaseModel
from src.services.api.constants.requests import CreateBrainRequest
+from src.services.brain_lifecycle import BrainLifecycleService
from src.services.data.main import data_adapter
@@ -31,3 +31,30 @@ async def create_new_brain(request: CreateBrainRequest):
raise ValueError("brain_id must be alphanumeric and start with a letter")
result = await asyncio.to_thread(data_adapter.create_brain, request.brain_id)
return result
+
+
+def get_brain_lifecycle_service() -> BrainLifecycleService:
+ # Import lazily so lightweight system-route tests do not initialize every
+ # configured storage client before a lifecycle operation is requested.
+ from src.core.instances import (
+ cache_adapter,
+ graph_adapter,
+ vector_store_adapter,
+ )
+
+ return BrainLifecycleService(
+ data_client=data_adapter.data,
+ graph_client=graph_adapter.graph,
+ vector_client=vector_store_adapter.vector_store,
+ cache_client=cache_adapter.cache,
+ )
+
+
+async def clear_brain(brain_id: str, service: BrainLifecycleService):
+ result = await asyncio.to_thread(service.clear, brain_id)
+ return result.as_dict()
+
+
+async def delete_brain(brain_id: str, service: BrainLifecycleService):
+ result = await asyncio.to_thread(service.delete, brain_id)
+ return result.as_dict()
diff --git a/src/services/api/routes/system.py b/src/services/api/routes/system.py
index 9e136e5..c065f41 100644
--- a/src/services/api/routes/system.py
+++ b/src/services/api/routes/system.py
@@ -11,11 +11,21 @@ Modified By: Christian Nonis <[email protected]>
from fastapi import APIRouter, Request
from src.services.api.constants.requests import CreateBrainRequest
from src.services.api.controllers.system import (
- get_brains_list as get_brains_list_controller,
+ clear_brain as clear_brain_controller,
create_new_brain as create_new_brain_controller,
+ delete_brain as delete_brain_controller,
+ get_brain_lifecycle_service,
+ get_brains_list as get_brains_list_controller,
)
from src.constants.data import Brain
+from src.services.api.constants.responses import BrainLifecycleResponse
from src.services.api.errors import error_response
+from src.services.brain_lifecycle import (
+ BrainCleanupError,
+ BrainLifecycleBusyError,
+ BrainNotFoundError,
+ InvalidBrainIdError,
+)
system_router = APIRouter(prefix="/system", tags=["system"])
@@ -36,20 +46,95 @@ async def create_brain(request: CreateBrainRequest):
return await create_new_brain_controller(request)
-@system_router.get(path="/brains/{brain_id}/reset", include_in_schema=False) # TODO
-async def reset(brain_id: str, request: Request):
- """
- Resets the brain
- """
- return _not_implemented(request, brain_id, "reset")
+@system_router.post(
+ path="/brains/{brain_id}/clear",
+ response_model=BrainLifecycleResponse,
+)
+async def clear_brain(brain_id: str, request: Request):
+ """Clear all data for a brain while preserving its identity and PAT."""
+ try:
+ return await clear_brain_controller(
+ brain_id,
+ get_brain_lifecycle_service(),
+ )
+ except InvalidBrainIdError as error:
+ return error_response(
+ request,
+ status_code=400,
+ detail=str(error),
+ code="BRAIN_ID_INVALID",
+ message="The brain identifier is invalid.",
+ resolution="Use an alphanumeric brain ID that starts with a letter.",
+ )
+ except BrainNotFoundError as error:
+ return error_response(
+ request,
+ status_code=404,
+ detail=str(error),
+ code="BRAIN_NOT_FOUND",
+ message="The brain was not found.",
+ resolution="List brains and retry with an existing brain ID.",
+ )
+ except BrainLifecycleBusyError as error:
+ return error_response(
+ request,
+ status_code=409,
+ detail=str(error),
+ code="BRAIN_LIFECYCLE_BUSY",
+ message="Another lifecycle operation is already running.",
+ resolution="Wait for the current operation to finish, then retry.",
+ )
+ except BrainCleanupError as error:
+ return error_response(
+ request,
+ status_code=503,
+ detail="Brain cleanup failed.",
+ code="BRAIN_CLEANUP_FAILED",
+ message="The brain could not be cleared from every storage backend.",
+ resolution="Retry the idempotent operation after checking backend health.",
+ extra={"failed_backends": error.failed_backends},
+ )
-@system_router.get(path="/brains/{brain_id}/delete", include_in_schema=False) # TODO
-async def delete(brain_id: str, request: Request):
- """
- Deletes the brain and all its data
- """
- return _not_implemented(request, brain_id, "delete")
+@system_router.delete(
+ path="/brains/{brain_id}",
+ response_model=BrainLifecycleResponse,
+)
+async def delete_brain(brain_id: str, request: Request):
+ """Delete a brain's data, registry identity, PAT, and cached credentials."""
+ try:
+ return await delete_brain_controller(
+ brain_id,
+ get_brain_lifecycle_service(),
+ )
+ except InvalidBrainIdError as error:
+ return error_response(
+ request,
+ status_code=400,
+ detail=str(error),
+ code="BRAIN_ID_INVALID",
+ message="The brain identifier is invalid.",
+ resolution="Use an alphanumeric brain ID that starts with a letter.",
+ )
+ except BrainLifecycleBusyError as error:
+ return error_response(
+ request,
+ status_code=409,
+ detail=str(error),
+ code="BRAIN_LIFECYCLE_BUSY",
+ message="Another lifecycle operation is already running.",
+ resolution="Wait for the current operation to finish, then retry.",
+ )
+ except BrainCleanupError as error:
+ return error_response(
+ request,
+ status_code=503,
+ detail="Brain cleanup failed.",
+ code="BRAIN_CLEANUP_FAILED",
+ message="The brain could not be deleted from every storage backend.",
+ resolution="Retry the idempotent operation after checking backend health.",
+ extra={"failed_backends": error.failed_backends},
+ )
@system_router.post(
diff --git a/src/services/brain_lifecycle.py b/src/services/brain_lifecycle.py
new file mode 100644
index 0000000..6df7eeb
--- /dev/null
+++ b/src/services/brain_lifecycle.py
@@ -0,0 +1,196 @@
+"""Profile-aware lifecycle operations for BrainAPI brains."""
+
+from __future__ import annotations
+
+from contextlib import contextmanager
+from dataclasses import dataclass
+import logging
+from typing import Any, Iterator, Protocol
+
+
+logger = logging.getLogger(__name__)
+
+
+class BrainLifecycleError(RuntimeError):
+ """Base class for lifecycle failures safe to map at the API boundary."""
+
+
+class InvalidBrainIdError(BrainLifecycleError):
+ """Raised when a lifecycle target is invalid or reserved."""
+
+
+class BrainNotFoundError(BrainLifecycleError):
+ """Raised when a clear operation targets an unknown brain."""
+
+
+class BrainLifecycleBusyError(BrainLifecycleError):
+ """Raised when another lifecycle operation already owns the brain lock."""
+
+
+class BrainCleanupError(BrainLifecycleError):
+ """Raised after one or more storage backends fail to clear."""
+
+ def __init__(self, brain_id: str, failed_backends: list[str]):
+ self.brain_id = brain_id
+ self.failed_backends = failed_backends
+ super().__init__(
+ "Could not clear every storage backend for brain "
+ f'"{brain_id}": {", ".join(failed_backends)}'
+ )
+
+
+class DataLifecycleClient(Protocol):
+ def get_brain(self, name_key: str) -> Any: ...
+
+ def clear_brain_data(self, brain_id: str) -> Any: ...
+
+ def delete_brain_registry(self, brain_id: str) -> bool: ...
+
+
+class StorageLifecycleClient(Protocol):
+ def clear_brain_data(self, brain_id: str) -> Any: ...
+
+
+class CacheLifecycleClient(StorageLifecycleClient, Protocol):
+ client: Any
+
+ def clear_brain_registry_cache(self, brain_id: str) -> Any: ...
+
+
+@dataclass(frozen=True)
+class BrainLifecycleResult:
+ brain_id: str
+ operation: str
+ existed: bool
+ cleared_backends: list[str]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "success": True,
+ "brain_id": self.brain_id,
+ "operation": self.operation,
+ "existed": self.existed,
+ "cleared_backends": self.cleared_backends,
+ }
+
+
+def validate_brain_id(brain_id: str) -> str:
+ normalized = (brain_id or "").strip()
+ if (
+ not normalized
+ or not normalized.isalnum()
+ or not normalized[0].isalpha()
+ ):
+ raise InvalidBrainIdError(
+ "brain_id must be alphanumeric and start with a letter"
+ )
+ if normalized.lower() == "system":
+ raise InvalidBrainIdError('brain_id "system" is reserved')
+ return normalized
+
+
+class BrainLifecycleService:
+ """Clear or delete one brain across the active storage profile."""
+
+ def __init__(
+ self,
+ *,
+ data_client: DataLifecycleClient,
+ graph_client: StorageLifecycleClient,
+ vector_client: StorageLifecycleClient,
+ cache_client: CacheLifecycleClient,
+ ) -> None:
+ self._data = data_client
+ self._graph = graph_client
+ self._vector = vector_client
+ self._cache = cache_client
+
+ @contextmanager
+ def _lock(self, brain_id: str) -> Iterator[None]:
+ redis = getattr(self._cache, "client", None)
+ if redis is None or not hasattr(redis, "lock"):
+ yield
+ return
+
+ lock = redis.lock(
+ f"system:brain-lifecycle:{brain_id}",
+ timeout=300,
+ blocking_timeout=1,
+ )
+ if not lock.acquire(blocking=True):
+ raise BrainLifecycleBusyError(
+ f'Another lifecycle operation is running for brain "{brain_id}"'
+ )
+ try:
+ yield
+ finally:
+ try:
+ lock.release()
+ except Exception:
+ # The lock has a TTL and may already have expired. Cleanup must not
+ # turn a successful destructive operation into a false failure.
+ pass
+
+ def _clear_backends(self, brain_id: str) -> list[str]:
+ backends = (
+ ("data", self._data),
+ ("graph", self._graph),
+ ("vectors", self._vector),
+ ("cache", self._cache),
+ )
+ cleared: list[str] = []
+ failed: list[str] = []
+
+ for name, backend in backends:
+ try:
+ backend.clear_brain_data(brain_id)
+ cleared.append(name)
+ except Exception:
+ logger.exception(
+ "Failed to clear %s backend for brain %s",
+ name,
+ brain_id,
+ )
+ failed.append(name)
+
+ if failed:
+ raise BrainCleanupError(brain_id, failed)
+ return cleared
+
+ def clear(self, brain_id: str) -> BrainLifecycleResult:
+ brain_id = validate_brain_id(brain_id)
+ with self._lock(brain_id):
+ if self._data.get_brain(brain_id) is None:
+ raise BrainNotFoundError(f'Brain "{brain_id}" was not found')
+ cleared = self._clear_backends(brain_id)
+ return BrainLifecycleResult(
+ brain_id=brain_id,
+ operation="clear",
+ existed=True,
+ cleared_backends=cleared,
+ )
+
+ def delete(self, brain_id: str) -> BrainLifecycleResult:
+ brain_id = validate_brain_id(brain_id)
+ with self._lock(brain_id):
+ existed = self._data.get_brain(brain_id) is not None
+ cleared = self._clear_backends(brain_id)
+ try:
+ self._cache.clear_brain_registry_cache(brain_id)
+ except Exception:
+ logger.exception(
+ "Failed to clear registry cache for brain %s", brain_id
+ )
+ raise BrainCleanupError(brain_id, ["registry_cache"]) from None
+ try:
+ self._data.delete_brain_registry(brain_id)
+ except Exception:
+ logger.exception("Failed to delete registry for brain %s", brain_id)
+ raise BrainCleanupError(brain_id, ["registry"]) from None
+
+ return BrainLifecycleResult(
+ brain_id=brain_id,
+ operation="delete",
+ existed=existed,
+ cleared_backends=cleared,
+ )
diff --git a/tests/test_agent_readiness_api.py b/tests/test_agent_readiness_api.py
index 9c894f0..dd27595 100644
--- a/tests/test_agent_readiness_api.py
+++ b/tests/test_agent_readiness_api.py
@@ -328,7 +328,10 @@ class OpenApiContractTests(unittest.TestCase):
"#/components/schemas/ErrorResponse",
)
- self.assertNotIn("/system/brains/{brain_id}/reset", schema["paths"])
+ self.assertIn("/system/brains/{brain_id}/clear", schema["paths"])
+ self.assertIn("post", schema["paths"]["/system/brains/{brain_id}/clear"])
+ self.assertIn("/system/brains/{brain_id}", schema["paths"])
+ self.assertIn("delete", schema["paths"]["/system/brains/{brain_id}"])
self.assertIn("202", schema["paths"]["/ingest/file"]["post"]["responses"])
generic_refs = [
diff --git a/tests/test_brain_lifecycle.py b/tests/test_brain_lifecycle.py
new file mode 100644
index 0000000..ac7c273
--- /dev/null
+++ b/tests/test_brain_lifecycle.py
@@ -0,0 +1,139 @@
+from __future__ import annotations
+
+import pytest
+
+from src.services.brain_lifecycle import (
+ BrainCleanupError,
+ BrainLifecycleResult,
+ BrainLifecycleService,
+ BrainNotFoundError,
+ InvalidBrainIdError,
+ validate_brain_id,
+)
+
+
+class FakeStorage:
+ def __init__(self, name: str, events: list[str], fail: bool = False):
+ self.name = name
+ self.events = events
+ self.fail = fail
+
+ def clear_brain_data(self, brain_id: str) -> None:
+ self.events.append(f"clear:{self.name}:{brain_id}")
+ if self.fail:
+ raise RuntimeError(f"{self.name} unavailable")
+
+
+class FakeData(FakeStorage):
+ def __init__(
+ self,
+ events: list[str],
+ *,
+ exists: bool = True,
+ fail: bool = False,
+ ):
+ super().__init__("data", events, fail)
+ self.exists = exists
+
+ def get_brain(self, name_key: str):
+ self.events.append(f"get:{name_key}")
+ return {"name_key": name_key, "pat": "pat"} if self.exists else None
+
+ def delete_brain_registry(self, brain_id: str) -> bool:
+ self.events.append(f"registry:delete:{brain_id}")
+ was_present = self.exists
+ self.exists = False
+ return was_present
+
+
+class FakeCache(FakeStorage):
+ client = None
+
+ def __init__(self, events: list[str], fail: bool = False):
+ super().__init__("cache", events, fail)
+
+ def clear_brain_registry_cache(self, brain_id: str) -> None:
+ self.events.append(f"registry-cache:clear:{brain_id}")
+
+
+def service(
+ events: list[str],
+ *,
+ exists: bool = True,
+ failing_backend: str | None = None,
+) -> tuple[BrainLifecycleService, FakeData]:
+ data = FakeData(events, exists=exists, fail=failing_backend == "data")
+ return (
+ BrainLifecycleService(
+ data_client=data,
+ graph_client=FakeStorage(
+ "graph", events, fail=failing_backend == "graph"
+ ),
+ vector_client=FakeStorage(
+ "vectors", events, fail=failing_backend == "vectors"
+ ),
+ cache_client=FakeCache(events, fail=failing_backend == "cache"),
+ ),
+ data,
+ )
+
+
+def test_clear_preserves_brain_identity_and_clears_every_backend():
+ events: list[str] = []
+ lifecycle, data = service(events)
+
+ result = lifecycle.clear("demo")
+
+ assert result == BrainLifecycleResult(
+ brain_id="demo",
+ operation="clear",
+ existed=True,
+ cleared_backends=["data", "graph", "vectors", "cache"],
+ )
+ assert data.exists is True
+ assert "registry:delete:demo" not in events
+
+
+def test_clear_rejects_an_unknown_brain_without_touching_storage():
+ events: list[str] = []
+ lifecycle, _ = service(events, exists=False)
+
+ with pytest.raises(BrainNotFoundError):
+ lifecycle.clear("missing")
+
+ assert events == ["get:missing"]
+
+
+def test_delete_is_idempotent_and_invalidates_registry_cache():
+ events: list[str] = []
+ lifecycle, data = service(events, exists=False)
+
+ result = lifecycle.delete("gone")
+
+ assert result.existed is False
+ assert result.operation == "delete"
+ assert data.exists is False
+ assert events[-2:] == [
+ "registry-cache:clear:gone",
+ "registry:delete:gone",
+ ]
+
+
+def test_partial_cleanup_keeps_registry_for_a_safe_retry():
+ events: list[str] = []
+ lifecycle, data = service(events, failing_backend="graph")
+
+ with pytest.raises(BrainCleanupError) as caught:
+ lifecycle.delete("demo")
+
+ assert caught.value.failed_backends == ["graph"]
+ assert data.exists is True
+ assert "clear:vectors:demo" in events
+ assert "clear:cache:demo" in events
+ assert "registry:delete:demo" not in events
+
+
[email protected]("brain_id", ["", "123", "bad-id", "system"])
+def test_lifecycle_rejects_invalid_or_reserved_brain_ids(brain_id: str):
+ with pytest.raises(InvalidBrainIdError):
+ validate_brain_id(brain_id)
diff --git a/tests/test_production_hardening.py b/tests/test_production_hardening.py
index 2ff7f5a..0aadbfd 100644
--- a/tests/test_production_hardening.py
+++ b/tests/test_production_hardening.py
@@ -10,6 +10,7 @@ from fastapi.testclient import TestClient
from src.services.api.errors import install_error_handlers
from src.services.api.middlewares.auth import BrainPATMiddleware
from src.services.api.routes.system import system_router
+from src.services.brain_lifecycle import BrainLifecycleResult
from src.workers.redis_url import redis_connection_url
@@ -34,8 +35,6 @@ def test_malformed_authorization_fails_closed_with_401():
@pytest.mark.parametrize(
("path", "method", "operation"),
[
- ("/system/brains/demo/reset", "get", "reset"),
- ("/system/brains/demo/delete", "get", "delete"),
("/system/brains/demo/create-backup", "post", "create-backup"),
],
)
@@ -51,6 +50,43 @@ def test_unfinished_system_routes_return_structured_501(path, method, operation)
assert response.json()["operation"] == operation
+class _LifecycleStub:
+ def clear(self, brain_id: str):
+ return BrainLifecycleResult(
+ brain_id=brain_id,
+ operation="clear",
+ existed=True,
+ cleared_backends=["data", "graph", "vectors", "cache"],
+ )
+
+ def delete(self, brain_id: str):
+ return BrainLifecycleResult(
+ brain_id=brain_id,
+ operation="delete",
+ existed=True,
+ cleared_backends=["data", "graph", "vectors", "cache"],
+ )
+
+
+def test_brain_lifecycle_routes_use_non_get_destructive_methods():
+ app = FastAPI()
+ install_error_handlers(app)
+ app.include_router(system_router)
+
+ with patch(
+ "src.services.api.routes.system.get_brain_lifecycle_service",
+ return_value=_LifecycleStub(),
+ ):
+ client = TestClient(app)
+ cleared = client.post("/system/brains/demo/clear")
+ deleted = client.delete("/system/brains/demo")
+
+ assert cleared.status_code == 200
+ assert cleared.json()["operation"] == "clear"
+ assert deleted.status_code == 200
+ assert deleted.json()["operation"] == "delete"
+
+
def test_cors_defaults_and_production_wildcard_guard():
from src.services.api.app import _cors_allowed_origins