1use std::collections::{HashMap, HashSet};
93
94use gen_core::{
95 DoltHashId, HashId, NO_CHROMOSOME_INDEX, PATH_END_NODE_ID, PATH_START_NODE_ID,
96 PRESERVE_EDIT_SITE_CHROMOSOME_INDEX, Strand, is_terminal,
97};
98use gen_graph::{GenGraph, GraphEdge, GraphNode};
99use gen_models::{
100 block_group::BlockGroup,
101 block_group_edge::{AugmentedEdge, BlockGroupEdge},
102 db::GraphConnection,
103};
104use petgraph::graphmap::DiGraphMap;
105
106use crate::operations::{BlockGroupEdgeChange, BlockGroupEdgeKey, NodeChange, OperationDiffError};
107
108#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
109pub enum DiffChangeKind {
110 Unchanged,
111 Added,
112 Removed,
113 Modified,
114}
115
116#[derive(Clone, Copy, Debug, Eq, PartialEq)]
123enum EdgeOrigin {
124 Explicit,
126 Continuation,
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
131pub struct DiffChange {
132 pub kind: DiffChangeKind,
133 pub operation: Option<DoltHashId>,
134}
135
136impl DiffChange {
137 pub const fn unchanged() -> Self {
142 Self {
143 kind: DiffChangeKind::Unchanged,
144 operation: None,
145 }
146 }
147
148 pub const fn new(kind: DiffChangeKind, operation: Option<DoltHashId>) -> Self {
153 Self { kind, operation }
154 }
155
156 pub fn operation_or(self, default_operation: DoltHashId) -> DoltHashId {
161 self.operation.unwrap_or(default_operation)
162 }
163}
164
165#[derive(Clone, Debug)]
166pub struct BlockGroupDiff {
167 pub id: HashId,
168 pub source_block_group: Option<BlockGroup>,
169 pub target_block_group: Option<BlockGroup>,
170 pub graph: DiffGenGraph,
171}
172
173#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
179pub enum BlockGroupChangeKind {
180 Added,
181 Removed,
182 Modified,
183}
184
185impl BlockGroupDiff {
186 pub const fn change_kind(&self) -> Option<BlockGroupChangeKind> {
193 match (
194 self.source_block_group.is_some(),
195 self.target_block_group.is_some(),
196 ) {
197 (false, true) => Some(BlockGroupChangeKind::Added),
198 (true, false) => Some(BlockGroupChangeKind::Removed),
199 (true, true) => Some(BlockGroupChangeKind::Modified),
200 (false, false) => None,
201 }
202 }
203}
204
205#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
206pub struct DiffGraphNode {
207 pub node: GraphNode,
208 pub change: DiffChange,
209}
210
211#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
212pub struct DiffGraphEdge {
213 pub edge: GraphEdge,
214 pub change: DiffChange,
215}
216
217pub type DiffGenGraph = DiGraphMap<DiffGraphNode, Vec<DiffGraphEdge>>;
218
219pub struct DiffGenGraphRef<'a>(pub &'a DiffGenGraph);
220
221impl<'a> From<&'a DiffGenGraph> for DiffGenGraphRef<'a> {
222 fn from(graph: &'a DiffGenGraph) -> Self {
227 Self(graph)
228 }
229}
230
231impl<'a> From<DiffGenGraphRef<'a>> for GenGraph {
232 fn from(val: DiffGenGraphRef<'a>) -> Self {
238 let mut graph = GenGraph::new();
239 for node in val.0.nodes() {
240 graph.add_node(node.node);
241 }
242 for (src, dest, edges) in val.0.all_edges() {
243 let mapped_edges = edges.iter().map(|edge| edge.edge).collect::<Vec<_>>();
244 graph.add_edge(src.node, dest.node, mapped_edges);
245 }
246 graph
247 }
248}
249
250impl From<DiffGraphNode> for GraphNode {
251 fn from(node: DiffGraphNode) -> Self {
256 node.node
257 }
258}
259
260impl From<DiffGraphEdge> for GraphEdge {
261 fn from(edge: DiffGraphEdge) -> Self {
266 edge.edge
267 }
268}
269
270pub(crate) struct BlockGroupDiffInputs<'a> {
271 pub(crate) source_ref: &'a str,
272 pub(crate) target_ref: &'a str,
273 pub(crate) default_operation: DoltHashId,
274 pub(crate) edge_changes_by_block_group: &'a HashMap<HashId, Vec<BlockGroupEdgeChange>>,
275 pub(crate) block_group_operations_by_id: &'a HashMap<HashId, HashSet<DoltHashId>>,
276 pub(crate) node_changes: &'a [NodeChange],
277}
278
279pub(crate) struct EdgeDiffInput<'a> {
281 edges: &'a [AugmentedEdge],
282 spans: HashSet<GraphNode>,
283 node_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
284 edge_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
285}
286
287impl<'a> EdgeDiffInput<'a> {
288 pub(crate) fn unattributed(edges: &'a [AugmentedEdge]) -> Self {
290 Self {
291 edges,
292 spans: spans_from_edges(edges),
293 node_operations_by_id: None,
294 edge_operations_by_id: None,
295 }
296 }
297
298 pub(crate) fn with_attribution(
300 mut self,
301 node_operations_by_id: &'a HashMap<HashId, DoltHashId>,
302 edge_operations_by_id: &'a HashMap<HashId, DoltHashId>,
303 ) -> Self {
304 self.node_operations_by_id = Some(node_operations_by_id);
305 self.edge_operations_by_id = Some(edge_operations_by_id);
306 self
307 }
308
309 pub(crate) fn spans(&self) -> &HashSet<GraphNode> {
311 &self.spans
312 }
313}
314
315pub(crate) fn build_block_group_diff(
322 graph_conn: &GraphConnection,
323 block_group_id: HashId,
324 inputs: &BlockGroupDiffInputs<'_>,
325) -> Result<Option<BlockGroupDiff>, OperationDiffError> {
326 let Some(comparison) = build_block_group_comparison(graph_conn, block_group_id, inputs)? else {
327 return Ok(None);
328 };
329 if !diff_graph_has_changes(&comparison.graph)
330 && comparison.source_block_group.is_some()
331 && comparison.target_block_group.is_some()
332 {
333 return Ok(None);
334 }
335
336 Ok(Some(BlockGroupDiff {
337 id: block_group_id,
338 source_block_group: comparison.source_block_group,
339 target_block_group: comparison.target_block_group,
340 graph: comparison.graph,
341 }))
342}
343
344fn build_block_group_comparison(
352 graph_conn: &GraphConnection,
353 block_group_id: HashId,
354 inputs: &BlockGroupDiffInputs<'_>,
355) -> Result<Option<BlockGroupComparison>, OperationDiffError> {
356 let target_block_group =
357 BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.target_ref)).ok();
358 let source_block_group =
359 BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.source_ref)).ok();
360 if source_block_group.is_none() && target_block_group.is_none() {
361 return Ok(None);
362 }
363 let source_parent_block_group_id = target_block_group
367 .as_ref()
368 .and_then(|block_group| block_group.parent_block_group_id);
369 let target_parent_block_group_id = source_block_group
370 .as_ref()
371 .and_then(|block_group| block_group.parent_block_group_id);
372 let source_effective_block_group_id = source_block_group
373 .as_ref()
374 .map(|block_group| block_group.id)
375 .or(source_parent_block_group_id);
376 let target_effective_block_group_id = target_block_group
377 .as_ref()
378 .map(|block_group| block_group.id)
379 .or(target_parent_block_group_id);
380 let source_effective_history_ref = if source_block_group.is_some() {
385 Some(inputs.source_ref)
386 } else {
387 Some(inputs.target_ref)
388 };
389 let target_effective_history_ref = if target_block_group.is_some() {
390 Some(inputs.target_ref)
391 } else {
392 Some(inputs.source_ref)
393 };
394 let source_edges = load_block_group_edges(
413 graph_conn,
414 source_effective_block_group_id,
415 source_effective_history_ref,
416 );
417 let raw_block_group_edge_changes = inputs
418 .edge_changes_by_block_group
419 .get(&block_group_id)
420 .map(Vec::as_slice)
421 .unwrap_or(&[]);
422 let block_group_edge_changes =
423 effective_edge_changes_for_source(&source_edges, raw_block_group_edge_changes);
424 let target_edges = load_block_group_edges(
425 graph_conn,
426 target_effective_block_group_id,
427 target_effective_history_ref,
428 );
429 let source_input = EdgeDiffInput::unattributed(&source_edges);
430 let target_input = EdgeDiffInput::unattributed(&target_edges);
431 let operation_change_lookup = collect_input_operation_changes(
432 block_group_id,
433 inputs,
434 &block_group_edge_changes,
435 source_input.spans(),
436 target_input.spans(),
437 );
438 let graph = build_diff_graph_from_edges(
439 source_input.with_attribution(
440 &operation_change_lookup.source_node_operation_by_id,
441 &operation_change_lookup.source_edge_operation_by_id,
442 ),
443 target_input.with_attribution(
444 &operation_change_lookup.target_node_operation_by_id,
445 &operation_change_lookup.target_edge_operation_by_id,
446 ),
447 Some(inputs.default_operation),
448 );
449
450 Ok(Some(BlockGroupComparison {
451 source_block_group,
452 target_block_group,
453 graph,
454 }))
455}
456
457fn load_block_group_edges(
463 graph_conn: &GraphConnection,
464 block_group_id: Option<HashId>,
465 history_ref: Option<&str>,
466) -> Vec<AugmentedEdge> {
467 block_group_id.map_or_else(Vec::new, |block_group_id| {
468 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group_id, history_ref)
469 })
470}
471
472pub(crate) fn build_diff_graph_from_edges(
479 base: EdgeDiffInput<'_>,
480 query: EdgeDiffInput<'_>,
481 default_operation: Option<DoltHashId>,
482) -> DiffGenGraph {
483 let (base_nodes, query_nodes) = split_nodes_at_shared_boundaries(base.spans(), query.spans());
484 let no_operations = HashMap::new();
487 let base_graph = build_diff_input_graph(
488 base_nodes,
489 base.spans(),
490 base.edges,
491 base.node_operations_by_id.unwrap_or(&no_operations),
492 base.edge_operations_by_id.unwrap_or(&no_operations),
493 );
494 let query_graph = build_diff_input_graph(
495 query_nodes,
496 query.spans(),
497 query.edges,
498 query.node_operations_by_id.unwrap_or(&no_operations),
499 query.edge_operations_by_id.unwrap_or(&no_operations),
500 );
501 build_unified_diff_graph(&base_graph, &query_graph, default_operation)
502}
503
504fn spans_from_edges(edges: &[AugmentedEdge]) -> HashSet<GraphNode> {
509 let mut starts_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
524 let mut ends_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
525 for edge in edges.iter().map(|edge| &edge.edge) {
526 if !is_terminal(edge.source_node_id) {
527 ends_by_node_id
528 .entry(edge.source_node_id)
529 .or_default()
530 .insert(edge.source_coordinate);
531 }
532 if !is_terminal(edge.target_node_id) {
533 starts_by_node_id
534 .entry(edge.target_node_id)
535 .or_default()
536 .insert(edge.target_coordinate);
537 }
538 }
539
540 let mut node_ids = starts_by_node_id.keys().copied().collect::<HashSet<_>>();
541 node_ids.extend(ends_by_node_id.keys().copied());
542 let mut spans = HashSet::new();
543 for node_id in node_ids {
544 let empty_starts = HashSet::new();
545 let empty_ends = HashSet::new();
546 let starts = starts_by_node_id.get(&node_id).unwrap_or(&empty_starts);
547 let ends = ends_by_node_id.get(&node_id).unwrap_or(&empty_ends);
548 for (sequence_start, sequence_end) in coordinate_spans(starts, ends) {
549 spans.insert(GraphNode {
550 node_id,
551 sequence_start,
552 sequence_end,
553 });
554 }
555 }
556 spans
557}
558
559fn coordinate_spans(starts: &HashSet<i64>, ends: &HashSet<i64>) -> Vec<(i64, i64)> {
566 let mut coordinates = starts.union(ends).copied().collect::<Vec<_>>();
567 coordinates.sort();
568 coordinates.dedup();
569 if coordinates.len() <= 1 {
570 return coordinates
571 .first()
572 .copied()
573 .map(|coordinate| vec![(coordinate, coordinate)])
574 .unwrap_or_default();
575 }
576 coordinates
577 .windows(2)
578 .map(|window| (window[0], window[1]))
579 .collect()
580}
581
582fn split_nodes_at_shared_boundaries(
589 source_spans: &HashSet<GraphNode>,
590 target_spans: &HashSet<GraphNode>,
591) -> (HashSet<GraphNode>, HashSet<GraphNode>) {
592 let boundaries_by_node_id = collect_shared_boundaries(source_spans, target_spans);
593 (
594 split_spans_at_boundaries(source_spans, &boundaries_by_node_id),
595 split_spans_at_boundaries(target_spans, &boundaries_by_node_id),
596 )
597}
598
599fn collect_shared_boundaries(
605 source_spans: &HashSet<GraphNode>,
606 target_spans: &HashSet<GraphNode>,
607) -> HashMap<HashId, HashSet<i64>> {
608 let mut boundaries_by_node_id = HashMap::new();
609 for span in source_spans.iter().chain(target_spans) {
610 let boundaries = boundaries_by_node_id
611 .entry(span.node_id)
612 .or_insert_with(HashSet::new);
613 boundaries.insert(span.sequence_start);
614 boundaries.insert(span.sequence_end);
615 }
616 boundaries_by_node_id
617}
618
619fn split_spans_at_boundaries(
626 spans: &HashSet<GraphNode>,
627 boundaries_by_node_id: &HashMap<HashId, HashSet<i64>>,
628) -> HashSet<GraphNode> {
629 let mut nodes = HashSet::new();
630 for span in spans {
631 if span.sequence_start == span.sequence_end {
647 nodes.insert(*span);
648 continue;
649 }
650 let mut boundaries = boundaries_by_node_id
651 .get(&span.node_id)
652 .into_iter()
653 .flat_map(|boundaries| boundaries.iter())
654 .filter(|coordinate| {
655 **coordinate >= span.sequence_start && **coordinate <= span.sequence_end
656 })
657 .copied()
658 .collect::<Vec<_>>();
659 boundaries.sort();
660 boundaries.dedup();
661 if boundaries.len() < 2 {
662 nodes.insert(*span);
663 continue;
664 }
665 for window in boundaries.windows(2) {
666 let sequence_start = window[0];
667 let sequence_end = window[1];
668 if sequence_start == sequence_end {
669 continue;
670 }
671 nodes.insert(GraphNode {
672 node_id: span.node_id,
673 sequence_start,
674 sequence_end,
675 });
676 }
677 }
678 nodes
679}
680
681fn effective_edge_changes_for_source(
688 source_edges: &[AugmentedEdge],
689 edge_changes: &[BlockGroupEdgeChange],
690) -> Vec<BlockGroupEdgeChange> {
691 let source_edge_keys = source_edges
692 .iter()
693 .map(BlockGroupEdgeKey::from)
694 .collect::<HashSet<_>>();
695 edge_changes
696 .iter()
697 .copied()
698 .filter(
699 |edge_change| match (edge_change.old_key, edge_change.new_key) {
700 (None, Some(new_key)) => !source_edge_keys.contains(&new_key),
701 (Some(old_key), None) => source_edge_keys.contains(&old_key),
702 (Some(old_key), Some(new_key)) => {
703 source_edge_keys.contains(&old_key) || !source_edge_keys.contains(&new_key)
704 }
705 (None, None) => false,
706 },
707 )
708 .collect()
709}
710
711fn collect_input_operation_changes(
717 block_group_id: HashId,
718 inputs: &BlockGroupDiffInputs<'_>,
719 changed_edge_ids: &[BlockGroupEdgeChange],
720 source_spans: &HashSet<GraphNode>,
721 target_spans: &HashSet<GraphNode>,
722) -> InputOperationChangeLookup {
723 let mut change_lookup = InputOperationChangeLookup::default();
724 let Some(block_group_operations) = inputs.block_group_operations_by_id.get(&block_group_id)
725 else {
726 return change_lookup;
727 };
728 let source_node_ids = span_node_ids(source_spans);
729 let target_node_ids = span_node_ids(target_spans);
730 for node_change in inputs.node_changes {
731 if let (Some(old_node_id), Some(operation)) =
732 (node_change.old_node_id(), node_change.old_operation())
733 && block_group_operations.contains(&operation)
734 && source_node_ids.contains(&old_node_id)
735 && !target_node_ids.contains(&old_node_id)
736 {
737 change_lookup
738 .source_node_operation_by_id
739 .insert(old_node_id, operation);
740 }
741 if let (Some(new_node_id), Some(operation)) =
742 (node_change.new_node_id(), node_change.new_operation())
743 && block_group_operations.contains(&operation)
744 && target_node_ids.contains(&new_node_id)
745 && !source_node_ids.contains(&new_node_id)
746 {
747 change_lookup
748 .target_node_operation_by_id
749 .insert(new_node_id, operation);
750 }
751 }
752
753 for changed_edge_id in changed_edge_ids {
754 if let (Some(old_edge_id), Some(operation)) = (
755 changed_edge_id.old_edge_id(),
756 changed_edge_id.old_operation(),
757 ) {
758 change_lookup
759 .source_edge_operation_by_id
760 .insert(old_edge_id, operation);
761 }
762 if let (Some(new_edge_id), Some(operation)) = (
763 changed_edge_id.new_edge_id(),
764 changed_edge_id.new_operation(),
765 ) {
766 change_lookup
767 .target_edge_operation_by_id
768 .insert(new_edge_id, operation);
769 }
770 }
771 change_lookup
772}
773
774fn span_node_ids(spans: &HashSet<GraphNode>) -> HashSet<HashId> {
779 spans
780 .iter()
781 .filter(|span| !is_terminal(span.node_id))
782 .map(|span| span.node_id)
783 .collect()
784}
785
786pub(crate) fn build_unified_diff_graph(
793 source_graph: &DiffInputGraph,
794 target_graph: &DiffInputGraph,
795 default_operation: Option<DoltHashId>,
796) -> DiffGenGraph {
797 let merged_nodes = source_graph
798 .nodes()
799 .chain(target_graph.nodes())
800 .collect::<HashSet<_>>();
801
802 let merged_edge_keys = source_graph
803 .edges()
804 .map(|(edge_key, _)| edge_key)
805 .chain(target_graph.edges().map(|(edge_key, _)| edge_key))
806 .collect::<HashSet<_>>();
807 let mut diff_graph = DiffGenGraph::new();
808 for node in merged_nodes {
809 diff_graph.add_node(diff_graph_node(
810 node,
811 source_graph,
812 target_graph,
813 default_operation,
814 ));
815 }
816
817 let mut merged_edges_by_node_pair = HashMap::<(GraphNode, GraphNode), Vec<GraphEdgeKey>>::new();
818 for edge_key in merged_edge_keys {
819 merged_edges_by_node_pair
820 .entry((edge_key.source, edge_key.target))
821 .or_default()
822 .push(edge_key);
823 }
824 let mut merged_edge_pairs = merged_edges_by_node_pair.into_iter().collect::<Vec<_>>();
825 merged_edge_pairs.sort_by_key(|((source, target), _)| (*source, *target));
826 for ((source, target), edge_keys) in merged_edge_pairs {
827 let source_node = diff_graph_node(source, source_graph, target_graph, default_operation);
828 let target_node = diff_graph_node(target, source_graph, target_graph, default_operation);
829 let diff_edges = edge_keys
830 .iter()
831 .copied()
832 .map(|edge_key| DiffGraphEdge {
833 edge: graph_edge_for_key(source_graph, target_graph, edge_key),
834 change: merge_input_edge_changes(
835 source_graph.edge_metadata(edge_key),
836 target_graph.edge_metadata(edge_key),
837 default_operation,
838 ),
839 })
840 .collect::<Vec<_>>();
841 diff_graph.add_edge(source_node, target_node, diff_edges);
842 }
843
844 diff_graph
845}
846
847fn diff_graph_has_changes(graph: &DiffGenGraph) -> bool {
853 graph
854 .nodes()
855 .any(|node| node.change.kind != DiffChangeKind::Unchanged)
856 || graph.all_edges().any(|(_, _, edges)| {
857 edges
858 .iter()
859 .any(|edge| edge.change.kind != DiffChangeKind::Unchanged)
860 })
861}
862
863fn diff_graph_node(
869 node: GraphNode,
870 source_graph: &DiffInputGraph,
871 target_graph: &DiffInputGraph,
872 default_operation: Option<DoltHashId>,
873) -> DiffGraphNode {
874 let source_change = source_graph.node_change(node);
875 let target_change = target_graph.node_change(node);
876 DiffGraphNode {
877 node,
878 change: merge_input_changes(source_change, target_change, default_operation),
879 }
880}
881
882fn graph_edge_for_key(
889 source_graph: &DiffInputGraph,
890 target_graph: &DiffInputGraph,
891 edge_key: GraphEdgeKey,
892) -> GraphEdge {
893 target_graph
894 .edge(edge_key)
895 .or_else(|| source_graph.edge(edge_key))
896 .expect("should contain graph edge for merged diff key")
897}
898
899fn merge_input_changes(
906 source_change: Option<DiffChange>,
907 target_change: Option<DiffChange>,
908 default_operation: Option<DoltHashId>,
909) -> DiffChange {
910 match (source_change, target_change) {
911 (None, None) => DiffChange::unchanged(),
912 (None, Some(change)) => changed(DiffChangeKind::Added, change.operation, default_operation),
913 (Some(change), None) => {
914 changed(DiffChangeKind::Removed, change.operation, default_operation)
915 }
916 (Some(source_change), Some(target_change))
917 if source_change.kind == DiffChangeKind::Removed =>
918 {
919 changed(
920 DiffChangeKind::Removed,
921 source_change.operation.or(target_change.operation),
922 default_operation,
923 )
924 }
925 (Some(source_change), Some(target_change))
926 if target_change.kind == DiffChangeKind::Added =>
927 {
928 changed(
929 DiffChangeKind::Added,
930 target_change.operation.or(source_change.operation),
931 default_operation,
932 )
933 }
934 (Some(source_change), Some(target_change))
935 if source_change.operation.is_some()
936 || target_change.operation.is_some()
937 || source_change.kind != DiffChangeKind::Unchanged
938 || target_change.kind != DiffChangeKind::Unchanged =>
939 {
940 changed(
941 DiffChangeKind::Modified,
942 target_change.operation.or(source_change.operation),
943 default_operation,
944 )
945 }
946 (Some(_), Some(_)) => DiffChange::unchanged(),
947 }
948}
949
950fn merge_input_edge_changes(
956 source_metadata: Option<DiffInputEdgeMetadata>,
957 target_metadata: Option<DiffInputEdgeMetadata>,
958 default_operation: Option<DoltHashId>,
959) -> DiffChange {
960 if source_metadata
961 .into_iter()
962 .chain(target_metadata)
963 .any(|metadata| metadata.origin == EdgeOrigin::Continuation)
964 {
965 return DiffChange::unchanged();
966 }
967 let source_change = source_metadata.map(|metadata| metadata.change);
968 let target_change = target_metadata.map(|metadata| metadata.change);
969 merge_input_changes(source_change, target_change, default_operation)
970}
971
972fn changed(
977 kind: DiffChangeKind,
978 operation: Option<DoltHashId>,
979 default_operation: Option<DoltHashId>,
980) -> DiffChange {
981 DiffChange::new(kind, operation.or(default_operation))
982}
983
984pub(crate) fn build_diff_input_graph(
990 mut input_nodes: HashSet<GraphNode>,
991 continuation_spans: &HashSet<GraphNode>,
992 input_edges: &[AugmentedEdge],
993 node_operations_by_id: &HashMap<HashId, DoltHashId>,
994 edge_operations_by_id: &HashMap<HashId, DoltHashId>,
995) -> DiffInputGraph {
996 let mut graph = GenGraph::new();
997 let mut node_changes = HashMap::new();
998 let mut edge_metadata = HashMap::new();
999
1000 input_nodes.insert(path_start_graph_node());
1001 input_nodes.insert(path_end_graph_node());
1002 for node in &input_nodes {
1003 graph.add_node(*node);
1004 node_changes.insert(
1005 *node,
1006 node_operations_by_id
1007 .get(&node.node_id)
1008 .map_or_else(DiffChange::unchanged, |operation| {
1009 DiffChange::new(DiffChangeKind::Modified, Some(*operation))
1010 }),
1011 );
1012 }
1013
1014 let blocks_by_start = input_nodes
1015 .iter()
1016 .map(|node| ((node.node_id, node.sequence_start), *node))
1017 .collect::<HashMap<_, _>>();
1018 let blocks_by_end = input_nodes
1019 .iter()
1020 .map(|node| ((node.node_id, node.sequence_end), *node))
1021 .collect::<HashMap<_, _>>();
1022
1023 for augmented_edge in input_edges {
1024 if augmented_edge.chromosome_index == PRESERVE_EDIT_SITE_CHROMOSOME_INDEX {
1028 continue;
1029 }
1030 let source_node = blocks_by_end
1031 .get(&(
1032 augmented_edge.edge.source_node_id,
1033 augmented_edge.edge.source_coordinate,
1034 ))
1035 .copied();
1036 let target_node = blocks_by_start
1037 .get(&(
1038 augmented_edge.edge.target_node_id,
1039 augmented_edge.edge.target_coordinate,
1040 ))
1041 .copied();
1042 if let (Some(source_node), Some(target_node)) = (source_node, target_node) {
1043 let graph_edge = GraphEdge {
1044 edge_id: augmented_edge.edge.id,
1045 source_strand: augmented_edge.edge.source_strand,
1046 target_strand: augmented_edge.edge.target_strand,
1047 chromosome_index: augmented_edge.chromosome_index,
1048 phased: augmented_edge.phased,
1049 created_on: augmented_edge.created_on,
1050 };
1051 if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1052 existing_edges.push(graph_edge);
1053 } else {
1054 graph.add_edge(source_node, target_node, vec![graph_edge]);
1055 }
1056 edge_metadata.insert(
1057 GraphEdgeKey::new(source_node, target_node, graph_edge),
1058 DiffInputEdgeMetadata {
1059 change: edge_operations_by_id
1060 .get(&graph_edge.edge_id)
1061 .map_or_else(DiffChange::unchanged, |operation| {
1062 DiffChange::new(DiffChangeKind::Modified, Some(*operation))
1063 }),
1064 origin: EdgeOrigin::Explicit,
1065 },
1066 );
1067 }
1068 }
1069
1070 add_continuation_edges(
1071 &input_nodes,
1072 continuation_spans,
1073 &mut graph,
1074 &mut edge_metadata,
1075 );
1076 remove_unconnected_input_nodes(&mut graph, &mut node_changes);
1077
1078 DiffInputGraph {
1079 graph,
1080 node_changes,
1081 edge_metadata,
1082 }
1083}
1084
1085pub(crate) fn path_start_graph_node() -> GraphNode {
1090 GraphNode {
1091 node_id: PATH_START_NODE_ID,
1092 sequence_start: 0,
1093 sequence_end: 0,
1094 }
1095}
1096
1097pub(crate) fn path_end_graph_node() -> GraphNode {
1102 GraphNode {
1103 node_id: PATH_END_NODE_ID,
1104 sequence_start: 0,
1105 sequence_end: 0,
1106 }
1107}
1108
1109fn add_continuation_edges(
1116 input_nodes: &HashSet<GraphNode>,
1117 continuation_spans: &HashSet<GraphNode>,
1118 graph: &mut GenGraph,
1119 edge_metadata: &mut HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
1120) {
1121 for span in continuation_spans {
1122 if is_terminal(span.node_id) || span.sequence_start == span.sequence_end {
1137 continue;
1138 }
1139 let mut nodes = input_nodes
1140 .iter()
1141 .copied()
1142 .filter(|node| {
1143 node.node_id == span.node_id
1144 && node.sequence_start >= span.sequence_start
1145 && node.sequence_end <= span.sequence_end
1146 })
1147 .collect::<Vec<_>>();
1148 nodes.sort_by_key(|node| (node.sequence_start, node.sequence_end));
1149 for window in nodes.windows(2) {
1150 let source_node = window[0];
1151 let target_node = window[1];
1152 if source_node.sequence_end != target_node.sequence_start {
1153 continue;
1154 }
1155 let synthetic_edge = GraphEdge {
1156 edge_id: HashId::convert_str(&format!(
1157 "diff-continuation:{}:{}:{}:{}:{}",
1158 span.node_id,
1159 source_node.sequence_start,
1160 source_node.sequence_end,
1161 target_node.sequence_start,
1162 target_node.sequence_end
1163 )),
1164 source_strand: Strand::Forward,
1165 target_strand: Strand::Forward,
1166 chromosome_index: NO_CHROMOSOME_INDEX,
1167 phased: 0,
1168 created_on: 0,
1169 };
1170 if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1171 if existing_edges.contains(&synthetic_edge) {
1172 continue;
1173 }
1174 existing_edges.push(synthetic_edge);
1175 } else {
1176 graph.add_edge(source_node, target_node, vec![synthetic_edge]);
1177 }
1178 edge_metadata.insert(
1179 GraphEdgeKey::new(source_node, target_node, synthetic_edge),
1180 DiffInputEdgeMetadata {
1181 change: DiffChange::unchanged(),
1182 origin: EdgeOrigin::Continuation,
1183 },
1184 );
1185 }
1186 }
1187}
1188
1189fn remove_unconnected_input_nodes(
1196 graph: &mut GenGraph,
1197 node_changes: &mut HashMap<GraphNode, DiffChange>,
1198) {
1199 let mut connected_nodes = HashSet::new();
1200 for (source, target, _) in graph.all_edges() {
1201 connected_nodes.insert(source);
1202 connected_nodes.insert(target);
1203 }
1204 let disconnected_nodes = graph
1205 .nodes()
1206 .filter(|node| !is_terminal(node.node_id) && !connected_nodes.contains(node))
1207 .collect::<Vec<_>>();
1208 for node in disconnected_nodes {
1209 graph.remove_node(node);
1210 node_changes.remove(&node);
1211 }
1212}
1213
1214#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
1215pub(crate) struct GraphEdgeKey {
1216 source: GraphNode,
1217 target: GraphNode,
1218 edge_id: HashId,
1219 source_strand: Strand,
1220 target_strand: Strand,
1221 chromosome_index: i64,
1222 phased: i64,
1223}
1224
1225impl GraphEdgeKey {
1226 pub(crate) fn new(source: GraphNode, target: GraphNode, edge: GraphEdge) -> Self {
1232 Self {
1233 source,
1234 target,
1235 edge_id: edge.edge_id,
1236 source_strand: edge.source_strand,
1237 target_strand: edge.target_strand,
1238 chromosome_index: edge.chromosome_index,
1239 phased: edge.phased,
1240 }
1241 }
1242
1243 fn matches_edge(self, edge: GraphEdge) -> bool {
1248 self.edge_id == edge.edge_id
1249 && self.source_strand == edge.source_strand
1250 && self.target_strand == edge.target_strand
1251 && self.chromosome_index == edge.chromosome_index
1252 && self.phased == edge.phased
1253 }
1254}
1255
1256struct BlockGroupComparison {
1257 source_block_group: Option<BlockGroup>,
1258 target_block_group: Option<BlockGroup>,
1259 graph: DiffGenGraph,
1260}
1261
1262pub(crate) struct DiffInputGraph {
1263 graph: GenGraph,
1264 node_changes: HashMap<GraphNode, DiffChange>,
1265 edge_metadata: HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
1266}
1267
1268#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1274pub(crate) struct DiffInputEdgeMetadata {
1275 change: DiffChange,
1276 origin: EdgeOrigin,
1277}
1278
1279impl DiffInputGraph {
1280 fn nodes(&self) -> impl Iterator<Item = GraphNode> + '_ {
1282 self.node_changes.keys().copied()
1283 }
1284
1285 fn node_change(&self, node: GraphNode) -> Option<DiffChange> {
1287 self.node_changes.get(&node).copied()
1288 }
1289
1290 fn edges(&self) -> impl Iterator<Item = (GraphEdgeKey, DiffInputEdgeMetadata)> + '_ {
1292 self.edge_metadata
1293 .iter()
1294 .map(|(edge_key, metadata)| (*edge_key, *metadata))
1295 }
1296
1297 fn edge_metadata(&self, edge_key: GraphEdgeKey) -> Option<DiffInputEdgeMetadata> {
1299 self.edge_metadata.get(&edge_key).copied()
1300 }
1301
1302 fn edge(&self, edge_key: GraphEdgeKey) -> Option<GraphEdge> {
1304 self.graph
1305 .edge_weight(edge_key.source, edge_key.target)?
1306 .iter()
1307 .copied()
1308 .find(|edge| edge_key.matches_edge(*edge))
1309 }
1310}
1311
1312#[cfg(test)]
1313impl DiffInputGraph {
1314 pub(crate) const fn graph(&self) -> &GenGraph {
1316 &self.graph
1317 }
1318}
1319
1320#[derive(Debug, Default)]
1321struct InputOperationChangeLookup {
1322 source_node_operation_by_id: HashMap<HashId, DoltHashId>,
1323 target_node_operation_by_id: HashMap<HashId, DoltHashId>,
1324 source_edge_operation_by_id: HashMap<HashId, DoltHashId>,
1325 target_edge_operation_by_id: HashMap<HashId, DoltHashId>,
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330 use gen_models::edge::Edge;
1331
1332 use super::*;
1333
1334 fn topology_test_edge(source: HashId, target: HashId, source_coordinate: i64) -> AugmentedEdge {
1335 AugmentedEdge {
1336 edge: Edge {
1337 id: HashId::convert_str(&format!("{source}-{source_coordinate}-{target}")),
1338 source_node_id: source,
1339 source_coordinate,
1340 source_strand: Strand::Forward,
1341 target_node_id: target,
1342 target_coordinate: 0,
1343 target_strand: Strand::Forward,
1344 },
1345 chromosome_index: 0,
1346 phased: 0,
1347 created_on: 0,
1348 }
1349 }
1350
1351 #[test]
1352 fn test_tracks_added_edge() {
1353 let node_a = HashId::convert_str("topology-a");
1357 let node_b = HashId::convert_str("topology-b");
1358 let query_edges = vec![
1360 topology_test_edge(PATH_START_NODE_ID, node_a, 0),
1361 topology_test_edge(node_a, PATH_END_NODE_ID, 10),
1362 topology_test_edge(PATH_START_NODE_ID, node_b, 0),
1363 topology_test_edge(node_b, PATH_END_NODE_ID, 10),
1364 ];
1365 let connection = topology_test_edge(node_a, node_b, 10);
1366 let mut base_edges = query_edges.clone();
1367 base_edges.push(connection.clone());
1368 for (base, query, expected) in [
1369 (&base_edges, &query_edges, DiffChangeKind::Removed),
1370 (&query_edges, &base_edges, DiffChangeKind::Added),
1371 ] {
1372 let graph = build_diff_graph_from_edges(
1373 EdgeDiffInput::unattributed(base),
1374 EdgeDiffInput::unattributed(query),
1375 None,
1376 );
1377 assert!(
1378 graph
1379 .nodes()
1380 .all(|node| node.change.kind == DiffChangeKind::Unchanged)
1381 );
1382 let change = graph
1383 .all_edges()
1384 .flat_map(|(_, _, edges)| edges)
1385 .find(|edge| edge.edge.edge_id == connection.edge.id)
1386 .expect("should retain the differing explicit connection")
1387 .change;
1388 assert_eq!(
1389 change.kind, expected,
1390 "explicit membership must determine edge changes even when both nodes survive"
1391 );
1392 assert_eq!(change.operation, None);
1393 }
1394 }
1395
1396 #[test]
1397 fn test_tracks_chromosome_index_changes_for_diploids() {
1398 let node = HashId::convert_str("parallel-node");
1402 let query_edges = vec![
1403 topology_test_edge(PATH_START_NODE_ID, node, 0),
1404 topology_test_edge(node, PATH_END_NODE_ID, 10),
1405 ];
1406 let mut parallel = query_edges[0].clone();
1407 parallel.chromosome_index = 1;
1408 let mut base_edges = query_edges.clone();
1409 base_edges.push(parallel);
1410 for (base, query, expected) in [
1411 (&base_edges, &query_edges, DiffChangeKind::Removed),
1412 (&query_edges, &base_edges, DiffChangeKind::Added),
1413 ] {
1414 let graph = build_diff_graph_from_edges(
1415 EdgeDiffInput::unattributed(base),
1416 EdgeDiffInput::unattributed(query),
1417 None,
1418 );
1419 let parallel_change = graph
1420 .all_edges()
1421 .flat_map(|(_, _, edges)| edges)
1422 .find(|edge| edge.edge.chromosome_index == 1)
1423 .expect("should retain the differing parallel edge")
1424 .change;
1425 assert_eq!(
1426 parallel_change.kind, expected,
1427 "parallel membership differences must remain visible alongside shared edges"
1428 );
1429 assert_eq!(parallel_change.operation, None);
1430 let shared_change = graph
1431 .all_edges()
1432 .flat_map(|(_, _, edges)| edges)
1433 .find(|edge| {
1434 edge.edge.edge_id == query_edges[0].edge.id
1435 && edge.edge.chromosome_index == query_edges[0].chromosome_index
1436 })
1437 .expect("should retain the shared parallel edge")
1438 .change;
1439 assert_eq!(shared_change.kind, DiffChangeKind::Unchanged);
1440 assert_eq!(shared_change.operation, None);
1441 }
1442 }
1443
1444 #[test]
1445 fn test_operation_attribution() {
1446 let node_a = HashId::convert_str("attributed-topology-a");
1450 let node_b = HashId::convert_str("attributed-topology-b");
1451 let base_edges = vec![
1452 topology_test_edge(PATH_START_NODE_ID, node_a, 0),
1453 topology_test_edge(node_a, PATH_END_NODE_ID, 10),
1454 topology_test_edge(PATH_START_NODE_ID, node_b, 0),
1455 topology_test_edge(node_b, PATH_END_NODE_ID, 10),
1456 ];
1457 let connection = topology_test_edge(node_a, node_b, 10);
1458 let mut query_edges = base_edges.clone();
1459 query_edges.push(connection.clone());
1460 let operation = DoltHashId([9; 20]);
1461 let edge_operations = HashMap::from([(connection.edge.id, operation)]);
1462 let graph = build_diff_graph_from_edges(
1463 EdgeDiffInput::unattributed(&base_edges)
1464 .with_attribution(&HashMap::new(), &HashMap::new()),
1465 EdgeDiffInput::unattributed(&query_edges)
1466 .with_attribution(&HashMap::new(), &edge_operations),
1467 None,
1468 );
1469 let change = graph
1470 .all_edges()
1471 .flat_map(|(_, _, edges)| edges)
1472 .find(|edge| edge.edge.edge_id == connection.edge.id)
1473 .expect("should retain the added explicit connection")
1474 .change;
1475 assert_eq!(change.kind, DiffChangeKind::Added);
1476 assert_eq!(change.operation, Some(operation));
1477 }
1478
1479 #[test]
1480 fn test_continuation_is_neutral() {
1481 let node = HashId::convert_str("continuation-node");
1486 let continuous_edges = vec![
1487 topology_test_edge(PATH_START_NODE_ID, node, 0),
1488 topology_test_edge(node, PATH_END_NODE_ID, 10),
1489 ];
1490 let split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
1491 let split_end = topology_test_edge(node, PATH_END_NODE_ID, 5);
1492 let mut second_split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
1493 second_split_start.edge.id = HashId::convert_str("continuation-second-start");
1494 second_split_start.edge.target_coordinate = 5;
1495 let second_split_end = topology_test_edge(node, PATH_END_NODE_ID, 10);
1496 let split_edges = vec![split_start, split_end, second_split_start, second_split_end];
1497 let first_slice = GraphNode {
1498 node_id: node,
1499 sequence_start: 0,
1500 sequence_end: 5,
1501 };
1502 let second_slice = GraphNode {
1503 node_id: node,
1504 sequence_start: 5,
1505 sequence_end: 10,
1506 };
1507
1508 for (base, query) in [
1509 (&continuous_edges, &split_edges),
1510 (&split_edges, &continuous_edges),
1511 ] {
1512 let graph = build_diff_graph_from_edges(
1513 EdgeDiffInput::unattributed(base),
1514 EdgeDiffInput::unattributed(query),
1515 None,
1516 );
1517 let continuation_edges = graph
1518 .all_edges()
1519 .find_map(|(source, target, edges)| {
1520 (source.node == first_slice && target.node == second_slice).then_some(edges)
1521 })
1522 .expect("should retain the normalization continuation");
1523 assert!(
1524 continuation_edges
1525 .iter()
1526 .all(|edge| edge.change.kind == DiffChangeKind::Unchanged)
1527 );
1528 assert!(
1529 continuation_edges
1530 .iter()
1531 .all(|edge| edge.change.operation.is_none())
1532 );
1533 }
1534 }
1535
1536 fn block_group(id: i64) -> BlockGroup {
1537 BlockGroup {
1538 id: HashId::pad_str(id),
1539 collection_name: "collection".to_string(),
1540 sample_name: "sample".to_string(),
1541 name: "block-group".to_string(),
1542 created_on: 0,
1543 parent_block_group_id: None,
1544 is_default: false,
1545 }
1546 }
1547
1548 #[test]
1549 fn test_block_group_change_kind_is_derived_from_endpoint_membership() {
1550 let block_group = block_group(1);
1551 let block_group_id = block_group.id;
1552 let diff = |source_block_group, target_block_group| BlockGroupDiff {
1553 id: block_group_id,
1554 source_block_group,
1555 target_block_group,
1556 graph: DiffGenGraph::new(),
1557 };
1558
1559 assert_eq!(
1560 diff(None, Some(block_group.clone())).change_kind(),
1561 Some(BlockGroupChangeKind::Added)
1562 );
1563 assert_eq!(
1564 diff(Some(block_group.clone()), None).change_kind(),
1565 Some(BlockGroupChangeKind::Removed)
1566 );
1567 assert_eq!(
1568 diff(Some(block_group.clone()), Some(block_group)).change_kind(),
1569 Some(BlockGroupChangeKind::Modified)
1570 );
1571 assert_eq!(diff(None, None).change_kind(), None);
1572 }
1573
1574 #[test]
1575 fn test_split_nodes_at_shared_boundaries_exposes_removed_slice() {
1576 let node_id = HashId::convert_str("reference-node");
1577 let source_spans = HashSet::from([GraphNode {
1578 node_id,
1579 sequence_start: 0,
1580 sequence_end: 10,
1581 }]);
1582 let target_spans = HashSet::from([
1583 GraphNode {
1584 node_id,
1585 sequence_start: 0,
1586 sequence_end: 3,
1587 },
1588 GraphNode {
1589 node_id,
1590 sequence_start: 5,
1591 sequence_end: 10,
1592 },
1593 ]);
1594
1595 let (source_nodes, target_nodes) =
1596 split_nodes_at_shared_boundaries(&source_spans, &target_spans);
1597 let removed_slice = GraphNode {
1598 node_id,
1599 sequence_start: 3,
1600 sequence_end: 5,
1601 };
1602
1603 assert_eq!(
1604 source_nodes,
1605 HashSet::from([
1606 GraphNode {
1607 node_id,
1608 sequence_start: 0,
1609 sequence_end: 3,
1610 },
1611 removed_slice,
1612 GraphNode {
1613 node_id,
1614 sequence_start: 5,
1615 sequence_end: 10,
1616 },
1617 ])
1618 );
1619 assert_eq!(target_nodes, target_spans);
1620 assert!(source_nodes.contains(&removed_slice));
1621 assert!(!target_nodes.contains(&removed_slice));
1622 }
1623
1624 #[test]
1625 fn diff_graph_to_gen_graph_maps_nodes_and_edges() {
1626 let node_a = DiffGraphNode {
1627 node: GraphNode {
1628 node_id: HashId::pad_str(1),
1629 sequence_start: 0,
1630 sequence_end: 5,
1631 },
1632 change: DiffChange {
1633 kind: DiffChangeKind::Added,
1634 operation: Some(DoltHashId([10; 20])),
1635 },
1636 };
1637 let node_b = DiffGraphNode {
1638 node: GraphNode {
1639 node_id: HashId::pad_str(2),
1640 sequence_start: 5,
1641 sequence_end: 10,
1642 },
1643 change: DiffChange::unchanged(),
1644 };
1645 let mut diff_graph = DiffGenGraph::new();
1646 diff_graph.add_node(node_a);
1647 diff_graph.add_node(node_b);
1648 let edge = DiffGraphEdge {
1649 edge: GraphEdge {
1650 edge_id: HashId::pad_str(9),
1651 source_strand: Strand::Forward,
1652 target_strand: Strand::Forward,
1653 chromosome_index: 0,
1654 phased: 0,
1655 created_on: 0,
1656 },
1657 change: DiffChange {
1658 kind: DiffChangeKind::Added,
1659 operation: Some(DoltHashId([10; 20])),
1660 },
1661 };
1662 diff_graph.add_edge(node_a, node_b, vec![edge]);
1663
1664 let graph: GenGraph = DiffGenGraphRef(&diff_graph).into();
1665 assert_eq!(graph.nodes().count(), 2);
1666 assert_eq!(graph.all_edges().count(), 1);
1667 let weights = graph
1668 .all_edges()
1669 .next()
1670 .map(|(_, _, edges)| edges.clone())
1671 .expect("graph edge");
1672 assert_eq!(weights, vec![edge.edge]);
1673 }
1674}