Debian Codegraph @

tests/ducktape/test_transactions.py

raw symbols SCIP
1 """
2 Ducktape tests for transactions in async producer and consumer.
3 """
4 import uuid
5 import asyncio
6 from ducktape.tests.test import Test
7
8 from tests.ducktape.consumer_strategy import AsyncConsumerStrategy, SyncConsumerStrategy
9 from tests.ducktape.producer_strategy import SyncProducerStrategy, AsyncProducerStrategy
10 from tests.ducktape.services.kafka import KafkaClient
11
12
13 class TransactionsTest(Test):
14 def __init__(self, test_context):
15 super(TransactionsTest, self).__init__(test_context=test_context)
16 self.kafka = KafkaClient(test_context, bootstrap_servers="localhost:9092")
17
18 def setUp(self):
19 if not self.kafka.verify_connection():
20 raise Exception("Cannot connect to Kafka at localhost:9092. Please ensure Kafka is running.")
21
22 def _new_topic(self, partitions: int = 1) -> str:
23 topic = f"tx-{uuid.uuid4()}"
24 self.kafka.create_topic(topic, partitions=partitions, replication_factor=1)
25 assert self.kafka.wait_for_topic(topic, max_wait_time=30)
26 return topic
27
28 def _create_transactional_producer(self, producer_type):
29 """Create transactional producer based on type using producer_strategy"""
30 # Overrides for transactional producers
31 overrides = {
32 'transactional.id': f'{producer_type}-tx-producer-{uuid.uuid4()}',
33 'acks': 'all',
34 'enable.idempotence': True
35 }
36
37 if producer_type == "sync":
38 strategy = SyncProducerStrategy(self.kafka.bootstrap_servers(), self.logger)
39 return strategy.create_producer(config_overrides=overrides)
40 else: # async
41 strategy = AsyncProducerStrategy(self.kafka.bootstrap_servers(), self.logger)
42 return strategy.create_producer(config_overrides=overrides)
43
44 def _create_transactional_consumer(self, consumer_type, group_id=None):
45 """Create read_committed consumer based on type using strategy pattern"""
46 if group_id is None:
47 group_id = f'tx-consumer-{uuid.uuid4()}'
48
49 # Overrides for transactional consumers
50 overrides = {
51 'isolation.level': 'read_committed',
52 'enable.auto.commit': False,
53 'auto.offset.reset': 'earliest',
54 }
55
56 if consumer_type == "sync":
57 strategy = SyncConsumerStrategy(self.kafka.bootstrap_servers(), group_id, self.logger)
58 return strategy.create_consumer(config_overrides=overrides)
59 else: # async
60 strategy = AsyncConsumerStrategy(self.kafka.bootstrap_servers(), group_id, self.logger)
61 return strategy.create_consumer(config_overrides=overrides)
62
63 async def _transactional_produce(self, producer, topic: str, values: list[str], partition: int | None = None):
64 """Produce values within an active transaction using async producer."""
65 for i, v in enumerate(values):
66 kwargs = {'topic': topic, 'value': v}
67 if partition is not None:
68 kwargs['partition'] = partition
69
70 try:
71 await producer.produce(**kwargs)
72 except Exception as e:
73 print(f"ERROR: Failed to queue async message {i}: {e}")
74 raise
75
76 async def _seed_topic(self, topic: str, values: list[str]):
77 """Seed a topic using transactional producer."""
78 producer = self._create_transactional_producer("sync")
79 producer.init_transactions()
80 producer.begin_transaction()
81 for v in values:
82 producer.produce(topic, value=v)
83 producer.poll(0.0)
84 producer.commit_transaction()
85 producer.flush()
86
87 # =========== Functional tests (async) ===========
88
89 def test_commit_transaction(self):
90 """Committed transactional messages must be visible to read_committed consumer."""
91 async def run():
92 topic = self._new_topic()
93 producer = self._create_transactional_producer("async")
94 consumer = self._create_transactional_consumer("async")
95
96 try:
97 await producer.init_transactions()
98 await producer.begin_transaction()
99 await self._transactional_produce(producer, topic, [f'c{i}' for i in range(5)])
100 await producer.commit_transaction()
101 await consumer.subscribe([topic])
102
103 seen = []
104 for i in range(20):
105 msg = await consumer.poll(timeout=1.0)
106 if not msg:
107 continue
108 if msg.error():
109 continue
110
111 value = msg.value().decode('utf-8')
112 seen.append(value)
113 if len(seen) >= 5:
114 break
115
116 assert len(seen) == 5, f"expected 5 committed messages, got {len(seen)}"
117 finally:
118 await consumer.close()
119 asyncio.run(run())
120
121 def test_produce_after_abort_transaction(self):
122 """Test that produce() calls after abort_transaction() fail with STATE error.
123
124 Transactional producers can only produce within transaction boundaries.
125 After abort_transaction(), there is no active transaction, so produce() must fail.
126 """
127 async def run():
128 topic = self._new_topic()
129 producer = self._create_transactional_producer("async")
130
131 try:
132 await producer.init_transactions()
133 await producer.begin_transaction()
134
135 # Produce some messages within the transaction
136 await self._transactional_produce(producer, topic, ['msg1', 'msg2'])
137
138 # Abort the transaction
139 await producer.abort_transaction()
140
141 # Now try to produce without starting a new transaction
142 # This will fail with STATE error because transactional producers require active transactions
143 try:
144 future = await producer.produce(topic, value="should-fail")
145 await future # This should raise KafkaError{code=_STATE}
146 assert False, "Expected produce() after abort to fail, but it succeeded"
147 except Exception as e:
148 print("Expected error after abort: {e}")
149 assert "Local: Erroneous state" in str(e), f"Expected STATE error, got: {e}"
150
151 finally:
152 pass # No consumer needed for this test
153
154 asyncio.run(run())
155
156 def test_abort_transaction_then_retry_commit(self):
157 """Aborted messages must be invisible, and retrying with new transaction must only commit visible results."""
158 async def run():
159 topic = self._new_topic()
160 producer = self._create_transactional_producer("async")
161 consumer = self._create_transactional_consumer("async")
162
163 try:
164 await producer.init_transactions()
165
166 # Abort case
167 await producer.begin_transaction()
168 await self._transactional_produce(producer, topic, [f'a{i}' for i in range(3)])
169 await producer.abort_transaction()
170
171 await consumer.subscribe([topic])
172 aborted_seen = []
173 for _ in range(10):
174 msg = await consumer.poll(timeout=1.0)
175 if not msg or msg.error():
176 continue
177 val = msg.value().decode('utf-8')
178 if val.startswith('a'):
179 aborted_seen.append(val)
180 assert not aborted_seen, f"aborted messages should be invisible, saw {aborted_seen}"
181
182 # Retry-commit flow
183 await producer.begin_transaction()
184 retry_vals = [f'r{i}' for i in range(3)]
185 await self._transactional_produce(producer, topic, retry_vals)
186 await producer.commit_transaction()
187
188 # Verify only retry values appear
189 seen = []
190 for _ in range(20):
191 msg = await consumer.poll(timeout=1.0)
192 if not msg or msg.error():
193 continue
194 val = msg.value().decode('utf-8')
195 seen.append(val)
196 if all(rv in seen for rv in retry_vals):
197 break
198 assert all(rv in seen for rv in retry_vals), f"expected retry values {retry_vals}, saw {seen}"
199 assert all(not s.startswith('a') for s in seen), f"should not see aborted values, saw {seen}"
200 finally:
201 await consumer.close()
202 asyncio.run(run())
203
204 def test_send_offsets_to_transaction(self):
205 """Offsets committed atomically with produced results using send_offsets_to_transaction."""
206 async def run():
207 input_topic = self._new_topic()
208 output_topic = self._new_topic()
209
210 # Seed input
211 input_vals = [f'in{i}' for i in range(5)]
212 await self._seed_topic(input_topic, input_vals)
213
214 producer = self._create_transactional_producer("async")
215 consumer = self._create_transactional_consumer("async")
216 try:
217 await consumer.subscribe([input_topic])
218
219 # Consume a small batch from input
220 consumed = []
221 for _ in range(20):
222 msg = await consumer.poll(timeout=1.0)
223 if not msg or msg.error():
224 continue
225 consumed.append(msg)
226 if len(consumed) >= 3:
227 break
228 assert consumed, "expected to consume at least 1 message from input"
229
230 # Begin transaction: produce results and commit consumer offsets atomically
231 await producer.init_transactions()
232 await producer.begin_transaction()
233
234 out_vals = [f'out:{m.value().decode("utf-8")}' for m in consumed]
235 await self._transactional_produce(producer, output_topic, out_vals)
236
237 assignment = await consumer.assignment()
238 positions = await consumer.position(assignment)
239 group_metadata = await consumer.consumer_group_metadata()
240
241 await producer.send_offsets_to_transaction(positions, group_metadata)
242 await producer.commit_transaction()
243
244 # Verify output has results
245 out_consumer = self._create_transactional_consumer("async")
246 try:
247 await out_consumer.subscribe([output_topic])
248 seen = []
249 for _ in range(20):
250 msg = await out_consumer.poll(timeout=1.0)
251 if not msg or msg.error():
252 continue
253 seen.append(msg.value().decode('utf-8'))
254 if len(seen) >= len(out_vals):
255 break
256 assert set(seen) == set(out_vals), f"expected {out_vals}, saw {seen}"
257 finally:
258 await out_consumer.close()
259
260 # Verify committed offsets advanced to positions
261 committed = await consumer.committed(assignment)
262 for pos, comm in zip(positions, committed):
263 assert comm.offset >= pos.offset, f"committed {comm.offset} < position {pos.offset}"
264 finally:
265 await consumer.close()
266 asyncio.run(run())
267
268 def test_commit_multiple_topics_partitions(self):
269 """Commit atomically across multiple topics/partitions."""
270 async def run():
271 topic_a = self._new_topic(partitions=2)
272 topic_b = self._new_topic(partitions=1)
273
274 producer = self._create_transactional_producer("async")
275 consumer = self._create_transactional_consumer("async")
276 try:
277 await producer.init_transactions()
278 await producer.begin_transaction()
279 # Produce across A partitions and B
280 await self._transactional_produce(producer, topic_a, ["a0-p0", "a1-p0"], partition=0)
281 await self._transactional_produce(producer, topic_a, ["a0-p1", "a1-p1"], partition=1)
282 await self._transactional_produce(producer, topic_b, ["b0", "b1"]) # default partition
283 await producer.commit_transaction()
284
285 await consumer.subscribe([topic_a, topic_b])
286 expected = {"a0-p0", "a1-p0", "a0-p1", "a1-p1", "b0", "b1"}
287 seen = set()
288 for _ in range(30):
289 msg = await consumer.poll(timeout=1.0)
290 if not msg or msg.error():
291 continue
292 seen.add(msg.value().decode('utf-8'))
293 if seen == expected:
294 break
295 assert seen == expected, f"expected {expected}, saw {seen}"
296 finally:
297 await consumer.close()
298 asyncio.run(run())