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): fail any test that leaves a database transaction open, and fix the one that did (#15435)

Nicholas Tindlef6e96518361e
diff --git a/autogpt_platform/backend/backend/api/features/skills/routes_test.py b/autogpt_platform/backend/backend/api/features/skills/routes_test.py
index 485965c0a0..8dd0281cf5 100644
--- a/autogpt_platform/backend/backend/api/features/skills/routes_test.py
+++ b/autogpt_platform/backend/backend/api/features/skills/routes_test.py
@@ -184,6 +184,13 @@ def test_read_copilot_skill_returns_user_body(
)
),
)
+ # Unstubbed, listing the files upserts the user's workspace through the
+ # session's database client from TestClient's own event loop, and that
+ # write left its connection inside an open transaction for later tests.
+ mocker.patch(
+ "backend.api.features.skills.routes.list_user_skill_files",
+ AsyncMock(return_value=[]),
+ )
response = client.get("/skills/oauth_flow")
assert response.status_code == 200
diff --git a/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py b/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py
index 555e5ccdb8..f0c659144a 100644
--- a/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py
+++ b/autogpt_platform/backend/backend/api/features/store/profile_first_load_test.py
@@ -15,14 +15,12 @@ from contextvars import ContextVar
from typing import Literal
import pytest
-import pytest_asyncio
from prisma.actions import ProfileActions
from pydantic import BaseModel, ConfigDict
from backend.api.features.store import db as store_db
from backend.api.features.store import model as store_model
from backend.api.features.store.routes import get_profile
-from backend.data import db
from backend.data import profile as profile_module
from backend.data.db import prisma
from backend.data.user import get_or_create_user_with_status
@@ -35,17 +33,6 @@ _Role = Literal["read", "setup", "save"]
_ROLES: tuple[_Role, ...] = ("read", "setup", "save")
-@pytest_asyncio.fixture(scope="module", loop_scope="session", autouse=True)
-async def _fresh_connections(server: SpinTestServer):
- """Start on a fresh connection pool. These tests make inserts fail on
- purpose (the race's losing side), and a test earlier in the session can
- leave a pooled connection inside a transaction it never closed: one failure
- there aborts it for every later query, in this module and after it."""
- await db.disconnect()
- await db.connect()
- yield
-
-
@pytest.mark.asyncio(loop_scope="session")
async def test_a_profile_read_while_setup_creates_it_gets_the_one_profile(
server: SpinTestServer, monkeypatch: pytest.MonkeyPatch
diff --git a/autogpt_platform/backend/backend/conftest.py b/autogpt_platform/backend/backend/conftest.py
index 91f058d7a7..3e94b15180 100644
--- a/autogpt_platform/backend/backend/conftest.py
+++ b/autogpt_platform/backend/backend/conftest.py
@@ -1,9 +1,12 @@
import inspect
import logging
import os
+import sys
from contextlib import asynccontextmanager
+from datetime import datetime, timezone
from multiprocessing import get_all_start_methods, get_context, set_forkserver_preload
from threading import Thread
+from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
from uuid import uuid4
import pytest
@@ -15,6 +18,24 @@ from backend.util.logging import configure_logging
load_dotenv()
+
+def _with_query_param(url: str, key: str, value: str) -> str:
+ parsed = urlparse(url)
+ query = dict(parse_qsl(parsed.query))
+ query[key] = value
+ return urlunparse(parsed._replace(query=urlencode(query)))
+
+
+# Every database connection this session opens, the server fixture's service
+# processes included, carries this name, so no_leaked_db_transaction can tell
+# them from any other client of the same database. Set before anything imports
+# backend.data.db, which reads the URL once; the default is that module's own.
+os.environ["DATABASE_URL"] = _with_query_param(
+ os.environ.get("DATABASE_URL", "postgresql://localhost:5432"),
+ "application_name",
+ f"autogpt-tests-{uuid4().hex[:8]}",
+)
+
# NOTE: You can run tests like with the --log-cli-level=INFO to see the logs
# Set up logging
configure_logging()
@@ -57,6 +78,51 @@ async def server():
yield server
+@pytest_asyncio.fixture(autouse=True)
+async def no_leaked_db_transaction(request: pytest.FixtureRequest):
+ """Fail a test that leaves a database transaction open.
+
+ A connection back in the pool inside an open transaction runs every later
+ test's statements inside it: their writes are never committed, and the
+ first one that fails aborts the rest. Checked while the session's client
+ is connected, i.e. once a test has started the server.
+ """
+ started = datetime.now(timezone.utc)
+ yield
+ # Nothing can leak through a database layer this session never loaded,
+ # and checking that keeps Prisma out of unit-only runs.
+ if "backend.data.db" not in sys.modules:
+ return
+ from prisma import get_client
+
+ from backend.data.db_transaction_guard import end_leaked_transactions
+
+ # The registered client, not backend.data.db.prisma: a test's patch of that
+ # attribute can still be in place while this teardown runs.
+ client = get_client()
+ if not client.is_connected():
+ return
+ report = await end_leaked_transactions(client)
+ if not report.leaks:
+ return
+ pytest.fail(
+ f"{request.node.nodeid} left a database transaction open (test began "
+ f"{started.isoformat()}); every later test would have run inside it:\n"
+ + "\n".join(
+ f" pid {leak.pid}, {leak.state}, opened {leak.xact_start.isoformat()},"
+ f" last statement: {leak.last_query}"
+ for leak in report.leaks
+ )
+ + (
+ f"\nBackends {report.survivors} could not be confirmed ended, so "
+ "later tests may still see their transactions."
+ if report.survivors
+ else ""
+ ),
+ pytrace=False,
+ )
+
+
@pytest.fixture(autouse=True)
def no_force_all_flags(monkeypatch: pytest.MonkeyPatch):
"""``load_dotenv()`` above copies ``.env`` into ``os.environ``, so a developer
diff --git a/autogpt_platform/backend/backend/data/db_transaction_guard.py b/autogpt_platform/backend/backend/data/db_transaction_guard.py
new file mode 100644
index 0000000000..c2e34186d0
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/db_transaction_guard.py
@@ -0,0 +1,191 @@
+"""Find database transactions a test left open, so the test can be failed.
+
+A connection that goes back to the pool inside an open transaction runs every
+later statement inside it: their writes are never committed, and the first one
+that fails aborts the rest (Postgres ``25P02``), in whatever test comes next.
+"""
+
+import asyncio
+from datetime import datetime, timezone
+
+from prisma import Prisma
+from prisma.errors import PrismaError
+from pydantic import BaseModel
+
+from backend.data.db import DISCONNECT_TIMEOUT
+
+_UNKNOWN_START = datetime.min.replace(tzinfo=timezone.utc)
+
+# The guard's own query shows its connection as active, not idle. It was
+# already inside a transaction if that transaction has written something (only
+# writes take a transaction id; this SELECT does not), or if it began before
+# this statement: a clean query sees statement_timestamp() within a fraction of
+# a millisecond of now().
+_OWN_CONNECTION_GAP_SECONDS = 0.002
+# A transaction still open this long after the first look was left open, not
+# caught mid-flight.
+_CONFIRM_AFTER_SECONDS = 0.5
+_TERMINATE_WAIT_MS = 5000
+
+# Only connections of this test session: conftest gives them all, the service
+# processes included, an application_name no other client of the database has.
+_OPEN_TRANSACTIONS_SQL = """
+SELECT a.pid,
+ a.pid = pg_backend_pid() AS is_own,
+ a.state,
+ a.xact_start,
+ a.backend_xid IS NOT NULL AS has_written,
+ EXTRACT(EPOCH FROM (statement_timestamp() - now())) AS own_gap,
+ left(a.query, 300) AS last_query
+FROM pg_stat_activity a
+WHERE a.datname = current_database()
+ AND a.xact_start IS NOT NULL
+ AND (a.pid = pg_backend_pid()
+ OR (current_setting('application_name') <> ''
+ AND a.application_name = current_setting('application_name')))
+"""
+
+
+# CASE, not AND: Postgres doesn't promise to skip the termination when the
+# backend is this connection's own, and terminating that would kill this query.
+_TERMINATE_SQL = """
+SELECT CASE
+ WHEN target.pid = pg_backend_pid() THEN true
+ WHEN NOT EXISTS (SELECT 1 FROM pg_stat_activity a WHERE a.pid = target.pid)
+ THEN true
+ ELSE pg_terminate_backend(target.pid, $2::bigint)
+ END AS gone
+FROM (SELECT $1::int AS pid) AS target
+"""
+
+
+class LeakedTransaction(BaseModel):
+ pid: int
+ xact_start: datetime
+ state: str
+ last_query: str
+
+
+class LeakReport(BaseModel):
+ leaks: list[LeakedTransaction]
+ # Backends not confirmed gone after the attempt to end them.
+ survivors: list[int]
+
+
+async def end_leaked_transactions(client: Prisma) -> LeakReport:
+ """Find every transaction left open, end them, and say which.
+
+ An aborted connection refuses the query that finds leaks, so while it is
+ the guard's own it hides every other one: after releasing, which replaces
+ it, look once more.
+ """
+ report = LeakReport(leaks=[], survivors=[])
+ for _ in range(2):
+ leaks = await find_leaked_transactions(client)
+ if not leaks:
+ break
+ report.leaks += leaks
+ report.survivors += await release_leaked_transactions(client, leaks)
+ return report
+
+
+async def find_leaked_transactions(client: Prisma) -> list[LeakedTransaction]:
+ """Transactions on the client's database still open after two looks."""
+ first = await _open_transactions(client)
+ if not first:
+ return []
+ await asyncio.sleep(_CONFIRM_AFTER_SECONDS)
+ second = {
+ (leak.pid, leak.xact_start): leak for leak in await _open_transactions(client)
+ }
+ return [
+ second[(leak.pid, leak.xact_start)]
+ for leak in first
+ if (leak.pid, leak.xact_start) in second
+ ]
+
+
+async def release_leaked_transactions(
+ client: Prisma, leaks: list[LeakedTransaction]
+) -> list[int]:
+ """End the leaked transactions and start the client on a fresh pool.
+
+ Postgres rolls back a transaction whose connection closes. Reconnecting
+ first closes this client's own connections, the leaked one included (which
+ may be too aborted to run anything); the fresh connection then terminates
+ the rest. Returns the backends not confirmed gone.
+ """
+ await client.disconnect(DISCONNECT_TIMEOUT)
+ await client.connect()
+ return [
+ leak.pid for leak in leaks if not await _terminate_backend(client, leak.pid)
+ ]
+
+
+async def _terminate_backend(client: Prisma, pid: int) -> bool:
+ """Whether *pid* is gone. Waits for it to exit, not just to be signalled."""
+ try:
+ rows = await client.query_raw(_TERMINATE_SQL, pid, _TERMINATE_WAIT_MS)
+ except PrismaError:
+ return False
+ return bool(rows[0]["gone"])
+
+
+async def _open_transactions(client: Prisma) -> list[LeakedTransaction]:
+ try:
+ rows = await _query_open_transactions(client)
+ except PrismaError as error:
+ # Only a connection already inside an aborted transaction refuses a
+ # plain SELECT like this one.
+ if not _is_aborted_transaction(error):
+ raise
+ return [
+ LeakedTransaction(
+ pid=0,
+ xact_start=_UNKNOWN_START,
+ state="idle in transaction (aborted), on the guard's connection",
+ last_query=str(error)[:300],
+ )
+ ]
+ return [
+ LeakedTransaction(
+ pid=row["pid"],
+ xact_start=row["xact_start"],
+ state=(
+ "idle in transaction, on the guard's connection"
+ if row["is_own"]
+ else row["state"] or ""
+ ),
+ last_query="" if row["is_own"] else row["last_query"] or "",
+ )
+ for row in rows
+ if _is_left_open(row)
+ ]
+
+
+async def _query_open_transactions(client: Prisma) -> list[dict]:
+ try:
+ return await client.query_raw(_OPEN_TRANSACTIONS_SQL)
+ except RuntimeError as error:
+ # A test that queried through this client from another event loop
+ # (TestClient runs requests on its own) leaves pooled HTTP connections
+ # bound to that loop once it closes. The first call after fails and the
+ # pool replaces them, as conftest's user setup also relies on.
+ if "Event loop is closed" not in str(error):
+ raise
+ return await client.query_raw(_OPEN_TRANSACTIONS_SQL)
+
+
+def _is_aborted_transaction(error: PrismaError) -> bool:
+ # A raw query reports the message, a model query the SQLSTATE code.
+ message = str(error)
+ return "25P02" in message or "current transaction is aborted" in message
+
+
+def _is_left_open(row: dict) -> bool:
+ if row["is_own"]:
+ return (
+ bool(row["has_written"])
+ or float(row["own_gap"]) > _OWN_CONNECTION_GAP_SECONDS
+ )
+ return str(row["state"]).startswith("idle in transaction")
diff --git a/autogpt_platform/backend/backend/data/db_transaction_guard_test.py b/autogpt_platform/backend/backend/data/db_transaction_guard_test.py
new file mode 100644
index 0000000000..d0cc6e31ce
--- /dev/null
+++ b/autogpt_platform/backend/backend/data/db_transaction_guard_test.py
@@ -0,0 +1,143 @@
+"""The leaked-transaction guard, on the real database it guards.
+
+conftest.py runs it after every test; these make sure it still sees a leak,
+and still lets a transaction that is merely in flight finish.
+"""
+
+import asyncio
+
+import pytest
+from prisma import Prisma
+from prisma.errors import PrismaError
+
+from backend.data import db
+from backend.data.db_transaction_guard import (
+ end_leaked_transactions,
+ find_leaked_transactions,
+ release_leaked_transactions,
+)
+from backend.util.test import SpinTestServer
+
+
[email protected](loop_scope="session")
+async def test_a_transaction_left_open_is_found_and_ended(server: SpinTestServer):
+ await db.prisma.execute_raw("BEGIN")
+ # The guard looks after the test has finished, never in the same instant.
+ await asyncio.sleep(0.01)
+
+ leaks = await find_leaked_transactions(db.prisma)
+ assert leaks, "a BEGIN left on a pooled connection went unnoticed"
+
+ await release_leaked_transactions(db.prisma, leaks)
+ assert await find_leaked_transactions(db.prisma) == []
+
+
[email protected](loop_scope="session")
+async def test_an_uncommitted_write_is_found_however_soon_the_guard_looks(
+ server: SpinTestServer,
+):
+ await db.prisma.execute_raw("BEGIN")
+ await db.prisma.execute_raw("CREATE TEMP TABLE leaked_write (id int)")
+
+ leaks = await find_leaked_transactions(db.prisma)
+ assert leaks, "an uncommitted write went unnoticed"
+
+ await release_leaked_transactions(db.prisma, leaks)
+ assert await find_leaked_transactions(db.prisma) == []
+
+
[email protected](loop_scope="session")
+async def test_an_aborted_transaction_left_open_is_found_and_ended(
+ server: SpinTestServer,
+):
+ """What the next test would otherwise inherit: every statement refused
+ with 25P02, the guard's own query included."""
+ await db.prisma.execute_raw("BEGIN")
+ with pytest.raises(PrismaError):
+ await db.prisma.execute_raw("SELECT 1 / 0")
+
+ leaks = await find_leaked_transactions(db.prisma)
+ assert leaks, "an aborted transaction went unnoticed"
+
+ await release_leaked_transactions(db.prisma, leaks)
+ assert await find_leaked_transactions(db.prisma) == []
+
+
[email protected](loop_scope="session")
+async def test_a_leak_on_another_connection_of_this_session_is_terminated(
+ server: SpinTestServer,
+):
+ """The service processes' connections carry the session's name too."""
+ other = Prisma(datasource={"url": db.DATABASE_URL})
+ await other.connect()
+ try:
+ await other.execute_raw("BEGIN")
+
+ leaks = await find_leaked_transactions(db.prisma)
+ assert leaks, "an open transaction on another session connection went unnoticed"
+
+ assert await release_leaked_transactions(db.prisma, leaks) == []
+ assert await find_leaked_transactions(db.prisma) == []
+ finally:
+ await other.disconnect()
+
+
[email protected](loop_scope="session")
+async def test_an_aborted_guard_connection_does_not_hide_another_leak(
+ server: SpinTestServer,
+):
+ """The aborted connection refuses the query that finds leaks, so a leak on
+ another connection stays hidden until it is gone. The next test must not
+ inherit that one, or be blamed for it."""
+ other = Prisma(datasource={"url": db.DATABASE_URL})
+ await other.connect()
+ try:
+ await other.execute_raw("BEGIN")
+ await other.execute_raw("CREATE TEMP TABLE hidden_leak (id int)")
+ await db.prisma.execute_raw("BEGIN")
+ with pytest.raises(PrismaError):
+ await db.prisma.execute_raw("SELECT 1 / 0")
+
+ report = await end_leaked_transactions(db.prisma)
+
+ assert len(report.leaks) == 2, report.leaks
+ assert report.survivors == []
+ assert await find_leaked_transactions(db.prisma) == []
+ finally:
+ await other.disconnect()
+
+
[email protected](loop_scope="session")
+async def test_a_transaction_held_by_another_client_is_left_alone(
+ server: SpinTestServer,
+):
+ """Someone else's session on the same database is not this test's leak."""
+ url = db.add_param(db.DATABASE_URL, "application_name", "someone-else")
+ outsider = Prisma(datasource={"url": url})
+ await outsider.connect()
+ try:
+ await outsider.execute_raw("BEGIN")
+
+ assert await find_leaked_transactions(db.prisma) == []
+ finally:
+ await outsider.execute_raw("ROLLBACK")
+ await outsider.disconnect()
+
+
[email protected](loop_scope="session")
+async def test_a_transaction_still_in_flight_is_not_reported(server: SpinTestServer):
+ inside = asyncio.Event()
+
+ async def hold_briefly():
+ async with db.transaction() as tx:
+ await tx.execute_raw("SELECT 1")
+ inside.set()
+ await asyncio.sleep(0.1)
+
+ holder = asyncio.create_task(hold_briefly())
+ await asyncio.wait_for(inside.wait(), timeout=5)
+
+ leaks = await find_leaked_transactions(db.prisma)
+ await holder
+
+ assert leaks == []