Debian Codegraph @

tests/ducktape/test_producer.py

raw symbols SCIP
1 """
2 Ducktape test for Confluent Kafka Python Producer
3 Assumes Kafka is already running on localhost:9092
4 """
5
6 import time
7 from ducktape.tests.test import Test
8 from ducktape.mark import matrix
9
10 from tests.ducktape.services.kafka import KafkaClient
11 from tests.ducktape.producer_benchmark_metrics import (
12 MetricsCollector,
13 MetricsBounds,
14 validate_metrics,
15 print_metrics_report,
16 )
17 from tests.ducktape.producer_strategy import SyncProducerStrategy, AsyncProducerStrategy
18
19
20 class SimpleProducerTest(Test):
21 """Test basic producer functionality with external Kafka"""
22
23 def __init__(self, test_context):
24 super(SimpleProducerTest, self).__init__(test_context=test_context)
25
26 # Set up Kafka client (assumes external Kafka running)
27 self.kafka = KafkaClient(test_context, bootstrap_servers="localhost:9092")
28
29 def setUp(self):
30 """Set up test environment"""
31 self.logger.info("Verifying connection to external Kafka at localhost:9092")
32
33 if not self.kafka.verify_connection():
34 raise Exception(
35 "Cannot connect to Kafka at localhost:9092. "
36 "Please ensure Kafka is running."
37 )
38
39 self.logger.info("Successfully connected to Kafka")
40
41 def create_producer(self, producer_type, config_overrides=None):
42 """Create appropriate producer strategy based on type"""
43 if producer_type == "sync":
44 strategy = SyncProducerStrategy(self.kafka.bootstrap_servers(), self.logger)
45 else: # async
46 strategy = AsyncProducerStrategy(
47 self.kafka.bootstrap_servers(), self.logger
48 )
49
50 # Store config overrides for later use in create_producer
51 strategy.config_overrides = config_overrides
52 return strategy
53
54 @matrix(producer_type=["sync", "async"])
55 def test_basic_produce(self, producer_type):
56 """Test basic message production with comprehensive metrics and bounds validation"""
57
58 topic_name = f"test-{producer_type}-topic"
59 test_duration = 5.0 # 5 seconds
60
61 # Create topic
62 self.kafka.create_topic(topic_name, partitions=1, replication_factor=1)
63
64 # Wait for topic to be available with retry logic
65 topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30)
66 assert topic_ready, (
67 f"Topic {topic_name} was not created within timeout. "
68 f"Available topics: {self.kafka.list_topics()}"
69 )
70
71 # Initialize metrics collection and bounds
72 metrics = MetricsCollector()
73 bounds = MetricsBounds()
74
75 # Create appropriate producer strategy
76 strategy = self.create_producer(producer_type)
77
78 # Assign metrics collector to strategy
79 strategy.metrics = metrics
80
81 self.logger.info(
82 f"Testing {producer_type} producer for {test_duration} seconds"
83 )
84
85 # Start metrics collection
86 metrics.start()
87
88 # Message formatter
89 def message_formatter(msg_num):
90 return f"Test message {msg_num}", f"key-{msg_num}"
91
92 # Containers for results
93 delivered_messages = []
94 failed_messages = []
95
96 # Run the test
97 start_time = time.time()
98 messages_sent = strategy.produce_messages(
99 topic_name,
100 test_duration,
101 start_time,
102 message_formatter,
103 delivered_messages,
104 failed_messages,
105 )
106
107 # Finalize metrics collection
108 metrics.finalize()
109
110 # Get comprehensive metrics summary
111 metrics_summary = metrics.get_summary()
112 is_valid, violations = validate_metrics(metrics_summary, bounds)
113
114 # Print comprehensive metrics report
115 self.logger.info(f"=== {producer_type.upper()} PRODUCER METRICS REPORT ===")
116 print_metrics_report(metrics_summary, is_valid, violations)
117
118 # Enhanced assertions using metrics
119 assert messages_sent > 0, "No messages were sent"
120 assert len(delivered_messages) > 0, "No messages were delivered"
121 assert (
122 metrics_summary["messages_delivered"] > 0
123 ), "No messages were delivered (metrics)"
124 assert (
125 metrics_summary["send_throughput_msg_per_sec"] > 10
126 ), f"Send throughput too low: {metrics_summary['send_throughput_msg_per_sec']:.2f} msg/s"
127
128 # Validate against performance bounds
129 if not is_valid:
130 self.logger.error(
131 "Performance bounds validation failed: %s", "; ".join(violations)
132 )
133 assert False, f"Performance bounds validation failed: {'; '.join(violations)}"
134
135 self.logger.info(
136 "Successfully completed basic production test with comprehensive metrics"
137 )
138
139 @matrix(producer_type=["sync", "async"])
140 def test_basic_produce_with_transaction(self, producer_type):
141 """Test basic transactional message production with comprehensive metrics and bounds validation"""
142
143 topic_name = f"test-{producer_type}-topic-with-transaction"
144 test_duration = 5.0 # 5 seconds
145
146 # Create topic
147 self.kafka.create_topic(topic_name, partitions=1, replication_factor=1)
148
149 # Wait for topic to be available with retry logic
150 topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30)
151 assert topic_ready, (
152 f"Topic {topic_name} was not created within timeout. "
153 f"Available topics: {self.kafka.list_topics()}"
154 )
155
156 # Initialize metrics collection and bounds
157 metrics = MetricsCollector()
158 import os
159
160 config_path = os.path.join(
161 os.path.dirname(__file__), "transaction_benchmark_bounds.json"
162 )
163 bounds = MetricsBounds.from_config_file(config_path)
164
165 # Create appropriate producer strategy
166 strategy = self.create_producer(producer_type)
167
168 # Assign metrics collector to strategy
169 strategy.metrics = metrics
170
171 self.logger.info(
172 f"Testing {producer_type} producer for {test_duration} seconds"
173 )
174
175 # Start metrics collection
176 metrics.start()
177
178 # Message formatter
179 def message_formatter(msg_num):
180 return f"Test message {msg_num}", f"key-{msg_num}"
181
182 # Containers for results
183 delivered_messages = []
184 failed_messages = []
185
186 # Run the test
187 start_time = time.time()
188 messages_sent = strategy.produce_messages(
189 topic_name,
190 test_duration,
191 start_time,
192 message_formatter,
193 delivered_messages,
194 failed_messages,
195 use_transaction=True,
196 )
197
198 # Finalize metrics collection
199 metrics.finalize()
200
201 # Get comprehensive metrics summary
202 metrics_summary = metrics.get_summary()
203 is_valid, violations = validate_metrics(metrics_summary, bounds)
204
205 # Print comprehensive metrics report
206 self.logger.info(
207 f"=== {producer_type.upper()} PRODUCER WITH TRANSACTION METRICS REPORT ==="
208 )
209 print_metrics_report(metrics_summary, is_valid, violations)
210
211 # Enhanced assertions using metrics
212 assert messages_sent > 0, "No messages were sent"
213 assert len(delivered_messages) > 0, "No messages were delivered"
214 assert (
215 metrics_summary["messages_delivered"] > 0
216 ), "No messages were delivered (metrics)"
217 assert (
218 metrics_summary["send_throughput_msg_per_sec"] > 10
219 ), f"Send throughput too low: {metrics_summary['send_throughput_msg_per_sec']:.2f} msg/s"
220
221 # Validate against performance bounds
222 if not is_valid:
223 self.logger.error(
224 "Performance bounds validation failed: %s", "; ".join(violations)
225 )
226 assert False, f"Performance bounds validation failed: {'; '.join(violations)}"
227
228 self.logger.info(
229 "Successfully completed basic production test with comprehensive metrics with transaction"
230 )
231
232 @matrix(producer_type=["sync", "async"], test_duration=[2, 5, 10])
233 def test_produce_multiple_batches(self, producer_type, test_duration):
234 """Test batch throughput with comprehensive metrics and bounds validation"""
235
236 topic_name = f"{producer_type}-batch-test-topic-{test_duration}s"
237
238 # Create topic
239 self.kafka.create_topic(topic_name, partitions=2, replication_factor=1)
240
241 # Wait for topic to be available with retry logic
242 topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30)
243 assert topic_ready, f"Topic {topic_name} was not created within timeout"
244
245 # Initialize metrics collection and bounds
246 metrics = MetricsCollector()
247 bounds = MetricsBounds()
248 # Adjust bounds for different test durations
249 if test_duration <= 2:
250 bounds.min_throughput_msg_per_sec = 50.0 # Lower threshold for short tests
251
252 # Create appropriate producer strategy
253 strategy = self.create_producer(producer_type)
254
255 # Assign metrics collector to strategy
256 strategy.metrics = metrics
257
258 self.logger.info(
259 f"Testing {producer_type} producer with batches for {test_duration} seconds"
260 )
261
262 # Start metrics collection
263 metrics.start()
264
265 # Message formatter for batch test
266 def message_formatter(msg_num):
267 return f"Batch message {msg_num}", f"batch-key-{msg_num}"
268
269 # Containers for results
270 delivered_messages = []
271 failed_messages = []
272
273 # Run the test
274 start_time = time.time()
275 messages_sent = strategy.produce_messages(
276 topic_name,
277 test_duration,
278 start_time,
279 message_formatter,
280 delivered_messages,
281 failed_messages,
282 )
283
284 # Finalize metrics collection
285 metrics.finalize()
286
287 # Get comprehensive metrics summary
288 metrics_summary = metrics.get_summary()
289 is_valid, violations = validate_metrics(metrics_summary, bounds)
290
291 # Get AIOProducer built-in metrics for comparison (async only)
292 final_metrics = strategy.get_final_metrics()
293
294 # Print comprehensive metrics report
295 self.logger.info(
296 f"=== {producer_type.upper()} BATCH TEST ({test_duration}s) METRICS REPORT ==="
297 )
298 print_metrics_report(metrics_summary, is_valid, violations)
299
300 if final_metrics:
301 # Get the actual metrics dictionary
302 producer_metrics_summary = final_metrics.get_summary()
303 if producer_metrics_summary:
304 self.logger.info("=== Producer Built-in Metrics ===")
305 self.logger.info(
306 f"Runtime: {producer_metrics_summary['duration_seconds']:.2f}s"
307 )
308 self.logger.info(
309 f"Success Rate: {producer_metrics_summary['success_rate']:.3f}"
310 )
311 self.logger.info(
312 f"Throughput: {producer_metrics_summary['send_throughput_msg_per_sec']:.1f} msg/sec"
313 )
314 self.logger.info(
315 f"Latency: Avg={producer_metrics_summary['avg_latency_ms']:.1f}ms"
316 )
317
318 # Enhanced assertions using metrics
319 assert messages_sent > 0, "No messages were sent"
320 assert len(delivered_messages) > 0, "No messages were delivered"
321 assert (
322 metrics_summary["messages_delivered"] > 0
323 ), "No messages were delivered (metrics)"
324 assert (
325 metrics_summary["send_throughput_msg_per_sec"] > 10
326 ), f"Send throughput too low: {metrics_summary['send_throughput_msg_per_sec']:.2f} msg/s"
327
328 # Validate against performance bounds
329 if not is_valid:
330 self.logger.error(
331 "Performance bounds validation failed for %ds test: %s",
332 test_duration,
333 "; ".join(violations),
334 )
335 assert False, f"Performance bounds validation failed for {test_duration}s test: {'; '.join(violations)}"
336
337 self.logger.info(
338 "Successfully completed %ds batch production test with comprehensive metrics",
339 test_duration,
340 )
341
342 @matrix(
343 producer_type=["sync", "async"], compression_type=["none", "gzip", "snappy"]
344 )
345 def test_produce_with_compression(self, producer_type, compression_type):
346 """Test compression throughput with comprehensive metrics and bounds validation"""
347
348 topic_name = f"{producer_type}-compression-test-{compression_type}"
349 test_duration = 5.0 # 5 seconds
350
351 # Create topic
352 self.kafka.create_topic(topic_name, partitions=1, replication_factor=1)
353
354 # Wait for topic to be available with retry logic
355 topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30)
356 assert topic_ready, f"Topic {topic_name} was not created within timeout"
357
358 # Initialize metrics collection and bounds
359 metrics = MetricsCollector()
360 bounds = MetricsBounds()
361 # Adjust bounds for compression tests (may be slower with large messages)
362 bounds.min_throughput_msg_per_sec = 5.0 # Lower threshold for large messages
363 bounds.max_p95_latency_ms = 5000.0 # Allow higher latency for compression
364
365 # Create appropriate producer strategy with compression config
366 compression_config = {}
367 if compression_type != "none":
368 compression_config["compression.type"] = compression_type
369
370 # Configure polling intervals based on compression type and producer type
371 if producer_type == "async":
372 polling_config = {
373 "gzip": 10, # Poll every 10 messages for gzip (frequent)
374 "snappy": 50, # Poll every 50 messages for snappy (moderate)
375 "none": 100, # Poll every 100 messages for none (standard)
376 }
377 else: # sync
378 # Sync producers need more frequent polling to prevent buffer overflow as throughput is very high
379 polling_config = {
380 "gzip": 5, # Poll every 5 messages for gzip (most frequent)
381 "snappy": 25, # Poll every 25 messages for snappy (moderate)
382 "none": 50, # Poll every 50 messages for none (standard)
383 }
384 poll_interval = polling_config.get(
385 compression_type, 50 if producer_type == "sync" else 100
386 )
387
388 strategy = self.create_producer(producer_type, compression_config)
389 strategy.poll_interval = poll_interval
390
391 # Assign metrics collector to strategy
392 strategy.metrics = metrics
393
394 self.logger.info(
395 f"Testing {producer_type} producer with {compression_type} compression "
396 f"for {test_duration} seconds"
397 )
398 self.logger.info(f"Using polling interval: {poll_interval} messages per poll")
399
400 # Start metrics collection
401 metrics.start()
402
403 # Create larger messages to test compression effectiveness
404 large_message = "x" * 1000 # 1KB message
405
406 # Message formatter for compression test
407 def message_formatter(msg_num):
408 return f"{large_message}-{msg_num}", f"comp-key-{msg_num}"
409
410 # Containers for results
411 delivered_messages = []
412 failed_messages = []
413
414 # Run the test
415 start_time = time.time()
416 messages_sent = strategy.produce_messages(
417 topic_name,
418 test_duration,
419 start_time,
420 message_formatter,
421 delivered_messages,
422 failed_messages,
423 )
424
425 # Finalize metrics collection
426 metrics.finalize()
427
428 # Get comprehensive metrics summary
429 metrics_summary = metrics.get_summary()
430 is_valid, violations = validate_metrics(metrics_summary, bounds)
431
432 # Get AIOProducer built-in metrics for comparison (async only)
433 final_metrics = strategy.get_final_metrics()
434
435 # Print comprehensive metrics report
436 self.logger.info(
437 f"=== {producer_type.upper()} COMPRESSION TEST ({compression_type}) METRICS REPORT ==="
438 )
439 print_metrics_report(metrics_summary, is_valid, violations)
440
441 if final_metrics:
442 # Get the actual metrics dictionary
443 producer_metrics_summary = final_metrics.get_summary()
444 if producer_metrics_summary:
445 self.logger.info("=== Producer Built-in Metrics ===")
446 self.logger.info(
447 f"Runtime: {producer_metrics_summary['duration_seconds']:.2f}s"
448 )
449 self.logger.info(
450 f"Success Rate: {producer_metrics_summary['success_rate']:.3f}"
451 )
452 self.logger.info(
453 f"Throughput: {producer_metrics_summary['send_throughput_msg_per_sec']:.1f} msg/sec"
454 )
455 self.logger.info(
456 f"Latency: Avg={producer_metrics_summary['avg_latency_ms']:.1f}ms"
457 )
458
459 # Enhanced assertions using metrics
460 assert messages_sent > 0, "No messages were sent"
461 assert len(delivered_messages) > 0, "No messages were delivered"
462 assert (
463 metrics_summary["messages_delivered"] > 0
464 ), "No messages were delivered (metrics)"
465 assert metrics_summary["send_throughput_msg_per_sec"] > 5, (
466 f"Send throughput too low for {compression_type}: "
467 f"{metrics_summary['send_throughput_msg_per_sec']:.2f} msg/s"
468 )
469
470 # Validate against performance bounds
471 if not is_valid:
472 self.logger.error(
473 "Performance bounds validation failed for %s compression: %s",
474 compression_type,
475 "; ".join(violations),
476 )
477 assert False, (
478 f"Performance bounds validation failed for {compression_type} compression: "
479 f"{'; '.join(violations)}"
480 )
481
482 self.logger.info(
483 "Successfully completed %s compression test with comprehensive metrics",
484 compression_type,
485 )
486
487 @matrix(
488 producer_type=["sync", "async"], serialization_type=["avro", "json", "protobuf"]
489 )
490 def test_basic_produce_with_schema_registry(
491 self, producer_type, serialization_type
492 ):
493 """
494 Test producer with Schema Registry serialization.
495
496 Note: in this test, we are producing messages with the same schema,
497 a realistic high-throughput production scenario.
498 As we have cache for schemas, only the first message will make HTTP calls to Schema Registry server.
499 Performance impact comes from serialization overhead, not network calls.
500 """
501
502 topic_name = f"performance-test-produce-{serialization_type or 'plain'}-topic"
503 test_duration = 5.0
504
505 # Create topic and wait until ready
506 self.kafka.create_topic(topic_name, partitions=1, replication_factor=1)
507 topic_ready = self.kafka.wait_for_topic(topic_name, max_wait_time=30)
508 assert topic_ready, f"Topic {topic_name} was not created within timeout"
509
510 # Initialize metrics
511 metrics = MetricsCollector()
512 bounds = MetricsBounds()
513
514 # Create appropriate producer strategy
515 strategy = self.create_producer(producer_type)
516 strategy.metrics = metrics
517
518 # Start metrics collection
519 metrics.start()
520
521 # Message formatter - realistic pattern where messages use same schema
522 def message_formatter(i):
523 try:
524 # Create message content based on serialization type
525 if serialization_type == "protobuf":
526 from tests.integration.schema_registry.data.proto import (
527 PublicTestProto_pb2,
528 )
529
530 message_value = PublicTestProto_pb2.TestMessage(
531 test_string=f"User{i}",
532 test_bool=i % 2 == 0,
533 test_bytes=f"bytes{i}".encode("utf-8"),
534 test_double=float(i),
535 test_float=float(i),
536 test_fixed32=i,
537 test_fixed64=i,
538 test_int32=i,
539 test_int64=i,
540 test_sfixed32=i,
541 test_sfixed64=i,
542 test_sint32=i,
543 test_sint64=i,
544 test_uint32=i,
545 test_uint64=i,
546 )
547 elif serialization_type: # Avro or JSON
548 # Match the Protobuf schema structure for Avro/JSON
549 # For JSON, convert bytes to base64 string
550 if serialization_type == "json":
551 test_bytes = f"bytes{i}" # JSON uses string for bytes
552 else:
553 test_bytes = f"bytes{i}".encode(
554 "utf-8"
555 ) # Avro uses actual bytes
556
557 message_value = {
558 "test_string": f"User{i}",
559 "test_bool": i % 2 == 0,
560 "test_bytes": test_bytes,
561 "test_double": float(i),
562 "test_float": float(i),
563 "test_fixed32": i,
564 "test_fixed64": i,
565 "test_int32": i,
566 "test_int64": i,
567 "test_sfixed32": i,
568 "test_sfixed64": i,
569 "test_sint32": i,
570 "test_sint64": i,
571 "test_uint32": i,
572 "test_uint64": i,
573 }
574 else:
575 # Plain messages - no complex structure needed
576 message_value = f"Test message {i}" # Simple string message
577
578 return (message_value, f"key-{i}")
579 except Exception as e:
580 self.logger.error(f"Error creating message {i}: {e}")
581 return (f"Test message {i}", f"key-{i}")
582
583 delivered_messages = []
584 failed_messages = []
585
586 start_time = time.time()
587 messages_sent = strategy.produce_messages(
588 topic_name,
589 test_duration,
590 start_time,
591 message_formatter,
592 delivered_messages,
593 failed_messages,
594 serialization_type,
595 )
596
597 # Finalize and validate metrics
598 metrics.finalize()
599 metrics_summary = metrics.get_summary()
600 is_valid, violations = validate_metrics(metrics_summary, bounds)
601
602 self.logger.info(
603 f"=== {producer_type.upper()} {serialization_type.upper()} SR METRICS REPORT ==="
604 )
605 print_metrics_report(metrics_summary, is_valid, violations)
606
607 assert messages_sent > 0, "No messages were sent"
608 assert len(delivered_messages) > 0, "No messages were delivered"
609 assert (
610 metrics_summary["messages_delivered"] > 0
611 ), "No messages were delivered (metrics)"
612 assert (
613 metrics_summary["send_throughput_msg_per_sec"] > 10
614 ), f"Send throughput too low: {metrics_summary['send_throughput_msg_per_sec']:.2f} msg/s"
615
616 if not is_valid:
617 self.logger.error(
618 "Performance bounds validation failed: %s", "; ".join(violations)
619 )
620 assert False, f"Performance bounds validation failed: {'; '.join(violations)}"
621
622 self.logger.info(
623 "Successfully completed SR production test with comprehensive metrics"
624 )
625
626 def tearDown(self):
627 """Clean up test environment"""
628 self.logger.info("Test completed - external Kafka service remains running")