1use std::collections::{HashMap, HashSet};
61
62use gen_core::{CommitRef, DoltHashId, HashId, errors::ConfigError};
63use gen_models::{
64 block_group_edge::AugmentedEdge,
65 db::GraphConnection,
66 errors::OperationError,
67 history::{HistoryError, HistoryStore, dolt::DoltHistoryStore},
68};
69use thiserror::Error;
70
71pub use crate::graph::{BlockGroupChangeKind, BlockGroupDiff};
72use crate::graph::{BlockGroupDiffInputs, build_block_group_diff};
73
74#[derive(Debug, Error)]
75pub enum OperationDiffError {
76 #[error("No current operation is checked out.")]
77 NoCurrentOperation,
78 #[error("Operation {0} not found.")]
79 OperationMissing(DoltHashId),
80 #[error("Unable to find path between {0} and {1}.")]
81 PathNotFound(DoltHashId, DoltHashId),
82 #[error("Config error: {0}")]
83 Config(#[from] ConfigError),
84 #[error("SQLite error: {0}")]
85 Sqlite(#[from] rusqlite::Error),
86 #[error("I/O error: {0}")]
87 Io(#[from] std::io::Error),
88 #[error(transparent)]
89 OperationError(#[from] OperationError),
90 #[error(transparent)]
91 History(#[from] HistoryError),
92}
93
94#[derive(Clone, Debug)]
99pub struct OperationDiff {
100 pub operations: Vec<DoltHashId>,
101 pub diff_graph: Vec<BlockGroupDiff>,
102}
103
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
121pub enum DiffRange {
122 TwoDot,
124 ThreeDot,
126}
127
128impl DiffRange {
129 fn between(self, source_ref: &str, target_ref: &str) -> String {
130 let separator = match self {
131 Self::TwoDot => "..",
132 Self::ThreeDot => "...",
133 };
134 format!("{source_ref}{separator}{target_ref}")
135 }
136}
137
138impl OperationDiff {
139 fn empty() -> Self {
140 Self {
141 operations: Vec::new(),
142 diff_graph: Vec::new(),
143 }
144 }
145}
146
147pub fn collect_operation_diff(
152 graph_conn: &GraphConnection,
153 source_hash: Option<DoltHashId>,
154 target_hash: DoltHashId,
155 range: DiffRange,
156) -> Result<OperationDiff, OperationDiffError> {
157 let history_store = DoltHistoryStore::new(graph_conn);
158 let target_ref = target_hash.to_string();
159 let source_ref = source_hash
160 .map(|hash| hash.to_string())
161 .unwrap_or_else(|| format!("{target_ref}~1"));
162 let (graph_source_ref, operation_start_hash) = match (range, source_hash) {
163 (DiffRange::ThreeDot, Some(source_commit)) => {
164 if !history_store.commit_exists(&source_commit)? {
165 return Err(OperationDiffError::OperationMissing(source_commit));
166 }
167 if !history_store.commit_exists(&target_hash)? {
168 return Err(OperationDiffError::OperationMissing(target_hash));
169 }
170 let merge_base = history_store.merge_base(
171 &CommitRef(source_ref.clone()),
172 &CommitRef(target_ref.clone()),
173 )?;
174 (merge_base.to_string(), Some(merge_base))
175 }
176 _ => (source_ref.clone(), source_hash),
177 };
178 let operations = operation_hashes_for_diff(&history_store, operation_start_hash, target_hash)?;
179 if operations.is_empty() {
180 return Ok(OperationDiff::empty());
181 }
182
183 let diff_ref = range.between(&source_ref, &target_ref);
184 build_dolt_operation_diff(
185 graph_conn,
186 &graph_source_ref,
187 &target_ref,
188 &diff_ref,
189 operations,
190 target_hash,
191 )
192}
193
194fn build_dolt_operation_diff(
200 graph_conn: &GraphConnection,
201 source_ref: &str,
202 target_ref: &str,
203 diff_ref: &str,
204 operations: Vec<DoltHashId>,
205 target_hash: DoltHashId,
206) -> Result<OperationDiff, OperationDiffError> {
207 let changes = collect_block_group_changes(graph_conn, diff_ref)?;
208 let node_changes = collect_node_changes(graph_conn, diff_ref)?;
209 let BlockGroupChanges {
210 block_group_ids,
211 edge_changes: edge_changes_by_block_group,
212 operations_by_block_group_id: block_group_operations_by_id,
213 } = changes;
214
215 let mut block_group_ids = block_group_ids.into_iter().collect::<Vec<_>>();
216 block_group_ids.sort();
217 let diff_inputs = BlockGroupDiffInputs {
218 source_ref,
219 target_ref,
220 default_operation: target_hash,
221 edge_changes_by_block_group: &edge_changes_by_block_group,
222 block_group_operations_by_id: &block_group_operations_by_id,
223 node_changes: &node_changes,
224 };
225 let mut diff_graph = Vec::new();
226 for block_group_id in block_group_ids {
227 if let Some(block_group_diff) =
228 build_block_group_diff(graph_conn, block_group_id, &diff_inputs)?
229 {
230 diff_graph.push(block_group_diff);
231 }
232 }
233
234 Ok(OperationDiff {
235 operations,
236 diff_graph,
237 })
238}
239
240fn operation_hashes_for_diff(
247 history_store: &impl HistoryStore,
248 source_hash: Option<DoltHashId>,
249 target_hash: DoltHashId,
250) -> Result<Vec<DoltHashId>, OperationDiffError> {
251 if source_hash == Some(target_hash) {
252 return Ok(Vec::new());
253 }
254
255 let target_ref = target_hash.to_string();
256 let history_entries = history_store.log_for_ref(&CommitRef(target_ref), None)?;
257 let history_hashes = history_entries
258 .into_iter()
259 .rev()
260 .map(|entry| entry.commit_hash)
261 .collect::<Vec<_>>();
262 let target_index = history_hashes
263 .iter()
264 .position(|candidate| *candidate == target_hash)
265 .ok_or(OperationDiffError::OperationMissing(target_hash))?;
266
267 let operations = match source_hash {
268 None => vec![target_hash],
269 Some(source_hash) => match history_hashes
270 .iter()
271 .position(|candidate| *candidate == source_hash)
272 {
273 Some(source_index) if source_index > target_index => {
274 return Err(OperationDiffError::PathNotFound(source_hash, target_hash));
275 }
276 Some(source_index) => history_hashes[source_index + 1..=target_index].to_vec(),
277 None if history_store.commit_exists(&source_hash)? => {
278 vec![source_hash, target_hash]
279 }
280 None => return Err(OperationDiffError::OperationMissing(source_hash)),
281 },
282 };
283 Ok(operations)
284}
285
286fn collect_block_group_changes(
291 graph_conn: &GraphConnection,
292 diff_ref: &str,
293) -> Result<BlockGroupChanges, OperationDiffError> {
294 let mut changes = BlockGroupChanges::default();
295 let block_group_query = format!(
296 "SELECT to_id,
297 from_id,
298 NULL,
299 NULL,
300 NULL,
301 NULL,
302 NULL,
303 NULL,
304 to_commit,
305 diff_type
306 FROM dolt_diff_block_groups('{diff_ref}')"
307 );
308 let mut block_group_statement = graph_conn.prepare(&block_group_query)?;
309 let block_group_rows =
310 block_group_statement.query_map([], DoltBlockGroupChangeRow::from_row)?;
311 for row in block_group_rows {
312 let row = row?;
313 row.record_block_group(&mut changes);
314 }
315
316 let edge_query = format!(
317 "SELECT to_block_group_id,
318 from_block_group_id,
319 to_edge_id,
320 from_edge_id,
321 to_chromosome_index,
322 from_chromosome_index,
323 to_phased,
324 from_phased,
325 to_commit,
326 diff_type
327 FROM dolt_diff_block_group_edges('{diff_ref}')"
328 );
329 let mut edge_statement = graph_conn.prepare(&edge_query)?;
330 let edge_rows = edge_statement.query_map([], DoltBlockGroupChangeRow::from_row)?;
331 for row in edge_rows {
332 let row = row?;
333 row.record_block_group(&mut changes);
334 if let Some(edge_change) = row.edge_change() {
335 changes
336 .edge_changes
337 .entry(edge_change.block_group_id())
338 .or_default()
339 .push(edge_change);
340 }
341 }
342
343 Ok(changes)
344}
345
346fn collect_node_changes(
351 graph_conn: &GraphConnection,
352 diff_ref: &str,
353) -> Result<Vec<NodeChange>, OperationDiffError> {
354 let query =
355 format!("SELECT to_id, from_id, to_commit, diff_type FROM dolt_diff_nodes('{diff_ref}')");
356 let mut node_changes = Vec::new();
357 let mut statement = graph_conn.prepare(&query)?;
358 let rows = statement.query_map([], |row| {
359 Ok((
360 row.get::<_, Option<HashId>>(0)?,
361 row.get::<_, Option<HashId>>(1)?,
362 row.get::<_, Option<DoltHashId>>(2)?,
363 row.get::<_, String>(3)?,
364 ))
365 })?;
366 for row in rows {
367 let (to_node_id, from_node_id, to_commit, diff_type) = row?;
368 let operation = to_commit;
369 match diff_type.as_str() {
370 "added" => {
371 if let Some(new_node_id) = to_node_id {
372 node_changes.push(NodeChange::Added {
373 new_node_id,
374 operation,
375 });
376 }
377 }
378 "removed" => {
379 if let Some(old_node_id) = from_node_id {
380 node_changes.push(NodeChange::Removed {
381 old_node_id,
382 operation,
383 });
384 }
385 }
386 "modified" => {
387 if let (Some(old_node_id), Some(new_node_id)) = (from_node_id, to_node_id) {
388 node_changes.push(NodeChange::Modified {
389 old_node_id,
390 new_node_id,
391 old_operation: operation,
392 new_operation: operation,
393 });
394 }
395 }
396 _ => {}
397 }
398 }
399
400 Ok(node_changes)
401}
402
403#[derive(Debug, Default)]
408struct BlockGroupChanges {
409 block_group_ids: HashSet<HashId>,
411 edge_changes: HashMap<HashId, Vec<BlockGroupEdgeChange>>,
413 operations_by_block_group_id: HashMap<HashId, HashSet<DoltHashId>>,
415}
416
417impl BlockGroupChanges {
418 fn record_operation(&mut self, block_group_id: HashId, operation: Option<DoltHashId>) {
419 if let Some(operation) = operation {
420 self.operations_by_block_group_id
421 .entry(block_group_id)
422 .or_default()
423 .insert(operation);
424 }
425 }
426}
427
428#[derive(Debug)]
433struct DoltBlockGroupChangeRow {
434 to_block_group_id: Option<HashId>,
436 from_block_group_id: Option<HashId>,
438 to_edge_id: Option<HashId>,
440 from_edge_id: Option<HashId>,
442 to_chromosome_index: Option<i64>,
444 from_chromosome_index: Option<i64>,
446 to_phased: Option<i64>,
448 from_phased: Option<i64>,
450 to_commit: Option<DoltHashId>,
452 diff_type: String,
454}
455
456impl DoltBlockGroupChangeRow {
457 fn from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Self> {
459 Ok(Self {
460 to_block_group_id: row.get(0)?,
461 from_block_group_id: row.get(1)?,
462 to_edge_id: row.get(2)?,
463 from_edge_id: row.get(3)?,
464 to_chromosome_index: row.get(4)?,
465 from_chromosome_index: row.get(5)?,
466 to_phased: row.get(6)?,
467 from_phased: row.get(7)?,
468 to_commit: row.get(8)?,
469 diff_type: row.get(9)?,
470 })
471 }
472
473 fn record_block_group(&self, changes: &mut BlockGroupChanges) {
475 if matches!(self.diff_type.as_str(), "added" | "removed" | "modified")
476 && let Some(block_group_id) = self.to_block_group_id.or(self.from_block_group_id)
477 {
478 changes.block_group_ids.insert(block_group_id);
479 changes.record_operation(block_group_id, self.change_operation());
480 }
481 }
482
483 fn edge_change(&self) -> Option<BlockGroupEdgeChange> {
488 match self.diff_type.as_str() {
489 "added" => {
490 let block_group_id = self.to_block_group_id?;
491 let new_key =
492 self.edge_key(self.to_edge_id, self.to_chromosome_index, self.to_phased)?;
493 Some(BlockGroupEdgeChange {
494 block_group_id,
495 old_key: None,
496 new_key: Some(new_key),
497 old_operation: None,
498 new_operation: self.change_operation(),
499 })
500 }
501 "removed" => {
502 let block_group_id = self.from_block_group_id?;
503 let old_key = self.edge_key(
504 self.from_edge_id,
505 self.from_chromosome_index,
506 self.from_phased,
507 )?;
508 Some(BlockGroupEdgeChange {
509 block_group_id,
510 old_key: Some(old_key),
511 new_key: None,
512 old_operation: self.change_operation(),
513 new_operation: None,
514 })
515 }
516 "modified" => {
517 let block_group_id = self.to_block_group_id.or(self.from_block_group_id)?;
518 let old_key = self.edge_key(
519 self.from_edge_id,
520 self.from_chromosome_index,
521 self.from_phased,
522 )?;
523 let new_key =
524 self.edge_key(self.to_edge_id, self.to_chromosome_index, self.to_phased)?;
525 Some(BlockGroupEdgeChange {
526 block_group_id,
527 old_key: Some(old_key),
528 new_key: Some(new_key),
529 old_operation: self.change_operation(),
530 new_operation: self.change_operation(),
531 })
532 }
533 _ => None,
534 }
535 }
536
537 fn edge_key(
539 &self,
540 edge_id: Option<HashId>,
541 chromosome_index: Option<i64>,
542 phased: Option<i64>,
543 ) -> Option<BlockGroupEdgeKey> {
544 Some(BlockGroupEdgeKey {
545 edge_id: edge_id?,
546 chromosome_index: chromosome_index?,
547 phased: phased?,
548 })
549 }
550
551 fn change_operation(&self) -> Option<DoltHashId> {
553 self.to_commit
554 }
555}
556
557#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
562pub(crate) struct BlockGroupEdgeKey {
563 edge_id: HashId,
564 chromosome_index: i64,
565 phased: i64,
566}
567
568impl From<&AugmentedEdge> for BlockGroupEdgeKey {
569 fn from(edge: &AugmentedEdge) -> Self {
571 Self {
572 edge_id: edge.edge.id,
573 chromosome_index: edge.chromosome_index,
574 phased: edge.phased,
575 }
576 }
577}
578
579#[derive(Clone, Copy, Debug, Eq, PartialEq)]
584pub(crate) enum NodeChange {
585 Added {
586 new_node_id: HashId,
587 operation: Option<DoltHashId>,
588 },
589 Removed {
590 old_node_id: HashId,
591 operation: Option<DoltHashId>,
592 },
593 Modified {
594 old_node_id: HashId,
595 new_node_id: HashId,
596 old_operation: Option<DoltHashId>,
597 new_operation: Option<DoltHashId>,
598 },
599}
600
601impl NodeChange {
602 pub(crate) fn old_node_id(&self) -> Option<HashId> {
604 match self {
605 NodeChange::Added { .. } => None,
606 NodeChange::Removed { old_node_id, .. } => Some(*old_node_id),
607 NodeChange::Modified { old_node_id, .. } => Some(*old_node_id),
608 }
609 }
610
611 pub(crate) fn new_node_id(&self) -> Option<HashId> {
613 match self {
614 NodeChange::Added { new_node_id, .. } => Some(*new_node_id),
615 NodeChange::Removed { .. } => None,
616 NodeChange::Modified { new_node_id, .. } => Some(*new_node_id),
617 }
618 }
619
620 pub(crate) fn old_operation(&self) -> Option<DoltHashId> {
622 match self {
623 NodeChange::Added { .. } => None,
624 NodeChange::Removed { operation, .. } => *operation,
625 NodeChange::Modified { old_operation, .. } => *old_operation,
626 }
627 }
628
629 pub(crate) fn new_operation(&self) -> Option<DoltHashId> {
631 match self {
632 NodeChange::Added { operation, .. } => *operation,
633 NodeChange::Removed { .. } => None,
634 NodeChange::Modified { new_operation, .. } => *new_operation,
635 }
636 }
637}
638
639#[derive(Clone, Copy, Debug, Eq, PartialEq)]
644pub(crate) struct BlockGroupEdgeChange {
645 block_group_id: HashId,
646 pub(crate) old_key: Option<BlockGroupEdgeKey>,
648 pub(crate) new_key: Option<BlockGroupEdgeKey>,
650 old_operation: Option<DoltHashId>,
652 new_operation: Option<DoltHashId>,
654}
655
656impl BlockGroupEdgeChange {
657 fn block_group_id(&self) -> HashId {
659 self.block_group_id
660 }
661
662 pub(crate) fn old_edge_id(&self) -> Option<HashId> {
664 self.old_key.map(|key| key.edge_id)
665 }
666
667 pub(crate) fn new_edge_id(&self) -> Option<HashId> {
669 self.new_key.map(|key| key.edge_id)
670 }
671
672 pub(crate) fn old_operation(&self) -> Option<DoltHashId> {
674 self.old_operation
675 }
676
677 pub(crate) fn new_operation(&self) -> Option<DoltHashId> {
679 self.new_operation
680 }
681}
682
683#[cfg(test)]
684mod tests {
685 use std::collections::{HashMap, HashSet};
686
687 use gen_core::{
688 BranchName, CommitRef, DoltHashId, HashId, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand,
689 Workspace,
690 };
691 use gen_graph::{GenGraph, GraphEdge, GraphNode};
692 use gen_models::{
693 block_group::{BlockGroup, NewBlockGroup},
694 block_group_edge::{AugmentedEdge, BlockGroupEdge, BlockGroupEdgeData},
695 collection::Collection,
696 db::DbContext,
697 edge::{Edge, GroupBlock},
698 history::{HistoryStore, dolt::DoltHistoryStore},
699 node::Node,
700 path::Path,
701 sample::{NewSample, Sample},
702 sequence::Sequence,
703 };
704 use petgraph::Direction;
705 use rusqlite::params;
706 use tempfile::tempdir;
707
708 use super::{
709 BlockGroupDiff, BlockGroupEdgeChange, BlockGroupEdgeKey, DiffRange, OperationDiffError,
710 collect_block_group_changes, collect_operation_diff,
711 };
712 use crate::{
713 graph::{
714 DiffChangeKind, DiffGenGraph, DiffInputGraph, GraphEdgeKey, build_diff_input_graph,
715 build_unified_diff_graph, path_end_graph_node, path_start_graph_node,
716 },
717 test_helpers::{get_config_connection, get_connection as test_get_connection},
718 };
719
720 fn setup_history_context() -> DbContext {
721 let tmp_dir = tempdir().expect("should create temp dir").keep();
722 let workspace = Workspace::new(tmp_dir);
723 workspace.ensure_gen_dir();
724 let graph_conn = test_get_connection(workspace.graph_db_path().unwrap().to_str().unwrap())
725 .expect("should create graph database");
726 let config_conn = get_config_connection(workspace.gen_db_path().unwrap().to_str().unwrap())
727 .expect("should create config database");
728 DbContext::new(workspace, graph_conn, config_conn).expect("should create db context")
729 }
730
731 fn create_linear_block_group(
732 context: &gen_models::db::DbContext,
733 collection_name: &str,
734 sample_name: &str,
735 block_group_name: &str,
736 node_name: &str,
737 sequence_bases: &str,
738 ) -> BlockGroup {
739 let graph_conn = context.graph().conn();
740 Collection::get_or_create(graph_conn, collection_name).expect("should create collection");
741 Sample::get_or_create(
742 graph_conn,
743 NewSample {
744 name: sample_name,
745 is_reference: false,
746 },
747 )
748 .expect("should create sample");
749 let block_group = BlockGroup::create(
750 graph_conn,
751 NewBlockGroup {
752 collection_name,
753 sample_name,
754 name: block_group_name,
755 ..Default::default()
756 },
757 )
758 .expect("should create block group");
759 let sequence = Sequence::new()
760 .sequence_type("DNA")
761 .sequence(sequence_bases)
762 .name(node_name)
763 .save(graph_conn)
764 .expect("should save sequence");
765 let node_id = Node::create(
766 graph_conn,
767 &sequence.hash,
768 &HashId::convert_str(&format!("{block_group_name}-{node_name}")),
769 )
770 .expect("should create node");
771 let start_edge = Edge::create(
772 graph_conn,
773 PATH_START_NODE_ID,
774 0,
775 Strand::Forward,
776 node_id,
777 0,
778 Strand::Forward,
779 )
780 .expect("should create start edge");
781 let end_edge = Edge::create(
782 graph_conn,
783 node_id,
784 sequence.length,
785 Strand::Forward,
786 PATH_END_NODE_ID,
787 0,
788 Strand::Forward,
789 )
790 .expect("should create end edge");
791 BlockGroupEdge::bulk_create(
792 graph_conn,
793 &[
794 BlockGroupEdgeData {
795 block_group_id: block_group.id,
796 edge_id: start_edge.id,
797 chromosome_index: 0,
798 phased: 0,
799 },
800 BlockGroupEdgeData {
801 block_group_id: block_group.id,
802 edge_id: end_edge.id,
803 chromosome_index: 0,
804 phased: 0,
805 },
806 ],
807 );
808 Path::create(
809 graph_conn,
810 block_group_name,
811 &block_group.id,
812 &[start_edge.id, end_edge.id],
813 )
814 .expect("should create path");
815 block_group
816 }
817
818 fn replace_linear_block_group_path(
819 context: &gen_models::db::DbContext,
820 block_group: &BlockGroup,
821 node_name: &str,
822 sequence_bases: &str,
823 ) {
824 let graph_conn = context.graph().conn();
825 let existing_edges =
826 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, None)
827 .into_iter()
828 .map(|edge| BlockGroupEdgeData {
829 block_group_id: block_group.id,
830 edge_id: edge.edge.id,
831 chromosome_index: edge.chromosome_index,
832 phased: edge.phased,
833 })
834 .collect::<Vec<_>>();
835 Path::delete(graph_conn, &block_group.name, &block_group.id);
836 BlockGroupEdge::bulk_delete(graph_conn, &existing_edges);
837
838 let sequence = Sequence::new()
839 .sequence_type("DNA")
840 .sequence(sequence_bases)
841 .name(node_name)
842 .save(graph_conn)
843 .expect("should save replacement sequence");
844 let node_id = Node::create(
845 graph_conn,
846 &sequence.hash,
847 &HashId::convert_str(&format!("{}-{node_name}", block_group.name)),
848 )
849 .expect("should create replacement node");
850 let start_edge = Edge::create(
851 graph_conn,
852 PATH_START_NODE_ID,
853 0,
854 Strand::Forward,
855 node_id,
856 0,
857 Strand::Forward,
858 )
859 .expect("should create replacement start edge");
860 let end_edge = Edge::create(
861 graph_conn,
862 node_id,
863 sequence.length,
864 Strand::Forward,
865 PATH_END_NODE_ID,
866 0,
867 Strand::Forward,
868 )
869 .expect("should create replacement end edge");
870 BlockGroupEdge::bulk_create(
871 graph_conn,
872 &[
873 BlockGroupEdgeData {
874 block_group_id: block_group.id,
875 edge_id: start_edge.id,
876 chromosome_index: 0,
877 phased: 0,
878 },
879 BlockGroupEdgeData {
880 block_group_id: block_group.id,
881 edge_id: end_edge.id,
882 chromosome_index: 0,
883 phased: 0,
884 },
885 ],
886 );
887 Path::create(
888 graph_conn,
889 &block_group.name,
890 &block_group.id,
891 &[start_edge.id, end_edge.id],
892 )
893 .expect("should recreate path");
894 }
895
896 fn commit_operation(context: &gen_models::db::DbContext, message: &str) -> DoltHashId {
897 let history_store = DoltHistoryStore::new(context.graph().conn());
898 history_store
899 .commit_all(message)
900 .expect("should commit graph changes")
901 }
902
903 fn commit_hash_ref(operation_hash: DoltHashId) -> CommitRef {
904 CommitRef(operation_hash.to_string())
905 }
906
907 struct DivergentHistory {
908 context: DbContext,
909 source_block_group: BlockGroup,
910 target_block_group: BlockGroup,
911 source_hash: DoltHashId,
912 target_hash: DoltHashId,
913 }
914
915 fn setup_divergent_history() -> DivergentHistory {
927 let mut context = setup_history_context();
928 let graph_conn = context.graph().conn();
929 let graph_db_path = context
930 .workspace()
931 .graph_db_path()
932 .expect("should resolve graph database path");
933 let history_store = DoltHistoryStore::new(graph_conn);
934
935 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
936 let base = commit_operation(&context, "seed");
937 let source_block_group =
938 create_linear_block_group(&context, "c", "s", "main", "main", "CCCCC");
939 let source_hash = commit_operation(&context, "main op");
940 history_store
941 .create_branch(
942 &BranchName("source".to_string()),
943 Some(&commit_hash_ref(source_hash)),
944 )
945 .expect("should preserve the source branch");
946 history_store
947 .reset_hard(&commit_hash_ref(base))
948 .expect("should reset main to the common base");
949 let reopened_graph = gen_models::db::get_connection(&graph_db_path)
950 .expect("should reopen graph database after reset");
951 gen_models::history::dolt::connect_branch(&reopened_graph, "main")
952 .expect("should reconnect the main branch");
953 context.set_graph(reopened_graph);
954 let target_block_group =
955 create_linear_block_group(&context, "c", "s", "feature", "feature", "GGGGG");
956 let target_hash = commit_operation(&context, "feature op");
957
958 DivergentHistory {
959 context,
960 source_block_group,
961 target_block_group,
962 source_hash,
963 target_hash,
964 }
965 }
966
967 fn switch_branch(context: &gen_models::db::DbContext, branch_name: &str) {
968 let history_store = DoltHistoryStore::new(context.graph().conn());
969 history_store
970 .checkout_branch(&BranchName(branch_name.to_string()))
971 .expect("should checkout history branch");
972 }
973
974 fn create_feature_branch(
975 context: &gen_models::db::DbContext,
976 base_operation_hash: DoltHashId,
977 branch_name: &str,
978 ) {
979 let history_store = DoltHistoryStore::new(context.graph().conn());
980 history_store
981 .create_branch(
982 &BranchName(branch_name.to_string()),
983 Some(&commit_hash_ref(base_operation_hash)),
984 )
985 .expect("should create history branch");
986 switch_branch(context, branch_name);
987 }
988
989 fn test_augmented_edge(
990 edge_id: HashId,
991 source_node_id: HashId,
992 source_coordinate: i64,
993 target_node_id: HashId,
994 target_coordinate: i64,
995 ) -> AugmentedEdge {
996 AugmentedEdge {
997 edge: Edge {
998 id: edge_id,
999 source_node_id,
1000 source_coordinate,
1001 source_strand: Strand::Forward,
1002 target_node_id,
1003 target_coordinate,
1004 target_strand: Strand::Forward,
1005 },
1006 chromosome_index: 0,
1007 phased: 0,
1008 created_on: 0,
1009 }
1010 }
1011
1012 fn apply_edge_changes(
1013 graph_conn: &gen_models::db::GraphConnection,
1014 source_edges: &[AugmentedEdge],
1015 edge_changes: &[BlockGroupEdgeChange],
1016 target_ref: &str,
1017 ) -> Result<Vec<AugmentedEdge>, OperationDiffError> {
1018 let mut edges_by_key = source_edges
1019 .iter()
1020 .cloned()
1021 .map(|edge| (BlockGroupEdgeKey::from(&edge), edge))
1022 .collect::<HashMap<_, _>>();
1023
1024 for edge_change in edge_changes {
1025 if let Some(old_key) = edge_change.old_key {
1026 edges_by_key.remove(&old_key);
1027 }
1028 if let Some(new_key) = edge_change.new_key {
1029 let edge = load_augmented_edge(
1030 graph_conn,
1031 edge_change.block_group_id,
1032 new_key,
1033 target_ref,
1034 )?;
1035 edges_by_key.insert(new_key, edge);
1036 }
1037 }
1038
1039 let mut edges = edges_by_key.into_values().collect::<Vec<_>>();
1040 edges.sort_by(|left, right| {
1041 right
1042 .created_on
1043 .cmp(&left.created_on)
1044 .then_with(|| left.edge.id.cmp(&right.edge.id))
1045 .then_with(|| left.chromosome_index.cmp(&right.chromosome_index))
1046 .then_with(|| left.phased.cmp(&right.phased))
1047 });
1048 Ok(edges)
1049 }
1050
1051 fn load_augmented_edge(
1052 graph_conn: &gen_models::db::GraphConnection,
1053 block_group_id: HashId,
1054 edge_key: BlockGroupEdgeKey,
1055 history_ref: &str,
1056 ) -> Result<AugmentedEdge, OperationDiffError> {
1057 let query = "SELECT
1058 edges.id,
1059 edges.source_node_id,
1060 edges.source_coordinate,
1061 edges.source_strand,
1062 edges.target_node_id,
1063 edges.target_coordinate,
1064 edges.target_strand,
1065 block_group_edges.chromosome_index,
1066 block_group_edges.phased,
1067 block_group_edges.created_on
1068 FROM dolt_at_block_group_edges(?1) AS block_group_edges
1069 JOIN dolt_at_edges(?1) AS edges ON edges.id = block_group_edges.edge_id
1070 WHERE block_group_edges.block_group_id = ?2
1071 AND block_group_edges.edge_id = ?3
1072 AND block_group_edges.chromosome_index = ?4
1073 AND block_group_edges.phased = ?5";
1074 graph_conn
1075 .query_row(
1076 query,
1077 params![
1078 history_ref,
1079 block_group_id,
1080 edge_key.edge_id,
1081 edge_key.chromosome_index,
1082 edge_key.phased
1083 ],
1084 |row| {
1085 Ok(AugmentedEdge {
1086 edge: Edge {
1087 id: row.get(0)?,
1088 source_node_id: row.get(1)?,
1089 source_coordinate: row.get(2)?,
1090 source_strand: row.get(3)?,
1091 target_node_id: row.get(4)?,
1092 target_coordinate: row.get(5)?,
1093 target_strand: row.get(6)?,
1094 },
1095 chromosome_index: row.get(7)?,
1096 phased: row.get(8)?,
1097 created_on: row.get(9)?,
1098 })
1099 },
1100 )
1101 .map_err(OperationDiffError::from)
1102 }
1103
1104 fn build_diff_input(
1105 input_blocks: &[GroupBlock],
1106 input_edges: &[AugmentedEdge],
1107 node_operations_by_id: &HashMap<HashId, DoltHashId>,
1108 edge_operations_by_id: &HashMap<HashId, DoltHashId>,
1109 ) -> DiffInputGraph {
1110 let input_nodes = input_blocks
1111 .iter()
1112 .map(|block| GraphNode {
1113 node_id: block.node_id,
1114 sequence_start: block.start,
1115 sequence_end: block.end,
1116 })
1117 .collect::<HashSet<_>>();
1118 let continuation_spans = input_nodes.clone();
1119 build_diff_input_graph(
1120 input_nodes,
1121 &continuation_spans,
1122 input_edges,
1123 node_operations_by_id,
1124 edge_operations_by_id,
1125 )
1126 }
1127
1128 fn graph_edge_keys(graph: &GenGraph) -> HashSet<GraphEdgeKey> {
1129 graph
1130 .all_edges()
1131 .flat_map(|(source, target, edges)| {
1132 edges
1133 .iter()
1134 .copied()
1135 .map(move |edge| GraphEdgeKey::new(source, target, edge))
1136 })
1137 .collect()
1138 }
1139
1140 fn test_graph_node(node_id: HashId, sequence_start: i64, sequence_end: i64) -> GraphNode {
1141 GraphNode {
1142 node_id,
1143 sequence_start,
1144 sequence_end,
1145 }
1146 }
1147
1148 fn test_terminal_block(block_index: i64, node_id: HashId) -> GroupBlock {
1149 GroupBlock::new(
1150 block_index,
1151 node_id,
1152 &Sequence::new().sequence_type("DNA").sequence("").build(),
1153 0,
1154 0,
1155 )
1156 }
1157
1158 fn assert_diff_edge_kind(
1159 graph: &DiffGenGraph,
1160 source: GraphNode,
1161 target: GraphNode,
1162 expected_kind: DiffChangeKind,
1163 ) {
1164 let source = graph
1165 .nodes()
1166 .find(|node| node.node == source)
1167 .expect("should contain source node");
1168 let target = graph
1169 .nodes()
1170 .find(|node| node.node == target)
1171 .expect("should contain target node");
1172 let edge_changes = graph
1173 .edge_weight(source, target)
1174 .expect("should contain edge between nodes");
1175 assert!(
1176 edge_changes
1177 .iter()
1178 .any(|edge| edge.change.kind == expected_kind),
1179 "edge should contain expected change kind {expected_kind:?}: {edge_changes:?}"
1180 );
1181 }
1182
1183 fn assert_all_nodes_connected_to(graph: &DiffGenGraph, start: GraphNode) {
1184 let start = graph
1185 .nodes()
1186 .find(|node| node.node == start)
1187 .expect("should contain start node");
1188 let mut visited = HashSet::new();
1189 let mut stack = vec![start];
1190 while let Some(current) = stack.pop() {
1191 if !visited.insert(current) {
1192 continue;
1193 }
1194 for neighbor in graph
1195 .neighbors_directed(current, Direction::Outgoing)
1196 .chain(graph.neighbors_directed(current, Direction::Incoming))
1197 {
1198 if !visited.contains(&neighbor) {
1199 stack.push(neighbor);
1200 }
1201 }
1202 }
1203 assert_eq!(
1204 visited.len(),
1205 graph.nodes().count(),
1206 "unified diff graph should be a single connected component"
1207 );
1208 }
1209
1210 #[test]
1211 fn test_one_operation_diff_uses_dolt_history() {
1212 let context = setup_history_context();
1213 let graph_conn = context.graph().conn();
1214
1215 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1216 let base_op = commit_operation(&context, "seed");
1217 let expected_block_group =
1218 create_linear_block_group(&context, "c", "s", "bg", "one", "CCCCC");
1219 let head = commit_operation(&context, "add");
1220
1221 let diff = collect_operation_diff(graph_conn, Some(base_op), head, DiffRange::TwoDot)
1222 .expect("diff");
1223 assert_eq!(diff.operations, vec![head]);
1224 assert_eq!(diff.diff_graph.len(), 1);
1225 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
1226 assert!(diff.diff_graph[0].source_block_group.is_none());
1227 assert_eq!(
1228 diff.diff_graph[0].target_block_group.as_ref(),
1229 Some(&expected_block_group)
1230 );
1231 assert_block_group_graph_shape(&diff.diff_graph[0]);
1232 }
1233
1234 #[test]
1235 fn test_initial_operation_diff_contains_added_block_groups_from_history() {
1236 let context = setup_history_context();
1237 let graph_conn = context.graph().conn();
1238
1239 let expected_block_group =
1240 create_linear_block_group(&context, "c", "s", "bg", "one", "AAAAA");
1241 let head = commit_operation(&context, "add");
1242
1243 let diff = collect_operation_diff(graph_conn, None, head, DiffRange::TwoDot).expect("diff");
1244 assert_eq!(diff.operations, vec![head]);
1245 assert_eq!(diff.diff_graph.len(), 1);
1246 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
1247 assert!(diff.diff_graph[0].source_block_group.is_none());
1248 assert_eq!(
1249 diff.diff_graph[0].target_block_group.as_ref(),
1250 Some(&expected_block_group)
1251 );
1252 assert_block_group_graph_shape(&diff.diff_graph[0]);
1253 }
1254
1255 #[test]
1256 fn test_operation_diff_rejects_missing_from_commit() {
1257 let context = setup_history_context();
1258 let graph_conn = context.graph().conn();
1259
1260 let missing_parent_hash = DoltHashId([1; 20]);
1261 create_linear_block_group(&context, "c", "s", "bg", "one", "AAAAA");
1262 let head = commit_operation(&context, "add");
1263
1264 let error = collect_operation_diff(
1265 graph_conn,
1266 Some(missing_parent_hash),
1267 head,
1268 DiffRange::TwoDot,
1269 )
1270 .expect_err("should reject a missing from commit");
1271 assert!(matches!(
1272 error,
1273 OperationDiffError::OperationMissing(hash) if hash == missing_parent_hash
1274 ));
1275 }
1276
1277 #[test]
1278 fn test_one_operation_diff_returns_removed_markers_in_unified_diff_graph() {
1279 let context = setup_history_context();
1280 let graph_conn = context.graph().conn();
1281
1282 let removed_block_group =
1283 create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1284 let base = commit_operation(&context, "seed");
1285 let block_group_edges =
1286 BlockGroupEdge::edges_for_block_group(graph_conn, &removed_block_group.id, None)
1287 .into_iter()
1288 .map(|edge| BlockGroupEdgeData {
1289 block_group_id: removed_block_group.id,
1290 edge_id: edge.edge.id,
1291 chromosome_index: edge.chromosome_index,
1292 phased: edge.phased,
1293 })
1294 .collect::<Vec<_>>();
1295 Path::delete(
1296 graph_conn,
1297 &removed_block_group.name,
1298 &removed_block_group.id,
1299 );
1300 BlockGroupEdge::bulk_delete(graph_conn, &block_group_edges);
1301 BlockGroup::delete(
1302 graph_conn,
1303 &removed_block_group.collection_name,
1304 &removed_block_group.sample_name,
1305 &removed_block_group.name,
1306 )
1307 .expect("should delete block group");
1308 let head = commit_operation(&context, "remove bg");
1309
1310 let diff =
1311 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
1312 assert_eq!(diff.operations, vec![head]);
1313 assert_eq!(diff.diff_graph.len(), 1);
1314 assert_eq!(diff.diff_graph[0].id, removed_block_group.id);
1315 assert_eq!(
1316 diff.diff_graph[0].source_block_group.as_ref(),
1317 Some(&removed_block_group)
1318 );
1319 assert!(diff.diff_graph[0].target_block_group.is_none());
1320 assert!(
1321 diff.diff_graph[0]
1322 .graph
1323 .nodes()
1324 .any(|node| node.change.kind == DiffChangeKind::Removed
1325 && node.change.operation == Some(head)),
1326 "removed nodes should be marked as removed and attributed to the removing operation"
1327 );
1328 assert!(
1329 diff.diff_graph[0]
1330 .graph
1331 .all_edges()
1332 .any(|(_, _, edges)| edges
1333 .iter()
1334 .any(|edge| edge.change.kind == DiffChangeKind::Removed
1335 && edge.change.operation == Some(head))),
1336 "removed edges should be marked as removed and attributed to the removing operation"
1337 );
1338 }
1339
1340 #[test]
1341 fn test_modified_block_group_returns_added_and_removed_markers_in_unified_diff_graph() {
1342 let context = setup_history_context();
1343 let graph_conn = context.graph().conn();
1344
1345 let block_group = create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1346 let base = commit_operation(&context, "seed");
1347 replace_linear_block_group_path(&context, &block_group, "replacement", "CCCCC");
1348 let head = commit_operation(&context, "replace bg path");
1349
1350 let diff =
1351 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
1352 assert_eq!(diff.diff_graph.len(), 1);
1353 assert!(diff.diff_graph[0].source_block_group.is_some());
1354 assert!(diff.diff_graph[0].target_block_group.is_some());
1355 assert!(
1356 diff.diff_graph[0]
1357 .graph
1358 .nodes()
1359 .any(|node| node.change.kind == DiffChangeKind::Added),
1360 "modified block group should contain added nodes"
1361 );
1362 assert!(
1363 diff.diff_graph[0]
1364 .graph
1365 .nodes()
1366 .any(|node| node.change.kind == DiffChangeKind::Removed),
1367 "modified block group should contain removed nodes"
1368 );
1369 assert!(
1370 diff.diff_graph[0]
1371 .graph
1372 .all_edges()
1373 .any(|(_, _, edges)| edges
1374 .iter()
1375 .any(|edge| edge.change.kind == DiffChangeKind::Added)),
1376 "modified block group should contain added edges"
1377 );
1378 assert!(
1379 diff.diff_graph[0]
1380 .graph
1381 .all_edges()
1382 .any(|(_, _, edges)| edges
1383 .iter()
1384 .any(|edge| edge.change.kind == DiffChangeKind::Removed)),
1385 "modified block group should contain removed edges"
1386 );
1387 }
1388
1389 #[test]
1390 fn test_source_graph_plus_dolt_changes_reconstructs_target_graph() {
1391 let context = setup_history_context();
1392 let graph_conn = context.graph().conn();
1393
1394 let block_group = create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1395 let base = commit_operation(&context, "seed");
1396 replace_linear_block_group_path(&context, &block_group, "replacement", "CCCCC");
1397 let head = commit_operation(&context, "replace bg path");
1398 let source_ref = commit_hash_ref(base).0;
1399 let target_ref = commit_hash_ref(head).0;
1400
1401 let source_edges =
1402 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, Some(&source_ref));
1403 let changes = collect_block_group_changes(
1404 graph_conn,
1405 &DiffRange::TwoDot.between(&source_ref, &target_ref),
1406 )
1407 .expect("should collect block group changes");
1408 let edge_changes = changes
1409 .edge_changes
1410 .get(&block_group.id)
1411 .expect("should contain edge changes for replaced path");
1412 let reconstructed_edges =
1413 apply_edge_changes(graph_conn, &source_edges, edge_changes, &target_ref)
1414 .expect("should apply edge changes");
1415
1416 let reconstructed_blocks = Edge::blocks_from_edges(
1417 graph_conn,
1418 context.workspace(),
1419 &block_group.id,
1420 &reconstructed_edges,
1421 Some(&target_ref),
1422 )
1423 .expect("should build reconstructed blocks");
1424 let target_edges =
1425 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, Some(&target_ref));
1426 let target_blocks = Edge::blocks_from_edges(
1427 graph_conn,
1428 context.workspace(),
1429 &block_group.id,
1430 &target_edges,
1431 Some(&target_ref),
1432 )
1433 .expect("should build target blocks");
1434 let reconstructed_graph = build_diff_input(
1435 &reconstructed_blocks,
1436 &reconstructed_edges,
1437 &HashMap::new(),
1438 &HashMap::new(),
1439 );
1440 let target_graph = build_diff_input(
1441 &target_blocks,
1442 &target_edges,
1443 &HashMap::new(),
1444 &HashMap::new(),
1445 );
1446
1447 assert_eq!(
1448 graph_edge_keys(reconstructed_graph.graph()),
1449 graph_edge_keys(target_graph.graph())
1450 );
1451 assert_eq!(
1452 reconstructed_graph.graph().nodes().collect::<HashSet<_>>(),
1453 target_graph.graph().nodes().collect::<HashSet<_>>()
1454 );
1455 }
1456
1457 #[test]
1458 fn test_graph_edge_keys_ignore_created_on() {
1459 let source = GraphNode {
1460 node_id: HashId::convert_str("source"),
1461 sequence_start: 0,
1462 sequence_end: 4,
1463 };
1464 let target = GraphNode {
1465 node_id: HashId::convert_str("target"),
1466 sequence_start: 0,
1467 sequence_end: 4,
1468 };
1469 let edge_id = HashId::convert_str("edge");
1470 let mut left_graph = GenGraph::new();
1471 left_graph.add_edge(
1472 source,
1473 target,
1474 vec![GraphEdge {
1475 edge_id,
1476 source_strand: Strand::Forward,
1477 target_strand: Strand::Forward,
1478 chromosome_index: 0,
1479 phased: 0,
1480 created_on: 1,
1481 }],
1482 );
1483 let mut right_graph = GenGraph::new();
1484 right_graph.add_edge(
1485 source,
1486 target,
1487 vec![GraphEdge {
1488 edge_id,
1489 source_strand: Strand::Forward,
1490 target_strand: Strand::Forward,
1491 chromosome_index: 0,
1492 phased: 0,
1493 created_on: 2,
1494 }],
1495 );
1496
1497 assert_eq!(
1498 graph_edge_keys(&left_graph),
1499 graph_edge_keys(&right_graph),
1500 "edge comparison should ignore block-group edge timestamps"
1501 );
1502 }
1503
1504 #[test]
1505 fn test_diff_input_graph_keeps_endpoint_local_node_slices() {
1506 let operation = DoltHashId([100; 20]);
1507 let node_id = HashId::convert_str("reference-node");
1508 let sequence = Sequence::new()
1509 .sequence_type("DNA")
1510 .sequence("AAAGTTTTTT")
1511 .build();
1512 let start_edge_id = HashId::convert_str("start-edge");
1513 let end_edge_id = HashId::convert_str("end-edge");
1514 let source_blocks = vec![GroupBlock::new(0, node_id, &sequence, 0, 10)];
1515 let target_blocks = vec![
1516 GroupBlock::new(0, node_id, &sequence, 0, 3),
1517 GroupBlock::new(1, node_id, &sequence, 4, 10),
1518 ];
1519 let input_edges = vec![
1520 test_augmented_edge(start_edge_id, PATH_START_NODE_ID, 0, node_id, 0),
1521 test_augmented_edge(end_edge_id, node_id, 10, PATH_END_NODE_ID, 0),
1522 ];
1523 let source_input_graph = build_diff_input(
1524 &source_blocks,
1525 &input_edges,
1526 &HashMap::new(),
1527 &HashMap::new(),
1528 );
1529 let target_input_graph = build_diff_input(
1530 &target_blocks,
1531 &input_edges,
1532 &HashMap::new(),
1533 &HashMap::from([(node_id, operation)]),
1534 );
1535
1536 let source_nodes = source_input_graph.graph().nodes().collect::<HashSet<_>>();
1537 assert!(
1538 source_nodes.contains(&GraphNode {
1539 node_id,
1540 sequence_start: 0,
1541 sequence_end: 10,
1542 }),
1543 "source graph should preserve its own unsplit block"
1544 );
1545 assert!(
1546 !source_nodes.contains(&GraphNode {
1547 node_id,
1548 sequence_start: 3,
1549 sequence_end: 4,
1550 }),
1551 "source graph should not synthesize slices from target-only boundaries"
1552 );
1553 let target_nodes = target_input_graph.graph().nodes().collect::<HashSet<_>>();
1554 assert!(
1555 target_nodes.contains(&GraphNode {
1556 node_id,
1557 sequence_start: 0,
1558 sequence_end: 3,
1559 }) && target_nodes.contains(&GraphNode {
1560 node_id,
1561 sequence_start: 4,
1562 sequence_end: 10,
1563 }),
1564 "target graph should use target-local blocks"
1565 );
1566 }
1567
1568 #[test]
1569 fn test_diff_input_graph_keeps_terminal_blocks_for_endpoint_lookup() {
1570 let node_id = HashId::convert_str("regular-node");
1571 let sequence = Sequence::new().sequence_type("DNA").sequence("ATC").build();
1572 let edge_id = HashId::convert_str("edge-to-start");
1573 let input_blocks = vec![
1574 test_terminal_block(0, PATH_START_NODE_ID),
1575 GroupBlock::new(1, node_id, &sequence, 0, 3),
1576 test_terminal_block(2, PATH_END_NODE_ID),
1577 ];
1578 let input_edges = vec![test_augmented_edge(
1579 edge_id,
1580 node_id,
1581 3,
1582 PATH_START_NODE_ID,
1583 0,
1584 )];
1585
1586 let input_graph = build_diff_input(
1587 &input_blocks,
1588 &input_edges,
1589 &HashMap::new(),
1590 &HashMap::new(),
1591 );
1592
1593 let regular_node = test_graph_node(node_id, 0, 3);
1594 assert!(
1595 input_graph
1596 .graph()
1597 .edge_weight(regular_node, path_start_graph_node())
1598 .is_some(),
1599 "terminal blocks should participate in endpoint lookup regardless of edge direction"
1600 );
1601 }
1602
1603 #[test]
1604 fn test_unified_diff_graph_connects_deletion_and_addition_through_common_terminals() {
1605 let operation = DoltHashId([100; 20]);
1610 let prefix_node_id = HashId::convert_str("prefix");
1611 let deleted_node_id = HashId::convert_str("deleted");
1612 let middle_node_id = HashId::convert_str("middle");
1613 let inserted_node_id = HashId::convert_str("inserted");
1614 let suffix_node_id = HashId::convert_str("suffix");
1615 let prefix_sequence = Sequence::new().sequence_type("DNA").sequence("ATC").build();
1616 let deleted_sequence = Sequence::new().sequence_type("DNA").sequence("G").build();
1617 let middle_sequence = Sequence::new()
1618 .sequence_type("DNA")
1619 .sequence("ATCGAT")
1620 .build();
1621 let inserted_sequence = Sequence::new().sequence_type("DNA").sequence("AGA").build();
1622 let suffix_sequence = Sequence::new()
1623 .sequence_type("DNA")
1624 .sequence("CGATC")
1625 .build();
1626 let prefix_node = test_graph_node(prefix_node_id, 0, 3);
1627 let deleted_node = test_graph_node(deleted_node_id, 0, 1);
1628 let middle_node = test_graph_node(middle_node_id, 0, 6);
1629 let inserted_node = test_graph_node(inserted_node_id, 0, 3);
1630 let suffix_node = test_graph_node(suffix_node_id, 0, 5);
1631 let source_blocks = vec![
1632 test_terminal_block(0, PATH_START_NODE_ID),
1633 GroupBlock::new(1, prefix_node_id, &prefix_sequence, 0, 3),
1634 GroupBlock::new(2, deleted_node_id, &deleted_sequence, 0, 1),
1635 GroupBlock::new(3, middle_node_id, &middle_sequence, 0, 6),
1636 GroupBlock::new(4, suffix_node_id, &suffix_sequence, 0, 5),
1637 test_terminal_block(5, PATH_END_NODE_ID),
1638 ];
1639 let target_blocks = vec![
1640 test_terminal_block(0, PATH_START_NODE_ID),
1641 GroupBlock::new(1, prefix_node_id, &prefix_sequence, 0, 3),
1642 GroupBlock::new(2, middle_node_id, &middle_sequence, 0, 6),
1643 GroupBlock::new(3, inserted_node_id, &inserted_sequence, 0, 3),
1644 GroupBlock::new(4, suffix_node_id, &suffix_sequence, 0, 5),
1645 test_terminal_block(5, PATH_END_NODE_ID),
1646 ];
1647 let source_edges = vec![
1648 test_augmented_edge(
1649 HashId::convert_str("shared-start-edge"),
1650 PATH_START_NODE_ID,
1651 0,
1652 prefix_node_id,
1653 0,
1654 ),
1655 test_augmented_edge(
1656 HashId::convert_str("removed-prefix-deleted"),
1657 prefix_node_id,
1658 3,
1659 deleted_node_id,
1660 0,
1661 ),
1662 test_augmented_edge(
1663 HashId::convert_str("removed-deleted-middle"),
1664 deleted_node_id,
1665 1,
1666 middle_node_id,
1667 0,
1668 ),
1669 test_augmented_edge(
1670 HashId::convert_str("source-middle-suffix"),
1671 middle_node_id,
1672 6,
1673 suffix_node_id,
1674 0,
1675 ),
1676 test_augmented_edge(
1677 HashId::convert_str("shared-end-edge"),
1678 suffix_node_id,
1679 5,
1680 PATH_END_NODE_ID,
1681 0,
1682 ),
1683 ];
1684 let target_edges = vec![
1685 test_augmented_edge(
1686 HashId::convert_str("shared-start-edge"),
1687 PATH_START_NODE_ID,
1688 0,
1689 prefix_node_id,
1690 0,
1691 ),
1692 test_augmented_edge(
1693 HashId::convert_str("added-prefix-middle"),
1694 prefix_node_id,
1695 3,
1696 middle_node_id,
1697 0,
1698 ),
1699 test_augmented_edge(
1700 HashId::convert_str("added-middle-inserted"),
1701 middle_node_id,
1702 6,
1703 inserted_node_id,
1704 0,
1705 ),
1706 test_augmented_edge(
1707 HashId::convert_str("added-inserted-suffix"),
1708 inserted_node_id,
1709 3,
1710 suffix_node_id,
1711 0,
1712 ),
1713 test_augmented_edge(
1714 HashId::convert_str("shared-end-edge"),
1715 suffix_node_id,
1716 5,
1717 PATH_END_NODE_ID,
1718 0,
1719 ),
1720 ];
1721 let source_graph = build_diff_input(
1722 &source_blocks,
1723 &source_edges,
1724 &HashMap::new(),
1725 &HashMap::new(),
1726 );
1727 let target_graph = build_diff_input(
1728 &target_blocks,
1729 &target_edges,
1730 &HashMap::new(),
1731 &HashMap::new(),
1732 );
1733 let graph = build_unified_diff_graph(&source_graph, &target_graph, Some(operation));
1734
1735 assert_eq!(
1736 graph
1737 .nodes()
1738 .filter(|node| node.node.node_id == PATH_START_NODE_ID)
1739 .count(),
1740 1,
1741 "source and target paths should share one start terminal"
1742 );
1743 assert_eq!(
1744 graph
1745 .nodes()
1746 .filter(|node| node.node.node_id == PATH_END_NODE_ID)
1747 .count(),
1748 1,
1749 "source and target paths should share one end terminal"
1750 );
1751 assert!(
1752 graph.nodes().any(
1753 |node| node.node == deleted_node && node.change.kind == DiffChangeKind::Removed
1754 ),
1755 "deleted G node should be rendered as removed"
1756 );
1757 assert!(
1758 graph.nodes().any(|node| node.node == inserted_node
1759 && node.change.kind == DiffChangeKind::Added),
1760 "inserted AGA node should be rendered as added"
1761 );
1762 assert_diff_edge_kind(&graph, prefix_node, deleted_node, DiffChangeKind::Removed);
1763 assert_diff_edge_kind(&graph, deleted_node, middle_node, DiffChangeKind::Removed);
1764 assert_diff_edge_kind(&graph, prefix_node, middle_node, DiffChangeKind::Added);
1765 assert_diff_edge_kind(&graph, middle_node, suffix_node, DiffChangeKind::Removed);
1766 assert_diff_edge_kind(&graph, middle_node, inserted_node, DiffChangeKind::Added);
1767 assert_diff_edge_kind(&graph, inserted_node, suffix_node, DiffChangeKind::Added);
1768 assert_all_nodes_connected_to(&graph, path_start_graph_node());
1769 assert_diff_edge_kind(
1770 &graph,
1771 path_start_graph_node(),
1772 prefix_node,
1773 DiffChangeKind::Unchanged,
1774 );
1775 assert_diff_edge_kind(
1776 &graph,
1777 suffix_node,
1778 path_end_graph_node(),
1779 DiffChangeKind::Unchanged,
1780 );
1781 }
1782
1783 #[test]
1784 fn test_merges_multiple_history_operations_preserve_operation_attribution() {
1785 let context = setup_history_context();
1786 let graph_conn = context.graph().conn();
1787
1788 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1789 let base = commit_operation(&context, "seed");
1790 create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1791 let first_operation = commit_operation(&context, "add one");
1792 create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1793 let second_operation = commit_operation(&context, "add two");
1794
1795 let expected_first_change =
1796 collect_operation_diff(graph_conn, Some(base), first_operation, DiffRange::TwoDot)
1797 .expect("first operation diff")
1798 .diff_graph
1799 .into_iter()
1800 .flat_map(|block_group| block_group.graph.nodes().collect::<Vec<_>>())
1801 .find(|node| {
1802 node.change.kind == DiffChangeKind::Added
1803 && node.change.operation == Some(first_operation)
1804 })
1805 .expect("first operation should add a node");
1806 let expected_second_change = collect_operation_diff(
1807 graph_conn,
1808 Some(first_operation),
1809 second_operation,
1810 DiffRange::TwoDot,
1811 )
1812 .expect("second operation diff")
1813 .diff_graph
1814 .into_iter()
1815 .flat_map(|block_group| block_group.graph.nodes().collect::<Vec<_>>())
1816 .find(|node| {
1817 node.change.kind == DiffChangeKind::Added
1818 && node.change.operation == Some(second_operation)
1819 })
1820 .expect("second operation should add a node");
1821
1822 let diff =
1823 collect_operation_diff(graph_conn, Some(base), second_operation, DiffRange::TwoDot)
1824 .expect("diff");
1825 assert_eq!(diff.operations, vec![first_operation, second_operation]);
1826
1827 let merged_changes = diff
1828 .diff_graph
1829 .iter()
1830 .flat_map(|block_group| block_group.graph.nodes())
1831 .map(|node| (node.node, node.change.kind))
1832 .collect::<HashSet<_>>();
1833
1834 assert!(
1835 merged_changes.contains(&(
1836 expected_first_change.node,
1837 expected_first_change.change.kind
1838 )),
1839 "merged diff should contain the node change introduced by the first operation"
1840 );
1841 assert!(
1842 merged_changes.contains(&(
1843 expected_second_change.node,
1844 expected_second_change.change.kind,
1845 )),
1846 "merged diff should contain the node change introduced by the second operation"
1847 );
1848 }
1849
1850 #[test]
1851 fn test_merges_multiple_history_operations() {
1852 let context = setup_history_context();
1853 let graph_conn = context.graph().conn();
1854
1855 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1856 let op1 = commit_operation(&context, "seed");
1857 let bg_one = create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1858 let op2 = commit_operation(&context, "add one");
1859 let bg_two = create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1860 let op3 = commit_operation(&context, "add two");
1861
1862 let diff =
1863 collect_operation_diff(graph_conn, Some(op1), op3, DiffRange::TwoDot).expect("diff");
1864 assert_eq!(diff.operations, vec![op2, op3]);
1865 assert_eq!(diff.diff_graph.len(), 2);
1866 assert_eq!(
1867 diff.diff_graph
1868 .iter()
1869 .map(|block_group| block_group.id)
1870 .collect::<Vec<_>>(),
1871 vec![bg_one.id, bg_two.id]
1872 );
1873 }
1874
1875 #[test]
1876 fn test_diff_to_non_head_commit_uses_target_history_state() {
1877 let context = setup_history_context();
1878 let graph_conn = context.graph().conn();
1879
1880 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1881 let base = commit_operation(&context, "seed");
1882 let bg_one = create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1883 let op_one = commit_operation(&context, "add one");
1884 let bg_two = create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1885 let op_two = commit_operation(&context, "add two");
1886
1887 let diff = collect_operation_diff(graph_conn, Some(base), op_one, DiffRange::TwoDot)
1888 .expect("diff");
1889 assert_eq!(diff.operations, vec![op_one]);
1890 assert_eq!(diff.diff_graph.len(), 1);
1891 assert_eq!(diff.diff_graph[0].id, bg_one.id);
1892 assert_ne!(diff.diff_graph[0].id, bg_two.id);
1893
1894 let later_diff =
1895 collect_operation_diff(graph_conn, Some(op_one), op_two, DiffRange::TwoDot)
1896 .expect("diff");
1897 assert_eq!(later_diff.operations, vec![op_two]);
1898 assert_eq!(later_diff.diff_graph.len(), 1);
1899 assert_eq!(later_diff.diff_graph[0].id, bg_two.id);
1900 }
1901
1902 #[test]
1903 fn diff_against_itself_is_empty() {
1904 let context = setup_history_context();
1905 let graph_conn = context.graph().conn();
1906 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1907 let base = commit_operation(&context, "seed");
1908 let diff =
1909 collect_operation_diff(graph_conn, Some(base), base, DiffRange::TwoDot).expect("diff");
1910 assert!(diff.operations.is_empty());
1911 }
1912
1913 #[test]
1914 fn test_two_dot_diff_reports_changes_on_both_divergent_branches() {
1915 let history = setup_divergent_history();
1916 let graph_conn = history.context.graph().conn();
1917 let source_ref = history.source_hash.to_string();
1918 let target_ref = history.target_hash.to_string();
1919 let raw_changes = collect_block_group_changes(
1920 graph_conn,
1921 &DiffRange::TwoDot.between(&source_ref, &target_ref),
1922 )
1923 .expect("should collect changes across branches");
1924 assert_eq!(
1925 raw_changes.block_group_ids,
1926 HashSet::from([history.source_block_group.id, history.target_block_group.id,]),
1927 "Dolt diff rows should contain the source removal and target addition"
1928 );
1929
1930 let diff = collect_operation_diff(
1931 graph_conn,
1932 Some(history.source_hash),
1933 history.target_hash,
1934 DiffRange::TwoDot,
1935 )
1936 .expect("should collect endpoint diff");
1937 assert_eq!(
1938 diff.operations,
1939 vec![history.source_hash, history.target_hash]
1940 );
1941 assert_eq!(
1942 diff.diff_graph.len(),
1943 2,
1944 "expected source {source:?} and target {target:?} changes, got block groups {:?}",
1945 diff.diff_graph
1946 .iter()
1947 .map(|block_group| block_group.id)
1948 .collect::<Vec<_>>(),
1949 source = history.source_block_group.id,
1950 target = history.target_block_group.id,
1951 );
1952 let source_diff = diff
1953 .diff_graph
1954 .iter()
1955 .find(|block_group| block_group.id == history.source_block_group.id)
1956 .expect("source-only block group should be reported as removed");
1957 assert!(source_diff.source_block_group.is_some());
1958 assert!(source_diff.target_block_group.is_none());
1959 let target_diff = diff
1960 .diff_graph
1961 .iter()
1962 .find(|block_group| block_group.id == history.target_block_group.id)
1963 .expect("target-only block group should be reported as added");
1964 assert!(target_diff.source_block_group.is_none());
1965 assert!(target_diff.target_block_group.is_some());
1966 }
1967
1968 #[test]
1969 fn test_three_dot_diff_reports_target_changes_from_merge_base() {
1970 let history = setup_divergent_history();
1971 let merge_base_diff = collect_operation_diff(
1972 history.context.graph().conn(),
1973 Some(history.source_hash),
1974 history.target_hash,
1975 DiffRange::ThreeDot,
1976 )
1977 .expect("should collect merge-base diff");
1978 assert_eq!(merge_base_diff.operations, vec![history.target_hash]);
1979 assert_eq!(
1980 merge_base_diff.diff_graph.len(),
1981 1,
1982 "three-dot diff should only report target changes from the merge base"
1983 );
1984 let target_diff = &merge_base_diff.diff_graph[0];
1985 assert_eq!(target_diff.id, history.target_block_group.id);
1986 assert!(target_diff.source_block_group.is_none());
1987 assert!(target_diff.target_block_group.is_some());
1988 }
1989
1990 #[test]
1991 fn test_uses_default_graph_database_for_history_diffs() {
1992 let context = setup_history_context();
1993 let graph_conn = context.graph().conn();
1994
1995 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1996 let base = commit_operation(&context, "seed");
1997 let expected_block_group =
1998 create_linear_block_group(&context, "c", "s", "db-one", "one", "CCCCC");
1999 let head = commit_operation(&context, "add");
2000
2001 let diff =
2002 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
2003 assert_eq!(diff.operations, vec![head]);
2004 assert_eq!(diff.diff_graph.len(), 1);
2005 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
2006 }
2007
2008 #[test]
2009 fn test_diffs_follow_reset_replacement_history() {
2010 let mut context = setup_history_context();
2011 let graph_conn = context.graph().conn();
2012 let graph_db_path = context
2013 .workspace()
2014 .graph_db_path()
2015 .expect("should resolve graph db path");
2016 let history_store = DoltHistoryStore::new(graph_conn);
2017
2018 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
2019 let base = commit_operation(&context, "seed");
2020 let retained_block_group =
2021 create_linear_block_group(&context, "c", "s", "retained", "one", "CCCCC");
2022 let retained_commit = commit_operation(&context, "retained");
2023 let discarded_block_group =
2024 create_linear_block_group(&context, "c", "s", "discarded", "two", "GGGGG");
2025 commit_operation(&context, "discarded");
2026
2027 history_store
2028 .reset_hard(&commit_hash_ref(retained_commit))
2029 .expect("should reset to retained commit");
2030 let reopened_graph =
2031 gen_models::db::get_connection(&graph_db_path).expect("should reopen graph db");
2032 gen_models::history::dolt::connect_branch(&reopened_graph, "main")
2033 .expect("should reconnect reopened main branch");
2034 context.set_graph(reopened_graph);
2035 let replacement_block_group =
2036 create_linear_block_group(&context, "c", "s", "replacement", "three", "TTTTT");
2037 let replacement_commit = commit_operation(&context, "replacement");
2038 let reopened_graph_after_replacement =
2039 gen_models::db::get_connection(&graph_db_path).expect("should reopen graph db");
2040 gen_models::history::dolt::connect_branch(&reopened_graph_after_replacement, "main")
2041 .expect("should reconnect reopened main branch");
2042 let discarded_exists = reopened_graph_after_replacement
2043 .query_row(
2044 "SELECT EXISTS(SELECT 1 FROM block_groups WHERE id = ?1)",
2045 params![discarded_block_group.id],
2046 |row| row.get::<_, bool>(0),
2047 )
2048 .expect("should query reopened reset snapshot");
2049 let graph_conn = context.graph().conn();
2050 let diff = collect_operation_diff(
2051 graph_conn,
2052 Some(base),
2053 replacement_commit,
2054 DiffRange::TwoDot,
2055 )
2056 .expect("diff");
2057 assert_eq!(diff.operations, vec![retained_commit, replacement_commit]);
2058 assert!(
2059 !discarded_exists,
2060 "discarded block group should not remain in the post-reset snapshot"
2061 );
2062 assert_eq!(diff.diff_graph.len(), 2);
2063 let added_ids = diff
2064 .diff_graph
2065 .iter()
2066 .map(|block_group| block_group.id)
2067 .collect::<HashSet<_>>();
2068 assert_eq!(
2069 added_ids,
2070 HashSet::from([retained_block_group.id, replacement_block_group.id])
2071 );
2072 assert!(
2073 diff.diff_graph
2074 .iter()
2075 .all(|block_group| block_group.id != discarded_block_group.id),
2076 "discarded commit should not survive the reset path"
2077 );
2078 }
2079
2080 #[test]
2081 fn test_merge_commit_diff_includes_merged_branch_state() {
2082 let context = setup_history_context();
2083 let graph_conn = context.graph().conn();
2084 let history_store = DoltHistoryStore::new(graph_conn);
2085
2086 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
2087 let base = commit_operation(&context, "seed");
2088 let main_block_group =
2089 create_linear_block_group(&context, "c", "s", "main", "main", "CCCCC");
2090 let main_commit = commit_operation(&context, "main");
2091
2092 create_feature_branch(&context, base, "feature");
2093 let feature_block_group =
2094 create_linear_block_group(&context, "c", "s", "feature", "feature", "GGGGG");
2095 commit_operation(&context, "feature");
2096
2097 switch_branch(&context, "main");
2098 graph_conn
2099 .with_transaction(|| history_store.merge(&CommitRef("feature".to_string())))
2100 .expect("should merge feature branch");
2101 let merge_commit = history_store
2102 .current_head()
2103 .expect("should resolve current head")
2104 .expect("should have merge head");
2105 let merge_hash = merge_commit;
2106
2107 let diff = collect_operation_diff(graph_conn, Some(base), merge_hash, DiffRange::TwoDot)
2108 .expect("diff");
2109 assert!(
2110 diff.operations.contains(&main_commit),
2111 "diff should include main-branch history"
2112 );
2113 assert!(
2114 diff.operations.contains(&merge_hash),
2115 "diff should include the merge commit"
2116 );
2117 let added_ids = diff
2118 .diff_graph
2119 .iter()
2120 .map(|block_group| block_group.id)
2121 .collect::<HashSet<_>>();
2122 assert_eq!(
2123 added_ids,
2124 HashSet::from([main_block_group.id, feature_block_group.id])
2125 );
2126 }
2127
2128 fn assert_block_group_graph_shape(block_group_diff: &BlockGroupDiff) {
2129 assert_eq!(block_group_diff.graph.nodes().count(), 3);
2130 assert_eq!(block_group_diff.graph.all_edges().count(), 2);
2131 }
2132}