AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
perf(backend/copilot): metadata-only fetch for chat ownership checks (#13038)
Zamil Majdy9373d6149519
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex a94a90aa11..023ae22220 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -19,12 +19,12 @@ from backend.copilot.db import get_chat_messages_paginatedfrom backend.copilot.executor.utils import enqueue_cancel_task, enqueue_copilot_turnfrom backend.copilot.model import (ChatMessage,- ChatSession,+ ChatSessionInfo,ChatSessionMetadata,append_and_save_message,create_chat_session,delete_chat_session,- get_chat_session,+ get_chat_session_metadata,get_or_create_builder_session,get_user_sessions,update_session_title,@@ -109,9 +109,14 @@ config = ChatConfig()async def _validate_and_get_session(session_id: str,user_id: str | None,-) -> ChatSession:- """Validate session exists and belongs to user."""- session = await get_chat_session(session_id, user_id)+) -> ChatSessionInfo:+ """Validate session exists and belongs to user.++ Returns metadata-only — callers needing the message history must use+ ``get_chat_session`` directly. Bypassing the message-loading path+ avoids a multi-KB cache deserialisation per ownership check.+ """+ session = await get_chat_session_metadata(session_id, user_id)if not session:raise NotFoundError(f"Session {session_id} not found.")return session@@ -491,12 +496,7 @@ async def disconnect_session_stream(backend releases XREAD listeners immediately rather than waiting forthe 5-10 s timeout."""- session = await get_chat_session(session_id, user_id)- if not session:- raise HTTPException(- status_code=404,- detail=f"Session {session_id} not found or access denied",- )+ await _validate_and_get_session(session_id, user_id)await stream_registry.disconnect_all_listeners(session_id)return Response(status_code=204)@@ -1538,7 +1538,12 @@ async def health_check() -> dict:# Create and retrieve session to verify full data layersession = await create_chat_session(health_check_user_id, dry_run=False)- await get_chat_session(session.session_id, health_check_user_id)+ fetched = await get_chat_session_metadata(session.session_id, health_check_user_id)+ if fetched is None:+ raise HTTPException(+ status_code=503,+ detail="Chat read path unhealthy: session not found after create",+ )return {"status": "healthy",diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 51a59e9bce..9862edbaca 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -1734,7 +1734,7 @@ def test_disconnect_stream_returns_204_and_awaits_registry() -> None:mock_session = MagicMock()mocker.patch(- "backend.api.features.chat.routes.get_chat_session",+ "backend.api.features.chat.routes.get_chat_session_metadata",new_callable=AsyncMock,return_value=mock_session,)@@ -1755,7 +1755,7 @@ def test_disconnect_stream_returns_404_when_session_missing(test_user_id: str,) -> None:mocker.patch(- "backend.api.features.chat.routes.get_chat_session",+ "backend.api.features.chat.routes.get_chat_session_metadata",new_callable=AsyncMock,return_value=None,)@@ -1917,6 +1917,66 @@ def test_create_session_rejects_unknown_fields(assert response.status_code == 422+def test_health_check_returns_503_when_metadata_read_returns_none(+ mocker: pytest_mock.MockerFixture,+) -> None:+ # Round-trips create-then-read; if the read path returns None despite+ # a successful create, the health endpoint must surface the failure.+ from backend.copilot.model import ChatSession++ mocker.patch(+ "backend.data.user.get_or_create_user",+ new_callable=AsyncMock,+ return_value=None,+ )+ mocker.patch(+ "backend.api.features.chat.routes.create_chat_session",+ new_callable=AsyncMock,+ side_effect=lambda uid, *, dry_run: ChatSession.new(uid, dry_run=dry_run),+ )+ mocker.patch(+ "backend.api.features.chat.routes.get_chat_session_metadata",+ new_callable=AsyncMock,+ return_value=None,+ )++ response = client.get("/health")+ assert response.status_code == 503+ assert "unhealthy" in response.json()["detail"].lower()+++def test_health_check_returns_healthy_on_round_trip_success(+ mocker: pytest_mock.MockerFixture,+) -> None:+ # Happy path: create + read both succeed → 200 with healthy body.+ from backend.copilot.model import ChatSession, ChatSessionInfo++ mocker.patch(+ "backend.data.user.get_or_create_user",+ new_callable=AsyncMock,+ return_value=None,+ )+ fake_session = ChatSession.new("health-check-user", dry_run=False)+ mocker.patch(+ "backend.api.features.chat.routes.create_chat_session",+ new_callable=AsyncMock,+ return_value=fake_session,+ )+ mocker.patch(+ "backend.api.features.chat.routes.get_chat_session_metadata",+ new_callable=AsyncMock,+ return_value=ChatSessionInfo(+ **{**fake_session.model_dump(exclude={"messages"})}+ ),+ )++ response = client.get("/health")+ assert response.status_code == 200+ body = response.json()+ assert body["status"] == "healthy"+ assert body["service"] == "chat"++def test_resolve_session_permissions_blocks_out_of_scope_tools() -> None:"""Builder-bound sessions return a blacklist of the three tools thatconflict with the panel's graph-bound scope. Regular sessions returndiff --git a/autogpt_platform/backend/backend/copilot/builder_context.py b/autogpt_platform/backend/backend/copilot/builder_context.pyindex 9f36350d1c..65f4e9aa78 100644--- a/autogpt_platform/backend/backend/copilot/builder_context.py+++ b/autogpt_platform/backend/backend/copilot/builder_context.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport loggingfrom typing import Any-from backend.copilot.model import ChatSession+from backend.copilot.model import ChatSession, ChatSessionInfofrom backend.copilot.permissions import CopilotPermissionsfrom backend.copilot.tools.agent_generator import get_agent_as_jsonfrom backend.copilot.tools.get_agent_building_guide import _load_guide@@ -31,10 +31,14 @@ BUILDER_BLOCKED_TOOLS: tuple[str, ...] = (def resolve_session_permissions(- session: ChatSession | None,+ session: ChatSessionInfo | None,) -> CopilotPermissions | None:"""Blacklist :data:`BUILDER_BLOCKED_TOOLS` for builder-bound sessions,- return ``None`` (unrestricted) otherwise."""+ return ``None`` (unrestricted) otherwise.++ Reads ``metadata.builder_graph_id`` only — works on either the bare+ ``ChatSessionInfo`` (no messages) or the full ``ChatSession``.+ """if session is None or not session.metadata.builder_graph_id:return Nonereturn CopilotPermissions(diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 06b5df9cc4..6b5e54586e 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -555,6 +555,30 @@ async def get_chat_session(return session+async def get_chat_session_metadata(+ session_id: str,+ user_id: str | None = None,+) -> ChatSessionInfo | None:+ """Get chat session metadata only (no messages).++ Goes directly to the DB by primary key — bypasses the Redis cache,+ which stores the full session and would deserialize the entire message+ history just to read ``user_id``. Use this for ownership/existence+ checks; use ``get_chat_session`` when the message history is actually+ needed.+ """+ session_meta = await chat_db().get_chat_session_metadata(session_id)+ if session_meta is None:+ return None+ if user_id is not None and session_meta.user_id != user_id:+ logger.warning(+ f"Session {session_id} user id mismatch: "+ f"{session_meta.user_id} != {user_id}"+ )+ return None+ return session_meta++async def _get_session_from_cache(session_id: str) -> ChatSession | None:"""Get a chat session from Redis cache."""redis_key = _get_session_cache_key(session_id)diff --git a/autogpt_platform/backend/backend/data/db_manager.py b/autogpt_platform/backend/backend/data/db_manager.pyindex 1d297a89d0..9f5da2aa9a 100644--- a/autogpt_platform/backend/backend/data/db_manager.py+++ b/autogpt_platform/backend/backend/data/db_manager.py@@ -380,6 +380,7 @@ class DatabaseManager(AppService):# ============ CoPilot Chat Sessions ============ #get_chat_session = _(chat_db.get_chat_session)+ get_chat_session_metadata = _(chat_db.get_chat_session_metadata)create_chat_session = _(chat_db.create_chat_session)update_chat_session = _(chat_db.update_chat_session)add_chat_message = _(chat_db.add_chat_message)@@ -605,6 +606,7 @@ class DatabaseManagerAsyncClient(AppServiceClient):# ============ CoPilot Chat Sessions ============ #get_chat_session = d.get_chat_session+ get_chat_session_metadata = d.get_chat_session_metadatacreate_chat_session = d.create_chat_sessionupdate_chat_session = d.update_chat_sessionadd_chat_message = d.add_chat_message