Debian Codegraph @

t/integration/test_prefork_shutdown.py

raw
1 """Integration tests for prefork pool shutdown behaviour.
2
3 These tests verify that the prefork pool gracefully shuts down and maintains
4 heartbeats during the shutdown process, preventing connection loss during
5 worker drain.
6 """
7
8 from time import sleep
9
10 import pytest
11
12 from celery.contrib.testing.worker import start_worker
13 from celery.worker import state
14
15 from .tasks import sleeping
16
17 TEST_HEARTBEAT = 2
18
19 # Exceeds AMQP connection timeout (~4 seconds: broker closes after missing
20 # 2 consecutive 2-second heartbeats)
21 LONG_TASK_DURATION = 10
22
23 TIMEOUT = LONG_TASK_DURATION * 2
24
25
26 @pytest.fixture
27 def heartbeat_worker(celery_session_app):
28 """Worker with short heartbeat for testing purposes."""
29
30 # Temporarily lower heartbeat for this test
31 original_heartbeat = celery_session_app.conf.broker_heartbeat
32 celery_session_app.conf.broker_heartbeat = TEST_HEARTBEAT
33
34 original_acks_late = celery_session_app.conf.task_acks_late
35 celery_session_app.conf.task_acks_late = True
36
37 with start_worker(
38 celery_session_app,
39 pool="prefork",
40 without_heartbeat=False,
41 concurrency=4,
42 shutdown_timeout=TIMEOUT,
43 perform_ping_check=False,
44 ) as worker:
45 # Verify that low heartbeat is configured correctly
46 assert worker.consumer.amqheartbeat == TEST_HEARTBEAT
47
48 yield worker
49
50 celery_session_app.conf.broker_heartbeat = original_heartbeat
51 celery_session_app.conf.task_acks_late = original_acks_late
52
53
54 class test_prefork_shutdown:
55 """Test prefork shutdown with heartbeat maintenance."""
56
57 # Test timeout should be longer than worker timeout
58 @pytest.mark.timeout(timeout=TIMEOUT * 2)
59 @pytest.mark.usefixtures("heartbeat_worker")
60 def test_shutdown_with_long_running_tasks(self):
61 """Test that graceful shutdown completes long-running tasks without
62 connection loss.
63
64 This test verifies that when the prefork pool is shutting down with
65 long-running tasks, heartbeats continue to be sent to maintain the
66 broker connection.
67
68 - Heartbeat frames sent every 2 seconds
69 - Connection closes after 4 seconds (two missed frames) without heartbeats
70 - Tasks run 10 seconds to exceed 4-second threshold
71 """
72
73 # Submit multiple long-running tasks that will be active during shutdown
74 num_tasks = 3
75 results = []
76 for _ in range(num_tasks):
77 results.append(sleeping.delay(LONG_TASK_DURATION))
78
79 # Give time for tasks to start executing
80 sleep(1)
81
82 state.should_stop = True
83
84 # Wait for all tasks to complete. If heartbeats aren't maintained during
85 # shutdown, this will fail with `ConnectionResetError`, `BrokenPipeError`
86 # and `celery.exceptions.TimeoutError`.
87 for result in results:
88 result.get(timeout=TIMEOUT)
89 assert result.status == "SUCCESS"