binlog-inspect 0.4.0

Offline inspector for plaintext MySQL binary logs with JSON Lines, text and CSV output
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
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
// Copyright (c) 2026 houseme
// SPDX-License-Identifier: Apache-2.0

//! Convert mysql_common row values without exposing its types in the public event model.
//!
//! This module also pre-validates hostile table map optional metadata before it
//! reaches the underlying library: the library allocates variant vectors from
//! declared counts without bounding them, which aborts the process on crafted
//! input. The manual TLV walk in [`validate_table_map_metadata`] mirrors the
//! library's wire format exactly so no valid table map is rejected.
use crate::event::{CellValue, ColumnValue, RowImage, Signedness};
use mysql_common::{
    binlog::{events::TableMapEvent, row::BinlogRow, value::BinlogValue},
    constants::ColumnType,
    proto::MySerialize,
    value::Value,
};
use std::io;

/// Optional metadata field types (TLV type codes) accepted by the
/// pre-validation walk.
///
/// The underlying library only knows the types 1..=13; the partial-JSON types
/// 14 and 15 (WL#2955) are accepted here and stripped from the event body
/// before the library parses the table map, because its metadata iterator
/// rejects unknown types. Anything else is rejected.
const KNOWN_TLV_TYPES: [u8; 15] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// `SIGNEDNESS`: unsigned flags of numeric columns (MSB-first bitmap).
const TLV_SIGNEDNESS: u8 = 1;
/// `SET_STR_VALUE`: variant names of SET columns.
const TLV_SET_STR_VALUE: u8 = 5;
/// `ENUM_STR_VALUE`: variant names of ENUM columns.
const TLV_ENUM_STR_VALUE: u8 = 6;
/// `PARTIAL_JSON_UPDATE`: bitmap of columns logged as partial JSON updates.
const TLV_PARTIAL_JSON_UPDATE: u8 = 14;
/// `UPDATED_COLUMN_TYPES`: actual data types of updated columns.
const TLV_UPDATED_COLUMN_TYPES: u8 = 15;

/// Lowercase hex digits used for byte rendering.
const HEX: [u8; 16] = *b"0123456789abcdef";

pub(crate) fn decode_row(
    row: &BinlogRow,
    present: &[bool],
    signedness: &[Option<bool>],
) -> io::Result<RowImage> {
    let mut offset = 0;
    let mut columns = Vec::with_capacity(present.len());
    for (index, &included) in present.iter().enumerate() {
        if !included {
            columns.push(ColumnValue {
                index,
                name: None,
                mysql_type: None,
                signedness: None,
                value: CellValue::Absent,
            });
            continue;
        }
        let column = row.columns_ref().get(offset).ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "row bitmap and column count differ",
            )
        })?;
        let value = row
            .as_ref(offset)
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "row value missing"))?;
        let value = match value {
            BinlogValue::Value(value) => match value {
                Value::NULL => CellValue::Null,
                Value::Bytes(bytes) => {
                    let mut encoded = String::with_capacity(bytes.len() * 2);
                    for byte in bytes {
                        encoded.push(HEX[usize::from(byte >> 4)] as char);
                        encoded.push(HEX[usize::from(byte & 0x0f)] as char);
                    }
                    CellValue::Bytes(encoded)
                }
                Value::Int(n) => CellValue::Int(*n),
                Value::UInt(n) => CellValue::UInt(*n),
                Value::Float(n) => CellValue::Float(n.to_string()),
                Value::Double(n) => CellValue::Double(n.to_string()),
                Value::Date(year, month, day, hour, minute, second, micros) => CellValue::Date {
                    year: *year,
                    month: *month,
                    day: *day,
                    hour: *hour,
                    minute: *minute,
                    second: *second,
                    micros: *micros,
                },
                Value::Time(negative, days, hours, minutes, seconds, micros) => CellValue::Time {
                    negative: *negative,
                    days: *days,
                    hours: *hours,
                    minutes: *minutes,
                    seconds: *seconds,
                    micros: *micros,
                },
            },
            BinlogValue::Jsonb(value) => CellValue::Json(
                serde_json::Value::try_from(value.clone())
                    .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?,
            ),
            BinlogValue::JsonDiff(diffs) => {
                // Without a paired before image (see [`decode_rows_pair`])
                // there is nothing to apply the diffs to; they are preserved
                // as a recorded loss instead of failing the whole image.
                let (diffs, problem) = json_diff::parse_diffs(diffs);
                CellValue::PartialJson {
                    diffs,
                    reason: problem
                        .unwrap_or_else(|| "no before image to apply diffs against".to_owned()),
                }
            }
        };
        let mysql_type = column.column_type();
        let signedness = if mysql_type.is_numeric_type() {
            Some(match signedness.get(index).copied().flatten() {
                Some(true) => Signedness::Unsigned,
                Some(false) => Signedness::Signed,
                None => Signedness::Unknown,
            })
        } else {
            None
        };
        columns.push(ColumnValue {
            index,
            name: Some(column.name_str().into_owned()),
            mysql_type: Some(column_type_name(mysql_type).to_owned()),
            signedness,
            value,
        });
        offset += 1;
    }
    if offset != row.len() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "row bitmap and value count differ",
        ));
    }
    Ok(RowImage { columns })
}

/// Decodes the before and after images of an updated row as a pair.
///
/// Partial-JSON after images (WL#2955) carry a sequence of binlog JSON diffs
/// per JSON column instead of a full document. Each such sequence is applied
/// to the before image's decoded value at the same column index: on success
/// the after cell becomes [`CellValue::Json`] with the full new document, on
/// any failure it becomes [`CellValue::PartialJson`] with the preserved diffs
/// and the reason. Images without diffs decode exactly like [`decode_row`].
pub(crate) fn decode_rows_pair(
    before_row: Option<&BinlogRow>,
    after_row: Option<&BinlogRow>,
    before_present: Option<&[bool]>,
    after_present: Option<&[bool]>,
    signedness: &[Option<bool>],
) -> io::Result<(Option<RowImage>, Option<RowImage>)> {
    let before = before_row
        .map(|row| {
            decode_row(
                row,
                before_present.ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "missing before bitmap")
                })?,
                signedness,
            )
        })
        .transpose()?;
    let mut after = after_row
        .map(|row| {
            decode_row(
                row,
                after_present.ok_or_else(|| {
                    io::Error::new(io::ErrorKind::InvalidData, "missing after bitmap")
                })?,
                signedness,
            )
        })
        .transpose()?;
    if let (Some(before), Some(after)) = (&before, after.as_mut()) {
        apply_pair(before, after);
    }
    Ok((before, after))
}

/// Replaces the provisional [`CellValue::PartialJson`] cells of the after
/// image by applying their diffs against the before image's values.
///
/// Cells whose diffs were already resolved (or whose before counterpart
/// offers no JSON value to apply against) keep their state.
fn apply_pair(before: &RowImage, after: &mut RowImage) {
    let pending: Vec<usize> = after
        .columns
        .iter()
        .enumerate()
        .filter(|(_, cell)| matches!(cell.value, CellValue::PartialJson { .. }))
        .map(|(position, _)| position)
        .collect();
    for position in pending {
        let (diffs, index) = match &after.columns[position].value {
            CellValue::PartialJson { diffs, .. } => (diffs.to_vec(), after.columns[position].index),
            _ => continue,
        };
        let Some(before_cell) = before.columns.iter().find(|cell| cell.index == index) else {
            continue;
        };
        let replacement = match &before_cell.value {
            CellValue::Json(before_value) => {
                match json_diff::apply_json_diffs(before_value.clone(), &diffs) {
                    Ok(applied) => CellValue::Json(applied),
                    Err(error) => CellValue::PartialJson {
                        diffs,
                        reason: error.0,
                    },
                }
            }
            CellValue::Absent => CellValue::PartialJson {
                diffs,
                reason: "before column is absent".to_owned(),
            },
            _ => CellValue::PartialJson {
                diffs,
                reason: "before value is not JSON".to_owned(),
            },
        };
        after.columns[position].value = replacement;
    }
}

/// Collects the present-column bitmap, validating that it covers all `n` columns.
///
/// Bits beyond `n` are legitimate padding; fewer than `n` bits means a
/// truncated bitmap, which must not be silently accepted.
pub(crate) fn present_bits(bits: impl Iterator<Item = bool>, n: usize) -> io::Result<Vec<bool>> {
    let collected: Vec<bool> = bits.take(n).collect();
    if collected.len() != n {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "row bitmap length does not match column count",
        ));
    }
    Ok(collected)
}

/// Canonical stable name for a MySQL column type.
///
/// The library's `Debug` output must not leak into the output model, so every
/// [`ColumnType`] variant maps to its short constant name.
pub(crate) fn column_type_name(column_type: ColumnType) -> &'static str {
    match column_type {
        ColumnType::MYSQL_TYPE_DECIMAL => "DECIMAL",
        ColumnType::MYSQL_TYPE_TINY => "TINY",
        ColumnType::MYSQL_TYPE_SHORT => "SHORT",
        ColumnType::MYSQL_TYPE_LONG => "LONG",
        ColumnType::MYSQL_TYPE_FLOAT => "FLOAT",
        ColumnType::MYSQL_TYPE_DOUBLE => "DOUBLE",
        ColumnType::MYSQL_TYPE_NULL => "NULL",
        ColumnType::MYSQL_TYPE_TIMESTAMP => "TIMESTAMP",
        ColumnType::MYSQL_TYPE_LONGLONG => "LONGLONG",
        ColumnType::MYSQL_TYPE_INT24 => "INT24",
        ColumnType::MYSQL_TYPE_DATE => "DATE",
        ColumnType::MYSQL_TYPE_TIME => "TIME",
        ColumnType::MYSQL_TYPE_DATETIME => "DATETIME",
        ColumnType::MYSQL_TYPE_YEAR => "YEAR",
        ColumnType::MYSQL_TYPE_NEWDATE => "NEWDATE",
        ColumnType::MYSQL_TYPE_VARCHAR => "VARCHAR",
        ColumnType::MYSQL_TYPE_BIT => "BIT",
        ColumnType::MYSQL_TYPE_TIMESTAMP2 => "TIMESTAMP2",
        ColumnType::MYSQL_TYPE_DATETIME2 => "DATETIME2",
        ColumnType::MYSQL_TYPE_TIME2 => "TIME2",
        ColumnType::MYSQL_TYPE_TYPED_ARRAY => "TYPED_ARRAY",
        ColumnType::MYSQL_TYPE_VECTOR => "VECTOR",
        ColumnType::MYSQL_TYPE_UNKNOWN => "UNKNOWN",
        ColumnType::MYSQL_TYPE_JSON => "JSON",
        ColumnType::MYSQL_TYPE_NEWDECIMAL => "NEWDECIMAL",
        ColumnType::MYSQL_TYPE_ENUM => "ENUM",
        ColumnType::MYSQL_TYPE_SET => "SET",
        ColumnType::MYSQL_TYPE_TINY_BLOB => "TINY_BLOB",
        ColumnType::MYSQL_TYPE_MEDIUM_BLOB => "MEDIUM_BLOB",
        ColumnType::MYSQL_TYPE_LONG_BLOB => "LONG_BLOB",
        ColumnType::MYSQL_TYPE_BLOB => "BLOB",
        ColumnType::MYSQL_TYPE_VAR_STRING => "VAR_STRING",
        ColumnType::MYSQL_TYPE_STRING => "STRING",
        ColumnType::MYSQL_TYPE_GEOMETRY => "GEOMETRY",
    }
}

/// Extract signedness in table-column order; None means metadata is unavailable.
///
/// The SIGNEDNESS TLV is located with a direct walk of the re-serialized
/// table map body instead of the library's metadata extractor: the library's
/// iterator hard-errors on the partial-JSON metadata types (14, 15) that
/// partial-JSON binlogs carry, which would defeat their handling.
pub(crate) fn signedness(map: &TableMapEvent<'_>) -> io::Result<Vec<Option<bool>>> {
    let bits = signedness_bits(map)?;
    let mut numeric = 0usize;
    let mut result = Vec::new();
    for index in 0..map.columns_count() as usize {
        let ty = map
            .get_column_type(index)
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
            .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "missing column type"))?;
        result.push(if ty.is_numeric_type() {
            let bit = bitmap_bit(bits.as_deref(), numeric);
            numeric += 1;
            bit
        } else {
            None
        });
    }
    Ok(result)
}

/// Reads the SIGNEDNESS (type 1) TLV value of a table map event, if any.
///
/// The event is serialized back into its wire body (always the current
/// 6-byte-table-id form) and the optional metadata block is located with the
/// same structural walk the pre-validation uses, so the raw TLV bytes can be
/// scanned without going through the library's metadata iterator. The last
/// SIGNEDNESS entry wins, mirroring the library's extraction.
fn signedness_bits(map: &TableMapEvent<'_>) -> io::Result<Option<Vec<u8>>> {
    let mut body = Vec::new();
    map.serialize(&mut body);
    let pos = walk_table_map_header(&body, 8)
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "table map does not fit"))?;
    let mut signedness = None;
    for entry in collect_tlvs(&body[pos..])? {
        if entry.field_type == TLV_SIGNEDNESS {
            signedness = Some(body[pos + entry.value.start..pos + entry.value.end].to_vec());
        }
    }
    Ok(signedness)
}

/// Reads one bit of an MSB-first bitmap (`0x80 >> (index % 8)` of byte
/// `index / 8`, one bit per column of the covered kind in table order).
///
/// Bits beyond the available bytes mean the metadata was absent or shorter
/// than the column count; the library reports unknown signedness then, too.
fn bitmap_bit(bytes: Option<&[u8]>, index: usize) -> Option<bool> {
    let byte = *bytes?.get(index / 8)?;
    Some(byte & (0x80 >> (index % 8)) != 0)
}

/// One scanned optional metadata TLV entry: its field type, the byte range of
/// the whole entry (type byte, length prefix, and value), and the byte range
/// of the value alone — both relative to the metadata block.
struct TlvEntry {
    field_type: u8,
    entry: std::ops::Range<usize>,
    value: std::ops::Range<usize>,
}

/// Scans the optional metadata block into its TLV entries.
///
/// Length prefixes are decoded with the library's strict reader, so a
/// non-canonical `0xfb`/`0xff` prefix or a truncated prefix is an error, and a
/// declared length that exceeds the metadata block is an error — mirroring the
/// previous inline walk exactly.
fn collect_tlvs(meta: &[u8]) -> io::Result<Vec<TlvEntry>> {
    let mut pos = 0;
    let mut entries = Vec::new();
    while pos < meta.len() {
        let start = pos;
        let field_type = meta[pos];
        pos += 1;
        let len = match read_lenenc(meta, &mut pos)? {
            Some(len) => len as usize,
            // Invalid length-encoded integer; the library rejects it as well.
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid optional metadata length",
                ));
            }
        };
        let value_start = pos;
        let Some(value_end) = pos.checked_add(len).filter(|end| *end <= meta.len()) else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "optional metadata TLV exceeds table map bounds",
            ));
        };
        entries.push(TlvEntry {
            field_type,
            entry: start..value_end,
            value: value_start..value_end,
        });
        pos = value_end;
    }
    Ok(entries)
}

/// Validates table map optional metadata against the raw event bytes before
/// the library parses it.
///
/// Walks the same structure the library's `TableMapEvent` deserializer walks
/// (identical field order and encodings), then checks every optional metadata
/// TLV: declared lengths must fit the remaining bytes, only field types known
/// to the library or belonging to the partial-JSON extension are accepted, and
/// ENUM/SET variant counts must fit the TLV value (the library allocates from
/// the declared count without bounding it).
///
/// Structural shortfalls deliberately return `Ok`: the library rejects those
/// deterministically with an end-of-stream error, so there is nothing to
/// prevent. Only cases that could abort the process are rejected here.
pub(crate) fn validate_table_map_metadata(body: &[u8], tme_header_length: u8) -> io::Result<()> {
    let pos = match walk_table_map_header(body, tme_header_length) {
        Some(pos) => pos,
        // The structure does not fit; the library will reject this event.
        None => return Ok(()),
    };
    for entry in collect_tlvs(&body[pos..])? {
        if !KNOWN_TLV_TYPES.contains(&entry.field_type) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "unknown optional metadata field type",
            ));
        }
        if entry.field_type == TLV_SET_STR_VALUE || entry.field_type == TLV_ENUM_STR_VALUE {
            validate_enum_set_variants(&body[pos + entry.value.start..pos + entry.value.end])?;
        }
    }
    Ok(())
}

/// Byte ranges (relative to the table map event body) of the optional
/// metadata entries the underlying library cannot iterate.
///
/// The library stores a table map's optional metadata raw and iterates it
/// lazily when decoding rows; its iterator rejects the partial-JSON types 14
/// (`PARTIAL_JSON_UPDATE`) and 15 (`UPDATED_COLUMN_TYPES`) with a hard error,
/// so those entries must be removed from the event body before the library
/// parses the table map. Returns `None` when the event structure does not fit
/// the expected layout — the library rejects such events deterministically,
/// so there is nothing to strip.
pub(crate) fn unsupported_tlv_ranges(
    body: &[u8],
    tme_header_length: u8,
) -> io::Result<Option<Vec<std::ops::Range<usize>>>> {
    let Some(pos) = walk_table_map_header(body, tme_header_length) else {
        return Ok(None);
    };
    let mut ranges = Vec::new();
    for entry in collect_tlvs(&body[pos..])? {
        if entry.field_type == TLV_PARTIAL_JSON_UPDATE
            || entry.field_type == TLV_UPDATED_COLUMN_TYPES
        {
            ranges.push((pos + entry.entry.start)..(pos + entry.entry.end));
        }
    }
    Ok(Some(ranges))
}

/// Walks the fixed part of a table map event and returns the offset of the
/// optional metadata block, or `None` if the event is too short.
fn walk_table_map_header(body: &[u8], tme_header_length: u8) -> Option<usize> {
    let mut pos = 0;
    // Old servers declare a 6-byte post-header and carry a 4-byte table id.
    pos += if tme_header_length == 6 { 4 } else { 6 };
    pos += 2; // flags
    for _ in 0..2 {
        let name_len = *body.get(pos)?;
        pos += 1 + usize::from(name_len) + 1; // length byte, name, NUL
    }
    // The library reads both counts through ParseBuf, whose lenenc decoding
    // maps the non-canonical 0xfb/0xff prefixes to zero instead of failing;
    // mirroring that keeps the walk running for events the library accepts.
    let columns_count = read_lenenc_lenient(body, &mut pos).ok()? as usize;
    let types_end = pos.checked_add(columns_count)?;
    if types_end > body.len() {
        return None;
    }
    pos = types_end;
    let meta_len = read_lenenc_lenient(body, &mut pos).ok()? as usize;
    let meta_end = pos.checked_add(meta_len)?;
    if meta_end > body.len() {
        return None;
    }
    pos = meta_end;
    let null_bytes = columns_count.div_ceil(8);
    let null_end = pos.checked_add(null_bytes)?;
    if null_end > body.len() {
        return None;
    }
    Some(null_end)
}

/// Validates the variant list of a SET/ENUM optional metadata TLV.
///
/// The library allocates a vector with the declared variant count before
/// reading anything, so an inflated count must be rejected here. The count is
/// decoded through the library's `ParseBuf` lenenc semantics (`0xfb`/`0xff`
/// mean zero), mirroring `RawInt<LenEnc>`.
fn validate_enum_set_variants(value: &[u8]) -> io::Result<()> {
    let mut pos = 0;
    let num_variants = read_lenenc_lenient(value, &mut pos)? as usize;
    // Every variant needs at least one length byte, so a count larger than the
    // remaining bytes can never be satisfied.
    if num_variants > value.len() - pos {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "enum/set variant count exceeds TLV bounds",
        ));
    }
    for _ in 0..num_variants {
        let len = match read_lenenc(value, &mut pos)? {
            Some(len) => len as usize,
            None => {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "invalid variant length",
                ));
            }
        };
        let Some(end) = pos.checked_add(len) else {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "variant length exceeds TLV bounds",
            ));
        };
        if end > value.len() {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "variant name exceeds TLV bounds",
            ));
        }
        pos = end;
    }
    Ok(())
}

/// Reads a MySQL length-encoded integer the way the library's `ReadMysqlExt`
/// does for optional metadata TLV lengths: the non-canonical `0xfb`/`0xff`
/// prefixes are errors. Returns `None` for them.
fn read_lenenc(buf: &[u8], pos: &mut usize) -> io::Result<Option<u64>> {
    let Some(&first) = buf.get(*pos) else {
        return Err(io::Error::new(
            io::ErrorKind::InvalidData,
            "unexpected end of length-encoded integer",
        ));
    };
    let extra = match first {
        x if x <= 0xfa => {
            *pos += 1;
            return Ok(Some(u64::from(x)));
        }
        0xfc => 2,
        0xfd => 3,
        0xfe => 8,
        0xfb | 0xff => return Ok(None),
        _ => unreachable!(),
    };
    let end = pos
        .checked_add(1 + extra)
        .filter(|end| *end <= buf.len())
        .ok_or_else(|| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                "unexpected end of length-encoded integer",
            )
        })?;
    let mut raw = [0u8; 8];
    raw[..extra].copy_from_slice(&buf[*pos + 1..end]);
    *pos = end;
    Ok(Some(u64::from_le_bytes(raw)))
}

/// Reads a length-encoded integer through the library's `ParseBuf` semantics,
/// where the `0xfb`/`0xff` prefix byte is consumed and decodes to zero
/// instead of failing.
fn read_lenenc_lenient(buf: &[u8], pos: &mut usize) -> io::Result<u64> {
    match read_lenenc(buf, pos)? {
        Some(value) => Ok(value),
        None => {
            *pos += 1; // consume the prefix the way the library does
            Ok(0)
        }
    }
}

/// Application of WL#2955 binlog JSON diffs to a before value.
///
/// A partial JSON after image stores, per JSON column, a sequence of logical
/// changes (`replace`/`insert`/`remove`) that the MySQL applier replays
/// against the before image's full document. This module parses the MySQL
/// JSON path text form of each diff and applies the operations to a
/// [`serde_json::Value`], matching the server's behavior of failing the whole
/// application when a path cannot be traversed or a precondition (existing
/// member, array bounds) does not hold.
mod json_diff {
    use crate::event::JsonDiffRecord;
    use mysql_common::binlog::jsondiff::{JsonDiff, JsonDiffOperation};

    /// Why a sequence of binlog JSON diffs could not be applied.
    ///
    /// The message is user-facing (it becomes the `reason` of
    /// [`CellValue::PartialJson`]), so it always names the offending path.
    #[derive(Debug, Clone, PartialEq)]
    pub(super) struct ApplyError(pub(super) String);

    /// The operation kind of a binlog JSON diff.
    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
    pub(super) enum Operation {
        /// Set the value at the path.
        Replace,
        /// Add a new member or array element at the path.
        Insert,
        /// Delete the member or array element at the path.
        Remove,
    }

    impl Operation {
        fn name(self) -> &'static str {
            match self {
                Self::Replace => "replace",
                Self::Insert => "insert",
                Self::Remove => "remove",
            }
        }

        fn parse(name: &str) -> Result<Self, ApplyError> {
            match name {
                "replace" => Ok(Self::Replace),
                "insert" => Ok(Self::Insert),
                "remove" => Ok(Self::Remove),
                other => Err(ApplyError(format!("unknown diff operation `{other}`"))),
            }
        }
    }

    /// One segment of a concrete MySQL JSON path.
    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Segment {
        /// An object member, resolved by name.
        Member(String),
        /// An array element, resolved by zero-based index.
        Index(usize),
    }

    /// Converts the library's parsed diffs of one column into model records.
    ///
    /// A diff whose binary JSON value cannot be represented as
    /// [`serde_json::Value`] (for example an opaque value) yields `None` for
    /// its value and is reported in the returned problem note instead of
    /// failing the whole column.
    pub(super) fn parse_diffs(diffs: &[JsonDiff<'_>]) -> (Vec<JsonDiffRecord>, Option<String>) {
        let mut parsed = Vec::with_capacity(diffs.len());
        let mut problem = None;
        for diff in diffs {
            let operation = match diff.operation() {
                JsonDiffOperation::REPLACE => Operation::Replace,
                JsonDiffOperation::INSERT => Operation::Insert,
                JsonDiffOperation::REMOVE => Operation::Remove,
            };
            let value = match diff.value() {
                Some(jsonb) => match serde_json::Value::try_from(jsonb.clone()) {
                    Ok(value) => Some(value),
                    Err(error) => {
                        problem.get_or_insert_with(|| {
                            format!("diff value is not representable as JSON ({error})")
                        });
                        None
                    }
                },
                None => None,
            };
            parsed.push(JsonDiffRecord {
                path: diff.path_str().into_owned(),
                operation: operation.name().to_owned(),
                value,
            });
        }
        (parsed, problem)
    }

    /// Applies a sequence of diffs to a before value, in order.
    ///
    /// Mirrors the MySQL applier: the first failure aborts the whole
    /// application, leaving no partial result behind.
    pub(super) fn apply_json_diffs(
        before: serde_json::Value,
        diffs: &[JsonDiffRecord],
    ) -> Result<serde_json::Value, ApplyError> {
        let mut value = before;
        for diff in diffs {
            apply_one(&mut value, diff)?;
        }
        Ok(value)
    }

    /// Applies a single diff to a value in place.
    fn apply_one(value: &mut serde_json::Value, diff: &JsonDiffRecord) -> Result<(), ApplyError> {
        let at = |what: &'static str| ApplyError(format!("path `{}`: {what}", diff.path));
        let operation = Operation::parse(&diff.operation)?;
        let segments = parse_path(&diff.path)?;
        let Some((last, parents)) = segments.split_last() else {
            // The bare `$` path targets the whole document.
            return match operation {
                Operation::Replace => {
                    let Some(new_value) = &diff.value else {
                        return Err(at("the operation carries no value"));
                    };
                    *value = new_value.clone();
                    Ok(())
                }
                Operation::Insert | Operation::Remove => {
                    Err(at("cannot insert or remove the document root"))
                }
            };
        };
        let mut current = value;
        for segment in parents {
            current = match segment {
                Segment::Member(key) => match current {
                    serde_json::Value::Object(map) => map
                        .get_mut(key)
                        .ok_or_else(|| at("parent path element does not exist"))?,
                    _ => return Err(at("parent path element is not an object")),
                },
                Segment::Index(index) => match current {
                    serde_json::Value::Array(items) => items
                        .get_mut(*index)
                        .ok_or_else(|| at("parent path element does not exist"))?,
                    _ => return Err(at("parent path element is not an array")),
                },
            };
        }
        let new_value = || {
            diff.value
                .clone()
                .ok_or_else(|| at("the operation carries no value"))
        };
        match operation {
            Operation::Replace => match (last, current) {
                (Segment::Member(key), serde_json::Value::Object(map)) => {
                    map.insert(key.clone(), new_value()?);
                    Ok(())
                }
                (Segment::Index(index), serde_json::Value::Array(items))
                    if *index < items.len() =>
                {
                    items[*index] = new_value()?;
                    Ok(())
                }
                _ => Err(at("replace target does not exist")),
            },
            Operation::Insert => match (last, current) {
                (Segment::Member(key), serde_json::Value::Object(map)) => {
                    if map.contains_key(key) {
                        return Err(at("insert on an existing member"));
                    }
                    map.insert(key.clone(), new_value()?);
                    Ok(())
                }
                (Segment::Index(index), serde_json::Value::Array(items))
                    if *index <= items.len() =>
                {
                    items.insert(*index, new_value()?);
                    Ok(())
                }
                _ => Err(at("insert target is not applicable")),
            },
            Operation::Remove => match (last, current) {
                (Segment::Member(key), serde_json::Value::Object(map)) => map
                    .remove(key)
                    .map(|_| ())
                    .ok_or_else(|| at("remove target does not exist")),
                (Segment::Index(index), serde_json::Value::Array(items))
                    if *index < items.len() =>
                {
                    items.remove(*index);
                    Ok(())
                }
                _ => Err(at("remove target does not exist")),
            },
        }
    }

    /// Parses the MySQL JSON path text form of a diff.
    ///
    /// Accepted accessors after the required `$`: bare member names
    /// (`[A-Za-z0-9_$]+`, the MySQL bare-key set), quoted member names
    /// (`."name"` and `["name"]`, double or single quotes, with backslash
    /// escapes), and array indices (`[0]`). Wildcards (`$.*`, `$**`) are
    /// rejected: binlog diffs always carry concrete paths.
    fn parse_path(path: &str) -> Result<Vec<Segment>, ApplyError> {
        let invalid =
            |what: &'static str| ApplyError(format!("invalid JSON path `{path}`: {what}"));
        let rest = path
            .strip_prefix('$')
            .ok_or_else(|| invalid("must start with `$`"))?;
        let bytes = rest.as_bytes();
        let mut pos = 0usize;
        let mut segments = Vec::new();
        while pos < bytes.len() {
            match bytes[pos] {
                b'.' => {
                    pos += 1;
                    if matches!(bytes.get(pos), Some(b'"') | Some(b'\'')) {
                        let quote = bytes[pos];
                        let key = read_quoted_member(rest, &mut pos, quote)?;
                        segments.push(Segment::Member(key));
                    } else {
                        let start = pos;
                        while bytes.get(pos).is_some_and(|byte| {
                            byte.is_ascii_alphanumeric() || *byte == b'_' || *byte == b'$'
                        }) {
                            pos += 1;
                        }
                        if pos == start {
                            return Err(invalid("empty member name"));
                        }
                        // Only ASCII was consumed, so slicing is valid UTF-8.
                        segments.push(Segment::Member(rest[start..pos].to_owned()));
                    }
                }
                b'[' => {
                    pos += 1;
                    if matches!(bytes.get(pos), Some(b'"') | Some(b'\'')) {
                        let quote = bytes[pos];
                        let key = read_quoted_member(rest, &mut pos, quote)?;
                        if bytes.get(pos) != Some(&b']') {
                            return Err(invalid("unterminated bracketed member"));
                        }
                        pos += 1;
                        segments.push(Segment::Member(key));
                    } else if bytes.get(pos).is_some_and(|byte| byte.is_ascii_digit()) {
                        let start = pos;
                        while bytes.get(pos).is_some_and(|byte| byte.is_ascii_digit()) {
                            pos += 1;
                        }
                        let index: usize = rest[start..pos]
                            .parse()
                            .map_err(|_| invalid("array index overflow"))?;
                        if bytes.get(pos) != Some(&b']') {
                            return Err(invalid("unterminated array index"));
                        }
                        pos += 1;
                        segments.push(Segment::Index(index));
                    } else {
                        return Err(invalid("expected a quoted member name or an array index"));
                    }
                }
                _ => return Err(invalid("unsupported path syntax")),
            }
        }
        Ok(segments)
    }

    /// Reads a quoted member name starting at the opening quote byte, which
    /// may be `"` or `'`, advancing `pos` past the closing quote.
    ///
    /// Backslash escapes mirror the common JSON forms (`\"`, `\'`, `\\`,
    /// `\n`, `\r`, `\t`, `\b`, `\0`, and `\uXXXX`); unknown escapes keep the
    /// escaped byte verbatim. Non-ASCII bytes are collected raw and validated
    /// as UTF-8 at the end.
    fn read_quoted_member(rest: &str, pos: &mut usize, quote: u8) -> Result<String, ApplyError> {
        let bytes = rest.as_bytes();
        *pos += 1; // opening quote
        let mut key = Vec::new();
        loop {
            let Some(&byte) = bytes.get(*pos) else {
                return Err(ApplyError(format!(
                    "invalid JSON path `${rest}`: unterminated quoted member name"
                )));
            };
            *pos += 1;
            match byte {
                byte if byte == quote => break,
                b'\\' => {
                    let Some(&escape) = bytes.get(*pos) else {
                        return Err(ApplyError(format!(
                            "invalid JSON path `${rest}`: unterminated escape sequence"
                        )));
                    };
                    *pos += 1;
                    match escape {
                        b'n' => key.push(b'\n'),
                        b'r' => key.push(b'\r'),
                        b't' => key.push(b'\t'),
                        b'b' => key.push(b'\x08'),
                        b'0' => key.push(0),
                        b'u' => {
                            let code = bytes
                                .get(*pos..*pos + 4)
                                .and_then(|raw| std::str::from_utf8(raw).ok())
                                .and_then(|raw| u32::from_str_radix(raw, 16).ok());
                            let Some(code) = code else {
                                return Err(ApplyError(format!(
                                    "invalid JSON path `${rest}`: invalid \\u escape"
                                )));
                            };
                            *pos += 4;
                            let Some(character) = char::from_u32(code) else {
                                return Err(ApplyError(format!(
                                    "invalid JSON path `${rest}`: invalid \\u escape"
                                )));
                            };
                            let mut encoded = [0; 4];
                            key.extend_from_slice(character.encode_utf8(&mut encoded).as_bytes());
                        }
                        other => key.push(other),
                    }
                }
                other => key.push(other),
            }
        }
        String::from_utf8(key).map_err(|_| {
            ApplyError(format!(
                "invalid JSON path `${rest}`: member name is not valid UTF-8"
            ))
        })
    }

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

        /// Builds a diff record the way the model stores them.
        fn rec(path: &str, operation: &str, value: Option<serde_json::Value>) -> JsonDiffRecord {
            JsonDiffRecord {
                path: path.to_owned(),
                operation: operation.to_owned(),
                value,
            }
        }

        #[test]
        fn replaces_inserts_and_removes_members_and_elements() {
            let doc = serde_json::json!({"a": 1, "b": [1, 2]});
            let diffs = vec![
                rec("$.b[1]", "replace", Some(serde_json::json!(99))),
                rec("$.c", "insert", Some(serde_json::json!("x"))),
                rec("$.a", "remove", None),
            ];
            let applied = apply_json_diffs(doc, &diffs).unwrap();
            assert_eq!(applied, serde_json::json!({"b": [1, 99], "c": "x"}));
        }

        #[test]
        fn array_insert_shifts_and_accepts_end_position() {
            let doc = serde_json::json!([1, 2, 3]);
            let insert = |index: usize| {
                let diffs = [rec(
                    &format!("$[{index}]"),
                    "insert",
                    Some(serde_json::json!(9)),
                )];
                apply_json_diffs(doc.clone(), &diffs)
            };
            assert_eq!(insert(1).unwrap(), serde_json::json!([1, 9, 2, 3]));
            // Inserting at the length appends.
            assert_eq!(insert(3).unwrap(), serde_json::json!([1, 2, 3, 9]));
            assert!(insert(4).is_err());
        }

        #[test]
        fn root_replace_swaps_the_document() {
            let doc = serde_json::json!({"a": 1});
            let diffs = [rec("$", "replace", Some(serde_json::json!([true])))];
            assert_eq!(
                apply_json_diffs(doc, &diffs).unwrap(),
                serde_json::json!([true])
            );
            let remove_root = [rec("$", "remove", None)];
            assert!(apply_json_diffs(serde_json::json!({}), &remove_root).is_err());
        }

        #[test]
        fn failures_name_the_offending_path() {
            let doc = serde_json::json!({"a": {"b": 1}});
            let remove = [rec("$.a.zz", "remove", None)];
            let error = apply_json_diffs(doc.clone(), &remove).unwrap_err();
            assert_eq!(error.0, "path `$.a.zz`: remove target does not exist");
            // A missing intermediate element is a failure, not a creation.
            let insert = [rec("$.zz.c", "insert", Some(serde_json::json!(1)))];
            let error = apply_json_diffs(doc, &insert).unwrap_err();
            assert!(
                error.0.contains("parent path element does not exist"),
                "{}",
                error.0
            );
        }

        #[test]
        fn insert_rejects_existing_members_and_replace_missing_ones() {
            let doc = serde_json::json!({"a": 1});
            let insert = [rec("$.a", "insert", Some(serde_json::json!(2)))];
            assert!(
                apply_json_diffs(doc.clone(), &insert)
                    .unwrap_err()
                    .0
                    .contains("insert on an existing member")
            );
            // Object replace is an upsert, like the task's applier contract.
            let replace = [rec("$.a", "replace", Some(serde_json::json!(2)))];
            assert_eq!(
                apply_json_diffs(doc, &replace).unwrap(),
                serde_json::json!({"a": 2})
            );
            // Array replace past the end is a failure.
            let doc = serde_json::json!([1]);
            let replace = [rec("$[3]", "replace", Some(serde_json::json!(2)))];
            assert!(
                apply_json_diffs(doc, &replace)
                    .unwrap_err()
                    .0
                    .contains("replace target does not exist")
            );
        }

        #[test]
        fn quoted_and_indexed_member_forms_are_accepted() {
            let doc = serde_json::json!({"a b": {"c.d": 1}});
            let diffs = [rec(
                r#"$."a b"["c.d"]"#,
                "replace",
                Some(serde_json::json!(2)),
            )];
            let applied = apply_json_diffs(doc, &diffs).unwrap();
            assert_eq!(applied, serde_json::json!({"a b": {"c.d": 2}}));
        }

        #[test]
        fn escapes_are_decoded_in_quoted_members() {
            let doc = serde_json::json!({"q\"k": 1});
            let diffs = [rec(r#"$."q\"k""#, "replace", Some(serde_json::json!(2)))];
            assert_eq!(
                apply_json_diffs(doc, &diffs).unwrap(),
                serde_json::json!({"q\"k": 2})
            );
        }

        #[test]
        fn unsupported_paths_are_rejected() {
            for path in [
                "a.b",                     // missing `$`
                "$.a-b",                   // `-` needs the quoted form
                "$..a",                    // ellipsis wildcard
                "$.a*",                    // wildcard
                "$[x]",                    // not an index
                "$.a[",                    // truncated
                "$.'a",                    // unterminated quote
                "$[99999999999999999999]", // index overflow
                "$.",                      // empty member
                "$.a.",                    // trailing accessor
            ] {
                let diffs = [rec(path, "replace", Some(serde_json::json!(1)))];
                let error = apply_json_diffs(serde_json::json!({}), &diffs).unwrap_err();
                assert!(
                    error.0.starts_with("invalid JSON path"),
                    "{path}: {}",
                    error.0
                );
            }
        }

        #[test]
        fn unknown_operation_names_are_rejected() {
            let diffs = [rec("$.a", "set", Some(serde_json::json!(1)))];
            let error = apply_json_diffs(serde_json::json!({}), &diffs).unwrap_err();
            assert!(error.0.contains("unknown diff operation"), "{}", error.0);
        }

        #[test]
        fn records_match_the_model_shape() {
            let records = [rec("$.a", "insert", Some(serde_json::json!(1)))];
            let serialized = serde_json::to_value(&records).unwrap();
            assert_eq!(serialized[0]["path"], "$.a");
            assert_eq!(serialized[0]["operation"], "insert");
            assert_eq!(serialized[0]["value"], 1);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use mysql_common::{
        binlog::{jsonb::Value as JsonbValue, jsondiff::JsonDiff},
        io::ParseBuf,
        proto::MyDeserialize,
    };
    use mysql_common::{constants::ColumnType, packets::Column};

    /// Parses binary jsonb bytes with the library, as a row value would be.
    fn jsonb(bytes: &[u8]) -> JsonbValue<'static> {
        let mut buf = ParseBuf(bytes);
        JsonbValue::deserialize((), &mut buf).unwrap().into_owned()
    }

    /// Parses one binary JSON diff (operation byte, path, optional value).
    fn diff(bytes: &[u8]) -> JsonDiff<'static> {
        let mut buf = ParseBuf(bytes);
        JsonDiff::deserialize((), &mut buf).unwrap().into_owned()
    }

    fn json_column() -> Column {
        Column::new(ColumnType::MYSQL_TYPE_JSON).with_name(b"doc")
    }

    /// Binary jsonb for `{"a": 1, "b": [1, 2]}` (small object form).
    ///
    /// jsonb offsets are relative to the container start (its element-count
    /// field), and the size field counts the container from that point.
    const JSONB_DOC: &[u8] = &[
        0x00, // small object
        0x02, 0x00, // two members
        0x1e, 0x00, // 30 bytes from the element-count field on
        0x12, 0x00, 0x01, 0x00, // key entry: "a" at offset 18, length 1
        0x13, 0x00, 0x01, 0x00, // key entry: "b" at offset 19, length 1
        0x05, 0x01, 0x00, // value entry at offset 12: int16 1 (inlined)
        0x02, 0x14, 0x00, // value entry at offset 15: small array at offset 20
        b'a', b'b', // key bytes at offsets 18, 19
        0x02, 0x00, 0x0a, 0x00, // small array: two elements, 10 bytes
        0x05, 0x01, 0x00, // int16 1 (inlined)
        0x05, 0x02, 0x00, // int16 2 (inlined)
    ];

    #[test]
    fn jsonb_fixture_parses_as_expected() {
        let value = serde_json::Value::try_from(jsonb(JSONB_DOC)).unwrap();
        assert_eq!(value, serde_json::json!({"a": 1, "b": [1, 2]}));
    }

    /// REPLACE `$.b[1]` with 99, as written into a partial JSON after image.
    fn replace_b1_with_99() -> JsonDiff<'static> {
        diff(&[
            0x00, // REPLACE
            6, b'$', b'.', b'b', b'[', b'1', b']', // path
            3, 0x05, 99, 0x00, // int16 99
        ])
    }

    #[test]
    fn pair_applies_a_replace_diff_to_the_before_value() {
        let before = BinlogRow::new(
            vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
            vec![json_column()].into(),
        );
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(vec![replace_b1_with_99()]))],
            vec![json_column()].into(),
        );
        let (before, after) = decode_rows_pair(
            Some(&before),
            Some(&after),
            Some(&[true]),
            Some(&[true]),
            &[],
        )
        .unwrap();
        assert_eq!(
            before.unwrap().columns[0].value,
            CellValue::Json(serde_json::json!({"a": 1, "b": [1, 2]}))
        );
        assert_eq!(
            after.unwrap().columns[0].value,
            CellValue::Json(serde_json::json!({"a": 1, "b": [1, 99]}))
        );
    }

    #[test]
    fn pair_applies_a_multi_diff_sequence_in_order() {
        let before = BinlogRow::new(
            vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
            vec![json_column()].into(),
        );
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(vec![
                replace_b1_with_99(),
                // INSERT `$.c` = "x": string jsonb (type 0x0c, varlen "x").
                diff(&[0x01, 3, b'$', b'.', b'c', 3, 0x0c, 1, b'x']),
                // REMOVE `$.a`.
                diff(&[0x02, 3, b'$', b'.', b'a']),
            ]))],
            vec![json_column()].into(),
        );
        let (_, after) = decode_rows_pair(
            Some(&before),
            Some(&after),
            Some(&[true]),
            Some(&[true]),
            &[],
        )
        .unwrap();
        assert_eq!(
            after.unwrap().columns[0].value,
            CellValue::Json(serde_json::json!({"b": [1, 99], "c": "x"}))
        );
    }

    #[test]
    fn pair_records_a_loss_when_the_diff_cannot_apply() {
        let before = BinlogRow::new(
            vec![Some(BinlogValue::Jsonb(jsonb(JSONB_DOC)))],
            vec![json_column()].into(),
        );
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(vec![
                // REMOVE `$.zz`: the member does not exist in the before value.
                diff(&[0x02, 4, b'$', b'.', b'z', b'z']),
            ]))],
            vec![json_column()].into(),
        );
        let (_, after) = decode_rows_pair(
            Some(&before),
            Some(&after),
            Some(&[true]),
            Some(&[true]),
            &[],
        )
        .unwrap();
        let CellValue::PartialJson { diffs, reason } = after.unwrap().columns[0].value.clone()
        else {
            panic!("expected a partial JSON record");
        };
        assert_eq!(reason, "path `$.zz`: remove target does not exist");
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].path, "$.zz");
        assert_eq!(diffs[0].operation, "remove");
        assert_eq!(diffs[0].value, None);
    }

    #[test]
    fn pair_records_a_loss_for_a_missing_or_non_json_before_value() {
        let diffs = || vec![replace_b1_with_99()];
        // The before image lacks the column entirely.
        let before = BinlogRow::new(vec![], vec![json_column()].into());
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(diffs()))],
            vec![json_column()].into(),
        );
        let (_, after) = decode_rows_pair(
            Some(&before),
            Some(&after),
            Some(&[false]),
            Some(&[true]),
            &[],
        )
        .unwrap();
        let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
            panic!("expected a partial JSON record");
        };
        assert_eq!(reason, "before column is absent");

        // The before image has no row at all.
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(diffs()))],
            vec![json_column()].into(),
        );
        let (_, after) = decode_rows_pair(None, Some(&after), None, Some(&[true]), &[]).unwrap();
        let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
            panic!("expected a partial JSON record");
        };
        assert_eq!(reason, "no before image to apply diffs against");

        // The before value is an integer, not JSON.
        let before = BinlogRow::new(
            vec![Some(BinlogValue::Value(Value::Int(7)))],
            vec![json_column()].into(),
        );
        let after = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(diffs()))],
            vec![json_column()].into(),
        );
        let (_, after) = decode_rows_pair(
            Some(&before),
            Some(&after),
            Some(&[true]),
            Some(&[true]),
            &[],
        )
        .unwrap();
        let CellValue::PartialJson { reason, .. } = after.unwrap().columns[0].value.clone() else {
            panic!("expected a partial JSON record");
        };
        assert_eq!(reason, "before value is not JSON");
    }

    #[test]
    fn without_a_pair_context_diffs_are_recorded_not_fatal() {
        let row = BinlogRow::new(
            vec![Some(BinlogValue::JsonDiff(vec![replace_b1_with_99()]))],
            vec![json_column()].into(),
        );
        let image = decode_row(&row, &[true], &[]).unwrap();
        let CellValue::PartialJson { diffs, reason } = image.columns[0].value.clone() else {
            panic!("expected a partial JSON record");
        };
        assert_eq!(diffs.len(), 1);
        assert_eq!(diffs[0].operation, "replace");
        assert_eq!(diffs[0].value, Some(serde_json::json!(99)));
        assert_eq!(reason, "no before image to apply diffs against");
    }

    #[test]
    fn distinguishes_absent_null_and_arbitrary_bytes() {
        let columns = vec![
            Column::new(ColumnType::MYSQL_TYPE_LONG).with_name(b"nil"),
            Column::new(ColumnType::MYSQL_TYPE_BLOB).with_name(b"payload"),
        ];
        let row = BinlogRow::new(
            vec![
                Some(BinlogValue::Value(Value::NULL)),
                Some(BinlogValue::Value(Value::Bytes(vec![0, 255, 34]))),
            ],
            columns.into(),
        );
        let image = decode_row(&row, &[false, true, true], &[None, None, None]).unwrap();
        let json = serde_json::to_value(image).unwrap();
        assert_eq!(json["columns"][0]["value"]["type"], "absent");
        assert_eq!(json["columns"][1]["value"]["type"], "null");
        assert_eq!(json["columns"][1]["signedness"], "unknown");
        assert_eq!(json["columns"][2]["value"]["value"], "00ff22");
        assert_eq!(json["columns"][2]["index"], 2);
        assert_eq!(json["columns"][1]["mysql_type"], "LONG");
        assert_eq!(json["columns"][2]["mysql_type"], "BLOB");
    }
    #[test]
    fn rejects_inconsistent_bitmap() {
        let row = BinlogRow::new(
            vec![Some(BinlogValue::Value(Value::Int(4)))],
            vec![Column::new(ColumnType::MYSQL_TYPE_LONG)].into(),
        );
        assert!(decode_row(&row, &[false], &[None]).is_err());
    }
    #[test]
    fn present_bits_must_cover_all_columns() {
        assert!(present_bits([true, false].into_iter(), 2).is_ok());
        let err = present_bits([true].into_iter(), 2).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        // Padding bits beyond n are ignored, not an error.
        assert!(present_bits([true, false, true, false].into_iter(), 2).is_ok());
    }
    #[test]
    fn column_type_names_are_canonical() {
        assert_eq!(
            column_type_name(ColumnType::MYSQL_TYPE_LONGLONG),
            "LONGLONG"
        );
        assert_eq!(column_type_name(ColumnType::MYSQL_TYPE_JSON), "JSON");
        assert_eq!(column_type_name(ColumnType::MYSQL_TYPE_VECTOR), "VECTOR");
    }
    #[test]
    fn enum_tlv_with_bogus_variant_count_is_rejected() {
        // ENUM_STR_VALUE TLV declaring an absurd variant count.
        let mut tlv = vec![6u8];
        tlv.push(4); // TLV length
        tlv.push(0xfe); // variant count: 8-byte length-encoded integer follows
        tlv.extend_from_slice(&u64::MAX.to_le_bytes()[..3]);
        let mut body = vec![0u8; 6 + 2]; // table id + flags
        body.push(1); // database name length
        body.extend_from_slice(b"d\0");
        body.push(1); // table name length
        body.extend_from_slice(b"t\0");
        body.push(1); // one column
        body.push(0x03); // LONG
        body.push(0); // no column metadata
        body.push(1); // one null-bitmap byte
        body.extend_from_slice(&tlv);
        let err = validate_table_map_metadata(&body, 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }
    #[test]
    fn well_formed_tlv_block_is_accepted() {
        // SIGNEDNESS for two numeric columns, plus ENUM_STR_VALUE with a
        // single variant "a".
        let mut tlv = vec![1u8, 1, 0];
        tlv.extend_from_slice(&[6, 3, 1, 1, b'a']);
        let mut body = vec![0u8; 6 + 2]; // table id + flags
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(2); // two columns
        body.extend_from_slice(&[0x03, 0x03]); // two LONG columns
        body.push(0); // no column metadata
        body.push(1); // one null-bitmap byte
        body.extend_from_slice(&tlv);
        validate_table_map_metadata(&body, 8).unwrap();
    }
    #[test]
    fn unknown_tlv_type_is_rejected() {
        let tlv = vec![99u8, 1, 0];
        let mut body = vec![0u8; 6 + 2];
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(1);
        body.push(0x03);
        body.push(0);
        body.push(1);
        body.extend_from_slice(&tlv);
        let err = validate_table_map_metadata(&body, 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    /// Builds a table map body whose optional metadata block is `tlv`, with a
    /// zero-prefix column count like the library's `ParseBuf` decoding yields.
    fn body_with_lenient_header(tlv: &[u8]) -> Vec<u8> {
        let mut body = vec![0u8; 6 + 2]; // table id + flags
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(0xfb); // non-canonical zero column count
        body.push(0); // no column metadata
        body.extend_from_slice(tlv);
        body
    }

    #[test]
    fn noncanonical_lenenc_prefixes_mirror_the_library() {
        // The library decodes a 0xfb column count as zero and keeps parsing,
        // so the pre-walk must continue too: the unknown TLV type after the
        // header is what gets rejected, not the prefix.
        let tlv = vec![99u8, 1, 0];
        let err = validate_table_map_metadata(&body_with_lenient_header(&tlv), 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("optional metadata field type"));
    }

    #[test]
    fn enum_variant_count_lenient_prefix_is_accepted() {
        // A 0xff variant count decodes to zero variants in the library.
        let tlv = vec![6u8, 1, 0xff];
        let mut body = vec![0u8; 6 + 2];
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(1);
        body.push(0x03);
        body.push(0);
        body.push(1);
        body.extend_from_slice(&tlv);
        validate_table_map_metadata(&body, 8).unwrap();
    }

    #[test]
    fn tlv_length_strict_prefix_is_rejected() {
        // TLV lengths go through the library's strict reader, so 0xff there
        // is an error, not a zero.
        let tlv = vec![1u8, 0xff, 0];
        let mut body = vec![0u8; 6 + 2]; // table id + flags
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(1);
        body.push(0x03);
        body.push(0);
        body.push(1);
        body.extend_from_slice(&tlv);
        let err = validate_table_map_metadata(&body, 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    /// Builds a table map body with one LONG and one JSON column whose
    /// optional metadata block is `tlv`.
    fn body_with_long_and_json(tlv: &[u8]) -> Vec<u8> {
        let mut body = vec![0u8; 6 + 2]; // table id + flags
        body.push(1);
        body.extend_from_slice(b"d\0");
        body.push(1);
        body.extend_from_slice(b"t\0");
        body.push(2); // two columns
        body.extend_from_slice(&[0x03, 0xf9]); // LONG, JSON
        body.push(0); // no column metadata
        body.push(1); // one null-bitmap byte
        body.extend_from_slice(tlv);
        body
    }

    #[test]
    fn partial_json_tlv_types_are_accepted() {
        // SIGNEDNESS (one numeric column, unsigned), PARTIAL_JSON_UPDATE
        // (one bit per column: only the JSON column is partial), and
        // UPDATED_COLUMN_TYPES (an opaque per-column type list).
        let mut tlv = vec![1u8, 1, 0x80];
        tlv.extend_from_slice(&[14, 1, 0x40]);
        tlv.extend_from_slice(&[15, 2, 0xf9, 0x00]);
        let body = body_with_long_and_json(&tlv);
        validate_table_map_metadata(&body, 8).unwrap();
        let ranges = unsupported_tlv_ranges(&body, 8).unwrap().unwrap();
        assert_eq!(ranges.len(), 2);
        // First range: the PARTIAL_JSON_UPDATE entry (type, length, value).
        let tlv_offset = body.len() - tlv.len();
        assert_eq!(ranges[0].start, tlv_offset + 3);
        assert_eq!(ranges[0].end, tlv_offset + 6);
        // Second range: the UPDATED_COLUMN_TYPES entry.
        assert_eq!(ranges[1].start, tlv_offset + 6);
        assert_eq!(ranges[1].end, tlv_offset + 6 + 4);
    }

    #[test]
    fn hostile_partial_json_tlv_lengths_are_rejected() {
        // PARTIAL_JSON_UPDATE declaring an 8-byte length-encoded size that
        // exceeds the body; the value length prefix must never overflow.
        let mut tlv = vec![14u8, 0xfe];
        tlv.extend_from_slice(&u64::MAX.to_le_bytes());
        let err = validate_table_map_metadata(&body_with_long_and_json(&tlv), 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("exceeds table map bounds"));
        // Same abuse for UPDATED_COLUMN_TYPES.
        let mut tlv = vec![15u8, 0xfe];
        tlv.extend_from_slice(&u64::MAX.to_le_bytes());
        let err = validate_table_map_metadata(&body_with_long_and_json(&tlv), 8).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn signedness_is_read_from_the_walk_not_the_library() {
        // Serialize a parsed table map whose metadata block carries
        // SIGNEDNESS plus the partial-JSON types the library rejects, then
        // check that signedness() still extracts the unsigned flag.
        let mut tlv = vec![1u8, 1, 0x80];
        tlv.extend_from_slice(&[14, 1, 0x40]);
        tlv.extend_from_slice(&[15, 2, 0xf9, 0x00]);
        let body = body_with_long_and_json(&tlv);
        let mut reader = mysql_common::binlog::EventStreamReader::new(
            mysql_common::binlog::consts::BinlogVersion::Version4,
        );
        let mut event = Vec::new();
        event.extend_from_slice(&0u32.to_le_bytes());
        event.push(19); // TABLE_MAP_EVENT
        event.extend_from_slice(&1u32.to_le_bytes()); // server id
        event.extend_from_slice(&(19 + body.len() as u32).to_le_bytes());
        event.extend_from_slice(&0u32.to_le_bytes()); // log pos
        event.extend_from_slice(&0u16.to_le_bytes()); // flags
        event.extend_from_slice(&body);
        reader
            .read(&mut std::io::Cursor::new(event))
            .unwrap()
            .unwrap();
        let map = reader.get_tme(0).unwrap();
        let signedness = signedness(map).unwrap();
        assert_eq!(signedness, vec![Some(true), None]);
    }
}