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.
fix(backend/copilot): replace dedup lock with idempotent append_and_save_message (#12814)
Zamil Majdy60b85640e757
diff --git a/autogpt_platform/backend/backend/api/features/chat/routes.py b/autogpt_platform/backend/backend/api/features/chat/routes.pyindex b5b1d0d6fe..63d49ac43a 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes.py@@ -18,7 +18,6 @@ from backend.copilot import stream_registryfrom backend.copilot.config import ChatConfig, CopilotLlmModel, CopilotModefrom backend.copilot.db import get_chat_messages_paginatedfrom backend.copilot.executor.utils import enqueue_cancel_task, enqueue_copilot_turn-from backend.copilot.message_dedup import acquire_dedup_lockfrom backend.copilot.model import (ChatMessage,ChatSession,@@ -913,9 +912,6 @@ async def stream_chat_post(# Also sanitise file_ids so only validated, workspace-scoped IDs are# forwarded downstream (e.g. to the executor via enqueue_copilot_turn).sanitized_file_ids: list[str] | None = None- # Capture the original message text BEFORE any mutation (attachment enrichment)- # so the idempotency hash is stable across retries.- original_message = request.messageif request.file_ids and user_id:# Filter to valid UUIDs only to prevent DB abusevalid_ids = [fid for fid in request.file_ids if _UUID_RE.match(fid)]@@ -944,58 +940,36 @@ async def stream_chat_post()request.message += files_block- # ── Idempotency guard ────────────────────────────────────────────────────- # Blocks duplicate executor tasks from concurrent/retried POSTs.- # See backend/copilot/message_dedup.py for the full lifecycle description.- dedup_lock = None- if request.is_user_message:- dedup_lock = await acquire_dedup_lock(- session_id, original_message, sanitized_file_ids- )- if dedup_lock is None and (original_message or sanitized_file_ids):-- async def _empty_sse() -> AsyncGenerator[str, None]:- yield StreamFinish().to_sse()- yield "data: [DONE]\n\n"-- return StreamingResponse(- _empty_sse(),- media_type="text/event-stream",- headers={- "Cache-Control": "no-cache",- "X-Accel-Buffering": "no",- "Connection": "keep-alive",- "x-vercel-ai-ui-message-stream": "v1",- },- )-# Atomically append user message to session BEFORE creating task to avoid# race condition where GET_SESSION sees task as "running" but message isn't- # saved yet. append_and_save_message re-fetches inside a lock to prevent- # message loss from concurrent requests.- #- # If any of these operations raises, release the dedup lock before propagating- # so subsequent retries are not blocked for 30 s.- try:- if request.message:- message = ChatMessage(- role="user" if request.is_user_message else "assistant",- content=request.message,- )- if request.is_user_message:- track_user_message(- user_id=user_id,- session_id=session_id,- message_length=len(request.message),- )- logger.info(f"[STREAM] Saving user message to session {session_id}")+ # saved yet. append_and_save_message returns None when a duplicate is+ # detected — in that case skip enqueue to avoid processing the message twice.+ is_duplicate_message = False+ if request.message:+ message = ChatMessage(+ role="user" if request.is_user_message else "assistant",+ content=request.message,+ )+ logger.info(f"[STREAM] Saving user message to session {session_id}")+ is_duplicate_message = (await append_and_save_message(session_id, message)- logger.info(f"[STREAM] User message saved for session {session_id}")+ ) is None+ logger.info(f"[STREAM] User message saved for session {session_id}")+ if not is_duplicate_message and request.is_user_message:+ track_user_message(+ user_id=user_id,+ session_id=session_id,+ message_length=len(request.message),+ )- # Create a task in the stream registry for reconnection support+ # Create a task in the stream registry for reconnection support.+ # For duplicate messages, skip create_session entirely so the infra-retry+ # client subscribes to the *existing* turn's Redis stream and receives the+ # in-progress executor output rather than an empty stream.+ turn_id = ""+ if not is_duplicate_message:turn_id = str(uuid4())log_meta["turn_id"] = turn_id-session_create_start = time.perf_counter()await stream_registry.create_session(session_id=session_id,@@ -1013,7 +987,6 @@ async def stream_chat_post(}},)-await enqueue_copilot_turn(session_id=session_id,user_id=user_id,@@ -1025,10 +998,10 @@ async def stream_chat_post(mode=request.mode,model=request.model,)- except Exception:- if dedup_lock:- await dedup_lock.release()- raise+ else:+ logger.info(+ f"[STREAM] Duplicate message detected for session {session_id}, skipping enqueue"+ )setup_time = (time.perf_counter() - stream_start_time) * 1000logger.info(@@ -1052,12 +1025,6 @@ async def stream_chat_post(subscriber_queue = Nonefirst_chunk_yielded = Falsechunks_yielded = 0- # True for every exit path except GeneratorExit (client disconnect).- # On disconnect the backend turn is still running — releasing the lock- # there would reopen the infra-retry duplicate window. The 30 s TTL- # is the fallback. All other exits (normal finish, early return, error)- # should release so the user can re-send the same message.- release_dedup_lock_on_exit = Truetry:# Subscribe from the position we captured before enqueuing# This avoids replaying old messages while catching all new ones@@ -1069,7 +1036,7 @@ async def stream_chat_post(if subscriber_queue is None:yield StreamFinish().to_sse()- return # finally releases dedup_lock+ return# Read from the subscriber queue and yield to SSElogger.info(@@ -1111,7 +1078,7 @@ async def stream_chat_post(}},)- break # finally releases dedup_lock+ breakexcept asyncio.TimeoutError:yield StreamHeartbeat().to_sse()@@ -1127,7 +1094,6 @@ async def stream_chat_post(}},)- release_dedup_lock_on_exit = Falseexcept Exception as e:elapsed = (time_module.perf_counter() - event_gen_start) * 1000logger.error(@@ -1142,10 +1108,7 @@ async def stream_chat_post(code="stream_error",).to_sse()yield StreamFinish().to_sse()- # finally releases dedup_lockfinally:- if dedup_lock and release_dedup_lock_on_exit:- await dedup_lock.release()# Unsubscribe when client disconnects or stream endsif subscriber_queue is not None:try:diff --git a/autogpt_platform/backend/backend/api/features/chat/routes_test.py b/autogpt_platform/backend/backend/api/features/chat/routes_test.pyindex 8d34832c82..a1ad07deae 100644--- a/autogpt_platform/backend/backend/api/features/chat/routes_test.py+++ b/autogpt_platform/backend/backend/api/features/chat/routes_test.py@@ -133,21 +133,12 @@ def test_stream_chat_rejects_too_many_file_ids():assert response.status_code == 422-def _mock_stream_internals(- mocker: pytest_mock.MockerFixture,- *,- redis_set_returns: object = True,-):+def _mock_stream_internals(mocker: pytest_mock.MockerFixture):"""Mock the async internals of stream_chat_post so tests can exercise- validation and enrichment logic without needing Redis/RabbitMQ.-- Args:- redis_set_returns: Value returned by the mocked Redis ``set`` call.- ``True`` (default) simulates a fresh key (new message);- ``None`` simulates a collision (duplicate blocked).+ validation and enrichment logic without needing RabbitMQ.Returns:- A namespace with ``redis``, ``save``, and ``enqueue`` mock objects so+ A namespace with ``save`` and ``enqueue`` mock objects socallers can make additional assertions about side-effects."""import types@@ -158,7 +149,7 @@ def _mock_stream_internals()mock_save = mocker.patch("backend.api.features.chat.routes.append_and_save_message",- return_value=None,+ return_value=MagicMock(), # non-None = message was saved (not a duplicate))mock_registry = mocker.MagicMock()mock_registry.create_session = mocker.AsyncMock(return_value=None)@@ -174,15 +165,9 @@ def _mock_stream_internals("backend.api.features.chat.routes.track_user_message",return_value=None,)- mock_redis = AsyncMock()- mock_redis.set = AsyncMock(return_value=redis_set_returns)- mocker.patch(- "backend.copilot.message_dedup.get_redis_async",- new_callable=AsyncMock,- return_value=mock_redis,+ return types.SimpleNamespace(+ save=mock_save, enqueue=mock_enqueue, registry=mock_registry)- ns = types.SimpleNamespace(redis=mock_redis, save=mock_save, enqueue=mock_enqueue)- return nsdef test_stream_chat_accepts_20_file_ids(mocker: pytest_mock.MockerFixture):@@ -211,6 +196,29 @@ def test_stream_chat_accepts_20_file_ids(mocker: pytest_mock.MockerFixture):assert response.status_code == 200+# ─── Duplicate message dedup ──────────────────────────────────────────+++def test_stream_chat_skips_enqueue_for_duplicate_message(+ mocker: pytest_mock.MockerFixture,+):+ """When append_and_save_message returns None (duplicate detected),+ enqueue_copilot_turn and stream_registry.create_session must NOT be called+ to avoid double-processing and to prevent overwriting the active stream's+ turn_id in Redis (which would cause reconnecting clients to miss the response)."""+ mocks = _mock_stream_internals(mocker)+ # Override save to return None — signalling a duplicate+ mocks.save.return_value = None++ response = client.post(+ "/sessions/sess-1/stream",+ json={"message": "hello"},+ )+ assert response.status_code == 200+ mocks.enqueue.assert_not_called()+ mocks.registry.create_session.assert_not_called()++# ─── UUID format filtering ─────────────────────────────────────────────@@ -706,237 +714,6 @@ class TestStripInjectedContext:assert result["content"] == "hello"-# ─── Idempotency / duplicate-POST guard ──────────────────────────────---def test_stream_chat_blocks_duplicate_post_returns_empty_sse(- mocker: pytest_mock.MockerFixture,-) -> None:- """A second POST with the same message within the 30-s window must return- an empty SSE stream (StreamFinish + [DONE]) so the frontend marks the- turn complete without creating a ghost response."""- # redis_set_returns=None simulates a collision: the NX key already exists.- ns = _mock_stream_internals(mocker, redis_set_returns=None)-- response = client.post(- "/sessions/sess-dup/stream",- json={"message": "duplicate message", "is_user_message": True},- )-- assert response.status_code == 200- body = response.text- # The response must contain StreamFinish (type=finish) and the SSE [DONE] terminator.- assert '"finish"' in body- assert "[DONE]" in body- # The empty SSE response must include the AI SDK protocol header so the- # frontend treats it as a valid stream and marks the turn complete.- assert response.headers.get("x-vercel-ai-ui-message-stream") == "v1"- # The duplicate guard must prevent save/enqueue side effects.- ns.save.assert_not_called()- ns.enqueue.assert_not_called()---def test_stream_chat_first_post_proceeds_normally(- mocker: pytest_mock.MockerFixture,-) -> None:- """The first POST (Redis NX key set successfully) must proceed through the- normal streaming path — no early return."""- ns = _mock_stream_internals(mocker, redis_set_returns=True)-- response = client.post(- "/sessions/sess-new/stream",- json={"message": "first message", "is_user_message": True},- )-- assert response.status_code == 200- # Redis set must have been called once with the NX flag.- ns.redis.set.assert_called_once()- call_kwargs = ns.redis.set.call_args- assert call_kwargs.kwargs.get("nx") is True---def test_stream_chat_dedup_skipped_for_non_user_messages(- mocker: pytest_mock.MockerFixture,-) -> None:- """System/assistant messages (is_user_message=False) bypass the dedup- guard — they are injected programmatically and must always be processed."""- ns = _mock_stream_internals(mocker, redis_set_returns=None)-- response = client.post(- "/sessions/sess-sys/stream",- json={"message": "system context", "is_user_message": False},- )-- # Even though redis_set_returns=None (would block a user message),- # the endpoint must proceed because is_user_message=False.- assert response.status_code == 200- ns.redis.set.assert_not_called()---def test_stream_chat_dedup_hash_uses_original_message_not_mutated(- mocker: pytest_mock.MockerFixture,-) -> None:- """The dedup hash must be computed from the original request message,- not the mutated version that has the [Attached files] block appended.- A file_id is sent so the route actually appends the [Attached files] block,- exercising the mutation path — the hash must still match the original text."""- import hashlib-- ns = _mock_stream_internals(mocker, redis_set_returns=True)-- file_id = "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"- # Mock workspace + prisma so the attachment block is actually appended.- mocker.patch(- "backend.api.features.chat.routes.get_or_create_workspace",- return_value=type("W", (), {"id": "ws-1"})(),- )- fake_file = type(- "F",- (),- {- "id": file_id,- "name": "doc.pdf",- "mimeType": "application/pdf",- "sizeBytes": 1024,- },- )()- mock_prisma = mocker.MagicMock()- mock_prisma.find_many = mocker.AsyncMock(return_value=[fake_file])- mocker.patch(- "prisma.models.UserWorkspaceFile.prisma",- return_value=mock_prisma,- )-- response = client.post(- "/sessions/sess-hash/stream",- json={- "message": "plain message",- "is_user_message": True,- "file_ids": [file_id],- },- )-- assert response.status_code == 200- ns.redis.set.assert_called_once()- call_args = ns.redis.set.call_args- dedup_key = call_args.args[0]-- # Hash must use the original message + sorted file IDs, not the mutated text.- expected_hash = hashlib.sha256(- f"sess-hash:plain message:{file_id}".encode()- ).hexdigest()[:16]- expected_key = f"chat:msg_dedup:sess-hash:{expected_hash}"- assert dedup_key == expected_key, (- f"Dedup key {dedup_key!r} does not match expected {expected_key!r} — "- "hash may be using mutated message or wrong inputs"- )---def test_stream_chat_dedup_key_released_after_stream_finish(- mocker: pytest_mock.MockerFixture,-) -> None:- """The dedup Redis key must be deleted after the turn completes (when- subscriber_queue is None the route yields StreamFinish immediately and- should release the key so the user can re-send the same message)."""- from unittest.mock import AsyncMock as _AsyncMock-- # Set up all internals manually so we can control subscribe_to_session.- mocker.patch(- "backend.api.features.chat.routes._validate_and_get_session",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.append_and_save_message",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.enqueue_copilot_turn",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.track_user_message",- return_value=None,- )- mock_registry = mocker.MagicMock()- mock_registry.create_session = _AsyncMock(return_value=None)- # None → early-finish path: StreamFinish yielded immediately, dedup key released.- mock_registry.subscribe_to_session = _AsyncMock(return_value=None)- mocker.patch(- "backend.api.features.chat.routes.stream_registry",- mock_registry,- )- mock_redis = mocker.AsyncMock()- mock_redis.set = _AsyncMock(return_value=True)- mocker.patch(- "backend.copilot.message_dedup.get_redis_async",- new_callable=_AsyncMock,- return_value=mock_redis,- )-- response = client.post(- "/sessions/sess-finish/stream",- json={"message": "hello", "is_user_message": True},- )-- assert response.status_code == 200- body = response.text- assert '"finish"' in body- # The dedup key must be released so intentional re-sends are allowed.- mock_redis.delete.assert_called_once()---def test_stream_chat_dedup_key_released_even_when_redis_delete_raises(- mocker: pytest_mock.MockerFixture,-) -> None:- """The route must not crash when the dedup Redis delete fails on the- subscriber_queue-is-None early-finish path (except Exception: pass)."""- from unittest.mock import AsyncMock as _AsyncMock-- mocker.patch(- "backend.api.features.chat.routes._validate_and_get_session",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.append_and_save_message",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.enqueue_copilot_turn",- return_value=None,- )- mocker.patch(- "backend.api.features.chat.routes.track_user_message",- return_value=None,- )- mock_registry = mocker.MagicMock()- mock_registry.create_session = _AsyncMock(return_value=None)- mock_registry.subscribe_to_session = _AsyncMock(return_value=None)- mocker.patch(- "backend.api.features.chat.routes.stream_registry",- mock_registry,- )- mock_redis = mocker.AsyncMock()- mock_redis.set = _AsyncMock(return_value=True)- # Make the delete raise so the except-pass branch is exercised.- mock_redis.delete = _AsyncMock(side_effect=RuntimeError("redis gone"))- mocker.patch(- "backend.copilot.message_dedup.get_redis_async",- new_callable=_AsyncMock,- return_value=mock_redis,- )-- # Should not raise even though delete fails.- response = client.post(- "/sessions/sess-finish-err/stream",- json={"message": "hello", "is_user_message": True},- )-- assert response.status_code == 200- assert '"finish"' in response.text- # delete must have been attempted — the except-pass branch silenced the error.- mock_redis.delete.assert_called_once()--# ─── DELETE /sessions/{id}/stream — disconnect listeners ──────────────diff --git a/autogpt_platform/backend/backend/copilot/message_dedup.py b/autogpt_platform/backend/backend/copilot/message_dedup.pydeleted file mode 100644index 2af13b559a..0000000000--- a/autogpt_platform/backend/backend/copilot/message_dedup.py+++ /dev/null@@ -1,71 +0,0 @@-"""Per-request idempotency lock for the /stream endpoint.--Prevents duplicate executor tasks from concurrent or retried POSTs (e.g. k8s-rolling-deploy retries, nginx upstream retries, rapid double-clicks).--Lifecycle-----------1. ``acquire()`` — computes a stable hash of (session_id, message, file_ids)- and atomically sets a Redis NX key. Returns a ``_DedupLock`` on success or- ``None`` when the key already exists (duplicate request).-2. ``release()`` — deletes the key. Must be called on turn completion or turn- error so the next legitimate send is never blocked.-3. On client disconnect (``GeneratorExit``) the lock must NOT be released —- the backend turn is still running, and releasing would reopen the duplicate- window for infra-level retries. The 30 s TTL is the safety net.-"""--import hashlib-import logging--from backend.data.redis_client import get_redis_async--logger = logging.getLogger(__name__)--_KEY_PREFIX = "chat:msg_dedup"-_TTL_SECONDS = 30---class _DedupLock:- def __init__(self, key: str, redis) -> None:- self._key = key- self._redis = redis-- async def release(self) -> None:- """Best-effort key deletion. The TTL handles failures silently."""- try:- await self._redis.delete(self._key)- except Exception:- pass---async def acquire_dedup_lock(- session_id: str,- message: str | None,- file_ids: list[str] | None,-) -> _DedupLock | None:- """Acquire the idempotency lock for this (session, message, files) tuple.-- Returns a ``_DedupLock`` when the lock is freshly acquired (first request).- Returns ``None`` when a duplicate is detected (lock already held).- Returns ``None`` when there is nothing to deduplicate (no message, no files).- """- if not message and not file_ids:- return None-- sorted_ids = ":".join(sorted(file_ids or []))- content_hash = hashlib.sha256(- f"{session_id}:{message or ''}:{sorted_ids}".encode()- ).hexdigest()[:16]- key = f"{_KEY_PREFIX}:{session_id}:{content_hash}"-- redis = await get_redis_async()- acquired = await redis.set(key, "1", ex=_TTL_SECONDS, nx=True)- if not acquired:- logger.warning(- f"[STREAM] Duplicate user message blocked for session {session_id}, "- f"hash={content_hash} — returning empty SSE",- )- return None-- return _DedupLock(key, redis)diff --git a/autogpt_platform/backend/backend/copilot/message_dedup_test.py b/autogpt_platform/backend/backend/copilot/message_dedup_test.pydeleted file mode 100644index 935ddd36b6..0000000000--- a/autogpt_platform/backend/backend/copilot/message_dedup_test.py+++ /dev/null@@ -1,94 +0,0 @@-"""Unit tests for backend.copilot.message_dedup."""--from unittest.mock import AsyncMock--import pytest-import pytest_mock--from backend.copilot.message_dedup import _KEY_PREFIX, acquire_dedup_lock---def _patch_redis(mocker: pytest_mock.MockerFixture, *, set_returns):- mock_redis = AsyncMock()- mock_redis.set = AsyncMock(return_value=set_returns)- mocker.patch(- "backend.copilot.message_dedup.get_redis_async",- new_callable=AsyncMock,- return_value=mock_redis,- )- return mock_redis---async def test_acquire_returns_none_when_no_message_no_files(- mocker: pytest_mock.MockerFixture,-) -> None:- """Nothing to deduplicate — no Redis call made, None returned."""- mock_redis = _patch_redis(mocker, set_returns=True)- result = await acquire_dedup_lock("sess-1", None, None)- assert result is None- mock_redis.set.assert_not_called()---async def test_acquire_returns_lock_on_first_request(- mocker: pytest_mock.MockerFixture,-) -> None:- """First request acquires the lock and returns a _DedupLock."""- mock_redis = _patch_redis(mocker, set_returns=True)- lock = await acquire_dedup_lock("sess-1", "hello", None)- assert lock is not None- mock_redis.set.assert_called_once()- key_arg = mock_redis.set.call_args.args[0]- assert key_arg.startswith(f"{_KEY_PREFIX}:sess-1:")---async def test_acquire_returns_none_on_duplicate(- mocker: pytest_mock.MockerFixture,-) -> None:- """Duplicate request (NX fails) returns None to signal the caller."""- _patch_redis(mocker, set_returns=None)- result = await acquire_dedup_lock("sess-1", "hello", None)- assert result is None---async def test_acquire_key_stable_across_file_order(- mocker: pytest_mock.MockerFixture,-) -> None:- """File IDs are sorted before hashing so order doesn't affect the key."""- mock_redis_1 = _patch_redis(mocker, set_returns=True)- await acquire_dedup_lock("sess-1", "msg", ["b", "a"])- key_ab = mock_redis_1.set.call_args.args[0]-- mock_redis_2 = _patch_redis(mocker, set_returns=True)- await acquire_dedup_lock("sess-1", "msg", ["a", "b"])- key_ba = mock_redis_2.set.call_args.args[0]-- assert key_ab == key_ba---async def test_release_deletes_key(- mocker: pytest_mock.MockerFixture,-) -> None:- """release() calls Redis delete exactly once."""- mock_redis = _patch_redis(mocker, set_returns=True)- lock = await acquire_dedup_lock("sess-1", "hello", None)- assert lock is not None- await lock.release()- mock_redis.delete.assert_called_once()---async def test_release_swallows_redis_error(- mocker: pytest_mock.MockerFixture,-) -> None:- """release() must not raise even when Redis delete fails."""- mock_redis = _patch_redis(mocker, set_returns=True)- mock_redis.delete = AsyncMock(side_effect=RuntimeError("redis down"))- lock = await acquire_dedup_lock("sess-1", "hello", None)- assert lock is not None- await lock.release() # must not raise- mock_redis.delete.assert_called_once()diff --git a/autogpt_platform/backend/backend/copilot/model.py b/autogpt_platform/backend/backend/copilot/model.pyindex 39229b7210..08019233e7 100644--- a/autogpt_platform/backend/backend/copilot/model.py+++ b/autogpt_platform/backend/backend/copilot/model.py@@ -1,9 +1,8 @@-import asyncioimport loggingimport uuid+from contextlib import asynccontextmanagerfrom datetime import UTC, datetime-from typing import Any, Self, cast-from weakref import WeakValueDictionary+from typing import Any, AsyncIterator, Self, castfrom openai.types.chat import (ChatCompletionAssistantMessageParam,@@ -522,10 +521,7 @@ async def upsert_chat_session(callers are aware of the persistence failure.RedisError: If the cache write fails (after successful DB write)."""- # Acquire session-specific lock to prevent concurrent upserts- lock = await _get_session_lock(session.session_id)-- async with lock:+ async with _get_session_lock(session.session_id) as _:# Always query DB for existing message count to ensure consistencyexisting_message_count = await chat_db().get_next_sequence(session.session_id)@@ -651,20 +647,50 @@ async def _save_session_to_db(msg.sequence = existing_message_count + i-async def append_and_save_message(session_id: str, message: ChatMessage) -> ChatSession:+async def append_and_save_message(+ session_id: str, message: ChatMessage+) -> ChatSession | None:"""Atomically append a message to a session and persist it.- Acquires the session lock, re-fetches the latest session state,- appends the message, and saves — preventing message loss when- concurrent requests modify the same session.- """- lock = await _get_session_lock(session_id)+ Returns the updated session, or None if the message was detected as a+ duplicate (idempotency guard). Callers must check for None and skip any+ downstream work (e.g. enqueuing a new LLM turn) when a duplicate is detected.- async with lock:- session = await get_chat_session(session_id)+ Uses _get_session_lock (Redis NX) to serialise concurrent writers across replicas.+ The idempotency check below provides a last-resort guard when the lock degrades.+ """+ async with _get_session_lock(session_id) as lock_acquired:+ # When the lock degraded (Redis down or 2s timeout), bypass cache for+ # the idempotency check. Stale cache could let two concurrent writers+ # both see the old state, pass the check, and write the same message.+ if lock_acquired:+ session = await get_chat_session(session_id)+ else:+ session = await _get_session_from_db(session_id)if session is None:raise ValueError(f"Session {session_id} not found")+ # Idempotency: skip if the trailing block of same-role messages already+ # contains this content. Uses is_message_duplicate which checks all+ # consecutive trailing messages of the same role, not just [-1].+ #+ # This collapses infra/nginx retries whether they land on the same pod+ # (serialised by the Redis lock) or a different pod.+ #+ # Legit same-text messages are distinguished by the assistant turn+ # between them: if the user said "yes", got a response, and says+ # "yes" again, session.messages[-1] is the assistant reply, so the+ # role check fails and the second message goes through normally.+ #+ # Edge case: if a turn dies without writing any assistant message,+ # the user's next send of the same text is blocked here permanently.+ # The fix is to ensure failed turns always write an error/timeout+ # assistant message so the session always ends on an assistant turn.+ if message.content is not None and is_message_duplicate(+ session.messages, message.role, message.content+ ):+ return None # duplicate — caller should skip enqueue+session.messages.append(message)existing_message_count = await chat_db().get_next_sequence(session_id)@@ -679,6 +705,9 @@ async def append_and_save_message(session_id: str, message: ChatMessage) -> Chatawait cache_chat_session(session)except Exception as e:logger.warning(f"Cache write failed for session {session_id}: {e}")+ # Invalidate the stale entry so future reads fall back to DB,+ # preventing a retry from bypassing the idempotency check above.+ await invalidate_session_cache(session_id)return session@@ -764,10 +793,6 @@ async def delete_chat_session(session_id: str, user_id: str | None = None) -> boexcept Exception as e:logger.warning(f"Failed to delete session {session_id} from cache: {e}")- # Clean up session lock (belt-and-suspenders with WeakValueDictionary)- async with _session_locks_mutex:- _session_locks.pop(session_id, None)-# Shut down any local browser daemon for this session (best-effort).# Inline import required: all tool modules import ChatSession from this# module, so any top-level import from tools.* would create a cycle.@@ -832,25 +857,38 @@ async def update_session_title(# ==================== Chat session locks ==================== #-_session_locks: WeakValueDictionary[str, asyncio.Lock] = WeakValueDictionary()-_session_locks_mutex = asyncio.Lock()+@asynccontextmanager+async def _get_session_lock(session_id: str) -> AsyncIterator[bool]:+ """Distributed Redis lock for a session, usable as an async context manager.-async def _get_session_lock(session_id: str) -> asyncio.Lock:- """Get or create a lock for a specific session to prevent concurrent upserts.+ Yields True if the lock was acquired, False if it timed out or Redis was+ unavailable. Callers should treat False as a degraded mode and prefer fresh+ DB reads over cache to avoid acting on stale state.- This was originally added to solve the specific problem of race conditions between- the session title thread and the conversation thread, which always occurs on the- same instance as we prevent rapid request sends on the frontend.-- Uses WeakValueDictionary for automatic cleanup: locks are garbage collected- when no coroutine holds a reference to them, preventing memory leaks from- unbounded growth of session locks. Explicit cleanup also occurs- in `delete_chat_session()`.+ Uses redis-py's built-in Lock (Lua-script acquire/release) so lock acquisition+ is atomic and release is owner-verified. Blocks up to 2s for a concurrent+ writer to finish; the 10s TTL ensures a dead pod never holds the lock forever."""- async with _session_locks_mutex:- lock = _session_locks.get(session_id)- if lock is None:- lock = asyncio.Lock()- _session_locks[session_id] = lock- return lock+ _lock_key = f"copilot:session_lock:{session_id}"+ lock = None+ acquired = False+ try:+ _redis = await get_redis_async()+ lock = _redis.lock(_lock_key, timeout=10, blocking_timeout=2)+ acquired = await lock.acquire(blocking=True)+ if not acquired:+ logger.warning(+ "Could not acquire session lock for %s within 2s", session_id+ )+ except Exception as e:+ logger.warning("Redis unavailable for session lock on %s: %s", session_id, e)++ try:+ yield acquired+ finally:+ if acquired and lock is not None:+ try:+ await lock.release()+ except Exception:+ pass # TTL will expire the keydiff --git a/autogpt_platform/backend/backend/copilot/model_test.py b/autogpt_platform/backend/backend/copilot/model_test.pyindex c78d63cc5a..e97ac24d51 100644--- a/autogpt_platform/backend/backend/copilot/model_test.py+++ b/autogpt_platform/backend/backend/copilot/model_test.py@@ -11,11 +11,13 @@ from openai.types.chat.chat_completion_message_tool_call_param import (ChatCompletionMessageToolCallParam,Function,)+from pytest_mock import MockerFixturefrom .model import (ChatMessage,ChatSession,Usage,+ append_and_save_message,get_chat_session,is_message_duplicate,maybe_append_user_message,@@ -574,3 +576,345 @@ def test_maybe_append_assistant_skips_duplicate():result = maybe_append_user_message(session, "dup", is_user_message=False)assert result is Falseassert len(session.messages) == 2+++# --------------------------------------------------------------------------- #+# append_and_save_message #+# --------------------------------------------------------------------------- #+++def _make_session_with_messages(*msgs: ChatMessage) -> ChatSession:+ s = ChatSession.new(user_id="u1", dry_run=False)+ s.messages = list(msgs)+ return s++[email protected](loop_scope="session")+async def test_append_and_save_message_returns_none_for_duplicate(+ mocker: MockerFixture,+) -> None:+ """append_and_save_message returns None when the trailing message is a duplicate."""++ session = _make_session_with_messages(+ ChatMessage(role="user", content="hello"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock()+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )++ result = await append_and_save_message(+ session.session_id, ChatMessage(role="user", content="hello")+ )+ assert result is None++[email protected](loop_scope="session")+async def test_append_and_save_message_appends_new_message(+ mocker: MockerFixture,+) -> None:+ """append_and_save_message appends a non-duplicate message and returns the session."""++ session = _make_session_with_messages(+ ChatMessage(role="user", content="hello"),+ ChatMessage(role="assistant", content="hi"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock()+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=2)+ ),+ )+ mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new_callable=mocker.AsyncMock,+ )++ new_msg = ChatMessage(role="user", content="second message")+ result = await append_and_save_message(session.session_id, new_msg)+ assert result is not None+ assert result.messages[-1].content == "second message"++[email protected](loop_scope="session")+async def test_append_and_save_message_raises_when_session_not_found(+ mocker: MockerFixture,+) -> None:+ """append_and_save_message raises ValueError when the session does not exist."""++ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock()+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=None,+ )++ with pytest.raises(ValueError, match="not found"):+ await append_and_save_message(+ "missing-session-id", ChatMessage(role="user", content="hi")+ )++[email protected](loop_scope="session")+async def test_append_and_save_message_uses_db_when_lock_degraded(+ mocker: MockerFixture,+) -> None:+ """When the Redis lock times out (acquired=False), the fallback reads from DB."""++ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="hi"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=False)+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mock_get_from_db = mocker.patch(+ "backend.copilot.model._get_session_from_db",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=1)+ ),+ )+ mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new_callable=mocker.AsyncMock,+ )++ new_msg = ChatMessage(role="user", content="new msg")+ result = await append_and_save_message(session.session_id, new_msg)+ # DB path was used (not cache-first)+ mock_get_from_db.assert_called_once_with(session.session_id)+ assert result is not None++[email protected](loop_scope="session")+async def test_append_and_save_message_raises_database_error_on_save_failure(+ mocker: MockerFixture,+) -> None:+ """When _save_session_to_db fails, append_and_save_message raises DatabaseError."""+ from backend.util.exceptions import DatabaseError++ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="hi"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock()+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ side_effect=RuntimeError("db down"),+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=1)+ ),+ )++ with pytest.raises(DatabaseError):+ await append_and_save_message(+ session.session_id, ChatMessage(role="user", content="new msg")+ )++[email protected](loop_scope="session")+async def test_append_and_save_message_invalidates_cache_on_cache_failure(+ mocker: MockerFixture,+) -> None:+ """When cache_chat_session fails, invalidate_session_cache is called to avoid stale reads."""++ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="hi"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock()+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=1)+ ),+ )+ mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new_callable=mocker.AsyncMock,+ side_effect=RuntimeError("redis write failed"),+ )+ mock_invalidate = mocker.patch(+ "backend.copilot.model.invalidate_session_cache",+ new_callable=mocker.AsyncMock,+ )++ result = await append_and_save_message(+ session.session_id, ChatMessage(role="user", content="new msg")+ )+ # DB write succeeded, cache invalidation was called+ mock_invalidate.assert_called_once_with(session.session_id)+ assert result is not None++[email protected](loop_scope="session")+async def test_append_and_save_message_uses_db_when_redis_unavailable(+ mocker: MockerFixture,+) -> None:+ """When get_redis_async raises, _get_session_lock yields False (degraded) and DB is read."""++ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="hi"),+ )+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ side_effect=ConnectionError("redis down"),+ )+ mock_get_from_db = mocker.patch(+ "backend.copilot.model._get_session_from_db",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=1)+ ),+ )+ mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new_callable=mocker.AsyncMock,+ )++ new_msg = ChatMessage(role="user", content="new msg")+ result = await append_and_save_message(session.session_id, new_msg)+ mock_get_from_db.assert_called_once_with(session.session_id)+ assert result is not None++[email protected](loop_scope="session")+async def test_append_and_save_message_lock_release_failure_is_ignored(+ mocker: MockerFixture,+) -> None:+ """If lock.release() raises, the exception is swallowed (TTL will clean up)."""++ session = _make_session_with_messages(+ ChatMessage(role="assistant", content="hi"),+ )+ mock_redis_lock = mocker.AsyncMock()+ mock_redis_lock.acquire = mocker.AsyncMock(return_value=True)+ mock_redis_lock.release = mocker.AsyncMock(+ side_effect=RuntimeError("release failed")+ )+ mock_redis_client = mocker.MagicMock()+ mock_redis_client.lock = mocker.MagicMock(return_value=mock_redis_lock)+ mocker.patch(+ "backend.copilot.model.get_redis_async",+ new_callable=mocker.AsyncMock,+ return_value=mock_redis_client,+ )+ mocker.patch(+ "backend.copilot.model.get_chat_session",+ new_callable=mocker.AsyncMock,+ return_value=session,+ )+ mocker.patch(+ "backend.copilot.model._save_session_to_db",+ new_callable=mocker.AsyncMock,+ )+ mocker.patch(+ "backend.copilot.model.chat_db",+ return_value=mocker.MagicMock(+ get_next_sequence=mocker.AsyncMock(return_value=1)+ ),+ )+ mocker.patch(+ "backend.copilot.model.cache_chat_session",+ new_callable=mocker.AsyncMock,+ )++ new_msg = ChatMessage(role="user", content="new msg")+ result = await append_and_save_message(session.session_id, new_msg)+ assert result is not Nonediff --git a/autogpt_platform/backend/backend/copilot/stream_registry.py b/autogpt_platform/backend/backend/copilot/stream_registry.pyindex 030763dbca..02fa21b574 100644--- a/autogpt_platform/backend/backend/copilot/stream_registry.py+++ b/autogpt_platform/backend/backend/copilot/stream_registry.py@@ -423,20 +423,33 @@ async def subscribe_to_session(extra={"json_fields": {**log_meta, "duration_ms": hgetall_time}},)- # RACE CONDITION FIX: If session not found, retry once after small delay- # This handles the case where subscribe_to_session is called immediately- # after create_session but before Redis propagates the write+ # RACE CONDITION FIX: If session not found, retry with backoff.+ # Duplicate requests skip create_session and subscribe immediately; the+ # original request's create_session (a Redis hset) may not have completed+ # yet. 3 × 100ms gives a 300ms window which covers DB-write latency on the+ # original request before the hset even starts.if not meta:- logger.warning(- "[TIMING] Session not found on first attempt, retrying after 50ms delay",- extra={"json_fields": {**log_meta}},- )- await asyncio.sleep(0.05) # 50ms- meta = await redis.hgetall(meta_key) # type: ignore[misc]- if not meta:+ _max_retries = 3+ _retry_delay = 0.1 # 100ms per attempt+ for attempt in range(_max_retries):+ logger.warning(+ f"[TIMING] Session not found (attempt {attempt + 1}/{_max_retries}), "+ f"retrying after {int(_retry_delay * 1000)}ms",+ extra={"json_fields": {**log_meta, "attempt": attempt + 1}},+ )+ await asyncio.sleep(_retry_delay)+ meta = await redis.hgetall(meta_key) # type: ignore[misc]+ if meta:+ logger.info(+ f"[TIMING] Session found after {attempt + 1} retries",+ extra={"json_fields": {**log_meta, "attempts": attempt + 1}},+ )+ break+ else:elapsed = (time.perf_counter() - start_time) * 1000logger.info(- f"[TIMING] Session still not found in Redis after retry ({elapsed:.1f}ms total)",+ f"[TIMING] Session still not found in Redis after {_max_retries} retries "+ f"({elapsed:.1f}ms total)",extra={"json_fields": {**log_meta,@@ -446,10 +459,6 @@ async def subscribe_to_session(},)return None- logger.info(- "[TIMING] Session found after retry",- extra={"json_fields": {**log_meta}},- )# Note: Redis client uses decode_responses=True, so keys are stringssession_status = meta.get("status", "")