ayaml-edit 1.0.0

Verified source-preserving edits for YAML documents built on ayaml.
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
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
use std::borrow::Cow;
use std::cmp::Ordering;
use std::error::Error as _;

use ayaml::{
    Event, Limits, Mapping, ParseOptions, PathSegment, ScalarStyle, Span, Value, parse_events,
};

use super::{
    BatchMatcher, CanonicalEvents, EditError, EditErrorKind, EditOp, EditOptions, TextEdit,
    apply_edits_bounded, batch_events_match, batch_events_match_dp_by_removals,
    batch_events_match_dp_by_replaces, batch_events_match_greedy,
    batch_events_match_greedy_with_probes, canonical_event, collect_canonical_events,
    format_inline_scalar, inspect_document, is_isolated_scalar_replace, one_run_removed,
    one_scalar_changed, remove_value_at_mut, replace_scalar, replace_scalar_with,
    select_batch_matcher, span_order, spliced_output_len, spliced_output_len_pairs,
    step_spliced_len, sync_matches_at, unwrap_inline_flow_scalar, validate_adjacent_spans,
    validate_edit_span, values_match_exact, verification_reparse_error,
    verify_batch_events_with_spans,
};

fn scalar(text: &str) -> String {
    format!("scalar {text:?} Plain None None")
}

fn non_scalar(label: &str) -> String {
    format!("mapping {label} None None")
}

#[test]
fn span_order_and_validation_helpers_enforce_bounds_and_ordering() {
    let ins = Span::new(2, 2);
    let rep = Span::new(2, 5);
    assert_eq!(span_order(ins, rep), Ordering::Less);
    assert_eq!(span_order(rep, ins), Ordering::Greater);
    assert_eq!(span_order(rep, rep), Ordering::Equal);

    assert!(TextEdit::new(ins, "x").is_insertion());
    assert!(!TextEdit::new(rep, "x").is_insertion());

    let sample = "aé🚀\n";
    assert_eq!(validate_edit_span(sample, Span::new(0, 1), 0), Ok(1));
    assert_eq!(validate_edit_span(sample, Span::new(1, 3), 1), Ok(3));
    assert!(validate_edit_span(sample, Span::new(2, 3), 0).is_err());
    assert!(validate_edit_span(sample, Span::new(3, 1), 0).is_err());
    assert!(validate_edit_span(sample, Span::new(0, 99), 0).is_err());
    assert!(validate_edit_span(sample, Span::new(1, 3), 2).is_err());

    assert!(validate_adjacent_spans(ins, rep).is_ok());
    assert!(validate_adjacent_spans(rep, ins).is_err());
    assert!(validate_adjacent_spans(Span::new(1, 3), Span::new(1, 5)).is_err());

    let edits = [
        TextEdit::new(Span::new(0, 1), "xyz"),
        TextEdit::new(Span::new(2, 4), ""),
    ];
    assert_eq!(spliced_output_len(6, &edits), Ok(6));
    assert_eq!(
        spliced_output_len_pairs(6, &[(Span::new(0, 1), 3), (Span::new(2, 4), 0)]),
        Ok(6)
    );
    assert_eq!(step_spliced_len(usize::MAX, Span::new(0, 0), 1), None);
}

#[test]
fn masked_edit_error_ignores_redacted_message_in_equality() {
    let a = EditError::new(EditErrorKind::VerificationFailed, "detail one");
    let b = EditError::new(EditErrorKind::VerificationFailed, "detail two");
    let c = EditError::new(EditErrorKind::Unsupported, "detail one");
    assert_eq!(a.masked(), b.masked());
    assert_ne!(a.masked(), c.masked());
    assert_eq!(a.masked().to_string(), "verification failed");
    assert!(a.masked().source().is_none());
}

#[test]
fn batch_events_match_preserves_pareto_incomparable_states() {
    // Two paths reach `(j=3, skip=2)`:
    // - `(removals=1, replaces=2)` by replacing X->B, B->C and deleting [Y, C]
    // - `(removals=2, replaces=0)` by deleting X and deleting Y
    // Followed by two scalar replacements (`old1->new1`, `old2->new2`), only `(2, 0)` can
    // succeed under `max_removals=2, max_replaces=2`.
    let before = vec![
        scalar("A"),
        scalar("X"),
        scalar("B"),
        scalar("Y"),
        scalar("C"),
        scalar("old1"),
        scalar("old2"),
    ];
    let after = vec![
        scalar("A"),
        scalar("B"),
        scalar("C"),
        scalar("new1"),
        scalar("new2"),
    ];
    assert!(batch_events_match(&before, &after, 2, 2));
    // Also verify symmetric DP branch (`max_replaces < max_removals`, 3 removals + 1 replace).
    let before_sym = vec![
        scalar("A"),
        scalar("X"),
        scalar("B"),
        scalar("Y"),
        scalar("C"),
        scalar("Z"),
        scalar("D"),
        scalar("old1"),
    ];
    let after_sym = vec![
        scalar("A"),
        scalar("B"),
        scalar("C"),
        scalar("D"),
        scalar("new1"),
    ];
    assert!(batch_events_match(&before_sym, &after_sym, 1, 3));
    assert!(!batch_events_match(&before_sym, &after_sym, 0, 3));
    assert!(!batch_events_match(&before_sym, &after_sym, 1, 2));
}

#[test]
fn edit_error_accessors_sources_and_masked_debug() {
    let a = EditError::new(EditErrorKind::VerificationFailed, "secret detail one");
    let b = EditError::new(EditErrorKind::VerificationFailed, "secret detail two");
    let c = EditError::new(EditErrorKind::Unsupported, "secret detail one");
    assert_eq!(a.message(), "secret detail one");
    assert_eq!(b.message(), "secret detail two");
    assert!(a.source().is_none());
    assert_eq!(a.masked(), b.masked());
    assert_ne!(a.masked(), c.masked());
    assert_eq!(a.masked().to_string(), "verification failed");
    assert!(a.masked().source().is_none());

    let dbg = format!("{:?}", a.masked());
    assert!(dbg.contains("MaskedEditError"), "debug={dbg:?}");
    assert!(dbg.contains("VerificationFailed"), "debug={dbg:?}");
    assert!(!dbg.contains("secret"), "debug leaked secret: {dbg:?}");

    let parse_err = replace_scalar("a: [1, 2\n", &[PathSegment::key("a")], &Value::from(1_u64))
        .expect_err("parse failure");
    assert_eq!(parse_err.kind(), EditErrorKind::Parse);
    assert!(parse_err.source().is_some());
    assert!(parse_err.masked().source_error().is_some());
    let parse_dbg = format!("{:?}", parse_err.masked());
    assert!(parse_dbg.contains("MaskedEditError"), "dbg={parse_dbg:?}");
    assert!(parse_dbg.contains("Parse"), "dbg={parse_dbg:?}");

    // `verification_reparse_error` keeps `source` ONLY for `ErrorKind::Limit`.
    let syntax_err = ayaml::parse_value("a: [1, 2\n").expect_err("syntax");
    let wrapped_syntax = verification_reparse_error("ctx", syntax_err);
    assert_eq!(wrapped_syntax.kind(), EditErrorKind::VerificationFailed);
    assert!(wrapped_syntax.source().is_none());

    let limit_opts = ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(2));
    let limit_err = ayaml::parse_value_with("a: 1\n", &limit_opts).expect_err("limit");
    let wrapped_limit = verification_reparse_error("ctx", limit_err);
    assert_eq!(wrapped_limit.kind(), EditErrorKind::VerificationFailed);
    assert!(wrapped_limit.source().is_some());

    // `values_match_exact` checks BOTH value equality AND mapping key order (`Debug` repr).
    let mut m1 = Mapping::new();
    m1.insert(Value::from("a"), Value::from(1_u64));
    m1.insert(Value::from("b"), Value::from(2_u64));
    let mut m2 = Mapping::new();
    m2.insert(Value::from("b"), Value::from(2_u64));
    m2.insert(Value::from("a"), Value::from(1_u64));
    let v1 = Value::Mapping(m1);
    let v2 = Value::Mapping(m2);
    assert_eq!(v1, v2);
    assert!(values_match_exact(&v1, &v1));
    assert!(!values_match_exact(&v1, &v2));
    assert!(!values_match_exact(
        &Value::from(1_u64),
        &Value::from(2_u64)
    ));
}

#[test]
fn inspect_document_canonical_events_and_limits_boundaries() {
    let opts = ParseOptions::new();

    // Multi-document rejects early with the multi-document message.
    let multi = inspect_document("a: 1\n---\nb: 2\n", &opts).expect_err("multi-doc");
    assert_eq!(multi.kind(), EditErrorKind::Unsupported);
    assert!(
        multi.message().contains("multi-document"),
        "msg={:?}",
        multi.message()
    );

    // Undefined alias (with no anchor anywhere) hits the `Event::Alias` arm directly.
    let alias = inspect_document("a: *missing\n", &opts).expect_err("alias");
    assert_eq!(alias.kind(), EditErrorKind::Unsupported);
    assert!(
        alias.message().contains("aliases"),
        "msg={:?}",
        alias.message()
    );

    // Anchored and tagged sequences/mappings hit the collection-start arm.
    for (input, needle) in [
        ("a: &anc [1, 2]\n", "anchors"),
        ("a: !custom [1, 2]\n", "tags"),
        ("a: &anc\n  k: 1\n", "anchors"),
        ("a: !custom\n  k: 1\n", "tags"),
    ] {
        let err = inspect_document(input, &opts).expect_err(input);
        assert_eq!(err.kind(), EditErrorKind::Unsupported, "{input:?}");
        assert!(
            err.message().contains(needle),
            "{input:?}: msg={:?}",
            err.message()
        );
    }

    // `CanonicalEvents::push` marks ONLY non-empty scalar events.
    let mut ce = CanonicalEvents::new();
    let events: Vec<_> = parse_events("a:\nb: 1\n")
        .expect("stream")
        .collect::<Result<_, _>>()
        .expect("events");
    for ev in &events {
        ce.push(ev);
    }
    let scalar_flags: Vec<(bool, bool)> = events
        .iter()
        .zip(&ce.is_non_empty_scalar)
        .map(|(ev, &flag)| {
            (
                matches!(ev, Event::Scalar { .. }) && !ev.span().is_empty(),
                flag,
            )
        })
        .collect();
    assert!(scalar_flags.iter().any(|&(exp, _)| exp));
    assert!(scalar_flags.iter().any(|&(exp, _)| !exp));
    for (expected, actual) in scalar_flags {
        assert_eq!(actual, expected);
    }
    // Specifically verify empty-span scalar is false and non-empty MappingStart is false.
    assert!(events.iter().enumerate().any(|(i, ev)| {
        matches!(ev, Event::Scalar { .. }) && ev.span().is_empty() && !ce.is_non_empty_scalar[i]
    }));
    assert!(events.iter().enumerate().any(|(i, ev)| {
        matches!(ev, Event::MappingStart { .. })
            && !ev.span().is_empty()
            && !ce.is_non_empty_scalar[i]
    }));

    // `canonical_event` produces distinct non-empty canonical forms across all event variants.
    let ev_scalar = Event::Scalar {
        value: Cow::Borrowed("hi"),
        raw: Cow::Borrowed("hi"),
        style: ScalarStyle::Plain,
        tag: None,
        anchor: None,
        span: Span::new(0, 2),
    };
    let ev_doc_start = Event::DocumentStart {
        explicit: true,
        span: Span::new(0, 3),
    };
    let ev_doc_end = Event::DocumentEnd {
        explicit: true,
        span: Span::new(4, 7),
    };
    let ev_directive = Event::Directive {
        name: Cow::Borrowed("YAML"),
        value: Cow::Borrowed("1.2"),
        span: Span::new(0, 9),
    };
    assert!(canonical_event(&ev_scalar).starts_with("scalar \"hi\""));
    assert_eq!(canonical_event(&ev_doc_start), "document true");
    assert_eq!(canonical_event(&ev_doc_end), "document end true");
    assert_eq!(canonical_event(&ev_directive), "directive YAML 1.2");
    assert_ne!(
        canonical_event(&ev_scalar),
        canonical_event(&Event::MappingEnd {
            span: Span::empty(0)
        })
    );
    assert_ne!(
        canonical_event(&Event::MappingEnd {
            span: Span::empty(0)
        }),
        ""
    );

    // `plan_replace_scalar` pre-check (`text.len() / 2` vs `* 2` and `% 2`):
    // 1. Replacement length 10 fits in `max_input_bytes = 16` (`a: abcdefghij\n` = 14 <= 16),
    //    catching `* 2` (20 > 16).
    let opts_16 = EditOptions::new().with_parse_options(
        ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(16)),
    );
    let ok = replace_scalar_with(
        "a: 1\n",
        &[PathSegment::key("a")],
        &Value::from("abcdefghij"),
        &opts_16,
    )
    .expect("10-byte replacement fits in 16 bytes");
    assert_eq!(ok.output(), "a: abcdefghij\n");

    // 2. Replacement length 40 under `max_input_bytes = 10` trips early `text.len() / 2 == 20`,
    //    producing `observed == 20` (whereas `% 2` bypasses pre-check and reports `observed == 11`).
    let opts_10 = EditOptions::new().with_parse_options(
        ParseOptions::new().with_limits(Limits::new().with_max_input_bytes(10)),
    );
    let pre_err = replace_scalar_with(
        "a: 1\n",
        &[PathSegment::key("a")],
        &Value::from("a".repeat(40)),
        &opts_10,
    )
    .expect_err("oversized replacement");
    assert_eq!(pre_err.kind(), EditErrorKind::VerificationFailed);
    let ayaml_src = pre_err
        .source()
        .and_then(|s| s.downcast_ref::<ayaml::Error>())
        .expect("ayaml::Error source");
    assert_eq!(
        ayaml_src.limit().map(ayaml::LimitExceeded::observed),
        Some(20)
    );

    // 3. Re-parse `max_scalar_bytes` failure preserves `source` on `VerificationFailed`.
    let opts_scalar_5 = EditOptions::new().with_parse_options(
        ParseOptions::new().with_limits(
            Limits::new()
                .with_max_input_bytes(100)
                .with_max_scalar_bytes(5),
        ),
    );
    let reparse_lim = replace_scalar_with(
        "a: 1\n",
        &[PathSegment::key("a")],
        &Value::from("123456"),
        &opts_scalar_5,
    )
    .expect_err("re-parse scalar limit");
    assert_eq!(reparse_lim.kind(), EditErrorKind::VerificationFailed);
    assert!(reparse_lim.source().is_some());

    // 4. `format_inline_scalar` exact tie `max_input_bytes + 3 == max_output_bytes` returns
    //    `Unsupported` (not `VerificationFailed`), catching `<` -> `<=`.
    let tie_limits = Limits::new()
        .with_max_input_bytes(5)
        .with_max_output_bytes(8);
    let tie_err =
        format_inline_scalar(&Value::from("1234567890"), &tie_limits).expect_err("output cap tie");
    assert_eq!(tie_err.kind(), EditErrorKind::Unsupported);

    // 5. `unwrap_inline_flow_scalar` rejects empty inner, newline inner, and missing brackets.
    assert_eq!(unwrap_inline_flow_scalar("[ok]\n").as_deref(), Ok("ok"));
    assert_eq!(
        unwrap_inline_flow_scalar("[]\n").expect_err("empty").kind(),
        EditErrorKind::Unsupported
    );
    assert_eq!(
        unwrap_inline_flow_scalar("[a\nb]\n")
            .expect_err("newline")
            .kind(),
        EditErrorKind::Unsupported
    );
    assert_eq!(
        unwrap_inline_flow_scalar("plain\n")
            .expect_err("unbracketed")
            .kind(),
        EditErrorKind::Unsupported
    );

    // 6. `remove_value_at_mut` boundaries for 1-item maps/seqs, missing keys, and OOB indices.
    let mut one_map = Value::Mapping({
        let mut m = Mapping::new();
        m.insert(Value::from("only"), Value::from(1_u64));
        m
    });
    assert!(!remove_value_at_mut(
        &mut one_map,
        &[PathSegment::key("only")]
    ));
    let mut two_map = Value::Mapping({
        let mut m = Mapping::new();
        m.insert(Value::from("a"), Value::from(1_u64));
        m.insert(Value::from("b"), Value::from(2_u64));
        m
    });
    assert!(!remove_value_at_mut(
        &mut two_map,
        &[PathSegment::key("missing")]
    ));
    assert!(remove_value_at_mut(&mut two_map, &[PathSegment::key("a")]));

    let mut one_seq = Value::Sequence(vec![Value::from(1_u64)]);
    assert!(!remove_value_at_mut(&mut one_seq, &[PathSegment::Index(0)]));
    let mut two_seq = Value::Sequence(vec![Value::from(1_u64), Value::from(2_u64)]);
    assert!(!remove_value_at_mut(&mut two_seq, &[PathSegment::Index(2)]));
    assert!(remove_value_at_mut(&mut two_seq, &[PathSegment::Index(0)]));
}

#[test]
fn one_scalar_changed_and_one_run_removed_boundaries() {
    let base = vec![non_scalar("Block"), scalar("a"), scalar("1"), scalar("b")];
    // Unchanged passes `one_scalar_changed`, fails `one_run_removed` (must strictly shrink).
    assert!(one_scalar_changed(&base, &base));
    assert!(!one_run_removed(&base, &base));

    // Exactly 1 scalar diff passes; 2 scalar diffs fail; non-scalar diff fails (both sides).
    let mut one_diff = base.clone();
    one_diff[2] = scalar("2");
    assert!(one_scalar_changed(&base, &one_diff));

    let mut two_diff = one_diff.clone();
    two_diff[3] = scalar("c");
    assert!(!one_scalar_changed(&base, &two_diff));

    let mut non_scalar_after = base.clone();
    non_scalar_after[2] = non_scalar("Flow");
    assert!(!one_scalar_changed(&base, &non_scalar_after));
    assert!(!one_scalar_changed(&non_scalar_after, &base));

    // `one_run_removed`: single contiguous deleted run passes, disjoint deletions fail,
    // and mismatched lengths without prefix+suffix match fail.
    let removed_mid = vec![non_scalar("Block"), scalar("a"), scalar("b")];
    assert!(one_run_removed(&base, &removed_mid));
    let disjoint = vec![scalar("a"), scalar("b")];
    assert!(!one_run_removed(&base, &disjoint));
    let mut altered_shorter = removed_mid;
    altered_shorter[1] = scalar("z");
    assert!(!one_run_removed(&base, &altered_shorter));
}

#[test]
fn verify_batch_events_with_spans_anchoring_and_rejections() {
    let opts = ParseOptions::new();

    // 1. Positive multi-op batch with grow (+1 byte), remove (-5 bytes), and untouched anchors
    //    including a scalar immediately adjacent to an edit end (`edits[edit_idx].span.end() == span.start()`)
    //    and a scalar immediately adjacent to an edit start (`span.end() == edits[edit_idx].span.start()`).
    let before = "a: 1\nb: 2\nc: 3\nd: 4\n";
    let after = "a: 100\nc: 3\nd: 4\n";
    let before_ev = collect_canonical_events(before, &opts).expect("before");
    let after_ev = collect_canonical_events(after, &opts).expect("after");
    let edits = [
        TextEdit {
            span: Span::new(3, 4),
            replacement: "100".to_owned(),
        },
        TextEdit {
            span: Span::new(5, 10),
            replacement: String::new(),
        },
    ];
    let op_rep = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("a")],
        value: Value::from(100_u64),
    };
    let op_rem = EditOp::RemoveEntry {
        path: vec![PathSegment::key("b")],
    };
    assert!(verify_batch_events_with_spans(
        &before_ev,
        &after_ev,
        &edits,
        &[&op_rep, &op_rem],
    ));

    // 2. Rejects unexpected modification outside the edited gap (`d: 4` -> `d: 9`) even though
    //    `c: 3` is an untouched anchor separating the edits from `d`.
    let bad_after = "a: 100\nc: 3\nd: 9\n";
    let bad_ev = collect_canonical_events(bad_after, &opts).expect("bad_after");
    assert!(!verify_batch_events_with_spans(
        &before_ev,
        &bad_ev,
        &edits,
        &[&op_rep, &op_rem],
    ));

    // 3. Rejects unexpected change BEFORE the first untouched anchor when gap budget is 0.
    let bad_prefix = "z: 1\nb: 2\nc: 3\nd: 4\n";
    let bad_prefix_ev = collect_canonical_events(bad_prefix, &opts).expect("bad_prefix");
    let edit_c = [
        TextEdit {
            span: Span::new(13, 14),
            replacement: "3".to_owned(),
        },
        TextEdit {
            span: Span::new(18, 19),
            replacement: "4".to_owned(),
        },
    ];
    let op_c = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("c")],
        value: Value::from(3_u64),
    };
    let op_d = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("d")],
        value: Value::from(4_u64),
    };
    assert!(!verify_batch_events_with_spans(
        &before_ev,
        &bad_prefix_ev,
        &edit_c,
        &[&op_c, &op_d],
    ));

    // 4. Shifted-span anchoring after a multi-byte grow edit catches a rogue change after the anchor
    //    even when a second op sits BEFORE the anchor.
    let shifted_before = "a: 1\nb: 2\nc: 3\nd: 4\n";
    let shifted_bad = "a: 1000\nb: 2\nc: 3\nd: 9\n";
    let sb_ev = collect_canonical_events(shifted_before, &opts).expect("sb");
    let sa_ev = collect_canonical_events(shifted_bad, &opts).expect("sa");
    let shift_edits = [
        TextEdit {
            span: Span::new(3, 4),
            replacement: "1000".to_owned(),
        },
        TextEdit {
            span: Span::new(8, 9),
            replacement: "2".to_owned(),
        },
    ];
    let op_b = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("b")],
        value: Value::from(2_u64),
    };
    assert!(!verify_batch_events_with_spans(
        &sb_ev,
        &sa_ev,
        &shift_edits,
        &[&op_rep, &op_b],
    ));

    // 5. Rejects two scalar replacements in ONE gap when only 1 ReplaceScalar op sits in that gap
    //    (anchored at `c: 3` with an extra replace op sitting AFTER `c: 3` at `d: 4`).
    //    Without span partitioning, global budget (2 replaces) would accept; WITH partitioning,
    //    gap 1 has budget 1 and MUST reject!
    let cross_gap_bad = "a: 10\nb: 9\nc: 3\nd: 4\n";
    let cross_gap_ev = collect_canonical_events(cross_gap_bad, &opts).expect("cross_gap");
    let edits_a_d = [
        TextEdit {
            span: Span::new(3, 4),
            replacement: "10".to_owned(),
        },
        TextEdit {
            span: Span::new(18, 19),
            replacement: "4".to_owned(),
        },
    ];
    assert!(!verify_batch_events_with_spans(
        &before_ev,
        &cross_gap_ev,
        &edits_a_d,
        &[&op_rep, &op_d],
    ));

    // 6. Overlapping/unsorted scalar spans in `before` (`span.start() < min_next_start`) and
    //    anchor immediately after an edit with shifted byte offset (`removed_bytes != added_bytes`
    //    with `removed_bytes > 1` and `added_bytes > 1`).
    let grow_before = "k1: aa\nk2: bb\nk3: cc\nk4: dd\n";
    let grow_after = "k1: aaaa\nk2: bb\nk3: cccc\nk4: dd\n";
    let gb_ev = collect_canonical_events(grow_before, &opts).expect("gb");
    let ga_ev = collect_canonical_events(grow_after, &opts).expect("ga");
    let grow_edits = [
        TextEdit {
            span: Span::new(4, 6),
            replacement: "aaaa".to_owned(),
        },
        TextEdit {
            span: Span::new(18, 20),
            replacement: "cccc".to_owned(),
        },
    ];
    let op_k1 = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("k1")],
        value: Value::from("aaaa"),
    };
    let op_k3 = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("k3")],
        value: Value::from("cccc"),
    };
    assert!(verify_batch_events_with_spans(
        &gb_ev,
        &ga_ev,
        &grow_edits,
        &[&op_k1, &op_k3],
    ));
    // And if `k2` is also mutated while `k3` is unchanged, anchor on `k4` vs `k2` must catch
    // gap-1 having 2 changes for 1 op!
    let grow_bad = "k1: aaaa\nk2: xx\nk3: cc\nk4: dd\n";
    let gbad_ev = collect_canonical_events(grow_bad, &opts).expect("gbad");
    assert!(!verify_batch_events_with_spans(
        &gb_ev,
        &gbad_ev,
        &grow_edits,
        &[&op_k1, &op_k3],
    ));
}

#[test]
fn verify_batch_events_with_spans_synthetic_and_edge_rejections() {
    let op_rep = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("a")],
        value: Value::from(100_u64),
    };
    let op_rem = EditOp::RemoveEntry {
        path: vec![PathSegment::key("b")],
    };
    let op_d = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("d")],
        value: Value::from(4_u64),
    };

    // 7. Synthetic overlapping span in `before` (`min_next_start` guard) and non-scalar events
    //    interleaved before/after anchors exercise every cursor branch cleanly.
    let synth_before = CanonicalEvents {
        texts: vec![
            non_scalar("Block"),
            scalar("a"),
            scalar("overlap"),
            scalar("1"),
            scalar("b"),
            scalar("2"),
        ],
        spans: vec![
            Span::new(0, 10),
            Span::new(0, 3),
            Span::new(1, 2), // starts before previous anchor's end (3) -> skipped by min_next_start
            Span::new(4, 5),
            Span::new(6, 7),
            Span::new(8, 9),
        ],
        is_non_empty_scalar: vec![false, true, true, true, true, true],
    };
    let synth_after = CanonicalEvents {
        texts: vec![
            non_scalar("Block"),
            scalar("a"),
            scalar("overlap"),
            scalar("9"),
            scalar("b"),
            scalar("8"),
        ],
        spans: vec![
            Span::new(0, 10),
            Span::new(0, 3),
            Span::new(1, 2),
            Span::new(4, 5),
            Span::new(6, 7),
            Span::new(8, 9),
        ],
        is_non_empty_scalar: vec![false, true, true, true, true, true],
    };
    let synth_edits = [
        TextEdit {
            span: Span::new(4, 5),
            replacement: "9".to_owned(),
        },
        TextEdit {
            span: Span::new(8, 9),
            replacement: "8".to_owned(),
        },
    ];
    assert!(verify_batch_events_with_spans(
        &synth_before,
        &synth_after,
        &synth_edits,
        &[&op_rep, &op_d],
    ));

    // Edit starting AT `span.end()` (`span.end() == edits[edit_idx].span.start()`) must NOT be
    // treated as overlapping `span`, so `span` still anchors!
    let touch_before = CanonicalEvents {
        texts: vec![scalar("k"), scalar("v1"), scalar("m"), scalar("v2")],
        spans: vec![
            Span::new(0, 2),
            Span::new(2, 4),
            Span::new(4, 6),
            Span::new(6, 8),
        ],
        is_non_empty_scalar: vec![true, true, true, true],
    };
    let touch_after_bad = CanonicalEvents {
        texts: vec![scalar("k"), scalar("X"), scalar("m"), scalar("Y")],
        spans: vec![
            Span::new(0, 2),
            Span::new(2, 4),
            Span::new(4, 6),
            Span::new(6, 8),
        ],
        is_non_empty_scalar: vec![true, true, true, true],
    };
    // Both edits are at span [4, 6) and [6, 8), so `k` [0, 2) touches neither, `v1` [2, 4) touches
    // edit 0 start (4) and MUST still anchor (meaning gap before `v1` has 0 edits, and changing
    // `v1` to `X` while moving `m` is caught!). Even simpler: edit 0 is [2, 4) (touches `k` end 2),
    // edit 1 is [6, 8) (touches `m` end 6); if `k` changes to `Z` and `v1` doesn't, `m` anchors!
    let touch_edits = [
        TextEdit {
            span: Span::new(2, 4),
            replacement: "11".to_owned(),
        },
        TextEdit {
            span: Span::new(6, 8),
            replacement: "22".to_owned(),
        },
    ];
    let touch_after_k_changed = CanonicalEvents {
        texts: vec![scalar("Z"), scalar("11"), scalar("m"), scalar("22")],
        spans: vec![
            Span::new(0, 2),
            Span::new(2, 4),
            Span::new(4, 6),
            Span::new(6, 8),
        ],
        is_non_empty_scalar: vec![true, true, true, true],
    };
    assert!(!verify_batch_events_with_spans(
        &touch_before,
        &touch_after_k_changed,
        &touch_edits,
        &[&op_rep, &op_d],
    ));
    // And with `k` and `m` untouched, `v1` and `v2` replaced succeeds.
    assert!(verify_batch_events_with_spans(
        &touch_before,
        &touch_after_bad,
        &touch_edits,
        &[&op_rep, &op_d],
    ));

    // Anchor where `before[b_idx]` has a span matching `after` ONLY after skipping earlier
    // non-matching `after` scalars (`a_span.start() < shifted_start`) and where an earlier
    // `before` scalar is missing in `after` (causing `after_cursor` to stop without matching
    // and then match the next anchor cleanly).
    let skip_before = CanonicalEvents {
        texts: vec![
            scalar("drop1"),
            scalar("drop2"),
            scalar("keep"),
            scalar("tail"),
        ],
        spans: vec![
            Span::new(0, 5),
            Span::new(5, 10),
            Span::new(10, 14),
            Span::new(14, 18),
        ],
        is_non_empty_scalar: vec![true, true, true, true],
    };
    let skip_after = CanonicalEvents {
        texts: vec![scalar("x"), scalar("keep"), scalar("tail2")],
        spans: vec![Span::new(0, 1), Span::new(5, 9), Span::new(9, 14)],
        is_non_empty_scalar: vec![true, true, true],
    };
    // Edit 0 removes [5, 10) (len 5 -> 0) and Edit 1 replaces [14, 18) with "tail2", shifting
    // `keep` from [10, 14) to [5, 9).
    let skip_after2 = CanonicalEvents {
        texts: vec![scalar("drop1"), scalar("keep"), scalar("tail2")],
        spans: vec![Span::new(0, 5), Span::new(5, 9), Span::new(9, 14)],
        is_non_empty_scalar: vec![true, true, true],
    };
    let skip_edits = [
        TextEdit {
            span: Span::new(5, 10),
            replacement: String::new(),
        },
        TextEdit {
            span: Span::new(14, 18),
            replacement: "tail2".to_owned(),
        },
    ];
    assert!(verify_batch_events_with_spans(
        &skip_before,
        &skip_after2,
        &skip_edits,
        &[&op_rem, &op_rep],
    ));
    assert!(!verify_batch_events_with_spans(
        &skip_before,
        &skip_after,
        &skip_edits,
        &[&op_rem, &op_rep],
    ));
}

#[test]
fn batch_events_match_and_both_dp_engines_cover_all_boundaries() {
    // 1. `max_removals == 0` fast path: scalar-vs-non-scalar rejections and `diffs <= max_replaces`.
    let b0 = vec![scalar("a"), scalar("b"), scalar("c")];
    let a0_non_scalar = vec![scalar("a"), non_scalar("Block"), scalar("c")];
    assert!(!batch_events_match(&b0, &a0_non_scalar, 2, 0));
    assert!(!batch_events_match(&a0_non_scalar, &b0, 2, 0));
    let a0_two = vec![scalar("x"), scalar("y"), scalar("c")];
    assert!(batch_events_match(&b0, &a0_two, 2, 0));
    assert!(!batch_events_match(&b0, &a0_two, 1, 0));

    // 2. Prefix/suffix stripping with `max_skip == 0` (`b.len() == a.len()`) when `max_removals > 0`
    //    and `max_replaces == 0` (must reject!) vs `max_replaces == 1`.
    let same_len_b = vec![scalar("p"), scalar("old"), scalar("s")];
    let same_len_a = vec![scalar("p"), scalar("new"), scalar("s")];
    assert!(!batch_events_match(&same_len_b, &same_len_a, 0, 1));
    assert!(batch_events_match(&same_len_b, &same_len_a, 1, 1));

    // 3. Direct tests on `batch_events_match_dp_by_removals` (`max_removals <= max_replaces`):
    //    - Pareto incomparable states (`removals=2, replaces=2`).
    let before = vec![
        scalar("A"),
        scalar("X"),
        scalar("B"),
        scalar("Y"),
        scalar("C"),
        scalar("old1"),
        scalar("old2"),
    ];
    let after = vec![
        scalar("A"),
        scalar("B"),
        scalar("C"),
        scalar("new1"),
        scalar("new2"),
    ];
    assert!(batch_events_match(&before, &after, 2, 2));
    assert!(!batch_events_match(&before, &after, 1, 2));
    assert!(!batch_events_match(&before, &after, 2, 1));

    //    - Multi-element contiguous removed run (`in_run` continuation, `skip` advances by 3 in 1 removal),
    //      plus scalar replacement right before and right after, plus non-scalar rejection.
    let run_b = vec![
        scalar("old1"),
        scalar("d1"),
        scalar("d2"),
        scalar("d3"),
        scalar("mid"),
        scalar("d4"),
        scalar("d5"),
        scalar("old2"),
    ];
    let run_a = vec![scalar("new1"), scalar("mid"), scalar("new2")];
    assert!(batch_events_match_dp_by_removals(&run_b, &run_a, 5, 2, 2));
    assert!(!batch_events_match_dp_by_removals(&run_b, &run_a, 5, 1, 2));
    assert!(!batch_events_match_dp_by_removals(&run_b, &run_a, 5, 2, 1));

    //    - Non-scalar cannot be replaced (only deleted) in `dp_by_removals`.
    let ns_b = vec![non_scalar("Block"), non_scalar("Flow"), scalar("end")];
    let ns_a = vec![scalar("x"), scalar("end")];
    assert!(!batch_events_match_dp_by_removals(&ns_b, &ns_a, 1, 1, 1));
    let ns_b2 = vec![scalar("d"), scalar("x"), scalar("end")];
    let ns_a2 = vec![non_scalar("Block"), scalar("end")];
    assert!(!batch_events_match_dp_by_removals(&ns_b2, &ns_a2, 1, 1, 1));

    //    - Trailing deletion at `j == a.len()` (must succeed with 1 removal and 0 replaces).
    let trail_b = vec![scalar("k"), scalar("d1"), scalar("d2")];
    let trail_a = vec![scalar("k")];
    assert!(batch_events_match_dp_by_removals(
        &trail_b, &trail_a, 2, 1, 1
    ));
    assert!(!batch_events_match_dp_by_removals(
        &trail_b, &trail_a, 2, 1, 0
    ));

    //    - Exact `max_replaces` boundary when entering match vs replace from `in_run` and `not_in`
    //      with multiple paths updating the same cell (`best < *slot`, `not_in < *slot`, `in_run < *slot`).
    let merge_b = vec![
        scalar("x"),
        scalar("a"),
        scalar("y"),
        scalar("a"),
        scalar("old"),
    ];
    let merge_a = vec![scalar("a"), scalar("new")];
    assert!(batch_events_match_dp_by_removals(
        &merge_b, &merge_a, 3, 2, 2
    ));
    assert!(!batch_events_match_dp_by_removals(
        &merge_b, &merge_a, 3, 0, 2
    ));

    // 4. Direct tests on `batch_events_match_dp_by_replaces` (`max_replaces < max_removals`):
    let before_sym = vec![
        scalar("A"),
        scalar("X"),
        scalar("B"),
        scalar("Y"),
        scalar("C"),
        scalar("Z"),
        scalar("D"),
        scalar("old1"),
    ];
    let after_sym = vec![
        scalar("A"),
        scalar("B"),
        scalar("C"),
        scalar("D"),
        scalar("new1"),
    ];
    assert!(batch_events_match(&before_sym, &after_sym, 1, 3));
    assert!(!batch_events_match(&before_sym, &after_sym, 0, 3));
    assert!(!batch_events_match(&before_sym, &after_sym, 1, 2));

    //    - Multi-element contiguous run + multiple removals + scalar replacement + trailing run.
    let rep_b = vec![
        scalar("d1"),
        scalar("d2"),
        non_scalar("K1"),
        scalar("d3"),
        scalar("d4"),
        non_scalar("K2"),
        scalar("old1"),
        scalar("d5"),
        scalar("d6"),
    ];
    let rep_a = vec![non_scalar("K1"), non_scalar("K2"), scalar("new1")];
    assert!(batch_events_match_dp_by_replaces(&rep_b, &rep_a, 6, 1, 3));
    assert!(!batch_events_match_dp_by_replaces(&rep_b, &rep_a, 6, 0, 3));
    assert!(!batch_events_match_dp_by_replaces(&rep_b, &rep_a, 6, 1, 2));

    //    - Two paths converging on the same `(skip, p)` cell in `dp_by_replaces` so `<` updates win
    //      over higher removal counts (`not_in + 1 < *slot`, `in_run < *slot`, `best < *slot`).
    let conv_b = vec![
        scalar("a"),
        scalar("b"),
        scalar("a"),
        scalar("c"),
        scalar("a"),
        scalar("old"),
    ];
    let conv_a = vec![scalar("a"), scalar("new")];
    assert!(batch_events_match_dp_by_replaces(&conv_b, &conv_a, 4, 1, 2));
    assert!(!batch_events_match_dp_by_replaces(
        &conv_b, &conv_a, 4, 1, 0
    ));
    // Non-scalar rejected for replacement in `dp_by_replaces`.
    assert!(!batch_events_match_dp_by_replaces(&ns_b, &ns_a, 1, 1, 2));
    assert!(!batch_events_match_dp_by_replaces(&ns_b2, &ns_a2, 1, 1, 2));

    // 5. Large DP cap (`> 1_000_000` cells) falls back to `batch_events_match_greedy` cleanly
    //    without allocating a huge DP table (1002 * 101 * 11 = 1,113,222 > 1_000_000).
    //    Under Miri, `select_batch_matcher` verifies the threshold directly in O(1).
    if !cfg!(miri) {
        let mut big_b = Vec::with_capacity(1102);
        let mut big_a = Vec::with_capacity(1002);
        big_b.push(scalar("old_head"));
        big_a.push(scalar("new_head"));
        for idx in 0..1000 {
            let s = scalar(&format!("item_{idx}"));
            big_b.push(s.clone());
            big_a.push(s);
        }
        for idx in 0..100 {
            big_b.push(scalar(&format!("drop_{idx}")));
        }
        big_b.push(scalar("old_tail"));
        big_a.push(scalar("new_tail"));
        assert!(batch_events_match(&big_b, &big_a, 10, 10));
        assert!(!batch_events_match(&big_b, &big_a, 1, 10));
    }
}

#[test]
fn batch_events_match_greedy_handles_mixed_replace_and_remove_orderings() {
    // 1. Replacement preceding a later removal (including trailing removal at end of `before`).
    let before = vec![
        scalar("k0"),
        scalar("old"),
        scalar("k1"),
        scalar("v1"),
        scalar("k2"),
        scalar("v2"),
        scalar("drop"),
        scalar("val"),
    ];
    let after = vec![
        scalar("k0"),
        scalar("new"),
        scalar("k1"),
        scalar("v1"),
        scalar("k2"),
        scalar("v2"),
    ];
    assert!(batch_events_match_greedy(&before, &after, 1, 1));
    assert!(!batch_events_match_greedy(&before, &after, 0, 1));
    assert!(!batch_events_match_greedy(&before, &after, 1, 0));

    // 2. Replacement immediately followed by a removed entry.
    let before_adj = vec![
        scalar("a"),
        scalar("1"),
        scalar("b"),
        scalar("2"),
        scalar("c"),
        scalar("3"),
    ];
    let after_adj = vec![scalar("a"), scalar("10"), scalar("c"), scalar("3")];
    assert!(batch_events_match_greedy(&before_adj, &after_adj, 1, 1));
    assert!(!batch_events_match_greedy(&before_adj, &after_adj, 0, 1));

    // 3. Removed nested collection immediately followed by a replaced scalar.
    let before_nested = vec![
        "mapping Block None None".to_owned(),
        scalar("k"),
        scalar("1"),
        "Discriminant(8)".to_owned(),
        scalar("2"),
        scalar("3"),
        scalar("4"),
    ];
    let after_nested = vec![scalar("20"), scalar("3"), scalar("4")];
    assert!(batch_events_match_greedy(
        &before_nested,
        &after_nested,
        1,
        1
    ));

    // 4. Removed mapping entry immediately followed by a mapping entry with replaced value
    //    (hits `key_then_replace` sync branch: `before[i+d] == after[j]`, both `[+1]` are scalar,
    //    and `[+2]` matches or ends `after`).
    let before_rem_rep = vec![
        scalar("a"),
        scalar("1"),
        scalar("b"),
        scalar("old"),
        scalar("c"),
        scalar("3"),
    ];
    let after_rem_rep = vec![scalar("b"), scalar("new"), scalar("c"), scalar("3")];
    assert!(batch_events_match_greedy(
        &before_rem_rep,
        &after_rem_rep,
        1,
        1
    ));
    assert!(!batch_events_match_greedy(
        &before_rem_rep,
        &after_rem_rep,
        0,
        1
    ));

    // 4b. `key_then_replace` at the exact tail of `after` (`j + 2 == after.len()`):
    //     removed entry followed by `b: old -> b: new` at EOF.
    let before_rem_tail = vec![scalar("a"), scalar("1"), scalar("b"), scalar("old")];
    let after_rem_tail = vec![scalar("b"), scalar("new")];
    assert!(batch_events_match_greedy(
        &before_rem_tail,
        &after_rem_tail,
        1,
        1
    ));
    assert!(!batch_events_match_greedy(
        &before_rem_tail,
        &after_rem_tail,
        0,
        1
    ));

    // 4c. `key_then_replace` must NOT falsely trigger when `[+1]` is non-scalar or `[+2]` mismatches.
    let before_rem_ns = vec![
        scalar("a"),
        scalar("1"),
        scalar("b"),
        non_scalar("Block"),
        scalar("c"),
    ];
    let after_rem_ns = vec![scalar("b"), scalar("new"), scalar("c")];
    assert!(!batch_events_match_greedy(
        &before_rem_ns,
        &after_rem_ns,
        1,
        1
    ));
    let before_rem_ns2 = vec![
        scalar("a"),
        scalar("1"),
        scalar("b"),
        scalar("old"),
        scalar("c"),
    ];
    let after_rem_ns2 = vec![scalar("b"), non_scalar("Block"), scalar("c")];
    assert!(!batch_events_match_greedy(
        &before_rem_ns2,
        &after_rem_ns2,
        1,
        1
    ));
}

#[test]
fn batch_events_match_greedy_isolated_replace_and_tail_boundaries() {
    // 5. Branch 1 (immediate isolated scalar replacement):
    //    5a. Two matching events after `(i, j)` (`j + 2 < after.len()` and `before[i+2] == after[j+2]`).
    let b_iso = vec![scalar("old"), scalar("m1"), scalar("m2"), scalar("drop")];
    let a_iso = vec![scalar("new"), scalar("m1"), scalar("m2")];
    assert!(batch_events_match_greedy(&b_iso, &a_iso, 1, 1));
    //    5b. Single matching tail with zero remaining skips (`j + 2 >= after.len() && rem_skip == 0`).
    let b_iso_tail = vec![scalar("old"), scalar("tail")];
    let a_iso_tail = vec![scalar("new"), scalar("tail")];
    assert!(batch_events_match_greedy(&b_iso_tail, &a_iso_tail, 1, 1));
    assert!(!batch_events_match_greedy(&b_iso_tail, &a_iso_tail, 0, 1));
    //    5c. Same single matching tail when `rem_skip > 0` MUST NOT blindly take branch 1 if a
    //        removal resyncs cleanly without burning a replace!
    let b_sync_not_rep = vec![scalar("drop"), scalar("keep"), scalar("tail")];
    let a_sync_not_rep = vec![scalar("keep"), scalar("tail")];
    assert!(batch_events_match_greedy(
        &b_sync_not_rep,
        &a_sync_not_rep,
        0,
        1
    ));
    //    5d. Two replacements in a row (zero removals, `rem_skip == 0`, hits `else if can_replace`
    //        and single-event tail `j + 1 == after.len()`).
    let b_two_rep = vec![scalar("o1"), scalar("o2")];
    let a_two_rep = vec![scalar("n1"), scalar("n2")];
    assert!(batch_events_match_greedy(&b_two_rep, &a_two_rep, 2, 0));
    assert!(!batch_events_match_greedy(&b_two_rep, &a_two_rep, 1, 0));

    // 6. Sync at single last element of `after` (`j + 1 == after.len()`, `next_matches` true).
    let b_last_sync = vec![scalar("d1"), scalar("d2"), scalar("end")];
    let a_last_sync = vec![scalar("end")];
    assert!(batch_events_match_greedy(&b_last_sync, &a_last_sync, 0, 1));
    assert!(!batch_events_match_greedy(&b_last_sync, &a_last_sync, 0, 0));

    // 7. Continuing an ALREADY-OPEN removal run (`in_run == true`) to a sync point must NOT
    //    increment `removals` a second time, and a trailing run while `in_run == true` also
    //    stays 1 removal.
    let b_cont = vec![
        non_scalar("Block"),
        non_scalar("Seq"),
        scalar("sync1"),
        scalar("sync2"),
    ];
    let a_cont = vec![scalar("sync1"), scalar("sync2")];
    assert!(batch_events_match_greedy(&b_cont, &a_cont, 0, 1));

    //    No-sync step-by-step removal (`sync == None`, `can_replace == false` because non-scalar)
    //    then continuing inside `in_run` until EOF (`i < before.len() && in_run`).
    let b_step_rem = vec![
        scalar("k"),
        non_scalar("Block"),
        non_scalar("Seq"),
        scalar("z"),
    ];
    let a_step_rem = vec![scalar("k"), scalar("z")];
    assert!(batch_events_match_greedy(&b_step_rem, &a_step_rem, 0, 1));
    assert!(!batch_events_match_greedy(&b_step_rem, &a_step_rem, 0, 0));

    //    Two consecutive non-sync scalar replacements while `rem_skip > 0` (`!in_run && can_replace`
    //    fallback when `sync == None`) followed by trailing deletion.
    let b_fallback_rep = vec![scalar("o1"), scalar("o2"), scalar("drop")];
    let a_fallback_rep = vec![scalar("n1"), scalar("n2")];
    assert!(batch_events_match_greedy(
        &b_fallback_rep,
        &a_fallback_rep,
        2,
        1
    ));
    assert!(!batch_events_match_greedy(
        &b_fallback_rep,
        &a_fallback_rep,
        1,
        1
    ));

    // 8. Two separate removals + two separate replacements verify `removals += 1` and `replaces += 1`
    //    (catching `+=` -> `*=` since `1 * 1 = 1 <= 1` would wrongly allow 2!).
    let b_two_rem = vec![
        scalar("a"),
        scalar("d1"),
        scalar("b"),
        scalar("d2"),
        scalar("c"),
    ];
    let a_two_rem = vec![scalar("a"), scalar("b"), scalar("c")];
    assert!(batch_events_match_greedy(&b_two_rem, &a_two_rem, 0, 2));
    assert!(!batch_events_match_greedy(&b_two_rem, &a_two_rem, 0, 1));

    // Two step-by-step removals separated by a match (`!in_run` -> `removals += 1` twice).
    let b_two_step = vec![
        non_scalar("A"),
        scalar("k1"),
        non_scalar("B"),
        scalar("k2"),
        scalar("k3"),
    ];
    let a_two_step = vec![scalar("k1"), scalar("k2"), scalar("k3")];
    assert!(batch_events_match_greedy(&b_two_step, &a_two_step, 0, 2));
    assert!(!batch_events_match_greedy(&b_two_step, &a_two_step, 0, 1));

    // Two isolated replacements (`branch 1` twice) + one removal must fail with `max_replaces = 1`.
    let b_two_iso = vec![
        scalar("o1"),
        scalar("m1"),
        scalar("m2"),
        scalar("o2"),
        scalar("m3"),
        scalar("m4"),
        scalar("drop"),
    ];
    let a_two_iso = vec![
        scalar("n1"),
        scalar("m1"),
        scalar("m2"),
        scalar("n2"),
        scalar("m3"),
        scalar("m4"),
    ];
    assert!(batch_events_match_greedy(&b_two_iso, &a_two_iso, 2, 1));
    assert!(!batch_events_match_greedy(&b_two_iso, &a_two_iso, 1, 1));

    // Two `else if can_replace` steps in a row (`rem_skip == 0`) with 2 replacements vs budget 1.
    let b_three_rep = vec![scalar("o1"), scalar("o2"), scalar("o3")];
    let a_three_rep = vec![scalar("n1"), scalar("n2"), scalar("n3")];
    assert!(batch_events_match_greedy(&b_three_rep, &a_three_rep, 3, 0));
    assert!(!batch_events_match_greedy(&b_three_rep, &a_three_rep, 2, 0));

    // 9. Trailing removal AFTER an earlier removal (`removals` goes 1 -> 2, must fail budget 1).
    let b_rem_and_trail = vec![scalar("d1"), scalar("k1"), scalar("k2"), scalar("d2")];
    let a_rem_and_trail = vec![scalar("k1"), scalar("k2")];
    assert!(batch_events_match_greedy(
        &b_rem_and_trail,
        &a_rem_and_trail,
        0,
        2
    ));
    assert!(!batch_events_match_greedy(
        &b_rem_and_trail,
        &a_rem_and_trail,
        0,
        1
    ));

    // 10. Rejects structural mismatch (non-scalar vs scalar) when no removal budget remains
    //     and when `before` runs out before `after` (`j != after.len()`).
    let before_adj = vec![
        scalar("a"),
        scalar("1"),
        scalar("b"),
        scalar("2"),
        scalar("c"),
        scalar("3"),
    ];
    let bad_after = vec!["mapping Block None None".to_owned(), scalar("3")];
    assert!(!batch_events_match_greedy(&before_adj, &bad_after, 1, 0));
    assert!(!batch_events_match_greedy(
        &[scalar("a")],
        &[scalar("a"), scalar("b")],
        1,
        1
    ));
    assert!(!batch_events_match_greedy(
        &[non_scalar("A")],
        &[scalar("a")],
        1,
        0
    ));
    assert!(!batch_events_match_greedy(
        &[scalar("a")],
        &[non_scalar("A")],
        1,
        0
    ));

    // 11. Probe budget exhaustion (`remaining_probes` decrements cleanly on long unmatchable scans).
    let mut probe_b: Vec<String> = (0..300).map(|k| non_scalar(&format!("x{k}"))).collect();
    probe_b.push(scalar("tail"));
    let probe_a = vec![scalar("nomatch"), scalar("tail")];
    assert!(!batch_events_match_greedy(&probe_b, &probe_a, 0, 1));
}

#[test]
fn format_inline_scalar_apply_edits_bounded_and_span_gap_verification() {
    let limits = Limits::default();
    // Flow indicators and ambiguous strings are always quoted inline.
    for tricky in ["a,b", "[x]", "{k}", "true", "null", "42", "a: b"] {
        let formatted = format_inline_scalar(&Value::from(tricky), &limits).expect(tricky);
        assert!(
            formatted.starts_with('\'') || formatted.starts_with('"'),
            "expected quoted inline scalar for {tricky:?}, got {formatted:?}"
        );
    }
    // Oversized scalar fails against `max_output_bytes` (`Unsupported`) and `max_input_bytes`
    // (`Verification` with `InputSizeLimit` source).
    let tight_out = Limits::default().with_max_output_bytes(4);
    assert_eq!(
        format_inline_scalar(&Value::from("1234567890"), &tight_out)
            .expect_err("tight output limit")
            .kind(),
        EditErrorKind::Unsupported
    );
    let tight_in = Limits::default().with_max_input_bytes(4);
    assert_eq!(
        format_inline_scalar(&Value::from("1234567890"), &tight_in)
            .expect_err("tight input limit")
            .kind(),
        EditErrorKind::VerificationFailed
    );

    // `apply_edits_bounded` rejects inputs whose spliced output exceeds `max_input_bytes`
    // before allocating the output string.
    let edit = TextEdit {
        span: Span::new(3, 4),
        replacement: "1234567890".to_owned(),
    };
    let tiny_input = Limits::default().with_max_input_bytes(8);
    let bounded_err = apply_edits_bounded("a: 1\n", &[edit], Some(&tiny_input))
        .expect_err("exceeds max_input_bytes");
    assert_eq!(bounded_err.kind(), EditErrorKind::VerificationFailed);

    // `verify_batch_events_with_spans` anchors untouched spans across replace + remove gaps.
    let before = "a: 1\nb: 2\nc: 3\n";
    let after = "a: 10\nc: 3\n";
    let opts = ParseOptions::new();
    let before_ev = collect_canonical_events(before, &opts).expect("before");
    let after_ev = collect_canonical_events(after, &opts).expect("after");
    let edits = [
        TextEdit {
            span: Span::new(3, 4),
            replacement: "10".to_owned(),
        },
        TextEdit {
            span: Span::new(5, 10),
            replacement: String::new(),
        },
    ];
    let op0 = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("a")],
        value: Value::from(10_u64),
    };
    let op1 = EditOp::RemoveEntry {
        path: vec![PathSegment::key("b")],
    };
    assert!(verify_batch_events_with_spans(
        &before_ev,
        &after_ev,
        &edits,
        &[&op0, &op1],
    ));
}

#[test]
fn verify_spans_select_matcher_dp_and_greedy_predicates_exact_boundaries() {
    let op_rep = EditOp::ReplaceScalar {
        path: vec![PathSegment::key("a")],
        value: Value::from(1_u64),
    };

    // 1. `verify_batch_events_with_spans` exact boundary guards:
    //    a) Adjacent anchors where `a0` starts at `1 > 0` (so `a0` is NOT skipped when `<` is
    //       mutated to `<=` or `==`), leaving `min_next_start = 3`, and `a1` starts right at `3`
    //       (`span.start() == min_next_start`) and ends right at `edit0.start() == 5`!
    let adj_before = CanonicalEvents {
        texts: vec![
            scalar("a"),
            scalar("x"),
            scalar("b"),
            scalar("y"),
            scalar("c"),
        ],
        spans: vec![
            Span::new(0, 2),
            Span::new(2, 4),
            Span::new(4, 6),
            Span::new(6, 8),
            Span::new(8, 10),
        ],
        is_non_empty_scalar: vec![true; 5],
    };
    let touch_before = CanonicalEvents {
        texts: vec![
            scalar("a0"),
            scalar("rogue"),
            scalar("a1"),
            scalar("e0"),
            scalar("e1"),
        ],
        spans: vec![
            Span::new(1, 3), // starts at 1 > 0 so `a0` always anchors (`min_next_start` -> 3)
            Span::new(2, 3), // non-scalar rogue inside gap between a0 and a1
            Span::new(3, 5), // starts at exact `min_next_start == 3`, ends at exact `edit0.start == 5`
            Span::new(5, 7),
            Span::new(7, 9),
        ],
        is_non_empty_scalar: vec![true, false, true, true, true],
    };
    let touch_after_bad = CanonicalEvents {
        texts: vec![
            scalar("a0"),
            scalar("ROGUE"), // rogue change between a0 and a1; gap before a1 has 0 ops!
            scalar("a1"),
            scalar("e0"),
            scalar("e1"),
        ],
        spans: vec![
            Span::new(1, 3),
            Span::new(2, 3),
            Span::new(3, 5),
            Span::new(5, 7),
            Span::new(7, 9),
        ],
        is_non_empty_scalar: vec![true, false, true, true, true],
    };
    let touch_edits = [
        TextEdit::new(Span::new(5, 7), "e0"),
        TextEdit::new(Span::new(7, 9), "e1"),
    ];
    // If `a1` anchors cleanly, gap `[a0..a1]` has 0 ops and catches `rogue` -> `ROGUE`!
    // If `<` -> `<=` or `==` skips `a1` (since `a1.start == 3 == min_next_start`), OR if `>` -> `>=`
    // skips `a1` (since `a1.end == 5 == edit0.start`), then `a1` does NOT anchor and `ROGUE` falls
    // into the tail gap which has 2 replace ops and FALSELY passes!
    assert!(!verify_batch_events_with_spans(
        &touch_before,
        &touch_after_bad,
        &touch_edits,
        &[&op_rep, &op_rep],
    ));

    //    b) Scalar strictly overlapping an edit (`span.end() > edit.start()`) must NOT anchor,
    //       even when its text & shifted span match in `after` (catches `edit_idx < edits.len()`
    //       and `span.end() > edits[edit_idx].span.start()` -> `==`, `<`).
    let ov_before = CanonicalEvents {
        texts: vec![scalar("old"), scalar("mid"), scalar("tail")],
        spans: vec![Span::new(0, 2), Span::new(3, 5), Span::new(8, 10)],
        is_non_empty_scalar: vec![true, true, true],
    };
    let ov_after = CanonicalEvents {
        texts: vec![scalar("NEW"), scalar("mid"), scalar("TAIL")],
        spans: vec![Span::new(0, 2), Span::new(3, 5), Span::new(8, 10)],
        is_non_empty_scalar: vec![true, true, true],
    };
    let ov_edits = [
        TextEdit::new(Span::new(0, 6), "123456"),
        TextEdit::new(Span::new(8, 10), "TAIL"),
    ];
    assert!(verify_batch_events_with_spans(
        &ov_before,
        &ov_after,
        &ov_edits,
        &[&op_rep, &op_rep],
    ));
    let short_after = CanonicalEvents {
        texts: vec![scalar("a")],
        spans: vec![Span::new(0, 2)],
        is_non_empty_scalar: vec![true],
    };
    assert!(!verify_batch_events_with_spans(
        &adj_before,
        &short_after,
        &[TextEdit::new(Span::new(2, 4), "x")],
        &[&op_rep],
    ));

    // 2. `select_batch_matcher`: exact `1_000_000` vs `1_000_001` boundary, `a_len == 0`,
    //    `max_skip == 0`, and `max_removals <= max_replaces` vs `>`.
    //    (999 + 1) * (999 + 1) * (0 + 1) = 1_000_000 -> exact DP; +1 pushes to 1_001_000 -> Greedy.
    assert_eq!(
        select_batch_matcher(999, 999, 0, 0),
        BatchMatcher::DpByRemovals
    );
    assert_eq!(select_batch_matcher(1_000, 999, 0, 0), BatchMatcher::Greedy);
    assert_eq!(
        select_batch_matcher(0, 1_000_000, 0, 0),
        BatchMatcher::Greedy
    );
    assert_eq!(
        select_batch_matcher(1_000_000, 0, 0, 0),
        BatchMatcher::Greedy
    );
    assert_eq!(
        select_batch_matcher(10, 5, 2, 2),
        BatchMatcher::DpByRemovals
    );
    assert_eq!(
        select_batch_matcher(10, 5, 3, 2),
        BatchMatcher::DpByRemovals
    );
    assert_eq!(
        select_batch_matcher(10, 5, 2, 3),
        BatchMatcher::DpByReplaces
    );
}

#[test]
fn dp_matchers_exact_multi_removal_and_replace_boundaries() {
    // 3. `dp_by_removals` & `dp_by_replaces` multi-removal / multi-replace index arithmetic:
    //    - 3 distinct removals with `max_removals = 2` MUST be rejected (catches `next_skip_base - r`
    //      and `next_skip_base * r` writing into an earlier `r` slot and under-charging removals!).
    let three_rem_b = vec![
        non_scalar("K0"),
        scalar("d1"),
        non_scalar("K1"),
        scalar("d2"),
        non_scalar("K2"),
        scalar("d3"),
        non_scalar("K3"),
    ];
    let three_rem_a = vec![
        non_scalar("K0"),
        non_scalar("K1"),
        non_scalar("K2"),
        non_scalar("K3"),
    ];
    assert!(batch_events_match_dp_by_removals(
        &three_rem_b,
        &three_rem_a,
        3,
        3,
        3
    ));
    assert!(!batch_events_match_dp_by_removals(
        &three_rem_b,
        &three_rem_a,
        3,
        3,
        2
    ));
    assert!(batch_events_match_dp_by_replaces(
        &three_rem_b,
        &three_rem_a,
        3,
        1,
        3
    ));
    assert!(!batch_events_match_dp_by_replaces(
        &three_rem_b,
        &three_rem_a,
        3,
        1,
        2
    ));

    //    - 3 scalar replacements + 2 multi-element removals with `max_replaces = 2` MUST fail in
    //      both DP engines (catches `best + 1` -> `best * 1` and `row_base + p` -> `- p`).
    let three_rep_b = vec![
        scalar("o1"),
        scalar("d1"),
        scalar("d2"),
        scalar("o2"),
        scalar("d3"),
        scalar("d4"),
        scalar("o3"),
    ];
    let three_rep_a = vec![scalar("n1"), scalar("n2"), scalar("n3")];
    assert!(batch_events_match_dp_by_removals(
        &three_rep_b,
        &three_rep_a,
        4,
        3,
        2
    ));
    assert!(!batch_events_match_dp_by_removals(
        &three_rep_b,
        &three_rep_a,
        4,
        2,
        2
    ));
    assert!(batch_events_match_dp_by_replaces(
        &three_rep_b,
        &three_rep_a,
        4,
        3,
        3
    ));
    assert!(!batch_events_match_dp_by_replaces(
        &three_rep_b,
        &three_rep_a,
        4,
        2,
        3
    ));
    // And 2 removals with `max_removals = 1` in `dp_by_replaces` catches `not_in + 1` -> `* 1`.
    let two_rem_b = vec![
        scalar("o1"),
        scalar("d1"),
        non_scalar("K1"),
        scalar("d2"),
        non_scalar("K2"),
    ];
    let two_rem_a = vec![scalar("n1"), non_scalar("K1"), non_scalar("K2")];
    assert!(batch_events_match_dp_by_replaces(
        &two_rem_b, &two_rem_a, 2, 1, 2
    ));
    assert!(!batch_events_match_dp_by_replaces(
        &two_rem_b, &two_rem_a, 2, 1, 1
    ));
    // 1 replacement BEFORE a `non_scalar` anchor and a 2-element contiguous removal (`p = 1` is
    // forced BEFORE `in_run`, catching `next_skip_base + p` -> `next_skip_base - p` at line 1295).
    let rep_then_run_b = vec![
        scalar("o1"),
        non_scalar("K0"),
        scalar("d1"),
        scalar("d2"),
        non_scalar("K1"),
    ];
    let rep_then_run_a = vec![scalar("n1"), non_scalar("K0"), non_scalar("K1")];
    assert!(batch_events_match_dp_by_replaces(
        &rep_then_run_b,
        &rep_then_run_a,
        2,
        1,
        1
    ));
}

#[test]
fn greedy_isolated_replace_sync_and_probe_boundaries() {
    // 4. `is_isolated_scalar_replace` & `sync_matches_at` direct unit tests using indices `i=3, j=3`
    //    so `3 + 2 = 5 != 6 = 3 * 2` and `3 + 1 = 4 != 3 = 3 * 1` catch every `+` -> `*` mutation.
    let iso_b = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("old"),
        scalar("m1"),
        scalar("m2"),
        scalar("extra"),
    ];
    let iso_a = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("new"),
        scalar("m1"),
        scalar("m2"),
    ];
    assert!(is_isolated_scalar_replace(&iso_b, &iso_a, 3, 3, 1));
    let mut iso_bad1 = iso_a.clone();
    iso_bad1[4] = scalar("diff1");
    assert!(!is_isolated_scalar_replace(&iso_b, &iso_bad1, 3, 3, 1));
    let mut iso_bad2 = iso_a.clone();
    iso_bad2[5] = scalar("diff2");
    assert!(!is_isolated_scalar_replace(&iso_b, &iso_bad2, 3, 3, 1));
    // Single matching tail (`j + 2 == after.len() == 5`, whereas `j * 2 == 6`) requires `rem_skip == 0`.
    let tail_b = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("old"),
        scalar("m1"),
    ];
    let tail_a = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("new"),
        scalar("m1"),
    ];
    assert!(is_isolated_scalar_replace(&tail_b, &tail_a, 3, 3, 0));
    assert!(!is_isolated_scalar_replace(&tail_b, &tail_a, 3, 3, 1));
    // Non-matching tail with `j + 2 == 5 < after.len() == 6` vs `j * 2 == 6 >= after.len()`:
    let mut iso_long_b = iso_b;
    iso_long_b[5] = scalar("other");
    assert!(!is_isolated_scalar_replace(&iso_long_b, &iso_a, 3, 3, 0));
    // Single-element tail (`j + 1 == after.len()`): both `.get(+1)` are `None`.
    assert!(is_isolated_scalar_replace(
        &[scalar("p0"), scalar("p1"), scalar("p2"), scalar("old")],
        &[scalar("p0"), scalar("p1"), scalar("p2"), scalar("new")],
        3,
        3,
        0
    ));
    assert!(!is_isolated_scalar_replace(
        &[
            scalar("p0"),
            scalar("p1"),
            scalar("p2"),
            scalar("old"),
            scalar("extra")
        ],
        &[scalar("p0"), scalar("p1"), scalar("p2"), scalar("new")],
        3,
        3,
        1
    ));

    //    - `sync_matches_at` direct boundary tests at `bi = 3, j = 3`:
    let sb = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("k"),
        scalar("old"),
        scalar("m2"),
        scalar("more"),
    ];
    let sa = vec![
        scalar("p0"),
        scalar("p1"),
        scalar("p2"),
        scalar("k"),
        scalar("new"),
        scalar("m2"),
    ];
    assert!(sync_matches_at(&sb, &sa, 3, 3, true));
    assert!(!sync_matches_at(&sb, &sa, 3, 3, false));
    let mut sa_bad2 = sa.clone();
    sa_bad2[5] = scalar("other");
    assert!(!sync_matches_at(&sb, &sa_bad2, 3, 3, true));
    // Exact 2-element tail (`j + 2 == 5 == sa[..5].len()`; `j * 2 == 6` differs when `sa` has 6):
    assert!(sync_matches_at(&sb[..5], &sa[..5], 3, 3, true));
    // Exact 1-element tail with LONGER `before` (`sb.get(4) = Some("old") != None = sa[..4].get(4)`):
    // catches `j + 1 == after.len()` -> `j * 1 == after.len()`!
    assert!(sync_matches_at(&sb, &sa[..4], 3, 3, false));
    assert!(sync_matches_at(&sb, &sb, 3, 3, false));
    let mut sb_ns = sb.clone();
    sb_ns[4] = non_scalar("B");
    assert!(!sync_matches_at(&sb_ns, &sa, 3, 3, true));
    let mut sa_ns = sa;
    sa_ns[4] = non_scalar("B");
    assert!(!sync_matches_at(&sb, &sa_ns, 3, 3, true));
}

#[test]
fn batch_events_match_greedy_with_probes_boundaries() {
    // 5. `batch_events_match_greedy_with_probes`:
    //    a) Spurious later match of `after[j]` INSIDE `rem_skip` (`rem_skip = 4 >= 3`) forces
    //       Branch 1 (`!in_run && can_replace && is_isolated_scalar_replace`) to replace `old -> new`
    //       instead of letting Branch 2 delete `[old, m1, m2]` and blow the 1-removal budget!
    let spur_b = vec![
        scalar("old"),
        scalar("m1"),
        scalar("m2"),
        scalar("new"),
        scalar("m1"),
        scalar("m2"),
        scalar("k1"),
        scalar("d1"),
        scalar("d2"),
        scalar("d3"),
        scalar("d4"),
        scalar("k2"),
    ];
    let spur_a = vec![
        scalar("new"),
        scalar("m1"),
        scalar("m2"),
        scalar("new"),
        scalar("m1"),
        scalar("m2"),
        scalar("k1"),
        scalar("k2"),
    ];
    assert!(batch_events_match_greedy(&spur_b, &spur_a, 1, 1));
    assert!(!batch_events_match_greedy(&spur_b, &spur_a, 0, 1));

    //    b) While `in_run == true`, Branch 1 and fallback replace MUST NOT trigger (`!in_run` guard).
    let inrun_b = vec![
        non_scalar("D0"),
        scalar("d1"),
        scalar("keep1"),
        scalar("keep2"),
    ];
    let inrun_a = vec![scalar("keep1"), scalar("keep2")];
    assert!(batch_events_match_greedy(&inrun_b, &inrun_a, 0, 1));
    let inrun_no_sync_b = vec![
        non_scalar("D0"),
        scalar("d1"),
        scalar("keep1"),
        scalar("keep2"),
        scalar("old_end"),
    ];
    let inrun_no_sync_a = vec![scalar("keep1"), scalar("keep2"), scalar("new_end")];
    assert!(batch_events_match_greedy_with_probes(
        &inrun_no_sync_b,
        &inrun_no_sync_a,
        1,
        1,
        0
    ));

    //    c) Exact `remaining_probes -= 1` decrement across TWO sequential syncs (catches `-=` -> `+=` / `/=`):
    //       Sync 1 needs `d = 2` probes (`remaining_probes: 4 -> 2`); Sync 2 needs `d = 3` probes!
    //       With budget 5 (2 + 3 = 5) -> TRUE; with budget 4 (4 - 2 = 2 < 3) -> FALSE (whereas
    //       `+= 1` raises probes to 6 >= 3 and `/= 1` keeps probes at 4 >= 3 -> both falsely pass!).
    let two_sync_b = vec![
        non_scalar("skip_a"),
        non_scalar("skip_b"),
        scalar("s1"),
        scalar("s2"),
        scalar("d1"),
        scalar("d2"),
        scalar("d3"),
        scalar("k"),
        scalar("old"),
        scalar("t"),
    ];
    let two_sync_a = vec![
        scalar("s1"),
        scalar("s2"),
        scalar("k"),
        scalar("new"),
        scalar("t"),
    ];
    assert!(batch_events_match_greedy_with_probes(
        &two_sync_b,
        &two_sync_a,
        1,
        2,
        5
    ));
    assert!(!batch_events_match_greedy_with_probes(
        &two_sync_b,
        &two_sync_a,
        1,
        2,
        4
    ));

    //    d) `sync_matches_at(..., replaces < max_replaces)` exact boundary (`<` -> `<=`):
    //       After `o0 -> n0` exhausts `max_replaces = 1`, `[k, old, end]` at `d = 1` satisfies
    //       `key_then_replace` ONLY if `has_replace_budget` is falsely true (`<=`); `<` skips it
    //       and syncs onto `[k, new, end]` at `d = 5` (1 removal, 0 extra replaces) -> TRUE!
    let rep_cap_sync_b = vec![
        scalar("o0"),
        non_scalar("drop_a"),
        scalar("k"),
        scalar("old"),
        scalar("end"),
        non_scalar("drop_b"),
        scalar("k"),
        scalar("new"),
        scalar("end"),
    ];
    let rep_cap_sync_a = vec![scalar("n0"), scalar("k"), scalar("new"), scalar("end")];
    assert!(batch_events_match_greedy(
        &rep_cap_sync_b,
        &rep_cap_sync_a,
        1,
        1
    ));

    //    e) `no_sync_j` memoization saves probes across consecutive `in_run` iterations at same `j`.
    let memo_b = vec![
        non_scalar("drop_a"),
        non_scalar("drop_b"),
        scalar("s0"),
        scalar("d3"),
        scalar("d4"),
        scalar("k"),
        scalar("old"),
        scalar("t"),
    ];
    let memo_a = vec![scalar("s0"), scalar("k"), scalar("new"), scalar("t")];
    assert!(batch_events_match_greedy_with_probes(
        &memo_b, &memo_a, 1, 2, 6
    ));
    let cap_rem_b = vec![
        non_scalar("drop_a"),
        scalar("a"),
        non_scalar("drop_b"),
        scalar("b"),
    ];
    let cap_rem_a = vec![scalar("a"), scalar("b")];
    assert!(!batch_events_match_greedy(&cap_rem_b, &cap_rem_a, 0, 1));

    //    f) Fallback replace at `i = 1` (`i += 1` vs `i *= 1`): after replacing `o1 -> n1` and
    //       `o2 -> n2` with `probes = 0`, matching `k1` at `i = 3` and deleting trailing `drop`
    //       succeeds in 1 removal; with `i *= 1`, `i` stays stuck at `1` and needs 2 removals -> FALSE!
    let fb_i1_b = vec![
        scalar("k0"),
        scalar("o1"),
        scalar("o2"),
        scalar("k1"),
        scalar("drop"),
    ];
    let fb_i1_a = vec![scalar("k0"), scalar("n1"), scalar("n2"), scalar("k1")];
    assert!(batch_events_match_greedy_with_probes(
        &fb_i1_b, &fb_i1_a, 2, 1, 0
    ));
    assert!(!batch_events_match_greedy_with_probes(
        &fb_i1_b, &fb_i1_a, 1, 1, 0
    ));
}