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.
This commit is contained in:
Herculino Trotta committed 2026-11-14 02:11:15 -03:00
1 parent 9714df8820
commit 00f014ccae
2 files changed
+25 -2

No files matched your search

+9 -1
View File
@@ -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
+16 -1
View File
@@ -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)