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): route execute_block user lookup through DB accessor (#13308)
Reinier van der Leer2d6ae95c09d6
diff --git a/autogpt_platform/backend/backend/copilot/tools/conftest.py b/autogpt_platform/backend/backend/copilot/tools/conftest.pyindex 88bccd64a0..6f10921e9f 100644--- a/autogpt_platform/backend/backend/copilot/tools/conftest.py+++ b/autogpt_platform/backend/backend/copilot/tools/conftest.py@@ -25,21 +25,24 @@ async def graph_cleanup(): # type: ignore[override]@pytest.fixture(autouse=True)def stub_user_lookup_in_helpers(monkeypatch):- """Stub ``user_db.get_user_by_id`` ONLY for the helpers.py-local binding.+ """Stub the ``user_db()`` accessor ONLY for the helpers.py-local binding.- ``prepare_block_for_execution`` reads the user record to plumb- ``user_timezone`` into ``ExecutionContext``. The existing tests don't+ ``execute_block`` reads the user record via ``user_db().get_user_by_id``+ to plumb ``user_timezone`` into ``ExecutionContext``. ``user_db`` is the+ connection-aware accessor from ``db_accessors`` (a callable returning the+ direct module or the DatabaseManager RPC client). The existing tests don'tneed a real DB for that.⚠️ We must patch the ``user_db`` name on the helpers module itself,- NOT ``helpers.user_db.get_user_by_id`` — the latter resolves through- the module reference and mutates ``backend.data.user.get_user_by_id``- globally, which leaks into unrelated callers (e.g. ``rate_limit``'s- ``user_db().get_user_by_id`` in ``run_agent_test``) and clobbers- their real-DB test users with our MagicMock.+ NOT ``helpers.user_db().get_user_by_id`` — patching through the returned+ client would mutate the shared accessor target globally, which leaks into+ unrelated callers (e.g. ``rate_limit``'s ``user_db().get_user_by_id`` in+ ``run_agent_test``) and clobbers their real-DB test users with our+ MagicMock."""user = MagicMock()user.timezone = "UTC"- stub = MagicMock()- stub.get_user_by_id = AsyncMock(return_value=user)+ client = MagicMock()+ client.get_user_by_id = AsyncMock(return_value=user)+ stub = MagicMock(return_value=client)monkeypatch.setattr("backend.copilot.tools.helpers.user_db", stub)diff --git a/autogpt_platform/backend/backend/copilot/tools/helpers.py b/autogpt_platform/backend/backend/copilot/tools/helpers.pyindex 31140a72e0..b924ebb1f7 100644--- a/autogpt_platform/backend/backend/copilot/tools/helpers.py+++ b/autogpt_platform/backend/backend/copilot/tools/helpers.py@@ -20,9 +20,8 @@ from backend.copilot.constants import ()from backend.copilot.model import ChatSessionfrom backend.copilot.sdk.file_ref import FileRefExpansionError, expand_file_refs_in_args-from backend.data import user as user_dbfrom backend.data.credit import UsageTransactionMetadata-from backend.data.db_accessors import credit_db, review_db, workspace_db+from backend.data.db_accessors import credit_db, review_db, user_db, workspace_dbfrom backend.data.execution import ExecutionContextfrom backend.data.model import CredentialsFieldInfo, CredentialsMetaInputfrom backend.executor.auto_credentials import (@@ -233,7 +232,7 @@ async def execute_block(# so an orphaned-session block call still runs instead of crashing.try:user_timezone = get_user_timezone_or_utc(- (await user_db.get_user_by_id(user_id)).timezone+ (await user_db().get_user_by_id(user_id)).timezone)except ValueError:user_timezone = "UTC"diff --git a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py b/autogpt_platform/backend/backend/copilot/tools/run_block_test.pyindex 9fc7a27961..3765085bbf 100644--- a/autogpt_platform/backend/backend/copilot/tools/run_block_test.py+++ b/autogpt_platform/backend/backend/copilot/tools/run_block_test.py@@ -1157,3 +1157,94 @@ class TestRunBlockCredentialsHidden:}cleaned = _strip_credentials_from_schema(schema, {"credentials"})assert "required" not in cleaned+++class TestExecuteBlockUserTimezoneAccessor:+ """The user-timezone lookup must go through the connection-aware+ ``user_db()`` accessor (sentry ClientNotConnectedError).++ ``execute_block`` runs in the copilot process, where the local Prisma+ engine is NOT connected (``db.is_connected()`` is False) and DB reads are+ served by the DatabaseManager RPC client. PR #13247 added a user lookup via+ the directly-imported ``backend.data.user`` module, which calls Prisma+ directly and blew up with ``ClientNotConnectedError``. Routing through the+ ``user_db()`` accessor picks the RPC client when disconnected.+ """++ @pytest.mark.asyncio(loop_scope="session")+ async def test_timezone_lookup_uses_accessor_not_direct_prisma(self):+ from backend.copilot.tools.helpers import execute_block++ mock_block = make_mock_block_with_schema(+ block_id="tz-block-id",+ name="Timezone Block",+ input_properties={},+ required_fields=[],+ )++ captured: dict[str, object] = {}++ async def _capture_ctx(_input, **kwargs):+ captured["ctx"] = kwargs["execution_context"]+ yield "result", "ok"++ mock_block.execute = _capture_ctx++ # Accessor returns the RPC client (disconnected-process behaviour);+ # the direct ``user_db.get_user_by_id`` would raise ClientNotConnectedError.+ rpc_client = MagicMock()+ rpc_client.get_user_by_id = AsyncMock(+ return_value=MagicMock(timezone="America/New_York")+ )++ mock_workspace_db = MagicMock()+ mock_workspace_db.get_or_create_workspace = AsyncMock(+ return_value=MagicMock(id="ws-tz")+ )++ with (+ patch(+ "backend.copilot.tools.helpers.user_db",+ return_value=rpc_client,+ ) as mock_user_db,+ patch(+ "backend.copilot.tools.helpers.workspace_db",+ return_value=mock_workspace_db,+ ),+ patch(+ "backend.copilot.tools.helpers.credit_db",+ return_value=_StubCreditDB(),+ ),+ patch(+ "backend.copilot.tools.helpers.block_usage_cost",+ return_value=(0, {}),+ ),+ ):+ response = await execute_block(+ block=mock_block,+ block_id="tz-block-id",+ input_data={},+ user_id="u-tz",+ session_id="s-tz",+ node_exec_id="n-tz",+ matched_credentials={},+ dry_run=False,+ )++ assert isinstance(response, BlockOutputResponse)+ assert response.success is True+ # Went through the accessor, not the directly-imported module.+ mock_user_db.assert_called_once()+ rpc_client.get_user_by_id.assert_awaited_once_with("u-tz")+ # The looked-up timezone was plumbed into the block's ExecutionContext.+ ctx = captured["ctx"]+ assert ctx is not None+ assert ctx.user_timezone == "America/New_York" # type: ignore[attr-defined]+++class _StubCreditDB:+ async def get_credits(self, _user_id: str) -> int:+ return 10_000++ async def spend_credits(self, **kwargs):+ return None