From 00f014ccae89480647c95eb4fc9df60631583d86 Mon Sep 17 00:00:00 2001 From: Herculino Trotta Date: Sat, 14 Nov 2026 02:11:15 -0300 Subject: [PATCH] fix(rules): keep the connection when tasks run inside a transaction Rule dry runs call tasks directly inside an atomic block they roll back. The connection cleanup wrapper closed that connection, so every dry run failed with a 500. --- app/apps/common/procrastinate.py | 10 +++++++++- app/apps/common/tests/test_procrastinate.py | 17 ++++++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/app/apps/common/procrastinate.py b/app/apps/common/procrastinate.py index 8e27e289..a6e2eebc 100644 --- a/app/apps/common/procrastinate.py +++ b/app/apps/common/procrastinate.py @@ -2,12 +2,20 @@ import functools import inspect import procrastinate -from django.db import close_old_connections +from django.db import close_old_connections as _close_old_connections +from django.db import connection _CONNECTION_CLEANUP_WRAPPED = "_wygiwyh_connection_cleanup_wrapped" +def close_old_connections(): + # Rule dry runs call tasks directly inside a transaction they roll back; + # closing its connection there would break it. Worker jobs never run in one. + if not connection.in_atomic_block: + _close_old_connections() + + def _wrap_task_with_django_connection_cleanup(task): if getattr(task.func, _CONNECTION_CLEANUP_WRAPPED, False): return diff --git a/app/apps/common/tests/test_procrastinate.py b/app/apps/common/tests/test_procrastinate.py index be175bf3..97a396ab 100644 --- a/app/apps/common/tests/test_procrastinate.py +++ b/app/apps/common/tests/test_procrastinate.py @@ -1,7 +1,7 @@ from unittest.mock import patch import procrastinate -from django.db import connection +from django.db import connection, transaction from django.test import SimpleTestCase, TransactionTestCase from procrastinate.testing import InMemoryConnector @@ -87,3 +87,18 @@ class ProcrastinateConnectionRecoveryTests(TransactionTestCase): connection.connection.close() self.assertEqual(task.func(), 1) + + def test_task_called_inside_a_transaction_keeps_its_connection(self): + """Rule dry runs call tasks directly inside a transaction they roll back.""" + + def sample_task(): + with connection.cursor() as cursor: + cursor.execute("SELECT 1") + return cursor.fetchone()[0] + + app, task = make_app_with_task(sample_task) + on_app_ready(app) + + with transaction.atomic(): + connection.close_at = 0 # obsolete, as with CONN_MAX_AGE=0 + self.assertEqual(task.func(), 1)