Debian Codegraph @

t/integration/test_rabbitmq_chord_unlock_routing.py

raw
1 import logging
2 import time
3 from concurrent.futures import ThreadPoolExecutor, as_completed
4
5 import pytest
6 from kombu import Exchange, Queue
7
8 from celery import Celery, chord
9 from celery.contrib.testing.worker import start_worker
10 from celery.result import allow_join_result
11
12 logger = logging.getLogger(__name__)
13
14
15 @pytest.fixture(scope="function")
16 def app():
17 """
18 Celery app configured to:
19 - Use quorum queues with topic exchanges
20 - Route chord_unlock to a dedicated quorum queue
21 """
22 app = Celery(
23 "test_app",
24 broker="pyamqp://guest:guest@rabbit:5672//",
25 backend="redis://redis/0",
26 )
27
28 app.conf.task_default_exchange_type = "topic"
29 app.conf.task_default_exchange = "default_exchange"
30 app.conf.task_default_queue = "default_queue"
31 app.conf.task_default_routing_key = "default"
32
33 app.conf.task_queues = [
34 Queue(
35 "header_queue",
36 Exchange("header_exchange", type="topic"),
37 routing_key="header_rk",
38 queue_arguments={"x-queue-type": "quorum"},
39 ),
40 Queue(
41 "chord_callback_queue",
42 Exchange("chord_callback_exchange", type="topic"),
43 routing_key="chord_callback_queue",
44 queue_arguments={"x-queue-type": "quorum"},
45 ),
46 ]
47
48 app.conf.task_routes = {
49 "celery.chord_unlock": {
50 "queue": "chord_callback_queue",
51 "exchange": "chord_callback_exchange",
52 "routing_key": "chord_callback_queue",
53 "exchange_type": "topic",
54 },
55 }
56
57 return app
58
59
60 @pytest.fixture
61 def add(app):
62 @app.task(bind=True, max_retries=3, default_retry_delay=1)
63 def add(self, x, y):
64 time.sleep(0.05)
65 return x + y
66 return add
67
68
69 @pytest.fixture
70 def summarize(app):
71 @app.task(bind=True, max_retries=3, default_retry_delay=1)
72 def summarize(self, results):
73 return sum(results)
74 return summarize
75
76
77 def wait_for_chord_unlock(chord_result, timeout=10, interval=0.2):
78 """
79 Waits for chord_unlock to be enqueued by polling the `parent` of the chord result.
80 This confirms that the header group finished and the callback is ready to run.
81 """
82 start = time.monotonic()
83 while time.monotonic() - start < timeout:
84 if chord_result.parent and chord_result.parent.ready():
85 return True
86 time.sleep(interval)
87 return False
88
89
90 @pytest.mark.amqp
91 @pytest.mark.timeout(90)
92 @pytest.mark.xfail(reason="chord_unlock routed to quorum/topic queue intermittently fails under load")
93 def test_chord_unlock_stress_routing_to_quorum_queue(app, add, summarize):
94 """
95 Reproduces Celery Discussion #9742 (intermittently):
96 When chord_unlock is routed to a quorum queue via topic exchange, it may not be consumed
97 even if declared and bound, leading to stuck results.
98
99 This stress test submits many chords rapidly, each routed explicitly via a topic exchange,
100 and waits to see how many complete.
101 """
102 chord_count = 50
103 header_fanout = 3
104 failures = []
105
106 pending_results = []
107
108 with allow_join_result():
109 # Submit chords BEFORE worker is running
110 for i in range(chord_count):
111 header = [
112 add.s(i, j).set(
113 queue="header_queue",
114 exchange="header_exchange",
115 routing_key="header_rk",
116 )
117 for j in range(header_fanout)
118 ]
119
120 callback = summarize.s().set(
121 queue="chord_callback_queue",
122 exchange="chord_callback_exchange",
123 routing_key="chord_callback_queue",
124 )
125
126 result = chord(header)(callback)
127 pending_results.append((i, result))
128
129 # Wait for chord_unlock tasks to be dispatched before starting the worker
130 for i, result in pending_results:
131 if not wait_for_chord_unlock(result):
132 logger.warning(f"[!] Chord {i}: unlock was not dispatched within timeout")
133
134 # Start worker that consumes both header and callback queues
135 with start_worker(
136 app, queues=["header_queue", "chord_callback_queue"], loglevel="info", perform_ping_check=False
137 ):
138 # Poll all chord results
139 with ThreadPoolExecutor(max_workers=10) as executor:
140 futures = {
141 executor.submit(result.get, timeout=20): (i, result)
142 for i, result in pending_results
143 }
144
145 for future in as_completed(futures):
146 i, result = futures[future]
147 try:
148 res = future.result()
149 logger.info(f"[✓] Chord {i} completed: {res}")
150 except Exception as exc:
151 logger.error(f"[✗] Chord {i} failed or stuck: {exc}")
152 failures.append((i, exc))
153
154 # Assertion: all chords should have completed
155 assert not failures, f"{len(failures)} of {chord_count} chords failed or got stuck"