gen-diff 0.3.1

Diff algorithms for the gen sequence graph and version control system.
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
//! Builds a connected, renderable graph describing changes between two states.
//!
//! This module is the graph-construction half of `gen-diff`.
//! [`crate::operations`] uses Dolt's table-diff functions to find affected block
//! groups, edges, and nodes and associate those rows with operations. This module
//! handles the boundary normalization, input construction, and graph unification.
//! The resulting graph is consumed by the CLI, patch preview, GenHub, and the
//! diff TUI to show unchanged context together with added, removed, and modified
//! graph elements.
//!
//! # Source and target terminology
//!
//! At a merge boundary, the **source** is the branch the changes are coming
//! from and the **target** is the branch they are being merged into. The
//! historical names in this crate use `source` and `target` differently:
//! `source_ref` is the graph's comparison baseline and `target_ref` is the
//! changed state being displayed. Consequently, a caller showing “merge source
//! branch into target branch” passes the merge target as the first/internal
//! source endpoint and the merge source as the second/internal target endpoint.
//! This is the source/target swap visible in merge-oriented callers.
//!
//! The same distinction applies to `source_block_group` and
//! `target_block_group` in [`BlockGroupDiff`]. They record whether the requested
//! block-group ID exists in the baseline and changed database states,
//! respectively; they do not identify the incoming and receiving branches of a
//! merge. Source/target on a [`GraphEdge`] is a third, unrelated use: it is only
//! the direction of that edge.
//!
//! # Block-group membership and effective graph snapshots
//!
//! Every block group, including one created for a child sample, owns a complete
//! set of `block_group_edges`. Copied memberships are stored as rows belonging
//! to the child block group, and its parent relationship is recorded separately
//! by `parent_block_group_id`. The child graph therefore does not need its
//! parent in order to load or reconstruct its stored state.
//!
//! A parent is selected only to make an added or removed child graph
//! biologically meaningful. The changed rows would show a child's entire graph
//! being removed or created. Thus, comparing to the parent shows the edits that
//! introduced in the child. `build_block_group_comparison` therefore
//! keeps two concepts separate:
//!
//! - `source_block_group` and `target_block_group` preserve actual membership
//!   of the requested ID and determine whether the block group is added,
//!   removed, or modified.
//! - `source_effective_block_group_id` and
//!   `target_effective_block_group_id` select the graph used for display. When
//!   the requested ID is absent, this may be the child's parent ID.
//!
//! The corresponding effective history ref comes from the endpoint where the
//! selected row is known to exist. Thus a target-only child uses its own graph
//! at `target_ref` and its parent graph at that same endpoint as the source
//! baseline; a source-only child uses the symmetric source-side pair. This
//! selection affects only the rendered graph. It never fills in the missing
//! `source_block_group` or `target_block_group`.
//!
//! Dolt's copied `block_group_edges` rows contain enough information to
//! reconstruct a new child's graph from the table diff. The effective parent is
//! not a workaround for incomplete diff rows. It supplies the inherited
//! comparison baseline, and `effective_edge_changes_for_source` filters copied
//! memberships that Dolt reports as added but that already exist in that
//! selected parent graph.
//!
//! # Graph-building approach
//!
//! Graph construction has three steps:
//!
//! 1. Load the selected endpoint edge sets and convert edge coordinates into
//!    [`GraphNode`] sequence slices. Coordinates are slices of the backing
//!    sequence, not positions in graph space.
//! 2. Split both sides at the union of their slice boundaries. For example,
//!    `N[0..10]` on one side and `N[0..4] + N[4..10]` on the other become the
//!    same two comparison units. Real path edges are retained,
//!    persistence-only edit-site marker edges are omitted, and neutral
//!    continuation edges reconnect slices that belong to one covered span.
//! 3. Union the normalized endpoint graphs into a [`DiffGenGraph`]. Presence
//!    and Dolt operation metadata determine each node's and edge's
//!    [`DiffChange`]. Start/end nodes and unchanged context remain in the result
//!    because the renderer needs a connected graph for layout.
//!
//! Loading both endpoint edge sets makes path membership and marker filtering
//! straightforward. An alternative is to load the baseline once and apply the
//! `block_group_edges` diff rows to reconstruct the changed graph; the copied
//! child rows are sufficient for that and it may be preferable if endpoint
//! loading becomes a measured bottleneck. Another alternative is a literal
//! database-membership diff with an empty missing side, but that intentionally
//! gives up the lineage-aware view. The current effective-ID/ref variables could
//! also be replaced by an explicit endpoint-snapshot struct resolved once
//! upstream; that would preserve the behavior while making the storage choice
//! less indirect.

use std::collections::{HashMap, HashSet};

use gen_core::{
    DoltHashId, HashId, NO_CHROMOSOME_INDEX, PATH_END_NODE_ID, PATH_START_NODE_ID,
    PRESERVE_EDIT_SITE_CHROMOSOME_INDEX, Strand, is_terminal,
};
use gen_graph::{GenGraph, GraphEdge, GraphNode};
use gen_models::{
    block_group::BlockGroup,
    block_group_edge::{AugmentedEdge, BlockGroupEdge},
    db::GraphConnection,
};
use petgraph::graphmap::DiGraphMap;

use crate::operations::{BlockGroupEdgeChange, BlockGroupEdgeKey, NodeChange, OperationDiffError};

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum DiffChangeKind {
    Unchanged,
    Added,
    Removed,
    Modified,
}

/// Records whether an input edge came from storage or graph normalization.
///
/// An explicit edge represents path topology stored for a block group, so its
/// presence is explicitly introduced. A continuation edge is created only to
/// reconnect adjacent slices after a shared comparison boundary splits a stored
/// span. This lets us mark these edges as not part of a diff.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum EdgeOrigin {
    /// A real path edge loaded from the block group's stored edge membership.
    Explicit,
    /// A synthetic connection between slices of one originally continuous span.
    Continuation,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct DiffChange {
    pub kind: DiffChangeKind,
    pub operation: Option<DoltHashId>,
}

impl DiffChange {
    /// Creates the neutral annotation used for graph elements shared by both endpoints.
    ///
    /// Input builders and merge helpers use this constructor so unchanged
    /// context has neither a change kind nor misleading operation attribution.
    pub const fn unchanged() -> Self {
        Self {
            kind: DiffChangeKind::Unchanged,
            operation: None,
        }
    }

    /// Creates an annotation from the change kind and attribution collected from Dolt.
    ///
    /// Input-graph construction uses this common constructor before the source
    /// and target annotations are consolidated into the rendered diff graph.
    pub const fn new(kind: DiffChangeKind, operation: Option<DoltHashId>) -> Self {
        Self { kind, operation }
    }

    /// Returns explicit attribution or the comparison's fallback operation.
    ///
    /// Change-merging code uses this when every rendered change must be tied to
    /// an operation even if the table-diff row did not provide one.
    pub fn operation_or(self, default_operation: DoltHashId) -> DoltHashId {
        self.operation.unwrap_or(default_operation)
    }
}

#[derive(Clone, Debug)]
pub struct BlockGroupDiff {
    pub id: HashId,
    pub source_block_group: Option<BlockGroup>,
    pub target_block_group: Option<BlockGroup>,
    pub graph: DiffGenGraph,
}

/// Describes how a block group differs between the comparison endpoints.
///
/// This is computed from block-group membership at the source and target. It is
/// intentionally distinct from [`DiffChangeKind`], which describes individual
/// graph elements and can therefore also be unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum BlockGroupChangeKind {
    Added,
    Removed,
    Modified,
}

impl BlockGroupDiff {
    /// Returns the block group's change classification for this comparison.
    ///
    /// `None` indicates an invalid diff with no block group at either endpoint.
    /// The classification is derived rather than stored so it cannot disagree
    /// with `source_block_group` and `target_block_group`. CLI and TUI views use
    /// the result to label the complete block-group diff.
    pub const fn change_kind(&self) -> Option<BlockGroupChangeKind> {
        match (
            self.source_block_group.is_some(),
            self.target_block_group.is_some(),
        ) {
            (false, true) => Some(BlockGroupChangeKind::Added),
            (true, false) => Some(BlockGroupChangeKind::Removed),
            (true, true) => Some(BlockGroupChangeKind::Modified),
            (false, false) => None,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct DiffGraphNode {
    pub node: GraphNode,
    pub change: DiffChange,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct DiffGraphEdge {
    pub edge: GraphEdge,
    pub change: DiffChange,
}

pub type DiffGenGraph = DiGraphMap<DiffGraphNode, Vec<DiffGraphEdge>>;

pub struct DiffGenGraphRef<'a>(pub &'a DiffGenGraph);

impl<'a> From<&'a DiffGenGraph> for DiffGenGraphRef<'a> {
    /// Wraps a borrowed diff graph for conversion without cloning its topology.
    ///
    /// Generic graph consumers use this adapter before stripping diff
    /// annotations through the `GenGraph` conversion.
    fn from(graph: &'a DiffGenGraph) -> Self {
        Self(graph)
    }
}

impl<'a> From<DiffGenGraphRef<'a>> for GenGraph {
    /// Projects a diff graph into the ordinary graph shape used by layout code.
    ///
    /// The conversion keeps nodes and edges but deliberately drops change
    /// annotations; the diff TUI uses the resulting `GenGraph` for layout while
    /// retaining the annotated graph for styling.
    fn from(val: DiffGenGraphRef<'a>) -> Self {
        let mut graph = GenGraph::new();
        for node in val.0.nodes() {
            graph.add_node(node.node);
        }
        for (src, dest, edges) in val.0.all_edges() {
            let mapped_edges = edges.iter().map(|edge| edge.edge).collect::<Vec<_>>();
            graph.add_edge(src.node, dest.node, mapped_edges);
        }
        graph
    }
}

impl From<DiffGraphNode> for GraphNode {
    /// Removes a node's diff annotation for consumers that only need graph topology.
    ///
    /// Conversion and rendering helpers use this projection instead of
    /// duplicating field access at each generic-graph boundary.
    fn from(node: DiffGraphNode) -> Self {
        node.node
    }
}

impl From<DiffGraphEdge> for GraphEdge {
    /// Removes an edge's diff annotation for consumers that only need graph topology.
    ///
    /// Conversion and rendering helpers use this projection when passing diff
    /// edges through APIs written for ordinary graph edges.
    fn from(edge: DiffGraphEdge) -> Self {
        edge.edge
    }
}

pub(crate) struct BlockGroupDiffInputs<'a> {
    pub(crate) source_ref: &'a str,
    pub(crate) target_ref: &'a str,
    pub(crate) default_operation: DoltHashId,
    pub(crate) edge_changes_by_block_group: &'a HashMap<HashId, Vec<BlockGroupEdgeChange>>,
    pub(crate) block_group_operations_by_id: &'a HashMap<HashId, HashSet<DoltHashId>>,
    pub(crate) node_changes: &'a [NodeChange],
}

/// When carrying out a diff based purely on edges.
pub(crate) struct EdgeDiffInput<'a> {
    edges: &'a [AugmentedEdge],
    spans: HashSet<GraphNode>,
    node_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
    edge_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
}

impl<'a> EdgeDiffInput<'a> {
    /// Creates an input whose changes have no operation attribution.
    pub(crate) fn unattributed(edges: &'a [AugmentedEdge]) -> Self {
        Self {
            edges,
            spans: spans_from_edges(edges),
            node_operations_by_id: None,
            edge_operations_by_id: None,
        }
    }

    /// Attaches operation attribution after callers have used the cached spans.
    pub(crate) fn with_attribution(
        mut self,
        node_operations_by_id: &'a HashMap<HashId, DoltHashId>,
        edge_operations_by_id: &'a HashMap<HashId, DoltHashId>,
    ) -> Self {
        self.node_operations_by_id = Some(node_operations_by_id);
        self.edge_operations_by_id = Some(edge_operations_by_id);
        self
    }

    /// Returns the cached sequence spans represented by this input's edges.
    pub(crate) fn spans(&self) -> &HashSet<GraphNode> {
        &self.spans
    }
}

/// Builds the renderable diff for one block group identified by table-diff discovery.
///
/// `build_dolt_operation_diff` calls this once per affected block group. It
/// resolves normalized endpoint input graphs, unifies them, and omits a
/// source-and-target block group when the resulting graph has no visible
/// changes, avoiding empty entries in command and TUI output.
pub(crate) fn build_block_group_diff(
    graph_conn: &GraphConnection,
    block_group_id: HashId,
    inputs: &BlockGroupDiffInputs<'_>,
) -> Result<Option<BlockGroupDiff>, OperationDiffError> {
    let Some(comparison) = build_block_group_comparison(graph_conn, block_group_id, inputs)? else {
        return Ok(None);
    };
    if !diff_graph_has_changes(&comparison.graph)
        && comparison.source_block_group.is_some()
        && comparison.target_block_group.is_some()
    {
        return Ok(None);
    }

    Ok(Some(BlockGroupDiff {
        id: block_group_id,
        source_block_group: comparison.source_block_group,
        target_block_group: comparison.target_block_group,
        graph: comparison.graph,
    }))
}

/// Builds a comparable graph while retaining block-group endpoint membership.
///
/// `build_block_group_diff` uses this preparation step to keep endpoint
/// membership separate from the lineage-aware graph chosen for display. It
/// loads complete endpoint edges, filters copied child memberships, aligns
/// sequence-slice boundaries, and attaches Dolt operation attribution because
/// the unified builder needs matching graph units and real path membership.
fn build_block_group_comparison(
    graph_conn: &GraphConnection,
    block_group_id: HashId,
    inputs: &BlockGroupDiffInputs<'_>,
) -> Result<Option<BlockGroupComparison>, OperationDiffError> {
    let target_block_group =
        BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.target_ref)).ok();
    let source_block_group =
        BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.source_ref)).ok();
    if source_block_group.is_none() && target_block_group.is_none() {
        return Ok(None);
    }
    // Added or removed child block groups only exist on one endpoint. The
    // opposite endpoint is represented by the child's parent so the diff
    // compares the child graph against the graph it diverged from.
    let source_parent_block_group_id = target_block_group
        .as_ref()
        .and_then(|block_group| block_group.parent_block_group_id);
    let target_parent_block_group_id = source_block_group
        .as_ref()
        .and_then(|block_group| block_group.parent_block_group_id);
    let source_effective_block_group_id = source_block_group
        .as_ref()
        .map(|block_group| block_group.id)
        .or(source_parent_block_group_id);
    let target_effective_block_group_id = target_block_group
        .as_ref()
        .map(|block_group| block_group.id)
        .or(target_parent_block_group_id);
    // When the block group exists on the endpoint, read it from that endpoint's
    // ref. When it does not, the effective id is the parent id discovered from
    // the other endpoint's child row, so the parent must be read from that
    // endpoint's ref instead.
    let source_effective_history_ref = if source_block_group.is_some() {
        Some(inputs.source_ref)
    } else {
        Some(inputs.target_ref)
    };
    let target_effective_history_ref = if target_block_group.is_some() {
        Some(inputs.target_ref)
    } else {
        Some(inputs.source_ref)
    };
    // Load both endpoint edge sets directly instead of replaying diff rows over
    // the source. Diff rows are still useful for attribution, but they are not
    // a complete graph description:
    //
    //   new sample with no sequence edits:
    //     source(parent):  start -> A -> end
    //     target(child):   start -> A -> end
    //
    // The copied child edges may have the same edge keys as the parent, so
    // replaying only changed keys can make the target look empty and hide the
    // created sample. Endpoint reads keep presence-only samples visible.
    //
    //   insertion/deletion edits:
    //     source: A -> B
    //     target: A -> I -> B, plus internal edit-site marker edges
    //
    // The target endpoint tells us which path edges are real graph choices and
    // lets the input builder filter marker edges before rendering.
    let source_edges = load_block_group_edges(
        graph_conn,
        source_effective_block_group_id,
        source_effective_history_ref,
    );
    let raw_block_group_edge_changes = inputs
        .edge_changes_by_block_group
        .get(&block_group_id)
        .map(Vec::as_slice)
        .unwrap_or(&[]);
    let block_group_edge_changes =
        effective_edge_changes_for_source(&source_edges, raw_block_group_edge_changes);
    let target_edges = load_block_group_edges(
        graph_conn,
        target_effective_block_group_id,
        target_effective_history_ref,
    );
    let source_input = EdgeDiffInput::unattributed(&source_edges);
    let target_input = EdgeDiffInput::unattributed(&target_edges);
    let operation_change_lookup = collect_input_operation_changes(
        block_group_id,
        inputs,
        &block_group_edge_changes,
        source_input.spans(),
        target_input.spans(),
    );
    let graph = build_diff_graph_from_edges(
        source_input.with_attribution(
            &operation_change_lookup.source_node_operation_by_id,
            &operation_change_lookup.source_edge_operation_by_id,
        ),
        target_input.with_attribution(
            &operation_change_lookup.target_node_operation_by_id,
            &operation_change_lookup.target_edge_operation_by_id,
        ),
        Some(inputs.default_operation),
    );

    Ok(Some(BlockGroupComparison {
        source_block_group,
        target_block_group,
        graph,
    }))
}

/// Loads all augmented path edges for an optional block group at one history ref.
///
/// `build_block_group_comparison` uses an empty vector for a genuinely missing
/// endpoint and a complete edge set otherwise. Centralizing that choice keeps
/// absence handling out of the span and input-graph builders.
fn load_block_group_edges(
    graph_conn: &GraphConnection,
    block_group_id: Option<HashId>,
    history_ref: Option<&str>,
) -> Vec<AugmentedEdge> {
    block_group_id.map_or_else(Vec::new, |block_group_id| {
        BlockGroupEdge::edges_for_block_group(graph_conn, &block_group_id, history_ref)
    })
}

/// Builds a graph diff from two complete edge sets.
///
/// Both inputs use one shared sequence-boundary plan so their normalized
/// `GraphNode` slices are directly comparable. Callers may attach operation
/// attribution to either input; elements present only in the query are added,
/// while elements present only in the base are removed.
pub(crate) fn build_diff_graph_from_edges(
    base: EdgeDiffInput<'_>,
    query: EdgeDiffInput<'_>,
    default_operation: Option<DoltHashId>,
) -> DiffGenGraph {
    let (base_nodes, query_nodes) = split_nodes_at_shared_boundaries(base.spans(), query.spans());
    // This is a failback case where no operations are provided. Edge sets can be input directly
    // to get a diff from and not have operations associated with the changes.
    let no_operations = HashMap::new();
    let base_graph = build_diff_input_graph(
        base_nodes,
        base.spans(),
        base.edges,
        base.node_operations_by_id.unwrap_or(&no_operations),
        base.edge_operations_by_id.unwrap_or(&no_operations),
    );
    let query_graph = build_diff_input_graph(
        query_nodes,
        query.spans(),
        query.edges,
        query.node_operations_by_id.unwrap_or(&no_operations),
        query.edge_operations_by_id.unwrap_or(&no_operations),
    );
    build_unified_diff_graph(&base_graph, &query_graph, default_operation)
}

/// Derives the sequence slices covered by an endpoint's path edges.
///
/// This methods exists because blocks_from_edges because loads sequences, which
/// can add quite a bit of overhead.
fn spans_from_edges(edges: &[AugmentedEdge]) -> HashSet<GraphNode> {
    // A diff graph node only needs a backing node id and a sequence slice. Do
    // not call Edge::blocks_from_edges here: that query fetches sequence text
    // so GroupBlock::sequence can work, but the diff graph resolves sequence
    // text later through the regular GraphNode rendering path.
    //
    //   endpoint edges:
    //     start -> A@0
    //     A@10 -> end
    //
    //   edge-derived span:
    //     A[0..10]
    //
    // Keeping this as edge-derived spans lets edge attribution stay attached
    // until the graph builder has both the display nodes and real path edges.
    let mut starts_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
    let mut ends_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
    for edge in edges.iter().map(|edge| &edge.edge) {
        if !is_terminal(edge.source_node_id) {
            ends_by_node_id
                .entry(edge.source_node_id)
                .or_default()
                .insert(edge.source_coordinate);
        }
        if !is_terminal(edge.target_node_id) {
            starts_by_node_id
                .entry(edge.target_node_id)
                .or_default()
                .insert(edge.target_coordinate);
        }
    }

    let mut node_ids = starts_by_node_id.keys().copied().collect::<HashSet<_>>();
    node_ids.extend(ends_by_node_id.keys().copied());
    let mut spans = HashSet::new();
    for node_id in node_ids {
        let empty_starts = HashSet::new();
        let empty_ends = HashSet::new();
        let starts = starts_by_node_id.get(&node_id).unwrap_or(&empty_starts);
        let ends = ends_by_node_id.get(&node_id).unwrap_or(&empty_ends);
        for (sequence_start, sequence_end) in coordinate_spans(starts, ends) {
            spans.insert(GraphNode {
                node_id,
                sequence_start,
                sequence_end,
            });
        }
    }
    spans
}

/// Turns observed entry and exit coordinates into ordered sequence intervals.
///
/// `spans_from_edges` uses adjacent coordinates rather than graph-space
/// positions because `GraphNode` ranges slice the backing sequence. The
/// resulting intervals are the endpoint-local spans later split at shared
/// source/target boundaries.
fn coordinate_spans(starts: &HashSet<i64>, ends: &HashSet<i64>) -> Vec<(i64, i64)> {
    let mut coordinates = starts.union(ends).copied().collect::<Vec<_>>();
    coordinates.sort();
    coordinates.dedup();
    if coordinates.len() <= 1 {
        return coordinates
            .first()
            .copied()
            .map(|coordinate| vec![(coordinate, coordinate)])
            .unwrap_or_default();
    }
    coordinates
        .windows(2)
        .map(|window| (window[0], window[1]))
        .collect()
}

/// Normalizes endpoint nodes to the same sequence-slice boundaries.
///
/// See `split_spans_at_boundaries` for a real explanation of what this does.
/// It essentially converts nodes so they can be compared across graphs, such as
/// the source graph having N[0:10] and target having N[0-3] -> N[6-10]. This converts
/// it to: N[0-3], N[3-6], N[6-10] so additions/removals can be properly described
fn split_nodes_at_shared_boundaries(
    source_spans: &HashSet<GraphNode>,
    target_spans: &HashSet<GraphNode>,
) -> (HashSet<GraphNode>, HashSet<GraphNode>) {
    let boundaries_by_node_id = collect_shared_boundaries(source_spans, target_spans);
    (
        split_spans_at_boundaries(source_spans, &boundaries_by_node_id),
        split_spans_at_boundaries(target_spans, &boundaries_by_node_id),
    )
}

/// Collects every endpoint boundary for each backing sequence node.
///
/// `split_nodes_at_shared_boundaries` uses this union as the shared cut
/// plan, ensuring source-only and target-only boundaries are applied
/// symmetrically before graph elements are classified.
fn collect_shared_boundaries(
    source_spans: &HashSet<GraphNode>,
    target_spans: &HashSet<GraphNode>,
) -> HashMap<HashId, HashSet<i64>> {
    let mut boundaries_by_node_id = HashMap::new();
    for span in source_spans.iter().chain(target_spans) {
        let boundaries = boundaries_by_node_id
            .entry(span.node_id)
            .or_insert_with(HashSet::new);
        boundaries.insert(span.sequence_start);
        boundaries.insert(span.sequence_end);
    }
    boundaries_by_node_id
}

/// Splits existing endpoint spans according to the shared boundary plan.
///
/// The normalization step uses this helper to divide only sequence already
/// present in that endpoint; it never fills gaps. That preserves membership
/// while giving `build_unified_diff_graph` equal-sized units to mark as added,
/// removed, or unchanged.
fn split_spans_at_boundaries(
    spans: &HashSet<GraphNode>,
    boundaries_by_node_id: &HashMap<HashId, HashSet<i64>>,
) -> HashSet<GraphNode> {
    let mut nodes = HashSet::new();
    for span in spans {
        // Split both endpoint graphs on the union of observed edge boundaries
        // for each backing node. GraphNode coordinates are sequence slices, not
        // path coordinates, so this only divides already-present sequence spans.
        //
        //   source before VCF edit:
        //     [0................................34]
        //
        //   target after deletion/insertion:
        //     [0..3] [4..10] [10..............34] and inserted [AGA]
        //
        //   source display nodes:
        //     [0..3] [3..4] [4..10] [10.......34]
        //
        // Without this split, the deleted [3..4] base is hidden inside a large
        // source block and cannot be colored as removed.
        if span.sequence_start == span.sequence_end {
            nodes.insert(*span);
            continue;
        }
        let mut boundaries = boundaries_by_node_id
            .get(&span.node_id)
            .into_iter()
            .flat_map(|boundaries| boundaries.iter())
            .filter(|coordinate| {
                **coordinate >= span.sequence_start && **coordinate <= span.sequence_end
            })
            .copied()
            .collect::<Vec<_>>();
        boundaries.sort();
        boundaries.dedup();
        if boundaries.len() < 2 {
            nodes.insert(*span);
            continue;
        }
        for window in boundaries.windows(2) {
            let sequence_start = window[0];
            let sequence_end = window[1];
            if sequence_start == sequence_end {
                continue;
            }
            nodes.insert(GraphNode {
                node_id: span.node_id,
                sequence_start,
                sequence_end,
            });
        }
    }
    nodes
}

/// Removes copied child-edge changes already represented by the effective source graph.
///
/// `build_block_group_comparison` uses this filter when a missing child
/// endpoint is displayed through its parent. Dolt reports the child's copied
/// memberships as additions, but suppressing keys already in that parent keeps
/// inherited paths from receiving false change attribution.
fn effective_edge_changes_for_source(
    source_edges: &[AugmentedEdge],
    edge_changes: &[BlockGroupEdgeChange],
) -> Vec<BlockGroupEdgeChange> {
    let source_edge_keys = source_edges
        .iter()
        .map(BlockGroupEdgeKey::from)
        .collect::<HashSet<_>>();
    edge_changes
        .iter()
        .copied()
        .filter(
            |edge_change| match (edge_change.old_key, edge_change.new_key) {
                (None, Some(new_key)) => !source_edge_keys.contains(&new_key),
                (Some(old_key), None) => source_edge_keys.contains(&old_key),
                (Some(old_key), Some(new_key)) => {
                    source_edge_keys.contains(&old_key) || !source_edge_keys.contains(&new_key)
                }
                (None, None) => false,
            },
        )
        .collect()
}

/// Builds endpoint-specific operation attribution for nodes and edges in each input graph.
///
/// `build_block_group_comparison` attaches this lookup to both edge inputs.
/// It intersects Dolt changes with the block group's represented operations and
/// endpoint membership so unrelated table rows do not color this graph.
fn collect_input_operation_changes(
    block_group_id: HashId,
    inputs: &BlockGroupDiffInputs<'_>,
    changed_edge_ids: &[BlockGroupEdgeChange],
    source_spans: &HashSet<GraphNode>,
    target_spans: &HashSet<GraphNode>,
) -> InputOperationChangeLookup {
    let mut change_lookup = InputOperationChangeLookup::default();
    let Some(block_group_operations) = inputs.block_group_operations_by_id.get(&block_group_id)
    else {
        return change_lookup;
    };
    let source_node_ids = span_node_ids(source_spans);
    let target_node_ids = span_node_ids(target_spans);
    for node_change in inputs.node_changes {
        if let (Some(old_node_id), Some(operation)) =
            (node_change.old_node_id(), node_change.old_operation())
            && block_group_operations.contains(&operation)
            && source_node_ids.contains(&old_node_id)
            && !target_node_ids.contains(&old_node_id)
        {
            change_lookup
                .source_node_operation_by_id
                .insert(old_node_id, operation);
        }
        if let (Some(new_node_id), Some(operation)) =
            (node_change.new_node_id(), node_change.new_operation())
            && block_group_operations.contains(&operation)
            && target_node_ids.contains(&new_node_id)
            && !source_node_ids.contains(&new_node_id)
        {
            change_lookup
                .target_node_operation_by_id
                .insert(new_node_id, operation);
        }
    }

    for changed_edge_id in changed_edge_ids {
        if let (Some(old_edge_id), Some(operation)) = (
            changed_edge_id.old_edge_id(),
            changed_edge_id.old_operation(),
        ) {
            change_lookup
                .source_edge_operation_by_id
                .insert(old_edge_id, operation);
        }
        if let (Some(new_edge_id), Some(operation)) = (
            changed_edge_id.new_edge_id(),
            changed_edge_id.new_operation(),
        ) {
            change_lookup
                .target_edge_operation_by_id
                .insert(new_edge_id, operation);
        }
    }
    change_lookup
}

/// Extracts non-terminal backing node IDs from an input's sequence spans.
///
/// `collect_input_operation_changes` uses these sets to attribute a node
/// only when its membership actually changes between the two endpoint graphs.
fn span_node_ids(spans: &HashSet<GraphNode>) -> HashSet<HashId> {
    spans
        .iter()
        .filter(|span| !is_terminal(span.node_id))
        .map(|span| span.node_id)
        .collect()
}

/// Unifies normalized inputs into the connected graph rendered as a diff.
///
/// Combines both inputs into one graph, marking nodes and edges as added,
/// removed, modified, or unchanged. Unchanged nodes and edges, including the
/// start and end nodes, remain so the CLI and TUI can display changes in
/// context.
pub(crate) fn build_unified_diff_graph(
    source_graph: &DiffInputGraph,
    target_graph: &DiffInputGraph,
    default_operation: Option<DoltHashId>,
) -> DiffGenGraph {
    let merged_nodes = source_graph
        .nodes()
        .chain(target_graph.nodes())
        .collect::<HashSet<_>>();

    let merged_edge_keys = source_graph
        .edges()
        .map(|(edge_key, _)| edge_key)
        .chain(target_graph.edges().map(|(edge_key, _)| edge_key))
        .collect::<HashSet<_>>();
    let mut diff_graph = DiffGenGraph::new();
    for node in merged_nodes {
        diff_graph.add_node(diff_graph_node(
            node,
            source_graph,
            target_graph,
            default_operation,
        ));
    }

    let mut merged_edges_by_node_pair = HashMap::<(GraphNode, GraphNode), Vec<GraphEdgeKey>>::new();
    for edge_key in merged_edge_keys {
        merged_edges_by_node_pair
            .entry((edge_key.source, edge_key.target))
            .or_default()
            .push(edge_key);
    }
    let mut merged_edge_pairs = merged_edges_by_node_pair.into_iter().collect::<Vec<_>>();
    merged_edge_pairs.sort_by_key(|((source, target), _)| (*source, *target));
    for ((source, target), edge_keys) in merged_edge_pairs {
        let source_node = diff_graph_node(source, source_graph, target_graph, default_operation);
        let target_node = diff_graph_node(target, source_graph, target_graph, default_operation);
        let diff_edges = edge_keys
            .iter()
            .copied()
            .map(|edge_key| DiffGraphEdge {
                edge: graph_edge_for_key(source_graph, target_graph, edge_key),
                change: merge_input_edge_changes(
                    source_graph.edge_metadata(edge_key),
                    target_graph.edge_metadata(edge_key),
                    default_operation,
                ),
            })
            .collect::<Vec<_>>();
        diff_graph.add_edge(source_node, target_node, diff_edges);
    }

    diff_graph
}

/// Reports whether a unified graph contains any visible node or edge change.
///
/// `build_block_group_diff` uses this scan to omit modified block groups whose
/// table rows normalize to unchanged graph content, while still retaining
/// membership-only additions and removals.
fn diff_graph_has_changes(graph: &DiffGenGraph) -> bool {
    graph
        .nodes()
        .any(|node| node.change.kind != DiffChangeKind::Unchanged)
        || graph.all_edges().any(|(_, _, edges)| {
            edges
                .iter()
                .any(|edge| edge.change.kind != DiffChangeKind::Unchanged)
        })
}

/// Creates one unified node by reconciling its endpoint annotations.
///
/// `build_unified_diff_graph` calls this for every normalized node and for edge
/// endpoints. Using one helper guarantees that topology keys and displayed node
/// styling share the same presence and attribution rules.
fn diff_graph_node(
    node: GraphNode,
    source_graph: &DiffInputGraph,
    target_graph: &DiffInputGraph,
    default_operation: Option<DoltHashId>,
) -> DiffGraphNode {
    let source_change = source_graph.node_change(node);
    let target_change = target_graph.node_change(node);
    DiffGraphNode {
        node,
        change: merge_input_changes(source_change, target_change, default_operation),
    }
}

/// Retrieves the concrete edge represented by a merged identity key.
///
/// `build_unified_diff_graph` prefers the target copy so current metadata is
/// rendered, then falls back to the source for removed edges. The key was
/// collected from one of those inputs, so absence from both is an invariant
/// violation.
fn graph_edge_for_key(
    source_graph: &DiffInputGraph,
    target_graph: &DiffInputGraph,
    edge_key: GraphEdgeKey,
) -> GraphEdge {
    target_graph
        .edge(edge_key)
        .or_else(|| source_graph.edge(edge_key))
        .expect("should contain graph edge for merged diff key")
}

/// Reconciles source and target presence plus attribution for one graph element.
///
/// Unified-node construction and the default edge path use this function.
/// Presence on only one side determines addition or removal; elements on both
/// sides become modified only when either input carries change metadata, which
/// keeps shared layout context neutral.
fn merge_input_changes(
    source_change: Option<DiffChange>,
    target_change: Option<DiffChange>,
    default_operation: Option<DoltHashId>,
) -> DiffChange {
    match (source_change, target_change) {
        (None, None) => DiffChange::unchanged(),
        (None, Some(change)) => changed(DiffChangeKind::Added, change.operation, default_operation),
        (Some(change), None) => {
            changed(DiffChangeKind::Removed, change.operation, default_operation)
        }
        (Some(source_change), Some(target_change))
            if source_change.kind == DiffChangeKind::Removed =>
        {
            changed(
                DiffChangeKind::Removed,
                source_change.operation.or(target_change.operation),
                default_operation,
            )
        }
        (Some(source_change), Some(target_change))
            if target_change.kind == DiffChangeKind::Added =>
        {
            changed(
                DiffChangeKind::Added,
                target_change.operation.or(source_change.operation),
                default_operation,
            )
        }
        (Some(source_change), Some(target_change))
            if source_change.operation.is_some()
                || target_change.operation.is_some()
                || source_change.kind != DiffChangeKind::Unchanged
                || target_change.kind != DiffChangeKind::Unchanged =>
        {
            changed(
                DiffChangeKind::Modified,
                target_change.operation.or(source_change.operation),
                default_operation,
            )
        }
        (Some(_), Some(_)) => DiffChange::unchanged(),
    }
}

/// Applies edge-specific reconciliation on top of the general input rules.
///
/// Continuation edges reconnect slices split during normalization, so they
/// stay unchanged. Explicit edges present in only one input are added or
/// removed.
fn merge_input_edge_changes(
    source_metadata: Option<DiffInputEdgeMetadata>,
    target_metadata: Option<DiffInputEdgeMetadata>,
    default_operation: Option<DoltHashId>,
) -> DiffChange {
    if source_metadata
        .into_iter()
        .chain(target_metadata)
        .any(|metadata| metadata.origin == EdgeOrigin::Continuation)
    {
        return DiffChange::unchanged();
    }
    let source_change = source_metadata.map(|metadata| metadata.change);
    let target_change = target_metadata.map(|metadata| metadata.change);
    merge_input_changes(source_change, target_change, default_operation)
}

/// Creates an attributed non-neutral change, filling missing Dolt attribution.
///
/// Input and edge merge helpers use the comparison's default operation so
/// every colored element can be grouped by operation in downstream views.
fn changed(
    kind: DiffChangeKind,
    operation: Option<DoltHashId>,
    default_operation: Option<DoltHashId>,
) -> DiffChange {
    DiffChange::new(kind, operation.or(default_operation))
}

/// Builds one endpoint's connected diff input from normalized nodes.
///
/// Builds one input for the diff. It connects sequence slices using explicit
/// edges and skips edges that are due to normalization, etc. If present, nodes
/// and edges are attributed to an operation.
pub(crate) fn build_diff_input_graph(
    mut input_nodes: HashSet<GraphNode>,
    continuation_spans: &HashSet<GraphNode>,
    input_edges: &[AugmentedEdge],
    node_operations_by_id: &HashMap<HashId, DoltHashId>,
    edge_operations_by_id: &HashMap<HashId, DoltHashId>,
) -> DiffInputGraph {
    let mut graph = GenGraph::new();
    let mut node_changes = HashMap::new();
    let mut edge_metadata = HashMap::new();

    input_nodes.insert(path_start_graph_node());
    input_nodes.insert(path_end_graph_node());
    for node in &input_nodes {
        graph.add_node(*node);
        node_changes.insert(
            *node,
            node_operations_by_id
                .get(&node.node_id)
                .map_or_else(DiffChange::unchanged, |operation| {
                    DiffChange::new(DiffChangeKind::Modified, Some(*operation))
                }),
        );
    }

    let blocks_by_start = input_nodes
        .iter()
        .map(|node| ((node.node_id, node.sequence_start), *node))
        .collect::<HashMap<_, _>>();
    let blocks_by_end = input_nodes
        .iter()
        .map(|node| ((node.node_id, node.sequence_end), *node))
        .collect::<HashMap<_, _>>();

    for augmented_edge in input_edges {
        // Edit-site marker edges preserve coordinates for later graph
        // operations. They are not path choices, so rendering them as diff
        // edges makes inserted/deleted sequence look unchanged.
        if augmented_edge.chromosome_index == PRESERVE_EDIT_SITE_CHROMOSOME_INDEX {
            continue;
        }
        let source_node = blocks_by_end
            .get(&(
                augmented_edge.edge.source_node_id,
                augmented_edge.edge.source_coordinate,
            ))
            .copied();
        let target_node = blocks_by_start
            .get(&(
                augmented_edge.edge.target_node_id,
                augmented_edge.edge.target_coordinate,
            ))
            .copied();
        if let (Some(source_node), Some(target_node)) = (source_node, target_node) {
            let graph_edge = GraphEdge {
                edge_id: augmented_edge.edge.id,
                source_strand: augmented_edge.edge.source_strand,
                target_strand: augmented_edge.edge.target_strand,
                chromosome_index: augmented_edge.chromosome_index,
                phased: augmented_edge.phased,
                created_on: augmented_edge.created_on,
            };
            if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
                existing_edges.push(graph_edge);
            } else {
                graph.add_edge(source_node, target_node, vec![graph_edge]);
            }
            edge_metadata.insert(
                GraphEdgeKey::new(source_node, target_node, graph_edge),
                DiffInputEdgeMetadata {
                    change: edge_operations_by_id
                        .get(&graph_edge.edge_id)
                        .map_or_else(DiffChange::unchanged, |operation| {
                            DiffChange::new(DiffChangeKind::Modified, Some(*operation))
                        }),
                    origin: EdgeOrigin::Explicit,
                },
            );
        }
    }

    add_continuation_edges(
        &input_nodes,
        continuation_spans,
        &mut graph,
        &mut edge_metadata,
    );
    remove_unconnected_input_nodes(&mut graph, &mut node_changes);

    DiffInputGraph {
        graph,
        node_changes,
        edge_metadata,
    }
}

/// Returns the canonical start terminal used in every input and unified graph.
///
/// The input builder and graph-layout tests use this shared value so endpoint
/// graphs remain connected to the same synthetic path boundary.
pub(crate) fn path_start_graph_node() -> GraphNode {
    GraphNode {
        node_id: PATH_START_NODE_ID,
        sequence_start: 0,
        sequence_end: 0,
    }
}

/// Returns the canonical end terminal used in every input and unified graph.
///
/// The input builder and graph-layout tests use this shared value so endpoint
/// graphs remain connected to the same synthetic path boundary.
pub(crate) fn path_end_graph_node() -> GraphNode {
    GraphNode {
        node_id: PATH_END_NODE_ID,
        sequence_start: 0,
        sequence_end: 0,
    }
}

/// Reconnects normalized slices that came from one continuous endpoint span.
///
/// `build_diff_input_graph` invokes this after mapping explicit edges.
/// It adds neutral synthetic edges only between adjacent slices covered by the
/// same original span, preserving renderable connectivity without bridging
/// genuine deletions or endpoint gaps.
fn add_continuation_edges(
    input_nodes: &HashSet<GraphNode>,
    continuation_spans: &HashSet<GraphNode>,
    graph: &mut GenGraph,
    edge_metadata: &mut HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
) {
    for span in continuation_spans {
        // Delayed block construction starts from the endpoint edges and keeps
        // each endpoint's real covered spans separate before splitting them
        // into display nodes. Add neutral continuation edges only inside a
        // span that exists in this endpoint:
        //
        //   endpoint span [0..10] split to [0..3] [3..4] [4..10]
        //     add grey continuations 0..3 -> 3..4 -> 4..10
        //
        //   endpoint spans [0..3] and [4..10]
        //     do not synthesize 0..3 -> 3..4 -> 4..10
        //
        // This is the point where the graph knows enough to split display
        // nodes without asking a second question about whether a boundary came
        // from the source or target path.
        if is_terminal(span.node_id) || span.sequence_start == span.sequence_end {
            continue;
        }
        let mut nodes = input_nodes
            .iter()
            .copied()
            .filter(|node| {
                node.node_id == span.node_id
                    && node.sequence_start >= span.sequence_start
                    && node.sequence_end <= span.sequence_end
            })
            .collect::<Vec<_>>();
        nodes.sort_by_key(|node| (node.sequence_start, node.sequence_end));
        for window in nodes.windows(2) {
            let source_node = window[0];
            let target_node = window[1];
            if source_node.sequence_end != target_node.sequence_start {
                continue;
            }
            let synthetic_edge = GraphEdge {
                edge_id: HashId::convert_str(&format!(
                    "diff-continuation:{}:{}:{}:{}:{}",
                    span.node_id,
                    source_node.sequence_start,
                    source_node.sequence_end,
                    target_node.sequence_start,
                    target_node.sequence_end
                )),
                source_strand: Strand::Forward,
                target_strand: Strand::Forward,
                chromosome_index: NO_CHROMOSOME_INDEX,
                phased: 0,
                created_on: 0,
            };
            if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
                if existing_edges.contains(&synthetic_edge) {
                    continue;
                }
                existing_edges.push(synthetic_edge);
            } else {
                graph.add_edge(source_node, target_node, vec![synthetic_edge]);
            }
            edge_metadata.insert(
                GraphEdgeKey::new(source_node, target_node, synthetic_edge),
                DiffInputEdgeMetadata {
                    change: DiffChange::unchanged(),
                    origin: EdgeOrigin::Continuation,
                },
            );
        }
    }
}

/// Removes non-terminal slices that no mapped or continuation edge reaches.
///
/// `build_diff_input_graph` uses this cleanup after edge construction.
/// Coordinate normalization can produce candidate slices unsupported by actual
/// endpoint topology; pruning them keeps the unified graph from displaying
/// isolated artifacts while retaining terminal anchors.
fn remove_unconnected_input_nodes(
    graph: &mut GenGraph,
    node_changes: &mut HashMap<GraphNode, DiffChange>,
) {
    let mut connected_nodes = HashSet::new();
    for (source, target, _) in graph.all_edges() {
        connected_nodes.insert(source);
        connected_nodes.insert(target);
    }
    let disconnected_nodes = graph
        .nodes()
        .filter(|node| !is_terminal(node.node_id) && !connected_nodes.contains(node))
        .collect::<Vec<_>>();
    for node in disconnected_nodes {
        graph.remove_node(node);
        node_changes.remove(&node);
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
pub(crate) struct GraphEdgeKey {
    source: GraphNode,
    target: GraphNode,
    edge_id: HashId,
    source_strand: Strand,
    target_strand: Strand,
    chromosome_index: i64,
    phased: i64,
}

impl GraphEdgeKey {
    /// Creates the stable edge identity used to union and annotate endpoint graphs.
    ///
    /// Input construction and continuation-edge insertion use this key instead
    /// of the full stored record so volatile `created_on` metadata does not
    /// turn an otherwise identical connection into a structural diff.
    pub(crate) fn new(source: GraphNode, target: GraphNode, edge: GraphEdge) -> Self {
        Self {
            source,
            target,
            edge_id: edge.edge_id,
            source_strand: edge.source_strand,
            target_strand: edge.target_strand,
            chromosome_index: edge.chromosome_index,
            phased: edge.phased,
        }
    }

    /// Tests whether a concrete edge has the structural identity represented by this key.
    ///
    /// `DiffInputGraph::edge` uses this after selecting a node pair because a
    /// `GenGraph` edge weight may contain multiple parallel edges.
    fn matches_edge(self, edge: GraphEdge) -> bool {
        self.edge_id == edge.edge_id
            && self.source_strand == edge.source_strand
            && self.target_strand == edge.target_strand
            && self.chromosome_index == edge.chromosome_index
            && self.phased == edge.phased
    }
}

struct BlockGroupComparison {
    source_block_group: Option<BlockGroup>,
    target_block_group: Option<BlockGroup>,
    graph: DiffGenGraph,
}

pub(crate) struct DiffInputGraph {
    graph: GenGraph,
    node_changes: HashMap<GraphNode, DiffChange>,
    edge_metadata: HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
}

/// Keeps an edge's displayed change separate from why the input contains it.
///
/// Stores an input edge's change annotation and origin. During comparison,
/// the origin tells us whether to mark a missing explicit edge as added or
/// removed, or leave a synthetic continuation unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct DiffInputEdgeMetadata {
    change: DiffChange,
    origin: EdgeOrigin,
}

impl DiffInputGraph {
    /// Iterates over the graph nodes present in this endpoint.
    fn nodes(&self) -> impl Iterator<Item = GraphNode> + '_ {
        self.node_changes.keys().copied()
    }

    /// Returns this endpoint's annotation for a node when it is present.
    fn node_change(&self, node: GraphNode) -> Option<DiffChange> {
        self.node_changes.get(&node).copied()
    }

    /// Iterates over stable edge keys and their input metadata.
    fn edges(&self) -> impl Iterator<Item = (GraphEdgeKey, DiffInputEdgeMetadata)> + '_ {
        self.edge_metadata
            .iter()
            .map(|(edge_key, metadata)| (*edge_key, *metadata))
    }

    /// Returns this endpoint's metadata for an edge when it is present.
    fn edge_metadata(&self, edge_key: GraphEdgeKey) -> Option<DiffInputEdgeMetadata> {
        self.edge_metadata.get(&edge_key).copied()
    }

    /// Returns the concrete graph edge represented by a stable key.
    fn edge(&self, edge_key: GraphEdgeKey) -> Option<GraphEdge> {
        self.graph
            .edge_weight(edge_key.source, edge_key.target)?
            .iter()
            .copied()
            .find(|edge| edge_key.matches_edge(*edge))
    }
}

#[cfg(test)]
impl DiffInputGraph {
    /// Exposes input topology to reconstruction tests without exposing its maps.
    pub(crate) const fn graph(&self) -> &GenGraph {
        &self.graph
    }
}

#[derive(Debug, Default)]
struct InputOperationChangeLookup {
    source_node_operation_by_id: HashMap<HashId, DoltHashId>,
    target_node_operation_by_id: HashMap<HashId, DoltHashId>,
    source_edge_operation_by_id: HashMap<HashId, DoltHashId>,
    target_edge_operation_by_id: HashMap<HashId, DoltHashId>,
}

#[cfg(test)]
mod tests {
    use gen_models::edge::Edge;

    use super::*;

    fn topology_test_edge(source: HashId, target: HashId, source_coordinate: i64) -> AugmentedEdge {
        AugmentedEdge {
            edge: Edge {
                id: HashId::convert_str(&format!("{source}-{source_coordinate}-{target}")),
                source_node_id: source,
                source_coordinate,
                source_strand: Strand::Forward,
                target_node_id: target,
                target_coordinate: 0,
                target_strand: Strand::Forward,
            },
            chromosome_index: 0,
            phased: 0,
            created_on: 0,
        }
    }

    #[test]
    fn test_tracks_added_edge() {
        // Simple graph like
        // source -> {a,b} -> end
        // adds a connection where a->b. Ensure we can track that new edge.
        let node_a = HashId::convert_str("topology-a");
        let node_b = HashId::convert_str("topology-b");
        // Only the base includes the extra A -> B connection.
        let query_edges = vec![
            topology_test_edge(PATH_START_NODE_ID, node_a, 0),
            topology_test_edge(node_a, PATH_END_NODE_ID, 10),
            topology_test_edge(PATH_START_NODE_ID, node_b, 0),
            topology_test_edge(node_b, PATH_END_NODE_ID, 10),
        ];
        let connection = topology_test_edge(node_a, node_b, 10);
        let mut base_edges = query_edges.clone();
        base_edges.push(connection.clone());
        for (base, query, expected) in [
            (&base_edges, &query_edges, DiffChangeKind::Removed),
            (&query_edges, &base_edges, DiffChangeKind::Added),
        ] {
            let graph = build_diff_graph_from_edges(
                EdgeDiffInput::unattributed(base),
                EdgeDiffInput::unattributed(query),
                None,
            );
            assert!(
                graph
                    .nodes()
                    .all(|node| node.change.kind == DiffChangeKind::Unchanged)
            );
            let change = graph
                .all_edges()
                .flat_map(|(_, _, edges)| edges)
                .find(|edge| edge.edge.edge_id == connection.edge.id)
                .expect("should retain the differing explicit connection")
                .change;
            assert_eq!(
                change.kind, expected,
                "explicit membership must determine edge changes even when both nodes survive"
            );
            assert_eq!(change.operation, None);
        }
    }

    #[test]
    fn test_tracks_chromosome_index_changes_for_diploids() {
        // Simple graph: source -> a -> end.
        // One input has two source -> a edges, one per chromosome.
        // Ensure the extra edge is Added/Removed while the shared edge stays unchanged.
        let node = HashId::convert_str("parallel-node");
        let query_edges = vec![
            topology_test_edge(PATH_START_NODE_ID, node, 0),
            topology_test_edge(node, PATH_END_NODE_ID, 10),
        ];
        let mut parallel = query_edges[0].clone();
        parallel.chromosome_index = 1;
        let mut base_edges = query_edges.clone();
        base_edges.push(parallel);
        for (base, query, expected) in [
            (&base_edges, &query_edges, DiffChangeKind::Removed),
            (&query_edges, &base_edges, DiffChangeKind::Added),
        ] {
            let graph = build_diff_graph_from_edges(
                EdgeDiffInput::unattributed(base),
                EdgeDiffInput::unattributed(query),
                None,
            );
            let parallel_change = graph
                .all_edges()
                .flat_map(|(_, _, edges)| edges)
                .find(|edge| edge.edge.chromosome_index == 1)
                .expect("should retain the differing parallel edge")
                .change;
            assert_eq!(
                parallel_change.kind, expected,
                "parallel membership differences must remain visible alongside shared edges"
            );
            assert_eq!(parallel_change.operation, None);
            let shared_change = graph
                .all_edges()
                .flat_map(|(_, _, edges)| edges)
                .find(|edge| {
                    edge.edge.edge_id == query_edges[0].edge.id
                        && edge.edge.chromosome_index == query_edges[0].chromosome_index
                })
                .expect("should retain the shared parallel edge")
                .change;
            assert_eq!(shared_change.kind, DiffChangeKind::Unchanged);
            assert_eq!(shared_change.operation, None);
        }
    }

    #[test]
    fn test_operation_attribution() {
        // Simple graph: source -> {a,b} -> end.
        // The query adds a -> b with an associated operation.
        // Ensure the new edge is Added and retains that operation.
        let node_a = HashId::convert_str("attributed-topology-a");
        let node_b = HashId::convert_str("attributed-topology-b");
        let base_edges = vec![
            topology_test_edge(PATH_START_NODE_ID, node_a, 0),
            topology_test_edge(node_a, PATH_END_NODE_ID, 10),
            topology_test_edge(PATH_START_NODE_ID, node_b, 0),
            topology_test_edge(node_b, PATH_END_NODE_ID, 10),
        ];
        let connection = topology_test_edge(node_a, node_b, 10);
        let mut query_edges = base_edges.clone();
        query_edges.push(connection.clone());
        let operation = DoltHashId([9; 20]);
        let edge_operations = HashMap::from([(connection.edge.id, operation)]);
        let graph = build_diff_graph_from_edges(
            EdgeDiffInput::unattributed(&base_edges)
                .with_attribution(&HashMap::new(), &HashMap::new()),
            EdgeDiffInput::unattributed(&query_edges)
                .with_attribution(&HashMap::new(), &edge_operations),
            None,
        );
        let change = graph
            .all_edges()
            .flat_map(|(_, _, edges)| edges)
            .find(|edge| edge.edge.edge_id == connection.edge.id)
            .expect("should retain the added explicit connection")
            .change;
        assert_eq!(change.kind, DiffChangeKind::Added);
        assert_eq!(change.operation, Some(operation));
    }

    #[test]
    fn test_continuation_is_neutral() {
        // One input:   source -> a[0..10] -> end
        // Other input: source -> {a[0..5], a[5..10]} -> end
        // Normalization splits the continuous span and connects a[0..5] -> a[5..10].
        // Ensure this synthetic connection stays neutral in either comparison direction.
        let node = HashId::convert_str("continuation-node");
        let continuous_edges = vec![
            topology_test_edge(PATH_START_NODE_ID, node, 0),
            topology_test_edge(node, PATH_END_NODE_ID, 10),
        ];
        let split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
        let split_end = topology_test_edge(node, PATH_END_NODE_ID, 5);
        let mut second_split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
        second_split_start.edge.id = HashId::convert_str("continuation-second-start");
        second_split_start.edge.target_coordinate = 5;
        let second_split_end = topology_test_edge(node, PATH_END_NODE_ID, 10);
        let split_edges = vec![split_start, split_end, second_split_start, second_split_end];
        let first_slice = GraphNode {
            node_id: node,
            sequence_start: 0,
            sequence_end: 5,
        };
        let second_slice = GraphNode {
            node_id: node,
            sequence_start: 5,
            sequence_end: 10,
        };

        for (base, query) in [
            (&continuous_edges, &split_edges),
            (&split_edges, &continuous_edges),
        ] {
            let graph = build_diff_graph_from_edges(
                EdgeDiffInput::unattributed(base),
                EdgeDiffInput::unattributed(query),
                None,
            );
            let continuation_edges = graph
                .all_edges()
                .find_map(|(source, target, edges)| {
                    (source.node == first_slice && target.node == second_slice).then_some(edges)
                })
                .expect("should retain the normalization continuation");
            assert!(
                continuation_edges
                    .iter()
                    .all(|edge| edge.change.kind == DiffChangeKind::Unchanged)
            );
            assert!(
                continuation_edges
                    .iter()
                    .all(|edge| edge.change.operation.is_none())
            );
        }
    }

    fn block_group(id: i64) -> BlockGroup {
        BlockGroup {
            id: HashId::pad_str(id),
            collection_name: "collection".to_string(),
            sample_name: "sample".to_string(),
            name: "block-group".to_string(),
            created_on: 0,
            parent_block_group_id: None,
            is_default: false,
        }
    }

    #[test]
    fn test_block_group_change_kind_is_derived_from_endpoint_membership() {
        let block_group = block_group(1);
        let block_group_id = block_group.id;
        let diff = |source_block_group, target_block_group| BlockGroupDiff {
            id: block_group_id,
            source_block_group,
            target_block_group,
            graph: DiffGenGraph::new(),
        };

        assert_eq!(
            diff(None, Some(block_group.clone())).change_kind(),
            Some(BlockGroupChangeKind::Added)
        );
        assert_eq!(
            diff(Some(block_group.clone()), None).change_kind(),
            Some(BlockGroupChangeKind::Removed)
        );
        assert_eq!(
            diff(Some(block_group.clone()), Some(block_group)).change_kind(),
            Some(BlockGroupChangeKind::Modified)
        );
        assert_eq!(diff(None, None).change_kind(), None);
    }

    #[test]
    fn test_split_nodes_at_shared_boundaries_exposes_removed_slice() {
        let node_id = HashId::convert_str("reference-node");
        let source_spans = HashSet::from([GraphNode {
            node_id,
            sequence_start: 0,
            sequence_end: 10,
        }]);
        let target_spans = HashSet::from([
            GraphNode {
                node_id,
                sequence_start: 0,
                sequence_end: 3,
            },
            GraphNode {
                node_id,
                sequence_start: 5,
                sequence_end: 10,
            },
        ]);

        let (source_nodes, target_nodes) =
            split_nodes_at_shared_boundaries(&source_spans, &target_spans);
        let removed_slice = GraphNode {
            node_id,
            sequence_start: 3,
            sequence_end: 5,
        };

        assert_eq!(
            source_nodes,
            HashSet::from([
                GraphNode {
                    node_id,
                    sequence_start: 0,
                    sequence_end: 3,
                },
                removed_slice,
                GraphNode {
                    node_id,
                    sequence_start: 5,
                    sequence_end: 10,
                },
            ])
        );
        assert_eq!(target_nodes, target_spans);
        assert!(source_nodes.contains(&removed_slice));
        assert!(!target_nodes.contains(&removed_slice));
    }

    #[test]
    fn diff_graph_to_gen_graph_maps_nodes_and_edges() {
        let node_a = DiffGraphNode {
            node: GraphNode {
                node_id: HashId::pad_str(1),
                sequence_start: 0,
                sequence_end: 5,
            },
            change: DiffChange {
                kind: DiffChangeKind::Added,
                operation: Some(DoltHashId([10; 20])),
            },
        };
        let node_b = DiffGraphNode {
            node: GraphNode {
                node_id: HashId::pad_str(2),
                sequence_start: 5,
                sequence_end: 10,
            },
            change: DiffChange::unchanged(),
        };
        let mut diff_graph = DiffGenGraph::new();
        diff_graph.add_node(node_a);
        diff_graph.add_node(node_b);
        let edge = DiffGraphEdge {
            edge: GraphEdge {
                edge_id: HashId::pad_str(9),
                source_strand: Strand::Forward,
                target_strand: Strand::Forward,
                chromosome_index: 0,
                phased: 0,
                created_on: 0,
            },
            change: DiffChange {
                kind: DiffChangeKind::Added,
                operation: Some(DoltHashId([10; 20])),
            },
        };
        diff_graph.add_edge(node_a, node_b, vec![edge]);

        let graph: GenGraph = DiffGenGraphRef(&diff_graph).into();
        assert_eq!(graph.nodes().count(), 2);
        assert_eq!(graph.all_edges().count(), 1);
        let weights = graph
            .all_edges()
            .next()
            .map(|(_, _, edges)| edges.clone())
            .expect("graph edge");
        assert_eq!(weights, vec![edge.edge]);
    }
}