Skip to content

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): make User RPC model forward-compatible during rolling deploys (#12707)

Zamil Majdyfa6ea3648815
diff --git a/autogpt_platform/backend/backend/data/model.py b/autogpt_platform/backend/backend/data/model.py
index fa95bffa21..add0c6b5cf 100644
--- a/autogpt_platform/backend/backend/data/model.py
+++ b/autogpt_platform/backend/backend/data/model.py
@@ -54,7 +54,6 @@ class User(BaseModel):
"""Application-layer User model with snake_case convention."""
model_config = ConfigDict(
- extra="forbid",
str_strip_whitespace=True,
)
diff --git a/autogpt_platform/backend/backend/executor/utils_test.py b/autogpt_platform/backend/backend/executor/utils_test.py
index 57069352f9..e708673756 100644
--- a/autogpt_platform/backend/backend/executor/utils_test.py
+++ b/autogpt_platform/backend/backend/executor/utils_test.py
@@ -1,10 +1,13 @@
+from datetime import datetime, timezone
from typing import cast
import pytest
from pytest_mock import MockerFixture
from backend.data.dynamic_fields import merge_execution_input, parse_execution_output
-from backend.data.execution import ExecutionStatus
+from backend.data.execution import ExecutionStatus, GraphExecutionWithNodes
+from backend.data.model import User
+from backend.executor.utils import add_graph_execution
from backend.util.mock import MockObject
@@ -473,6 +476,104 @@ async def test_add_graph_execution_is_repeatable(mocker: MockerFixture):
assert result2 == mock_graph_exec_2
+# ============================================================================
+# Regression test: RPC layer returns typed User model, not raw dict
+# ============================================================================
+
+
+async def test_add_graph_execution_via_rpc_returns_typed_user(
+ mocker: MockerFixture,
+):
+ """
+ Regression test: `add_graph_execution` accesses `user.timezone` on the User
+ returned by `get_user_by_id`. This test verifies the downstream code path
+ completes without AttributeError when `get_user_by_id` returns a proper typed
+ User model. Note: the mock returns a User directly — _get_return deserialization
+ is not exercised here; see TestGetReturn in util/service_test.py for that.
+ """
+ graph_id = "test-graph-id"
+ user_id = "test-user-id"
+
+ mock_graph = mocker.MagicMock()
+ mock_graph.version = 1
+
+ mock_graph_exec = mocker.MagicMock(spec=GraphExecutionWithNodes)
+ mock_graph_exec.id = "exec-id-rpc"
+ mock_graph_exec.node_executions = []
+ mock_graph_exec.status = ExecutionStatus.QUEUED
+ mock_graph_exec.graph_version = 1
+ mock_graph_exec.to_graph_execution_entry.return_value = mocker.MagicMock()
+
+ mock_queue = mocker.AsyncMock()
+ mock_event_bus = mocker.MagicMock()
+ mock_event_bus.publish = mocker.AsyncMock()
+
+ mock_validate = mocker.patch(
+ "backend.executor.utils.validate_and_construct_node_execution_input"
+ )
+ mock_validate.return_value = (mock_graph, [], {}, set())
+
+ mock_prisma = mocker.patch("backend.executor.utils.prisma")
+ mock_prisma.is_connected.return_value = (
+ False # prisma not connected: uses RPC path instead
+ )
+
+ # The RPC layer (_get_return) deserializes JSON dicts into typed Pydantic models.
+ # The mock simulates what add_graph_execution receives after that deserialization:
+ # a proper User model, not a raw dict.
+ mock_user = User(
+ id=user_id,
+ name=None,
+ created_at=datetime.now(timezone.utc),
+ updated_at=datetime.now(timezone.utc),
+ stripe_customer_id=None,
+ top_up_config=None,
+ timezone="UTC",
+ )
+
+ mock_db_client = mocker.MagicMock()
+ mock_db_client.get_user_by_id = mocker.AsyncMock(return_value=mock_user)
+ mock_db_client.get_graph_settings = mocker.AsyncMock(
+ return_value=mocker.MagicMock(
+ human_in_the_loop_safe_mode=False, sensitive_action_safe_mode=False
+ )
+ )
+ mock_db_client.create_graph_execution = mocker.AsyncMock(
+ return_value=mock_graph_exec
+ )
+ mock_db_client.update_graph_execution_stats = mocker.AsyncMock(
+ return_value=mock_graph_exec
+ )
+ mock_db_client.update_node_execution_status_batch = mocker.AsyncMock()
+ mock_workspace = mocker.MagicMock()
+ mock_workspace.id = "ws-id"
+ mock_db_client.get_or_create_workspace = mocker.AsyncMock(
+ return_value=mock_workspace
+ )
+ mock_db_client.increment_onboarding_runs = mocker.AsyncMock()
+
+ mocker.patch(
+ "backend.executor.utils.get_database_manager_async_client",
+ return_value=mock_db_client,
+ )
+ mocker.patch(
+ "backend.executor.utils.get_async_execution_queue", return_value=mock_queue
+ )
+ mocker.patch(
+ "backend.executor.utils.get_async_execution_event_bus",
+ return_value=mock_event_bus,
+ )
+
+ # Must not raise AttributeError: 'dict' object has no attribute 'timezone'
+ result = await add_graph_execution(
+ graph_id=graph_id,
+ user_id=user_id,
+ )
+ assert result == mock_graph_exec
+
+
# ============================================================================
# Tests for Optional Credentials Feature
# ============================================================================
diff --git a/autogpt_platform/backend/backend/util/service.py b/autogpt_platform/backend/backend/util/service.py
index 982b3d8ead..a1da0c1a68 100644
--- a/autogpt_platform/backend/backend/util/service.py
+++ b/autogpt_platform/backend/backend/util/service.py
@@ -26,6 +26,7 @@ from typing import (
)
import httpx
+import sentry_sdk
import uvicorn
from fastapi import FastAPI, Request, responses
from prisma.errors import DataError, UniqueViolationError
@@ -711,16 +712,16 @@ def get_service_client(
def _get_return(self, expected_return: TypeAdapter | None, result: Any) -> Any:
"""Validate and coerce the RPC result to the expected return type.
- Falls back to the raw result with a warning if validation fails.
+ Falls back to the raw result with a warning and Sentry capture if validation fails.
"""
if expected_return:
try:
return expected_return.validate_python(result)
except Exception as e:
logger.warning(
- "RPC return type validation failed, using raw result: %s",
- type(e).__name__,
+ f"RPC return type validation failed for {type(e).__name__}: {e}"
)
+ sentry_sdk.capture_exception(e)
return result
return result
diff --git a/autogpt_platform/backend/backend/util/service_test.py b/autogpt_platform/backend/backend/util/service_test.py
index 6f9a89d81b..e314a47f74 100644
--- a/autogpt_platform/backend/backend/util/service_test.py
+++ b/autogpt_platform/backend/backend/util/service_test.py
@@ -1,13 +1,17 @@
import asyncio
import contextlib
import time
+from datetime import datetime, timezone
from functools import cached_property
+from typing import Any, Protocol, cast
from unittest.mock import Mock
import httpx
import pytest
from prisma.errors import DataError, UniqueViolationError
+from pydantic import TypeAdapter
+from backend.data.model import User
from backend.util.service import (
AppService,
AppServiceClient,
@@ -21,6 +25,10 @@ from backend.util.service import (
TEST_SERVICE_PORT = 8765
+class _SupportsGetReturn(Protocol):
+ def _get_return(self, expected_return: TypeAdapter | None, result: Any) -> Any: ...
+
+
class ServiceTest(AppService):
def __init__(self):
super().__init__()
@@ -688,3 +696,46 @@ async def test_health_check_during_shutdown(test_service):
except (httpx.ConnectError, httpx.ConnectTimeout):
# Connection refused/timeout is also acceptable
pass
+
+
+# ============================================================================
+# Unit tests for DynamicClient._get_return
+# ============================================================================
+
+
+class TestGetReturn:
+ """Direct unit tests for DynamicClient._get_return typed-return contract."""
+
+ def _make_client(self) -> _SupportsGetReturn:
+ return cast(_SupportsGetReturn, get_service_client(ServiceTestClient))
+
+ def test_valid_dict_is_deserialized_to_user_model(self):
+ """TypeAdapter(User) + valid dict → User model returned with .timezone accessible.
+
+ User.model_config uses extra='ignore' so unknown fields (e.g. new columns added
+ in a newer database-manager deploy) are silently dropped instead of raising
+ ValidationError — making the RPC layer forward-compatible during rolling deploys.
+ """
+ now = datetime.now(timezone.utc).isoformat()
+ valid_dict = {
+ "id": "user-id",
+ "email": "[email protected]",
+ "created_at": now,
+ "updated_at": now,
+ "unknown_future_field": "some_value", # simulates a new DB field during deploy
+ }
+ client = self._make_client()
+ adapter = TypeAdapter(User)
+ result = client._get_return(adapter, valid_dict)
+
+ assert isinstance(result, User)
+ assert result.timezone is not None
+
+ def test_invalid_dict_falls_back_to_raw_result(self):
+ """TypeAdapter(User) + invalid dict (missing required fields) → fallback returns raw dict."""
+ invalid_dict = {"id": "user-id"} # missing email, created_at, updated_at
+ client = self._make_client()
+ adapter = TypeAdapter(User)
+
+ result = client._get_return(adapter, invalid_dict)
+ assert result == invalid_dict