asupersync-conformance 0.3.1

Conformance test suite for async runtime specifications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
//! Kafka RecordBatch v2 conformance tests per KIP-98.
//!
//! This module provides conformance tests for Kafka producer RecordBatch v2 format
//! to ensure compatibility with the Kafka wire protocol specification.
//!
//! # KIP-98 RecordBatch v2 Format
//!
//! The RecordBatch v2 format includes:
//! - Record attribute bits (compression, transactional, control, timestamp type)
//! - Producer ID/epoch/sequence for exactly-once semantics
//! - Varint encoding for timestamp deltas and key/value lengths
//! - Headers array encoding
//! - Base offset and last offset delta relationship
//! - CRC32 validation

use serde::{Deserialize, Serialize};

// ============================================================================
// KIP-98 RecordBatch v2 Format Structures
// ============================================================================

/// RecordBatch v2 format per KIP-98.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordBatchV2 {
    /// First offset in this batch.
    pub base_offset: i64,
    /// Length in bytes of the batch.
    pub batch_length: i32,
    /// Partition leader epoch.
    pub partition_leader_epoch: i32,
    /// Magic byte (must be 2 for RecordBatch v2).
    pub magic: i8,
    /// CRC32 checksum.
    pub crc: u32,
    /// Batch attributes.
    pub attributes: RecordAttribute,
    /// Delta from base_offset to last record.
    pub last_offset_delta: i32,
    /// Timestamp of first record in batch.
    pub first_timestamp: i64,
    /// Highest timestamp in batch.
    pub max_timestamp: i64,
    /// Producer ID for exactly-once semantics.
    pub producer_id: i64,
    /// Producer epoch.
    pub producer_epoch: i16,
    /// Base sequence number.
    pub base_sequence: i32,
    /// Number of records in batch.
    pub record_count: i32,
    /// Records in the batch.
    pub records: Vec<RecordV2>,
}

impl RecordBatchV2 {
    /// Create a new RecordBatch v2.
    pub fn new(
        base_offset: i64,
        producer_id: i64,
        producer_epoch: i16,
        base_sequence: i32,
    ) -> Self {
        Self {
            base_offset,
            batch_length: 0, // Will be calculated during encoding
            partition_leader_epoch: 0,
            magic: 2,
            crc: 0, // Will be calculated during encoding
            attributes: RecordAttribute::new(),
            last_offset_delta: 0,
            first_timestamp: 0,
            max_timestamp: 0,
            producer_id,
            producer_epoch,
            base_sequence,
            record_count: 0,
            records: Vec::new(),
        }
    }

    /// Set the base timestamp.
    pub fn with_base_timestamp(mut self, timestamp: i64) -> Self {
        self.first_timestamp = timestamp;
        self.max_timestamp = timestamp;
        self
    }

    /// Set the attributes.
    pub fn with_attributes(mut self, attributes: RecordAttribute) -> Self {
        self.attributes = attributes;
        self
    }

    /// Add a record to the batch.
    pub fn add_record(&mut self, record: RecordV2) {
        self.record_count += 1;
        self.last_offset_delta = record.offset_delta;

        // Update max timestamp
        let record_timestamp = self.first_timestamp + record.timestamp_delta;
        if record_timestamp > self.max_timestamp {
            self.max_timestamp = record_timestamp;
        }

        self.records.push(record);
    }
}

/// Record attribute bits per KIP-98.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RecordAttribute {
    /// Raw attribute value.
    value: u8,
}

impl RecordAttribute {
    /// Create new attributes with all bits clear.
    pub fn new() -> Self {
        Self { value: 0 }
    }

    /// Set compression type (bits 0-2).
    pub fn with_compression(mut self, compression: u8) -> Self {
        assert!(compression < 8, "Compression type must be 0-7");
        self.value = (self.value & 0xF8) | (compression & 0x07);
        self
    }

    /// Get compression type.
    pub fn compression(self) -> u8 {
        self.value & 0x07
    }

    /// Set timestamp type (bit 3).
    pub fn with_timestamp_type(mut self, timestamp_type: TimestampType) -> Self {
        match timestamp_type {
            TimestampType::CreateTime => self.value &= !0x08,
            TimestampType::LogAppendTime => self.value |= 0x08,
        }
        self
    }

    /// Get timestamp type.
    pub fn timestamp_type(self) -> TimestampType {
        if (self.value & 0x08) != 0 {
            TimestampType::LogAppendTime
        } else {
            TimestampType::CreateTime
        }
    }

    /// Set transactional bit (bit 4).
    pub fn with_transactional(mut self, transactional: bool) -> Self {
        if transactional {
            self.value |= 0x10;
        } else {
            self.value &= !0x10;
        }
        self
    }

    /// Check if this is a transactional record.
    pub fn is_transactional(self) -> bool {
        (self.value & 0x10) != 0
    }

    /// Set control bit (bit 5).
    pub fn with_control(mut self, control: bool) -> Self {
        if control {
            self.value |= 0x20;
        } else {
            self.value &= !0x20;
        }
        self
    }

    /// Check if this is a control record.
    pub fn is_control(self) -> bool {
        (self.value & 0x20) != 0
    }

    /// Get raw byte value.
    pub fn as_u8(self) -> u8 {
        self.value
    }
}

impl Default for RecordAttribute {
    fn default() -> Self {
        Self::new()
    }
}

/// Timestamp type for records.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum TimestampType {
    /// Timestamp set by producer.
    CreateTime,
    /// Timestamp set by broker.
    LogAppendTime,
}

/// Individual record in RecordBatch v2 format.
#[derive(Debug, Clone, PartialEq)]
pub struct RecordV2 {
    /// Length of record in bytes.
    pub length: i32,
    /// Record attributes (currently unused).
    pub attributes: u8,
    /// Timestamp delta from batch first_timestamp.
    pub timestamp_delta: i64,
    /// Offset delta from batch base_offset.
    pub offset_delta: i32,
    /// Key length (-1 for null).
    pub key_length: i32,
    /// Key bytes (None for null).
    pub key: Option<Vec<u8>>,
    /// Value length (-1 for null).
    pub value_length: i32,
    /// Value bytes (None for null).
    pub value: Option<Vec<u8>>,
    /// Number of headers.
    pub header_count: i32,
    /// Headers array.
    pub headers: Vec<Header>,
}

impl RecordV2 {
    /// Create a new record.
    pub fn new(key: Option<Vec<u8>>, value: Option<Vec<u8>>) -> Self {
        let key_length = key.as_ref().map(|k| k.len() as i32).unwrap_or(-1);
        let value_length = value.as_ref().map(|v| v.len() as i32).unwrap_or(-1);

        Self {
            length: 0, // Will be calculated during encoding
            attributes: 0,
            timestamp_delta: 0,
            offset_delta: 0,
            key_length,
            key,
            value_length,
            value,
            header_count: 0,
            headers: Vec::new(),
        }
    }

    /// Set timestamp delta.
    pub fn with_timestamp_delta(mut self, delta: i64) -> Self {
        self.timestamp_delta = delta;
        self
    }

    /// Set offset delta.
    pub fn with_offset_delta(mut self, delta: i32) -> Self {
        self.offset_delta = delta;
        self
    }

    /// Add a header.
    pub fn with_header(mut self, key: String, value: Option<Vec<u8>>) -> Self {
        self.headers.push(Header { key, value });
        self.header_count = self.headers.len() as i32;
        self
    }
}

/// Header in a record.
#[derive(Debug, Clone, PartialEq)]
pub struct Header {
    /// Header key.
    pub key: String,
    /// Header value (None for null).
    pub value: Option<Vec<u8>>,
}

// ============================================================================
// Wire Format Encoding/Decoding
// ============================================================================

/// Kafka RecordBatch v2 conformance harness.
pub struct KafkaConformanceHarness;

impl KafkaConformanceHarness {
    /// Create a new conformance harness.
    pub fn new() -> Self {
        Self
    }

    /// Encode a RecordBatch v2 to wire format.
    pub fn encode_record_batch(&self, batch: &RecordBatchV2) -> Vec<u8> {
        let mut buf = Vec::new();

        // Encode records first to calculate batch length
        let mut records_data = Vec::new();
        for record in &batch.records {
            let record_bytes = self.encode_record(record);
            records_data.extend_from_slice(&record_bytes);
        }

        // Calculate total batch length (everything after base_offset field)
        let batch_length = 49 + records_data.len(); // Fixed header is 49 bytes after base_offset

        // Encode fixed header
        buf.extend_from_slice(&batch.base_offset.to_be_bytes()); // 8 bytes
        buf.extend_from_slice(&(batch_length as i32).to_be_bytes()); // 4 bytes
        buf.extend_from_slice(&batch.partition_leader_epoch.to_be_bytes()); // 4 bytes
        buf.push(batch.magic as u8); // 1 byte

        // Reserve space for CRC32 (will calculate after)
        let crc_offset = buf.len();
        buf.extend_from_slice(&0u32.to_be_bytes()); // 4 bytes

        let crc_start = buf.len();

        // Encode attributes and remaining header
        buf.extend_from_slice(&batch.last_offset_delta.to_be_bytes()); // 4 bytes
        buf.extend_from_slice(&batch.first_timestamp.to_be_bytes()); // 8 bytes
        buf.extend_from_slice(&batch.max_timestamp.to_be_bytes()); // 8 bytes
        buf.extend_from_slice(&batch.producer_id.to_be_bytes()); // 8 bytes
        buf.extend_from_slice(&batch.producer_epoch.to_be_bytes()); // 2 bytes
        buf.extend_from_slice(&batch.base_sequence.to_be_bytes()); // 4 bytes
        buf.extend_from_slice(&batch.record_count.to_be_bytes()); // 4 bytes
        buf.push(batch.attributes.as_u8()); // 1 byte

        // Add records
        buf.extend_from_slice(&records_data);

        // Calculate CRC32 over everything after the CRC field
        let crc = crc32fast::hash(&buf[crc_start..]);

        // Write CRC32
        buf[crc_offset..crc_offset + 4].copy_from_slice(&crc.to_be_bytes());

        buf
    }

    /// Encode a single record.
    fn encode_record(&self, record: &RecordV2) -> Vec<u8> {
        let mut buf = Vec::new();

        // Calculate record length
        let mut length = 1; // attributes
        length += varint_len(record.timestamp_delta);
        length += varint_len(record.offset_delta as i64);
        length += varint_len(record.key_length as i64);
        if let Some(ref key) = record.key {
            length += key.len();
        }
        length += varint_len(record.value_length as i64);
        if let Some(ref value) = record.value {
            length += value.len();
        }
        length += varint_len(record.header_count as i64);
        for header in &record.headers {
            length += varint_len(header.key.len() as i64);
            length += header.key.len();
            length += varint_len(header.value.as_ref().map(|v| v.len()).unwrap_or(0) as i64);
            if let Some(ref value) = header.value {
                length += value.len();
            }
        }

        // Encode length as varint
        encode_varint(&mut buf, length as i64);

        // Encode record content
        buf.push(record.attributes);
        encode_varint(&mut buf, record.timestamp_delta);
        encode_varint(&mut buf, record.offset_delta as i64);

        // Encode key
        encode_varint(&mut buf, record.key_length as i64);
        if let Some(ref key) = record.key {
            buf.extend_from_slice(key);
        }

        // Encode value
        encode_varint(&mut buf, record.value_length as i64);
        if let Some(ref value) = record.value {
            buf.extend_from_slice(value);
        }

        // Encode headers
        encode_varint(&mut buf, record.header_count as i64);
        for header in &record.headers {
            encode_varint(&mut buf, header.key.len() as i64);
            buf.extend_from_slice(header.key.as_bytes());
            let value_len = header.value.as_ref().map(|v| v.len()).unwrap_or(0);
            encode_varint(&mut buf, value_len as i64);
            if let Some(ref value) = header.value {
                buf.extend_from_slice(value);
            }
        }

        buf
    }

    /// Decode a RecordBatch v2 from wire format.
    pub fn decode_record_batch(&self, data: &[u8]) -> Result<RecordBatchV2, String> {
        if data.len() < 61 {
            return Err("RecordBatch v2 must be at least 61 bytes".to_string());
        }

        let mut offset = 0;

        // Decode fixed header
        let base_offset = i64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let batch_length = i32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let partition_leader_epoch = i32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let magic = data[offset] as i8;
        offset += 1;

        if magic != 2 {
            return Err(format!("Invalid magic byte: {}, expected 2", magic));
        }

        let crc = u32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        // Validate CRC32
        let calculated_crc = crc32fast::hash(&data[offset..]);
        if crc != calculated_crc {
            return Err(format!(
                "CRC mismatch: got {}, expected {}",
                calculated_crc, crc
            ));
        }

        let last_offset_delta = i32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let first_timestamp = i64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let max_timestamp = i64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let producer_id = i64::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
            data[offset + 4],
            data[offset + 5],
            data[offset + 6],
            data[offset + 7],
        ]);
        offset += 8;

        let producer_epoch = i16::from_be_bytes([data[offset], data[offset + 1]]);
        offset += 2;

        let base_sequence = i32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let record_count = i32::from_be_bytes([
            data[offset],
            data[offset + 1],
            data[offset + 2],
            data[offset + 3],
        ]);
        offset += 4;

        let attributes = RecordAttribute {
            value: data[offset],
        };
        offset += 1;

        // Decode records
        let mut records = Vec::new();
        for _ in 0..record_count {
            let (record, bytes_read) = self.decode_record(&data[offset..])?;
            records.push(record);
            offset += bytes_read;
        }

        Ok(RecordBatchV2 {
            base_offset,
            batch_length,
            partition_leader_epoch,
            magic,
            crc,
            attributes,
            last_offset_delta,
            first_timestamp,
            max_timestamp,
            producer_id,
            producer_epoch,
            base_sequence,
            record_count,
            records,
        })
    }

    /// Decode a single record.
    fn decode_record(&self, data: &[u8]) -> Result<(RecordV2, usize), String> {
        let mut offset = 0;

        let (length, length_bytes) = decode_varint(&data[offset..])?;
        offset += length_bytes;

        let attributes = data[offset];
        offset += 1;

        let (timestamp_delta, td_bytes) = decode_varint(&data[offset..])?;
        offset += td_bytes;

        let (offset_delta, od_bytes) = decode_varint(&data[offset..])?;
        offset += od_bytes;

        // Decode key
        let (key_length, kl_bytes) = decode_varint(&data[offset..])?;
        offset += kl_bytes;

        let key = if key_length == -1 {
            None
        } else {
            let key_data = data[offset..offset + key_length as usize].to_vec();
            offset += key_length as usize;
            Some(key_data)
        };

        // Decode value
        let (value_length, vl_bytes) = decode_varint(&data[offset..])?;
        offset += vl_bytes;

        let value = if value_length == -1 {
            None
        } else {
            let value_data = data[offset..offset + value_length as usize].to_vec();
            offset += value_length as usize;
            Some(value_data)
        };

        // Decode headers
        let (header_count, hc_bytes) = decode_varint(&data[offset..])?;
        offset += hc_bytes;

        let mut headers = Vec::new();
        for _ in 0..header_count {
            let (key_len, kl_bytes) = decode_varint(&data[offset..])?;
            offset += kl_bytes;

            let header_key = String::from_utf8(data[offset..offset + key_len as usize].to_vec())
                .map_err(|e| format!("Invalid UTF-8 in header key: {}", e))?;
            offset += key_len as usize;

            let (value_len, vl_bytes) = decode_varint(&data[offset..])?;
            offset += vl_bytes;

            let header_value = if value_len == 0 {
                None
            } else {
                let value_data = data[offset..offset + value_len as usize].to_vec();
                offset += value_len as usize;
                Some(value_data)
            };

            headers.push(Header {
                key: header_key,
                value: header_value,
            });
        }

        let record = RecordV2 {
            length: length as i32,
            attributes,
            timestamp_delta,
            offset_delta: offset_delta as i32,
            key_length: key_length as i32,
            key,
            value_length: value_length as i32,
            value,
            header_count: header_count as i32,
            headers,
        };

        Ok((record, offset))
    }

    /// Run all format conformance tests.
    pub fn run_format_tests(&self) -> Vec<ConformanceTestResult> {
        vec![
            self.test_basic_encoding(),
            self.test_record_attributes(),
            self.test_varint_encoding(),
            self.test_headers_encoding(),
            self.test_exactly_once_fields(),
            self.test_offset_relationship(),
            self.test_transactional_batch(),
            self.test_control_batch(),
            self.test_null_key_value(),
            self.test_crc32_validation(),
            self.test_empty_batch(),
        ]
    }

    /// Test basic RecordBatch v2 encoding.
    fn test_basic_encoding(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(0, 12345, 0, 0).with_base_timestamp(1234567890000);

        let record = RecordV2::new(Some(b"test-key".to_vec()), Some(b"test-value".to_vec()))
            .with_timestamp_delta(0)
            .with_offset_delta(0);

        batch.add_record(record);

        // Encode the batch
        let encoded = self.encode_record_batch(&batch);

        // Basic format validation
        if encoded.len() < 61 {
            return ConformanceTestResult::fail(
                "basic_encoding".to_string(),
                "RecordBatch v2 must be at least 61 bytes".to_string(),
            );
        }

        if encoded[16] != 2 {
            return ConformanceTestResult::fail(
                "basic_encoding".to_string(),
                "Magic byte must be 2 for RecordBatch v2".to_string(),
            );
        }

        // Verify we can decode it back
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.magic != 2
                    || decoded.producer_id != 12345
                    || decoded.record_count != 1
                    || decoded.records.len() != 1
                    || decoded.records[0].key != Some(b"test-key".to_vec())
                    || decoded.records[0].value != Some(b"test-value".to_vec())
                {
                    return ConformanceTestResult::fail(
                        "basic_encoding".to_string(),
                        "Decoded batch does not match original".to_string(),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "basic_encoding".to_string(),
                    format!("Failed to decode batch: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("basic_encoding".to_string())
    }

    /// Test record attribute bits according to KIP-98.
    fn test_record_attributes(&self) -> ConformanceTestResult {
        // Test compression bits (0-2)
        for compression in 0..8 {
            let attr = RecordAttribute::new().with_compression(compression);
            if attr.compression() != compression {
                return ConformanceTestResult::fail(
                    "record_attributes".to_string(),
                    format!("Compression bits failed for type {}", compression),
                );
            }
        }

        // Test timestamp type bit (3)
        let attr_create = RecordAttribute::new().with_timestamp_type(TimestampType::CreateTime);
        let attr_append = RecordAttribute::new().with_timestamp_type(TimestampType::LogAppendTime);

        if attr_create.timestamp_type() != TimestampType::CreateTime
            || attr_append.timestamp_type() != TimestampType::LogAppendTime
            || (attr_create.as_u8() & 0x08) != 0
            || (attr_append.as_u8() & 0x08) != 0x08
        {
            return ConformanceTestResult::fail(
                "record_attributes".to_string(),
                "Timestamp type bit validation failed".to_string(),
            );
        }

        // Test transactional bit (4)
        let attr_false = RecordAttribute::new().with_transactional(false);
        let attr_true = RecordAttribute::new().with_transactional(true);

        if attr_false.is_transactional()
            || !attr_true.is_transactional()
            || (attr_false.as_u8() & 0x10) != 0
            || (attr_true.as_u8() & 0x10) != 0x10
        {
            return ConformanceTestResult::fail(
                "record_attributes".to_string(),
                "Transactional bit validation failed".to_string(),
            );
        }

        // Test control bit (5)
        let attr_false = RecordAttribute::new().with_control(false);
        let attr_true = RecordAttribute::new().with_control(true);

        if attr_false.is_control()
            || !attr_true.is_control()
            || (attr_false.as_u8() & 0x20) != 0
            || (attr_true.as_u8() & 0x20) != 0x20
        {
            return ConformanceTestResult::fail(
                "record_attributes".to_string(),
                "Control bit validation failed".to_string(),
            );
        }

        ConformanceTestResult::pass("record_attributes".to_string())
    }

    /// Test varint encoding for timestamp deltas.
    fn test_varint_encoding(&self) -> ConformanceTestResult {
        let test_deltas = [0, 1, 127, 128, 16383, 16384, 2097151, 2097152];

        let mut batch = RecordBatchV2::new(0, 12345, 0, 0).with_base_timestamp(1234567890000);

        for (i, &delta) in test_deltas.iter().enumerate() {
            let record = RecordV2::new(
                Some(format!("key-{}", i).into_bytes()),
                Some(format!("value-{}", i).into_bytes()),
            )
            .with_timestamp_delta(delta)
            .with_offset_delta(i as i32);

            batch.add_record(record);
        }

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.records.len() != test_deltas.len() {
                    return ConformanceTestResult::fail(
                        "varint_encoding".to_string(),
                        "Record count mismatch after varint encoding".to_string(),
                    );
                }

                for (i, &expected_delta) in test_deltas.iter().enumerate() {
                    if decoded.records[i].timestamp_delta != expected_delta {
                        return ConformanceTestResult::fail(
                            "varint_encoding".to_string(),
                            format!(
                                "Timestamp delta mismatch at index {}: got {}, expected {}",
                                i, decoded.records[i].timestamp_delta, expected_delta
                            ),
                        );
                    }
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "varint_encoding".to_string(),
                    format!("Failed to decode batch with varint encoding: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("varint_encoding".to_string())
    }

    /// Test headers array encoding.
    fn test_headers_encoding(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(0, 12345, 0, 0).with_base_timestamp(1234567890000);

        let record = RecordV2::new(
            Some(b"user-123".to_vec()),
            Some(b"{\"action\":\"login\"}".to_vec()),
        )
        .with_timestamp_delta(0)
        .with_offset_delta(0)
        .with_header("trace-id".to_string(), Some(b"abc-def-123".to_vec()))
        .with_header("user-agent".to_string(), Some(b"MyApp/1.0".to_vec()))
        .with_header("request-id".to_string(), Some(b"req-456".to_vec()));

        batch.add_record(record);

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.records.len() != 1 {
                    return ConformanceTestResult::fail(
                        "headers_encoding".to_string(),
                        "Should have exactly one record".to_string(),
                    );
                }

                let decoded_record = &decoded.records[0];
                if decoded_record.headers.len() != 3 {
                    return ConformanceTestResult::fail(
                        "headers_encoding".to_string(),
                        format!("Expected 3 headers, got {}", decoded_record.headers.len()),
                    );
                }

                let expected_headers = [
                    ("trace-id", Some(b"abc-def-123".to_vec())),
                    ("user-agent", Some(b"MyApp/1.0".to_vec())),
                    ("request-id", Some(b"req-456".to_vec())),
                ];

                for (i, (expected_key, expected_value)) in expected_headers.iter().enumerate() {
                    let header = &decoded_record.headers[i];
                    if &header.key != expected_key || &header.value != expected_value {
                        return ConformanceTestResult::fail(
                            "headers_encoding".to_string(),
                            format!(
                                "Header {} mismatch: expected {:?}, got {:?}",
                                i,
                                (expected_key, expected_value),
                                (&header.key, &header.value)
                            ),
                        );
                    }
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "headers_encoding".to_string(),
                    format!("Failed to decode batch with headers: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("headers_encoding".to_string())
    }

    /// Test producer ID, epoch, and sequence for exactly-once semantics.
    fn test_exactly_once_fields(&self) -> ConformanceTestResult {
        // Test with maximum values
        let producer_id = 9223372036854775807i64; // i64::MAX
        let producer_epoch = 32767i16; // i16::MAX
        let base_sequence = 2147483647i32; // i32::MAX

        let mut batch = RecordBatchV2::new(100, producer_id, producer_epoch, base_sequence)
            .with_base_timestamp(1234567890000);

        let record = RecordV2::new(
            Some(b"exactly-once-key".to_vec()),
            Some(b"exactly-once-value".to_vec()),
        )
        .with_timestamp_delta(0)
        .with_offset_delta(0);

        batch.add_record(record);

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.producer_id != producer_id
                    || decoded.producer_epoch != producer_epoch
                    || decoded.base_sequence != base_sequence
                {
                    return ConformanceTestResult::fail(
                        "exactly_once_fields".to_string(),
                        format!(
                            "Exactly-once fields mismatch: producer_id {} vs {}, epoch {} vs {}, sequence {} vs {}",
                            decoded.producer_id,
                            producer_id,
                            decoded.producer_epoch,
                            producer_epoch,
                            decoded.base_sequence,
                            base_sequence
                        ),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "exactly_once_fields".to_string(),
                    format!("Failed to decode batch with exactly-once fields: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("exactly_once_fields".to_string())
    }

    /// Test base_offset and last_offset_delta relationship.
    fn test_offset_relationship(&self) -> ConformanceTestResult {
        let base_offset = 1000i64;
        let mut batch =
            RecordBatchV2::new(base_offset, 55555, 1, 50).with_base_timestamp(1234567890000);

        // Add multiple records to test offset delta calculation
        for i in 0..10 {
            let record = RecordV2::new(
                Some(format!("offset-key-{}", i).into_bytes()),
                Some(format!("offset-value-{}", i).into_bytes()),
            )
            .with_timestamp_delta(i * 5)
            .with_offset_delta(i as i32);

            batch.add_record(record);
        }

        // Verify last_offset_delta is set correctly
        if batch.last_offset_delta != 9 {
            return ConformanceTestResult::fail(
                "offset_relationship".to_string(),
                format!(
                    "last_offset_delta should be 9 for 10 records (0-indexed), got {}",
                    batch.last_offset_delta
                ),
            );
        }

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.base_offset != base_offset
                    || decoded.last_offset_delta != 9
                    || decoded.record_count != 10
                {
                    return ConformanceTestResult::fail(
                        "offset_relationship".to_string(),
                        format!(
                            "Offset relationship validation failed: base {} vs {}, last_delta {} vs 9, count {} vs 10",
                            decoded.base_offset,
                            base_offset,
                            decoded.last_offset_delta,
                            decoded.record_count
                        ),
                    );
                }

                // Verify each record has the correct offset delta
                for (i, record) in decoded.records.iter().enumerate() {
                    if record.offset_delta != i as i32 {
                        return ConformanceTestResult::fail(
                            "offset_relationship".to_string(),
                            format!(
                                "Record {} has wrong offset_delta: {} vs {}",
                                i, record.offset_delta, i
                            ),
                        );
                    }
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "offset_relationship".to_string(),
                    format!("Failed to decode batch with offset relationship: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("offset_relationship".to_string())
    }

    /// Test transactional record batch.
    fn test_transactional_batch(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(100, 98765, 1, 42)
            .with_base_timestamp(1234567890000)
            .with_attributes(RecordAttribute::new().with_transactional(true));

        let record1 = RecordV2::new(Some(b"key1".to_vec()), Some(b"value1".to_vec()))
            .with_timestamp_delta(0)
            .with_offset_delta(0);

        let record2 = RecordV2::new(Some(b"key2".to_vec()), Some(b"value2".to_vec()))
            .with_timestamp_delta(100)
            .with_offset_delta(1);

        batch.add_record(record1);
        batch.add_record(record2);

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if !decoded.attributes.is_transactional()
                    || decoded.record_count != 2
                    || decoded.records.len() != 2
                {
                    return ConformanceTestResult::fail(
                        "transactional_batch".to_string(),
                        "Transactional attributes or record count validation failed".to_string(),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "transactional_batch".to_string(),
                    format!("Failed to decode transactional batch: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("transactional_batch".to_string())
    }

    /// Test control record batch.
    fn test_control_batch(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(200, 54321, 2, 10)
            .with_base_timestamp(1234567890000)
            .with_attributes(
                RecordAttribute::new()
                    .with_transactional(true)
                    .with_control(true),
            );

        // Control records typically have specific key/value structures
        let control_record = RecordV2::new(
            Some(b"\x00\x00".to_vec()), // Control record key
            Some(b"\x00".to_vec()),     // Control record value (commit)
        )
        .with_timestamp_delta(0)
        .with_offset_delta(0);

        batch.add_record(control_record);

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if !decoded.attributes.is_transactional()
                    || !decoded.attributes.is_control()
                    || decoded.record_count != 1
                {
                    return ConformanceTestResult::fail(
                        "control_batch".to_string(),
                        "Control attributes validation failed".to_string(),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "control_batch".to_string(),
                    format!("Failed to decode control batch: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("control_batch".to_string())
    }

    /// Test null key and value handling.
    fn test_null_key_value(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(400, 44444, 0, 0).with_base_timestamp(1234567890000);

        // Record with null key and value
        let record1 = RecordV2::new(None, None)
            .with_timestamp_delta(0)
            .with_offset_delta(0);

        // Record with null key but non-null value
        let record2 = RecordV2::new(None, Some(b"value-only".to_vec()))
            .with_timestamp_delta(50)
            .with_offset_delta(1);

        // Record with non-null key but null value
        let record3 = RecordV2::new(Some(b"key-only".to_vec()), None)
            .with_timestamp_delta(100)
            .with_offset_delta(2);

        batch.add_record(record1);
        batch.add_record(record2);
        batch.add_record(record3);

        // Encode and decode
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.record_count != 3 || decoded.records.len() != 3 {
                    return ConformanceTestResult::fail(
                        "null_key_value".to_string(),
                        format!("Expected 3 records, got {}", decoded.records.len()),
                    );
                }

                // Check null key/value
                if decoded.records[0].key.is_some()
                    || decoded.records[0].value.is_some()
                    || decoded.records[0].key_length != -1
                    || decoded.records[0].value_length != -1
                {
                    return ConformanceTestResult::fail(
                        "null_key_value".to_string(),
                        "Null key/value validation failed for record 0".to_string(),
                    );
                }

                // Check null key with value
                if decoded.records[1].key.is_some()
                    || decoded.records[1].value != Some(b"value-only".to_vec())
                    || decoded.records[1].key_length != -1
                    || decoded.records[1].value_length != 10
                {
                    return ConformanceTestResult::fail(
                        "null_key_value".to_string(),
                        "Null key with value validation failed for record 1".to_string(),
                    );
                }

                // Check key with null value
                if decoded.records[2].key != Some(b"key-only".to_vec())
                    || decoded.records[2].value.is_some()
                    || decoded.records[2].key_length != 8
                    || decoded.records[2].value_length != -1
                {
                    return ConformanceTestResult::fail(
                        "null_key_value".to_string(),
                        "Key with null value validation failed for record 2".to_string(),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "null_key_value".to_string(),
                    format!("Failed to decode batch with null key/value: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("null_key_value".to_string())
    }

    /// Test CRC32 validation.
    fn test_crc32_validation(&self) -> ConformanceTestResult {
        let mut batch = RecordBatchV2::new(0, 12345, 0, 0).with_base_timestamp(1234567890000);

        let record = RecordV2::new(
            Some(b"crc-test-key".to_vec()),
            Some(b"crc-test-value".to_vec()),
        );

        batch.add_record(record);

        // Encode the batch
        let mut encoded = self.encode_record_batch(&batch);

        // Verify it decodes correctly
        if self.decode_record_batch(&encoded).is_err() {
            return ConformanceTestResult::fail(
                "crc32_validation".to_string(),
                "Valid CRC32 batch failed to decode".to_string(),
            );
        }

        // Corrupt the CRC32 (at position 20-23)
        encoded[20] ^= 0xFF;

        // Should fail with CRC mismatch
        match self.decode_record_batch(&encoded) {
            Err(e) => {
                if !e.contains("CRC mismatch") {
                    return ConformanceTestResult::fail(
                        "crc32_validation".to_string(),
                        format!("Expected CRC mismatch error, got: {}", e),
                    );
                }
            }
            Ok(_) => {
                return ConformanceTestResult::fail(
                    "crc32_validation".to_string(),
                    "Expected CRC validation to fail".to_string(),
                );
            }
        }

        ConformanceTestResult::pass("crc32_validation".to_string())
    }

    /// Test empty record batch.
    fn test_empty_batch(&self) -> ConformanceTestResult {
        let batch = RecordBatchV2::new(500, 12345, 0, 0).with_base_timestamp(1234567890000);

        // Encode and decode empty batch
        let encoded = self.encode_record_batch(&batch);
        match self.decode_record_batch(&encoded) {
            Ok(decoded) => {
                if decoded.record_count != 0
                    || !decoded.records.is_empty()
                    || decoded.last_offset_delta != 0
                {
                    return ConformanceTestResult::fail(
                        "empty_batch".to_string(),
                        "Empty batch validation failed".to_string(),
                    );
                }
            }
            Err(e) => {
                return ConformanceTestResult::fail(
                    "empty_batch".to_string(),
                    format!("Failed to decode empty batch: {}", e),
                );
            }
        }

        ConformanceTestResult::pass("empty_batch".to_string())
    }
}

impl Default for KafkaConformanceHarness {
    fn default() -> Self {
        Self::new()
    }
}

// ============================================================================
// Conformance Test Result
// ============================================================================

/// Result of a Kafka conformance test.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConformanceTestResult {
    /// Test identifier.
    pub test_id: String,
    /// Whether the test passed.
    pub passed: bool,
    /// Error message if failed.
    pub error_message: Option<String>,
}

impl ConformanceTestResult {
    /// Create a passing test result.
    pub fn pass(test_id: String) -> Self {
        Self {
            test_id,
            passed: true,
            error_message: None,
        }
    }

    /// Create a failing test result.
    pub fn fail(test_id: String, error: String) -> Self {
        Self {
            test_id,
            passed: false,
            error_message: Some(error),
        }
    }
}

// ============================================================================
// Varint Encoding Utilities
// ============================================================================

/// Encode a signed 64-bit integer as a varint.
fn encode_varint(buf: &mut Vec<u8>, value: i64) {
    // Use zigzag encoding for signed values
    let unsigned = ((value << 1) ^ (value >> 63)) as u64;
    encode_varint_unsigned(buf, unsigned);
}

/// Encode an unsigned 64-bit integer as a varint.
fn encode_varint_unsigned(buf: &mut Vec<u8>, mut value: u64) {
    while value >= 0x80 {
        buf.push((value & 0x7F | 0x80) as u8);
        value >>= 7;
    }
    buf.push(value as u8);
}

/// Decode a varint from bytes.
fn decode_varint(data: &[u8]) -> Result<(i64, usize), String> {
    let (unsigned, bytes_read) = decode_varint_unsigned(data)?;

    // Decode zigzag encoding
    let signed = ((unsigned >> 1) as i64) ^ -((unsigned & 1) as i64);
    Ok((signed, bytes_read))
}

/// Decode an unsigned varint from bytes.
fn decode_varint_unsigned(data: &[u8]) -> Result<(u64, usize), String> {
    let mut result = 0u64;
    let mut shift = 0;
    let mut bytes_read = 0;

    for &byte in data.iter().take(10) {
        // Max 10 bytes for 64-bit varint
        bytes_read += 1;
        result |= ((byte & 0x7F) as u64) << shift;

        if (byte & 0x80) == 0 {
            return Ok((result, bytes_read));
        }

        shift += 7;
        if shift >= 64 {
            return Err("Varint too long".to_string());
        }
    }

    Err("Incomplete varint".to_string())
}

/// Calculate the number of bytes needed to encode a varint.
fn varint_len(value: i64) -> usize {
    let unsigned = ((value << 1) ^ (value >> 63)) as u64;
    varint_len_unsigned(unsigned)
}

/// Calculate the number of bytes needed to encode an unsigned varint.
fn varint_len_unsigned(mut value: u64) -> usize {
    if value == 0 {
        return 1;
    }

    let mut len = 0;
    while value > 0 {
        len += 1;
        value >>= 7;
    }
    len
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_varint_roundtrip() {
        let test_values = [
            -1,
            0,
            1,
            127,
            128,
            16383,
            16384,
            2097151,
            2097152,
            i64::MAX,
            i64::MIN,
        ];

        for &value in &test_values {
            let mut buf = Vec::new();
            encode_varint(&mut buf, value);

            let (decoded, bytes_read) = decode_varint(&buf).unwrap();
            assert_eq!(decoded, value);
            assert_eq!(bytes_read, buf.len());
        }
    }

    #[test]
    fn test_record_attribute_bits() {
        // Test all compression types
        for compression in 0..8 {
            let attr = RecordAttribute::new().with_compression(compression);
            assert_eq!(attr.compression(), compression);
        }

        // Test timestamp type
        let create_time = RecordAttribute::new().with_timestamp_type(TimestampType::CreateTime);
        let append_time = RecordAttribute::new().with_timestamp_type(TimestampType::LogAppendTime);

        assert_eq!(create_time.timestamp_type(), TimestampType::CreateTime);
        assert_eq!(append_time.timestamp_type(), TimestampType::LogAppendTime);

        // Test transactional bit
        let non_txn = RecordAttribute::new().with_transactional(false);
        let txn = RecordAttribute::new().with_transactional(true);

        assert!(!non_txn.is_transactional());
        assert!(txn.is_transactional());

        // Test control bit
        let non_control = RecordAttribute::new().with_control(false);
        let control = RecordAttribute::new().with_control(true);

        assert!(!non_control.is_control());
        assert!(control.is_control());
    }

    #[test]
    fn test_basic_encoding_roundtrip() {
        let harness = KafkaConformanceHarness::new();

        let mut batch = RecordBatchV2::new(100, 12345, 1, 42).with_base_timestamp(1234567890000);

        let record = RecordV2::new(Some(b"test-key".to_vec()), Some(b"test-value".to_vec()))
            .with_timestamp_delta(50)
            .with_offset_delta(0);

        batch.add_record(record);

        let encoded = harness.encode_record_batch(&batch);
        let decoded = harness.decode_record_batch(&encoded).unwrap();

        assert_eq!(decoded.base_offset, 100);
        assert_eq!(decoded.magic, 2);
        assert_eq!(decoded.producer_id, 12345);
        assert_eq!(decoded.producer_epoch, 1);
        assert_eq!(decoded.base_sequence, 42);
        assert_eq!(decoded.record_count, 1);
        assert_eq!(decoded.records.len(), 1);
        assert_eq!(decoded.records[0].key, Some(b"test-key".to_vec()));
        assert_eq!(decoded.records[0].value, Some(b"test-value".to_vec()));
        assert_eq!(decoded.records[0].timestamp_delta, 50);
    }
}