From 5af4c60b8ecffb0f5a7eec83a5cd56f74d405a61 Mon Sep 17 00:00:00 2001 From: Nicholas Tindle Date: Wed, 28 Jan 2026 00:39:01 -0600 Subject: [PATCH] fix(backend): use upsert in get_or_create_workspace to prevent race condition Concurrent first-time requests for the same user could both find no workspace and attempt to create, causing unique constraint violation. Using upsert handles this atomically. Co-Authored-By: Claude Opus 4.5 --- .../backend/backend/data/workspace.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/autogpt_platform/backend/backend/data/workspace.py b/autogpt_platform/backend/backend/data/workspace.py index 6fee11d0b3..431e2b6725 100644 --- a/autogpt_platform/backend/backend/data/workspace.py +++ b/autogpt_platform/backend/backend/data/workspace.py @@ -20,21 +20,22 @@ async def get_or_create_workspace(user_id: str) -> UserWorkspace: """ Get user's workspace, creating one if it doesn't exist. + Uses upsert to handle race conditions when multiple concurrent requests + attempt to create a workspace for the same user. + Args: user_id: The user's ID Returns: UserWorkspace instance """ - workspace = await UserWorkspace.prisma().find_unique(where={"userId": user_id}) - - if workspace is None: - workspace = await UserWorkspace.prisma().create( - data={ - "userId": user_id, - } - ) - logger.info(f"Created new workspace {workspace.id} for user {user_id}") + workspace = await UserWorkspace.prisma().upsert( + where={"userId": user_id}, + data={ + "create": {"userId": user_id}, + "update": {}, # No updates needed if exists + }, + ) return workspace