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::{
686 collections::{HashMap, HashSet},
687 fs,
688 };
689
690 use gen_core::{
691 BranchName, CommitRef, DoltHashId, HashId, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand,
692 Workspace,
693 };
694 use gen_graph::{GenGraph, GraphEdge, GraphNode};
695 use gen_models::{
696 block_group::{BlockGroup, NewBlockGroup},
697 block_group_edge::{AugmentedEdge, BlockGroupEdge, BlockGroupEdgeData},
698 collection::Collection,
699 db::DbContext,
700 edge::{Edge, GroupBlock},
701 history::{HistoryStore, dolt::DoltHistoryStore},
702 node::Node,
703 path::Path,
704 sample::{NewSample, Sample},
705 sequence::Sequence,
706 };
707 use petgraph::Direction;
708 use rusqlite::params;
709 use tempfile::tempdir;
710
711 use super::{
712 BlockGroupDiff, BlockGroupEdgeChange, BlockGroupEdgeKey, DiffRange, OperationDiffError,
713 collect_block_group_changes, collect_operation_diff,
714 };
715 use crate::{
716 graph::{
717 DiffChangeKind, DiffGenGraph, DiffInputGraph, GraphEdgeKey, build_diff_input_graph,
718 build_unified_diff_graph, path_end_graph_node, path_start_graph_node,
719 },
720 test_helpers::{TestContext, get_config_connection, get_connection as test_get_connection},
721 };
722
723 fn setup_history_context() -> TestContext {
724 let tmp_dir = tempdir().expect("should create temp dir");
725 let workspace = Workspace::new(tmp_dir.path());
726 workspace.ensure_gen_dir();
727 let graph_conn = test_get_connection(workspace.graph_db_path().unwrap().to_str().unwrap())
728 .expect("should create graph database");
729 let config_conn = get_config_connection(workspace.gen_db_path().unwrap().to_str().unwrap())
730 .expect("should create config database");
731 TestContext::new(
732 DbContext::new(workspace, graph_conn, config_conn).expect("should create db context"),
733 tmp_dir,
734 )
735 }
736
737 #[test]
738 fn test_setup_history_context_temp_dir_cleanup() {
739 let context = setup_history_context();
740 let base_dir = context.workspace().base_dir().to_path_buf();
741 let nested_asset = context
742 .workspace()
743 .asset_dir()
744 .expect("should resolve workspace asset directory")
745 .join("nested/fixture.txt");
746 fs::create_dir_all(
747 nested_asset
748 .parent()
749 .expect("should have a parent directory"),
750 )
751 .expect("should create nested fixture asset directory");
752 fs::write(&nested_asset, "temporary workspace asset")
753 .expect("should write nested fixture asset");
754
755 let context_clone = context.clone();
756 drop(context);
757 assert!(
758 base_dir.is_dir(),
759 "context clone should keep workspace alive"
760 );
761 assert_eq!(
762 fs::read_to_string(nested_asset).expect("should read nested fixture asset"),
763 "temporary workspace asset"
764 );
765
766 drop(context_clone);
767 assert!(
768 !base_dir.exists(),
769 "workspace should be removed after its last context drops"
770 );
771 }
772
773 fn create_linear_block_group(
774 context: &gen_models::db::DbContext,
775 collection_name: &str,
776 sample_name: &str,
777 block_group_name: &str,
778 node_name: &str,
779 sequence_bases: &str,
780 ) -> BlockGroup {
781 let graph_conn = context.graph().conn();
782 Collection::get_or_create(graph_conn, collection_name).expect("should create collection");
783 Sample::get_or_create(
784 graph_conn,
785 NewSample {
786 name: sample_name,
787 is_reference: false,
788 },
789 )
790 .expect("should create sample");
791 let block_group = BlockGroup::create(
792 graph_conn,
793 NewBlockGroup {
794 collection_name,
795 sample_name,
796 name: block_group_name,
797 ..Default::default()
798 },
799 )
800 .expect("should create block group");
801 let sequence = Sequence::new()
802 .sequence_type("DNA")
803 .sequence(sequence_bases)
804 .name(node_name)
805 .save(graph_conn)
806 .expect("should save sequence");
807 let node_id = Node::create(
808 graph_conn,
809 &sequence.hash,
810 &HashId::convert_str(&format!("{block_group_name}-{node_name}")),
811 )
812 .expect("should create node");
813 let start_edge = Edge::create(
814 graph_conn,
815 PATH_START_NODE_ID,
816 0,
817 Strand::Forward,
818 node_id,
819 0,
820 Strand::Forward,
821 )
822 .expect("should create start edge");
823 let end_edge = Edge::create(
824 graph_conn,
825 node_id,
826 sequence.length,
827 Strand::Forward,
828 PATH_END_NODE_ID,
829 0,
830 Strand::Forward,
831 )
832 .expect("should create end edge");
833 BlockGroupEdge::bulk_create(
834 graph_conn,
835 &[
836 BlockGroupEdgeData {
837 block_group_id: block_group.id,
838 edge_id: start_edge.id,
839 chromosome_index: 0,
840 phased: 0,
841 },
842 BlockGroupEdgeData {
843 block_group_id: block_group.id,
844 edge_id: end_edge.id,
845 chromosome_index: 0,
846 phased: 0,
847 },
848 ],
849 );
850 Path::create(
851 graph_conn,
852 block_group_name,
853 &block_group.id,
854 &[start_edge.id, end_edge.id],
855 )
856 .expect("should create path");
857 block_group
858 }
859
860 fn replace_linear_block_group_path(
861 context: &gen_models::db::DbContext,
862 block_group: &BlockGroup,
863 node_name: &str,
864 sequence_bases: &str,
865 ) {
866 let graph_conn = context.graph().conn();
867 let existing_edges =
868 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, None)
869 .into_iter()
870 .map(|edge| BlockGroupEdgeData {
871 block_group_id: block_group.id,
872 edge_id: edge.edge.id,
873 chromosome_index: edge.chromosome_index,
874 phased: edge.phased,
875 })
876 .collect::<Vec<_>>();
877 Path::delete(graph_conn, &block_group.name, &block_group.id);
878 BlockGroupEdge::bulk_delete(graph_conn, &existing_edges);
879
880 let sequence = Sequence::new()
881 .sequence_type("DNA")
882 .sequence(sequence_bases)
883 .name(node_name)
884 .save(graph_conn)
885 .expect("should save replacement sequence");
886 let node_id = Node::create(
887 graph_conn,
888 &sequence.hash,
889 &HashId::convert_str(&format!("{}-{node_name}", block_group.name)),
890 )
891 .expect("should create replacement node");
892 let start_edge = Edge::create(
893 graph_conn,
894 PATH_START_NODE_ID,
895 0,
896 Strand::Forward,
897 node_id,
898 0,
899 Strand::Forward,
900 )
901 .expect("should create replacement start edge");
902 let end_edge = Edge::create(
903 graph_conn,
904 node_id,
905 sequence.length,
906 Strand::Forward,
907 PATH_END_NODE_ID,
908 0,
909 Strand::Forward,
910 )
911 .expect("should create replacement end edge");
912 BlockGroupEdge::bulk_create(
913 graph_conn,
914 &[
915 BlockGroupEdgeData {
916 block_group_id: block_group.id,
917 edge_id: start_edge.id,
918 chromosome_index: 0,
919 phased: 0,
920 },
921 BlockGroupEdgeData {
922 block_group_id: block_group.id,
923 edge_id: end_edge.id,
924 chromosome_index: 0,
925 phased: 0,
926 },
927 ],
928 );
929 Path::create(
930 graph_conn,
931 &block_group.name,
932 &block_group.id,
933 &[start_edge.id, end_edge.id],
934 )
935 .expect("should recreate path");
936 }
937
938 fn commit_operation(context: &gen_models::db::DbContext, message: &str) -> DoltHashId {
939 let history_store = DoltHistoryStore::new(context.graph().conn());
940 history_store
941 .commit_all(message)
942 .expect("should commit graph changes")
943 }
944
945 fn commit_hash_ref(operation_hash: DoltHashId) -> CommitRef {
946 CommitRef(operation_hash.to_string())
947 }
948
949 struct DivergentHistory {
950 context: TestContext,
951 source_block_group: BlockGroup,
952 target_block_group: BlockGroup,
953 source_hash: DoltHashId,
954 target_hash: DoltHashId,
955 }
956
957 fn setup_divergent_history() -> DivergentHistory {
969 let mut context = setup_history_context();
970 let graph_conn = context.graph().conn();
971 let graph_db_path = context
972 .workspace()
973 .graph_db_path()
974 .expect("should resolve graph database path");
975 let history_store = DoltHistoryStore::new(graph_conn);
976
977 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
978 let base = commit_operation(&context, "seed");
979 let source_block_group =
980 create_linear_block_group(&context, "c", "s", "main", "main", "CCCCC");
981 let source_hash = commit_operation(&context, "main op");
982 history_store
983 .create_branch(
984 &BranchName("source".to_string()),
985 Some(&commit_hash_ref(source_hash)),
986 )
987 .expect("should preserve the source branch");
988 history_store
989 .reset_hard(&commit_hash_ref(base))
990 .expect("should reset main to the common base");
991 let reopened_graph = gen_models::db::get_connection(&graph_db_path)
992 .expect("should reopen graph database after reset");
993 gen_models::history::dolt::connect_branch(&reopened_graph, "main")
994 .expect("should reconnect the main branch");
995 context.set_graph(reopened_graph);
996 let target_block_group =
997 create_linear_block_group(&context, "c", "s", "feature", "feature", "GGGGG");
998 let target_hash = commit_operation(&context, "feature op");
999
1000 DivergentHistory {
1001 context,
1002 source_block_group,
1003 target_block_group,
1004 source_hash,
1005 target_hash,
1006 }
1007 }
1008
1009 fn switch_branch(context: &gen_models::db::DbContext, branch_name: &str) {
1010 let history_store = DoltHistoryStore::new(context.graph().conn());
1011 history_store
1012 .checkout_branch(&BranchName(branch_name.to_string()))
1013 .expect("should checkout history branch");
1014 }
1015
1016 fn create_feature_branch(
1017 context: &gen_models::db::DbContext,
1018 base_operation_hash: DoltHashId,
1019 branch_name: &str,
1020 ) {
1021 let history_store = DoltHistoryStore::new(context.graph().conn());
1022 history_store
1023 .create_branch(
1024 &BranchName(branch_name.to_string()),
1025 Some(&commit_hash_ref(base_operation_hash)),
1026 )
1027 .expect("should create history branch");
1028 switch_branch(context, branch_name);
1029 }
1030
1031 fn test_augmented_edge(
1032 edge_id: HashId,
1033 source_node_id: HashId,
1034 source_coordinate: i64,
1035 target_node_id: HashId,
1036 target_coordinate: i64,
1037 ) -> AugmentedEdge {
1038 AugmentedEdge {
1039 edge: Edge {
1040 id: edge_id,
1041 source_node_id,
1042 source_coordinate,
1043 source_strand: Strand::Forward,
1044 target_node_id,
1045 target_coordinate,
1046 target_strand: Strand::Forward,
1047 },
1048 chromosome_index: 0,
1049 phased: 0,
1050 created_on: 0,
1051 }
1052 }
1053
1054 fn apply_edge_changes(
1055 graph_conn: &gen_models::db::GraphConnection,
1056 source_edges: &[AugmentedEdge],
1057 edge_changes: &[BlockGroupEdgeChange],
1058 target_ref: &str,
1059 ) -> Result<Vec<AugmentedEdge>, OperationDiffError> {
1060 let mut edges_by_key = source_edges
1061 .iter()
1062 .cloned()
1063 .map(|edge| (BlockGroupEdgeKey::from(&edge), edge))
1064 .collect::<HashMap<_, _>>();
1065
1066 for edge_change in edge_changes {
1067 if let Some(old_key) = edge_change.old_key {
1068 edges_by_key.remove(&old_key);
1069 }
1070 if let Some(new_key) = edge_change.new_key {
1071 let edge = load_augmented_edge(
1072 graph_conn,
1073 edge_change.block_group_id,
1074 new_key,
1075 target_ref,
1076 )?;
1077 edges_by_key.insert(new_key, edge);
1078 }
1079 }
1080
1081 let mut edges = edges_by_key.into_values().collect::<Vec<_>>();
1082 edges.sort_by(|left, right| {
1083 right
1084 .created_on
1085 .cmp(&left.created_on)
1086 .then_with(|| left.edge.id.cmp(&right.edge.id))
1087 .then_with(|| left.chromosome_index.cmp(&right.chromosome_index))
1088 .then_with(|| left.phased.cmp(&right.phased))
1089 });
1090 Ok(edges)
1091 }
1092
1093 fn load_augmented_edge(
1094 graph_conn: &gen_models::db::GraphConnection,
1095 block_group_id: HashId,
1096 edge_key: BlockGroupEdgeKey,
1097 history_ref: &str,
1098 ) -> Result<AugmentedEdge, OperationDiffError> {
1099 let query = "SELECT
1100 edges.id,
1101 edges.source_node_id,
1102 edges.source_coordinate,
1103 edges.source_strand,
1104 edges.target_node_id,
1105 edges.target_coordinate,
1106 edges.target_strand,
1107 block_group_edges.chromosome_index,
1108 block_group_edges.phased,
1109 block_group_edges.created_on
1110 FROM dolt_at_block_group_edges(?1) AS block_group_edges
1111 JOIN dolt_at_edges(?1) AS edges ON edges.id = block_group_edges.edge_id
1112 WHERE block_group_edges.block_group_id = ?2
1113 AND block_group_edges.edge_id = ?3
1114 AND block_group_edges.chromosome_index = ?4
1115 AND block_group_edges.phased = ?5";
1116 graph_conn
1117 .query_row(
1118 query,
1119 params![
1120 history_ref,
1121 block_group_id,
1122 edge_key.edge_id,
1123 edge_key.chromosome_index,
1124 edge_key.phased
1125 ],
1126 |row| {
1127 Ok(AugmentedEdge {
1128 edge: Edge {
1129 id: row.get(0)?,
1130 source_node_id: row.get(1)?,
1131 source_coordinate: row.get(2)?,
1132 source_strand: row.get(3)?,
1133 target_node_id: row.get(4)?,
1134 target_coordinate: row.get(5)?,
1135 target_strand: row.get(6)?,
1136 },
1137 chromosome_index: row.get(7)?,
1138 phased: row.get(8)?,
1139 created_on: row.get(9)?,
1140 })
1141 },
1142 )
1143 .map_err(OperationDiffError::from)
1144 }
1145
1146 fn build_diff_input(
1147 input_blocks: &[GroupBlock],
1148 input_edges: &[AugmentedEdge],
1149 node_operations_by_id: &HashMap<HashId, DoltHashId>,
1150 edge_operations_by_id: &HashMap<HashId, DoltHashId>,
1151 ) -> DiffInputGraph {
1152 let input_nodes = input_blocks
1153 .iter()
1154 .map(|block| GraphNode {
1155 node_id: block.node_id,
1156 sequence_start: block.start,
1157 sequence_end: block.end,
1158 })
1159 .collect::<HashSet<_>>();
1160 let continuation_spans = input_nodes.clone();
1161 build_diff_input_graph(
1162 input_nodes,
1163 &continuation_spans,
1164 input_edges,
1165 node_operations_by_id,
1166 edge_operations_by_id,
1167 )
1168 }
1169
1170 fn graph_edge_keys(graph: &GenGraph) -> HashSet<GraphEdgeKey> {
1171 graph
1172 .all_edges()
1173 .flat_map(|(source, target, edges)| {
1174 edges
1175 .iter()
1176 .copied()
1177 .map(move |edge| GraphEdgeKey::new(source, target, edge))
1178 })
1179 .collect()
1180 }
1181
1182 fn test_graph_node(node_id: HashId, sequence_start: i64, sequence_end: i64) -> GraphNode {
1183 GraphNode {
1184 node_id,
1185 sequence_start,
1186 sequence_end,
1187 }
1188 }
1189
1190 fn test_terminal_block(block_index: i64, node_id: HashId) -> GroupBlock {
1191 GroupBlock::new(
1192 block_index,
1193 node_id,
1194 &Sequence::new().sequence_type("DNA").sequence("").build(),
1195 0,
1196 0,
1197 )
1198 }
1199
1200 fn assert_diff_edge_kind(
1201 graph: &DiffGenGraph,
1202 source: GraphNode,
1203 target: GraphNode,
1204 expected_kind: DiffChangeKind,
1205 ) {
1206 let source = graph
1207 .nodes()
1208 .find(|node| node.node == source)
1209 .expect("should contain source node");
1210 let target = graph
1211 .nodes()
1212 .find(|node| node.node == target)
1213 .expect("should contain target node");
1214 let edge_changes = graph
1215 .edge_weight(source, target)
1216 .expect("should contain edge between nodes");
1217 assert!(
1218 edge_changes
1219 .iter()
1220 .any(|edge| edge.change.kind == expected_kind),
1221 "edge should contain expected change kind {expected_kind:?}: {edge_changes:?}"
1222 );
1223 }
1224
1225 fn assert_all_nodes_connected_to(graph: &DiffGenGraph, start: GraphNode) {
1226 let start = graph
1227 .nodes()
1228 .find(|node| node.node == start)
1229 .expect("should contain start node");
1230 let mut visited = HashSet::new();
1231 let mut stack = vec![start];
1232 while let Some(current) = stack.pop() {
1233 if !visited.insert(current) {
1234 continue;
1235 }
1236 for neighbor in graph
1237 .neighbors_directed(current, Direction::Outgoing)
1238 .chain(graph.neighbors_directed(current, Direction::Incoming))
1239 {
1240 if !visited.contains(&neighbor) {
1241 stack.push(neighbor);
1242 }
1243 }
1244 }
1245 assert_eq!(
1246 visited.len(),
1247 graph.nodes().count(),
1248 "unified diff graph should be a single connected component"
1249 );
1250 }
1251
1252 #[test]
1253 fn test_one_operation_diff_uses_dolt_history() {
1254 let context = setup_history_context();
1255 let graph_conn = context.graph().conn();
1256
1257 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1258 let base_op = commit_operation(&context, "seed");
1259 let expected_block_group =
1260 create_linear_block_group(&context, "c", "s", "bg", "one", "CCCCC");
1261 let head = commit_operation(&context, "add");
1262
1263 let diff = collect_operation_diff(graph_conn, Some(base_op), head, DiffRange::TwoDot)
1264 .expect("diff");
1265 assert_eq!(diff.operations, vec![head]);
1266 assert_eq!(diff.diff_graph.len(), 1);
1267 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
1268 assert!(diff.diff_graph[0].source_block_group.is_none());
1269 assert_eq!(
1270 diff.diff_graph[0].target_block_group.as_ref(),
1271 Some(&expected_block_group)
1272 );
1273 assert_block_group_graph_shape(&diff.diff_graph[0]);
1274 }
1275
1276 #[test]
1277 fn test_initial_operation_diff_contains_added_block_groups_from_history() {
1278 let context = setup_history_context();
1279 let graph_conn = context.graph().conn();
1280
1281 let expected_block_group =
1282 create_linear_block_group(&context, "c", "s", "bg", "one", "AAAAA");
1283 let head = commit_operation(&context, "add");
1284
1285 let diff = collect_operation_diff(graph_conn, None, head, DiffRange::TwoDot).expect("diff");
1286 assert_eq!(diff.operations, vec![head]);
1287 assert_eq!(diff.diff_graph.len(), 1);
1288 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
1289 assert!(diff.diff_graph[0].source_block_group.is_none());
1290 assert_eq!(
1291 diff.diff_graph[0].target_block_group.as_ref(),
1292 Some(&expected_block_group)
1293 );
1294 assert_block_group_graph_shape(&diff.diff_graph[0]);
1295 }
1296
1297 #[test]
1298 fn test_operation_diff_rejects_missing_from_commit() {
1299 let context = setup_history_context();
1300 let graph_conn = context.graph().conn();
1301
1302 let missing_parent_hash = DoltHashId([1; 20]);
1303 create_linear_block_group(&context, "c", "s", "bg", "one", "AAAAA");
1304 let head = commit_operation(&context, "add");
1305
1306 let error = collect_operation_diff(
1307 graph_conn,
1308 Some(missing_parent_hash),
1309 head,
1310 DiffRange::TwoDot,
1311 )
1312 .expect_err("should reject a missing from commit");
1313 assert!(matches!(
1314 error,
1315 OperationDiffError::OperationMissing(hash) if hash == missing_parent_hash
1316 ));
1317 }
1318
1319 #[test]
1320 fn test_one_operation_diff_returns_removed_markers_in_unified_diff_graph() {
1321 let context = setup_history_context();
1322 let graph_conn = context.graph().conn();
1323
1324 let removed_block_group =
1325 create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1326 let base = commit_operation(&context, "seed");
1327 let block_group_edges =
1328 BlockGroupEdge::edges_for_block_group(graph_conn, &removed_block_group.id, None)
1329 .into_iter()
1330 .map(|edge| BlockGroupEdgeData {
1331 block_group_id: removed_block_group.id,
1332 edge_id: edge.edge.id,
1333 chromosome_index: edge.chromosome_index,
1334 phased: edge.phased,
1335 })
1336 .collect::<Vec<_>>();
1337 Path::delete(
1338 graph_conn,
1339 &removed_block_group.name,
1340 &removed_block_group.id,
1341 );
1342 BlockGroupEdge::bulk_delete(graph_conn, &block_group_edges);
1343 BlockGroup::delete(
1344 graph_conn,
1345 &removed_block_group.collection_name,
1346 &removed_block_group.sample_name,
1347 &removed_block_group.name,
1348 )
1349 .expect("should delete block group");
1350 let head = commit_operation(&context, "remove bg");
1351
1352 let diff =
1353 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
1354 assert_eq!(diff.operations, vec![head]);
1355 assert_eq!(diff.diff_graph.len(), 1);
1356 assert_eq!(diff.diff_graph[0].id, removed_block_group.id);
1357 assert_eq!(
1358 diff.diff_graph[0].source_block_group.as_ref(),
1359 Some(&removed_block_group)
1360 );
1361 assert!(diff.diff_graph[0].target_block_group.is_none());
1362 assert!(
1363 diff.diff_graph[0]
1364 .graph
1365 .nodes()
1366 .any(|node| node.change.kind == DiffChangeKind::Removed
1367 && node.change.operation == Some(head)),
1368 "removed nodes should be marked as removed and attributed to the removing operation"
1369 );
1370 assert!(
1371 diff.diff_graph[0]
1372 .graph
1373 .all_edges()
1374 .any(|(_, _, edges)| edges
1375 .iter()
1376 .any(|edge| edge.change.kind == DiffChangeKind::Removed
1377 && edge.change.operation == Some(head))),
1378 "removed edges should be marked as removed and attributed to the removing operation"
1379 );
1380 }
1381
1382 #[test]
1383 fn test_modified_block_group_returns_added_and_removed_markers_in_unified_diff_graph() {
1384 let context = setup_history_context();
1385 let graph_conn = context.graph().conn();
1386
1387 let block_group = create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1388 let base = commit_operation(&context, "seed");
1389 replace_linear_block_group_path(&context, &block_group, "replacement", "CCCCC");
1390 let head = commit_operation(&context, "replace bg path");
1391
1392 let diff =
1393 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
1394 assert_eq!(diff.diff_graph.len(), 1);
1395 assert!(diff.diff_graph[0].source_block_group.is_some());
1396 assert!(diff.diff_graph[0].target_block_group.is_some());
1397 assert!(
1398 diff.diff_graph[0]
1399 .graph
1400 .nodes()
1401 .any(|node| node.change.kind == DiffChangeKind::Added),
1402 "modified block group should contain added nodes"
1403 );
1404 assert!(
1405 diff.diff_graph[0]
1406 .graph
1407 .nodes()
1408 .any(|node| node.change.kind == DiffChangeKind::Removed),
1409 "modified block group should contain removed nodes"
1410 );
1411 assert!(
1412 diff.diff_graph[0]
1413 .graph
1414 .all_edges()
1415 .any(|(_, _, edges)| edges
1416 .iter()
1417 .any(|edge| edge.change.kind == DiffChangeKind::Added)),
1418 "modified block group should contain added edges"
1419 );
1420 assert!(
1421 diff.diff_graph[0]
1422 .graph
1423 .all_edges()
1424 .any(|(_, _, edges)| edges
1425 .iter()
1426 .any(|edge| edge.change.kind == DiffChangeKind::Removed)),
1427 "modified block group should contain removed edges"
1428 );
1429 }
1430
1431 #[test]
1432 fn test_source_graph_plus_dolt_changes_reconstructs_target_graph() {
1433 let context = setup_history_context();
1434 let graph_conn = context.graph().conn();
1435
1436 let block_group = create_linear_block_group(&context, "c", "s", "bg", "seed", "AAAAA");
1437 let base = commit_operation(&context, "seed");
1438 replace_linear_block_group_path(&context, &block_group, "replacement", "CCCCC");
1439 let head = commit_operation(&context, "replace bg path");
1440 let source_ref = commit_hash_ref(base).0;
1441 let target_ref = commit_hash_ref(head).0;
1442
1443 let source_edges =
1444 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, Some(&source_ref));
1445 let changes = collect_block_group_changes(
1446 graph_conn,
1447 &DiffRange::TwoDot.between(&source_ref, &target_ref),
1448 )
1449 .expect("should collect block group changes");
1450 let edge_changes = changes
1451 .edge_changes
1452 .get(&block_group.id)
1453 .expect("should contain edge changes for replaced path");
1454 let reconstructed_edges =
1455 apply_edge_changes(graph_conn, &source_edges, edge_changes, &target_ref)
1456 .expect("should apply edge changes");
1457
1458 let reconstructed_blocks = Edge::blocks_from_edges(
1459 graph_conn,
1460 context.workspace(),
1461 &block_group.id,
1462 &reconstructed_edges,
1463 Some(&target_ref),
1464 )
1465 .expect("should build reconstructed blocks");
1466 let target_edges =
1467 BlockGroupEdge::edges_for_block_group(graph_conn, &block_group.id, Some(&target_ref));
1468 let target_blocks = Edge::blocks_from_edges(
1469 graph_conn,
1470 context.workspace(),
1471 &block_group.id,
1472 &target_edges,
1473 Some(&target_ref),
1474 )
1475 .expect("should build target blocks");
1476 let reconstructed_graph = build_diff_input(
1477 &reconstructed_blocks,
1478 &reconstructed_edges,
1479 &HashMap::new(),
1480 &HashMap::new(),
1481 );
1482 let target_graph = build_diff_input(
1483 &target_blocks,
1484 &target_edges,
1485 &HashMap::new(),
1486 &HashMap::new(),
1487 );
1488
1489 assert_eq!(
1490 graph_edge_keys(reconstructed_graph.graph()),
1491 graph_edge_keys(target_graph.graph())
1492 );
1493 assert_eq!(
1494 reconstructed_graph.graph().nodes().collect::<HashSet<_>>(),
1495 target_graph.graph().nodes().collect::<HashSet<_>>()
1496 );
1497 }
1498
1499 #[test]
1500 fn test_graph_edge_keys_ignore_created_on() {
1501 let source = GraphNode {
1502 node_id: HashId::convert_str("source"),
1503 sequence_start: 0,
1504 sequence_end: 4,
1505 };
1506 let target = GraphNode {
1507 node_id: HashId::convert_str("target"),
1508 sequence_start: 0,
1509 sequence_end: 4,
1510 };
1511 let edge_id = HashId::convert_str("edge");
1512 let mut left_graph = GenGraph::new();
1513 left_graph.add_edge(
1514 source,
1515 target,
1516 vec![GraphEdge {
1517 edge_id,
1518 source_strand: Strand::Forward,
1519 target_strand: Strand::Forward,
1520 chromosome_index: 0,
1521 phased: 0,
1522 created_on: 1,
1523 }],
1524 );
1525 let mut right_graph = GenGraph::new();
1526 right_graph.add_edge(
1527 source,
1528 target,
1529 vec![GraphEdge {
1530 edge_id,
1531 source_strand: Strand::Forward,
1532 target_strand: Strand::Forward,
1533 chromosome_index: 0,
1534 phased: 0,
1535 created_on: 2,
1536 }],
1537 );
1538
1539 assert_eq!(
1540 graph_edge_keys(&left_graph),
1541 graph_edge_keys(&right_graph),
1542 "edge comparison should ignore block-group edge timestamps"
1543 );
1544 }
1545
1546 #[test]
1547 fn test_diff_input_graph_keeps_endpoint_local_node_slices() {
1548 let operation = DoltHashId([100; 20]);
1549 let node_id = HashId::convert_str("reference-node");
1550 let sequence = Sequence::new()
1551 .sequence_type("DNA")
1552 .sequence("AAAGTTTTTT")
1553 .build();
1554 let start_edge_id = HashId::convert_str("start-edge");
1555 let end_edge_id = HashId::convert_str("end-edge");
1556 let source_blocks = vec![GroupBlock::new(0, node_id, &sequence, 0, 10)];
1557 let target_blocks = vec![
1558 GroupBlock::new(0, node_id, &sequence, 0, 3),
1559 GroupBlock::new(1, node_id, &sequence, 4, 10),
1560 ];
1561 let input_edges = vec![
1562 test_augmented_edge(start_edge_id, PATH_START_NODE_ID, 0, node_id, 0),
1563 test_augmented_edge(end_edge_id, node_id, 10, PATH_END_NODE_ID, 0),
1564 ];
1565 let source_input_graph = build_diff_input(
1566 &source_blocks,
1567 &input_edges,
1568 &HashMap::new(),
1569 &HashMap::new(),
1570 );
1571 let target_input_graph = build_diff_input(
1572 &target_blocks,
1573 &input_edges,
1574 &HashMap::new(),
1575 &HashMap::from([(node_id, operation)]),
1576 );
1577
1578 let source_nodes = source_input_graph.graph().nodes().collect::<HashSet<_>>();
1579 assert!(
1580 source_nodes.contains(&GraphNode {
1581 node_id,
1582 sequence_start: 0,
1583 sequence_end: 10,
1584 }),
1585 "source graph should preserve its own unsplit block"
1586 );
1587 assert!(
1588 !source_nodes.contains(&GraphNode {
1589 node_id,
1590 sequence_start: 3,
1591 sequence_end: 4,
1592 }),
1593 "source graph should not synthesize slices from target-only boundaries"
1594 );
1595 let target_nodes = target_input_graph.graph().nodes().collect::<HashSet<_>>();
1596 assert!(
1597 target_nodes.contains(&GraphNode {
1598 node_id,
1599 sequence_start: 0,
1600 sequence_end: 3,
1601 }) && target_nodes.contains(&GraphNode {
1602 node_id,
1603 sequence_start: 4,
1604 sequence_end: 10,
1605 }),
1606 "target graph should use target-local blocks"
1607 );
1608 }
1609
1610 #[test]
1611 fn test_diff_input_graph_keeps_terminal_blocks_for_endpoint_lookup() {
1612 let node_id = HashId::convert_str("regular-node");
1613 let sequence = Sequence::new().sequence_type("DNA").sequence("ATC").build();
1614 let edge_id = HashId::convert_str("edge-to-start");
1615 let input_blocks = vec![
1616 test_terminal_block(0, PATH_START_NODE_ID),
1617 GroupBlock::new(1, node_id, &sequence, 0, 3),
1618 test_terminal_block(2, PATH_END_NODE_ID),
1619 ];
1620 let input_edges = vec![test_augmented_edge(
1621 edge_id,
1622 node_id,
1623 3,
1624 PATH_START_NODE_ID,
1625 0,
1626 )];
1627
1628 let input_graph = build_diff_input(
1629 &input_blocks,
1630 &input_edges,
1631 &HashMap::new(),
1632 &HashMap::new(),
1633 );
1634
1635 let regular_node = test_graph_node(node_id, 0, 3);
1636 assert!(
1637 input_graph
1638 .graph()
1639 .edge_weight(regular_node, path_start_graph_node())
1640 .is_some(),
1641 "terminal blocks should participate in endpoint lookup regardless of edge direction"
1642 );
1643 }
1644
1645 #[test]
1646 fn test_unified_diff_graph_connects_deletion_and_addition_through_common_terminals() {
1647 let operation = DoltHashId([100; 20]);
1652 let prefix_node_id = HashId::convert_str("prefix");
1653 let deleted_node_id = HashId::convert_str("deleted");
1654 let middle_node_id = HashId::convert_str("middle");
1655 let inserted_node_id = HashId::convert_str("inserted");
1656 let suffix_node_id = HashId::convert_str("suffix");
1657 let prefix_sequence = Sequence::new().sequence_type("DNA").sequence("ATC").build();
1658 let deleted_sequence = Sequence::new().sequence_type("DNA").sequence("G").build();
1659 let middle_sequence = Sequence::new()
1660 .sequence_type("DNA")
1661 .sequence("ATCGAT")
1662 .build();
1663 let inserted_sequence = Sequence::new().sequence_type("DNA").sequence("AGA").build();
1664 let suffix_sequence = Sequence::new()
1665 .sequence_type("DNA")
1666 .sequence("CGATC")
1667 .build();
1668 let prefix_node = test_graph_node(prefix_node_id, 0, 3);
1669 let deleted_node = test_graph_node(deleted_node_id, 0, 1);
1670 let middle_node = test_graph_node(middle_node_id, 0, 6);
1671 let inserted_node = test_graph_node(inserted_node_id, 0, 3);
1672 let suffix_node = test_graph_node(suffix_node_id, 0, 5);
1673 let source_blocks = vec![
1674 test_terminal_block(0, PATH_START_NODE_ID),
1675 GroupBlock::new(1, prefix_node_id, &prefix_sequence, 0, 3),
1676 GroupBlock::new(2, deleted_node_id, &deleted_sequence, 0, 1),
1677 GroupBlock::new(3, middle_node_id, &middle_sequence, 0, 6),
1678 GroupBlock::new(4, suffix_node_id, &suffix_sequence, 0, 5),
1679 test_terminal_block(5, PATH_END_NODE_ID),
1680 ];
1681 let target_blocks = vec![
1682 test_terminal_block(0, PATH_START_NODE_ID),
1683 GroupBlock::new(1, prefix_node_id, &prefix_sequence, 0, 3),
1684 GroupBlock::new(2, middle_node_id, &middle_sequence, 0, 6),
1685 GroupBlock::new(3, inserted_node_id, &inserted_sequence, 0, 3),
1686 GroupBlock::new(4, suffix_node_id, &suffix_sequence, 0, 5),
1687 test_terminal_block(5, PATH_END_NODE_ID),
1688 ];
1689 let source_edges = vec![
1690 test_augmented_edge(
1691 HashId::convert_str("shared-start-edge"),
1692 PATH_START_NODE_ID,
1693 0,
1694 prefix_node_id,
1695 0,
1696 ),
1697 test_augmented_edge(
1698 HashId::convert_str("removed-prefix-deleted"),
1699 prefix_node_id,
1700 3,
1701 deleted_node_id,
1702 0,
1703 ),
1704 test_augmented_edge(
1705 HashId::convert_str("removed-deleted-middle"),
1706 deleted_node_id,
1707 1,
1708 middle_node_id,
1709 0,
1710 ),
1711 test_augmented_edge(
1712 HashId::convert_str("source-middle-suffix"),
1713 middle_node_id,
1714 6,
1715 suffix_node_id,
1716 0,
1717 ),
1718 test_augmented_edge(
1719 HashId::convert_str("shared-end-edge"),
1720 suffix_node_id,
1721 5,
1722 PATH_END_NODE_ID,
1723 0,
1724 ),
1725 ];
1726 let target_edges = vec![
1727 test_augmented_edge(
1728 HashId::convert_str("shared-start-edge"),
1729 PATH_START_NODE_ID,
1730 0,
1731 prefix_node_id,
1732 0,
1733 ),
1734 test_augmented_edge(
1735 HashId::convert_str("added-prefix-middle"),
1736 prefix_node_id,
1737 3,
1738 middle_node_id,
1739 0,
1740 ),
1741 test_augmented_edge(
1742 HashId::convert_str("added-middle-inserted"),
1743 middle_node_id,
1744 6,
1745 inserted_node_id,
1746 0,
1747 ),
1748 test_augmented_edge(
1749 HashId::convert_str("added-inserted-suffix"),
1750 inserted_node_id,
1751 3,
1752 suffix_node_id,
1753 0,
1754 ),
1755 test_augmented_edge(
1756 HashId::convert_str("shared-end-edge"),
1757 suffix_node_id,
1758 5,
1759 PATH_END_NODE_ID,
1760 0,
1761 ),
1762 ];
1763 let source_graph = build_diff_input(
1764 &source_blocks,
1765 &source_edges,
1766 &HashMap::new(),
1767 &HashMap::new(),
1768 );
1769 let target_graph = build_diff_input(
1770 &target_blocks,
1771 &target_edges,
1772 &HashMap::new(),
1773 &HashMap::new(),
1774 );
1775 let graph = build_unified_diff_graph(&source_graph, &target_graph, Some(operation));
1776
1777 assert_eq!(
1778 graph
1779 .nodes()
1780 .filter(|node| node.node.node_id == PATH_START_NODE_ID)
1781 .count(),
1782 1,
1783 "source and target paths should share one start terminal"
1784 );
1785 assert_eq!(
1786 graph
1787 .nodes()
1788 .filter(|node| node.node.node_id == PATH_END_NODE_ID)
1789 .count(),
1790 1,
1791 "source and target paths should share one end terminal"
1792 );
1793 assert!(
1794 graph.nodes().any(
1795 |node| node.node == deleted_node && node.change.kind == DiffChangeKind::Removed
1796 ),
1797 "deleted G node should be rendered as removed"
1798 );
1799 assert!(
1800 graph.nodes().any(|node| node.node == inserted_node
1801 && node.change.kind == DiffChangeKind::Added),
1802 "inserted AGA node should be rendered as added"
1803 );
1804 assert_diff_edge_kind(&graph, prefix_node, deleted_node, DiffChangeKind::Removed);
1805 assert_diff_edge_kind(&graph, deleted_node, middle_node, DiffChangeKind::Removed);
1806 assert_diff_edge_kind(&graph, prefix_node, middle_node, DiffChangeKind::Added);
1807 assert_diff_edge_kind(&graph, middle_node, suffix_node, DiffChangeKind::Removed);
1808 assert_diff_edge_kind(&graph, middle_node, inserted_node, DiffChangeKind::Added);
1809 assert_diff_edge_kind(&graph, inserted_node, suffix_node, DiffChangeKind::Added);
1810 assert_all_nodes_connected_to(&graph, path_start_graph_node());
1811 assert_diff_edge_kind(
1812 &graph,
1813 path_start_graph_node(),
1814 prefix_node,
1815 DiffChangeKind::Unchanged,
1816 );
1817 assert_diff_edge_kind(
1818 &graph,
1819 suffix_node,
1820 path_end_graph_node(),
1821 DiffChangeKind::Unchanged,
1822 );
1823 }
1824
1825 #[test]
1826 fn test_merges_multiple_history_operations_preserve_operation_attribution() {
1827 let context = setup_history_context();
1828 let graph_conn = context.graph().conn();
1829
1830 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1831 let base = commit_operation(&context, "seed");
1832 create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1833 let first_operation = commit_operation(&context, "add one");
1834 create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1835 let second_operation = commit_operation(&context, "add two");
1836
1837 let expected_first_change =
1838 collect_operation_diff(graph_conn, Some(base), first_operation, DiffRange::TwoDot)
1839 .expect("first operation diff")
1840 .diff_graph
1841 .into_iter()
1842 .flat_map(|block_group| block_group.graph.nodes().collect::<Vec<_>>())
1843 .find(|node| {
1844 node.change.kind == DiffChangeKind::Added
1845 && node.change.operation == Some(first_operation)
1846 })
1847 .expect("first operation should add a node");
1848 let expected_second_change = collect_operation_diff(
1849 graph_conn,
1850 Some(first_operation),
1851 second_operation,
1852 DiffRange::TwoDot,
1853 )
1854 .expect("second operation diff")
1855 .diff_graph
1856 .into_iter()
1857 .flat_map(|block_group| block_group.graph.nodes().collect::<Vec<_>>())
1858 .find(|node| {
1859 node.change.kind == DiffChangeKind::Added
1860 && node.change.operation == Some(second_operation)
1861 })
1862 .expect("second operation should add a node");
1863
1864 let diff =
1865 collect_operation_diff(graph_conn, Some(base), second_operation, DiffRange::TwoDot)
1866 .expect("diff");
1867 assert_eq!(diff.operations, vec![first_operation, second_operation]);
1868
1869 let merged_changes = diff
1870 .diff_graph
1871 .iter()
1872 .flat_map(|block_group| block_group.graph.nodes())
1873 .map(|node| (node.node, node.change.kind))
1874 .collect::<HashSet<_>>();
1875
1876 assert!(
1877 merged_changes.contains(&(
1878 expected_first_change.node,
1879 expected_first_change.change.kind
1880 )),
1881 "merged diff should contain the node change introduced by the first operation"
1882 );
1883 assert!(
1884 merged_changes.contains(&(
1885 expected_second_change.node,
1886 expected_second_change.change.kind,
1887 )),
1888 "merged diff should contain the node change introduced by the second operation"
1889 );
1890 }
1891
1892 #[test]
1893 fn test_merges_multiple_history_operations() {
1894 let context = setup_history_context();
1895 let graph_conn = context.graph().conn();
1896
1897 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1898 let op1 = commit_operation(&context, "seed");
1899 let bg_one = create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1900 let op2 = commit_operation(&context, "add one");
1901 let bg_two = create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1902 let op3 = commit_operation(&context, "add two");
1903
1904 let diff =
1905 collect_operation_diff(graph_conn, Some(op1), op3, DiffRange::TwoDot).expect("diff");
1906 assert_eq!(diff.operations, vec![op2, op3]);
1907 assert_eq!(diff.diff_graph.len(), 2);
1908 assert_eq!(
1909 diff.diff_graph
1910 .iter()
1911 .map(|block_group| block_group.id)
1912 .collect::<Vec<_>>(),
1913 vec![bg_one.id, bg_two.id]
1914 );
1915 }
1916
1917 #[test]
1918 fn test_diff_to_non_head_commit_uses_target_history_state() {
1919 let context = setup_history_context();
1920 let graph_conn = context.graph().conn();
1921
1922 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1923 let base = commit_operation(&context, "seed");
1924 let bg_one = create_linear_block_group(&context, "c", "s", "bg1", "one", "CCCCC");
1925 let op_one = commit_operation(&context, "add one");
1926 let bg_two = create_linear_block_group(&context, "c", "s", "bg2", "two", "GGGGG");
1927 let op_two = commit_operation(&context, "add two");
1928
1929 let diff = collect_operation_diff(graph_conn, Some(base), op_one, DiffRange::TwoDot)
1930 .expect("diff");
1931 assert_eq!(diff.operations, vec![op_one]);
1932 assert_eq!(diff.diff_graph.len(), 1);
1933 assert_eq!(diff.diff_graph[0].id, bg_one.id);
1934 assert_ne!(diff.diff_graph[0].id, bg_two.id);
1935
1936 let later_diff =
1937 collect_operation_diff(graph_conn, Some(op_one), op_two, DiffRange::TwoDot)
1938 .expect("diff");
1939 assert_eq!(later_diff.operations, vec![op_two]);
1940 assert_eq!(later_diff.diff_graph.len(), 1);
1941 assert_eq!(later_diff.diff_graph[0].id, bg_two.id);
1942 }
1943
1944 #[test]
1945 fn diff_against_itself_is_empty() {
1946 let context = setup_history_context();
1947 let graph_conn = context.graph().conn();
1948 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
1949 let base = commit_operation(&context, "seed");
1950 let diff =
1951 collect_operation_diff(graph_conn, Some(base), base, DiffRange::TwoDot).expect("diff");
1952 assert!(diff.operations.is_empty());
1953 }
1954
1955 #[test]
1956 fn test_two_dot_diff_reports_changes_on_both_divergent_branches() {
1957 let history = setup_divergent_history();
1958 let graph_conn = history.context.graph().conn();
1959 let source_ref = history.source_hash.to_string();
1960 let target_ref = history.target_hash.to_string();
1961 let raw_changes = collect_block_group_changes(
1962 graph_conn,
1963 &DiffRange::TwoDot.between(&source_ref, &target_ref),
1964 )
1965 .expect("should collect changes across branches");
1966 assert_eq!(
1967 raw_changes.block_group_ids,
1968 HashSet::from([history.source_block_group.id, history.target_block_group.id,]),
1969 "Dolt diff rows should contain the source removal and target addition"
1970 );
1971
1972 let diff = collect_operation_diff(
1973 graph_conn,
1974 Some(history.source_hash),
1975 history.target_hash,
1976 DiffRange::TwoDot,
1977 )
1978 .expect("should collect endpoint diff");
1979 assert_eq!(
1980 diff.operations,
1981 vec![history.source_hash, history.target_hash]
1982 );
1983 assert_eq!(
1984 diff.diff_graph.len(),
1985 2,
1986 "expected source {source:?} and target {target:?} changes, got block groups {:?}",
1987 diff.diff_graph
1988 .iter()
1989 .map(|block_group| block_group.id)
1990 .collect::<Vec<_>>(),
1991 source = history.source_block_group.id,
1992 target = history.target_block_group.id,
1993 );
1994 let source_diff = diff
1995 .diff_graph
1996 .iter()
1997 .find(|block_group| block_group.id == history.source_block_group.id)
1998 .expect("source-only block group should be reported as removed");
1999 assert!(source_diff.source_block_group.is_some());
2000 assert!(source_diff.target_block_group.is_none());
2001 let target_diff = diff
2002 .diff_graph
2003 .iter()
2004 .find(|block_group| block_group.id == history.target_block_group.id)
2005 .expect("target-only block group should be reported as added");
2006 assert!(target_diff.source_block_group.is_none());
2007 assert!(target_diff.target_block_group.is_some());
2008 }
2009
2010 #[test]
2011 fn test_three_dot_diff_reports_target_changes_from_merge_base() {
2012 let history = setup_divergent_history();
2013 let merge_base_diff = collect_operation_diff(
2014 history.context.graph().conn(),
2015 Some(history.source_hash),
2016 history.target_hash,
2017 DiffRange::ThreeDot,
2018 )
2019 .expect("should collect merge-base diff");
2020 assert_eq!(merge_base_diff.operations, vec![history.target_hash]);
2021 assert_eq!(
2022 merge_base_diff.diff_graph.len(),
2023 1,
2024 "three-dot diff should only report target changes from the merge base"
2025 );
2026 let target_diff = &merge_base_diff.diff_graph[0];
2027 assert_eq!(target_diff.id, history.target_block_group.id);
2028 assert!(target_diff.source_block_group.is_none());
2029 assert!(target_diff.target_block_group.is_some());
2030 }
2031
2032 #[test]
2033 fn test_uses_default_graph_database_for_history_diffs() {
2034 let context = setup_history_context();
2035 let graph_conn = context.graph().conn();
2036
2037 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
2038 let base = commit_operation(&context, "seed");
2039 let expected_block_group =
2040 create_linear_block_group(&context, "c", "s", "db-one", "one", "CCCCC");
2041 let head = commit_operation(&context, "add");
2042
2043 let diff =
2044 collect_operation_diff(graph_conn, Some(base), head, DiffRange::TwoDot).expect("diff");
2045 assert_eq!(diff.operations, vec![head]);
2046 assert_eq!(diff.diff_graph.len(), 1);
2047 assert_eq!(diff.diff_graph[0].id, expected_block_group.id);
2048 }
2049
2050 #[test]
2051 fn test_diffs_follow_reset_replacement_history() {
2052 let mut context = setup_history_context();
2053 let graph_conn = context.graph().conn();
2054 let graph_db_path = context
2055 .workspace()
2056 .graph_db_path()
2057 .expect("should resolve graph db path");
2058 let history_store = DoltHistoryStore::new(graph_conn);
2059
2060 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
2061 let base = commit_operation(&context, "seed");
2062 let retained_block_group =
2063 create_linear_block_group(&context, "c", "s", "retained", "one", "CCCCC");
2064 let retained_commit = commit_operation(&context, "retained");
2065 let discarded_block_group =
2066 create_linear_block_group(&context, "c", "s", "discarded", "two", "GGGGG");
2067 commit_operation(&context, "discarded");
2068
2069 history_store
2070 .reset_hard(&commit_hash_ref(retained_commit))
2071 .expect("should reset to retained commit");
2072 let reopened_graph =
2073 gen_models::db::get_connection(&graph_db_path).expect("should reopen graph db");
2074 gen_models::history::dolt::connect_branch(&reopened_graph, "main")
2075 .expect("should reconnect reopened main branch");
2076 context.set_graph(reopened_graph);
2077 let replacement_block_group =
2078 create_linear_block_group(&context, "c", "s", "replacement", "three", "TTTTT");
2079 let replacement_commit = commit_operation(&context, "replacement");
2080 let reopened_graph_after_replacement =
2081 gen_models::db::get_connection(&graph_db_path).expect("should reopen graph db");
2082 gen_models::history::dolt::connect_branch(&reopened_graph_after_replacement, "main")
2083 .expect("should reconnect reopened main branch");
2084 let discarded_exists = reopened_graph_after_replacement
2085 .query_row(
2086 "SELECT EXISTS(SELECT 1 FROM block_groups WHERE id = ?1)",
2087 params![discarded_block_group.id],
2088 |row| row.get::<_, bool>(0),
2089 )
2090 .expect("should query reopened reset snapshot");
2091 let graph_conn = context.graph().conn();
2092 let diff = collect_operation_diff(
2093 graph_conn,
2094 Some(base),
2095 replacement_commit,
2096 DiffRange::TwoDot,
2097 )
2098 .expect("diff");
2099 assert_eq!(diff.operations, vec![retained_commit, replacement_commit]);
2100 assert!(
2101 !discarded_exists,
2102 "discarded block group should not remain in the post-reset snapshot"
2103 );
2104 assert_eq!(diff.diff_graph.len(), 2);
2105 let added_ids = diff
2106 .diff_graph
2107 .iter()
2108 .map(|block_group| block_group.id)
2109 .collect::<HashSet<_>>();
2110 assert_eq!(
2111 added_ids,
2112 HashSet::from([retained_block_group.id, replacement_block_group.id])
2113 );
2114 assert!(
2115 diff.diff_graph
2116 .iter()
2117 .all(|block_group| block_group.id != discarded_block_group.id),
2118 "discarded commit should not survive the reset path"
2119 );
2120 }
2121
2122 #[test]
2123 fn test_merge_commit_diff_includes_merged_branch_state() {
2124 let context = setup_history_context();
2125 let graph_conn = context.graph().conn();
2126 let history_store = DoltHistoryStore::new(graph_conn);
2127
2128 create_linear_block_group(&context, "c", "s", "seed", "seed", "AAAAA");
2129 let base = commit_operation(&context, "seed");
2130 let main_block_group =
2131 create_linear_block_group(&context, "c", "s", "main", "main", "CCCCC");
2132 let main_commit = commit_operation(&context, "main");
2133
2134 create_feature_branch(&context, base, "feature");
2135 let feature_block_group =
2136 create_linear_block_group(&context, "c", "s", "feature", "feature", "GGGGG");
2137 commit_operation(&context, "feature");
2138
2139 switch_branch(&context, "main");
2140 graph_conn
2141 .with_transaction(|| history_store.merge(&CommitRef("feature".to_string())))
2142 .expect("should merge feature branch");
2143 let merge_commit = history_store
2144 .current_head()
2145 .expect("should resolve current head")
2146 .expect("should have merge head");
2147 let merge_hash = merge_commit;
2148
2149 let diff = collect_operation_diff(graph_conn, Some(base), merge_hash, DiffRange::TwoDot)
2150 .expect("diff");
2151 assert!(
2152 diff.operations.contains(&main_commit),
2153 "diff should include main-branch history"
2154 );
2155 assert!(
2156 diff.operations.contains(&merge_hash),
2157 "diff should include the merge commit"
2158 );
2159 let added_ids = diff
2160 .diff_graph
2161 .iter()
2162 .map(|block_group| block_group.id)
2163 .collect::<HashSet<_>>();
2164 assert_eq!(
2165 added_ids,
2166 HashSet::from([main_block_group.id, feature_block_group.id])
2167 );
2168 }
2169
2170 fn assert_block_group_graph_shape(block_group_diff: &BlockGroupDiff) {
2171 assert_eq!(block_group_diff.graph.nodes().count(), 3);
2172 assert_eq!(block_group_diff.graph.all_edges().count(), 2);
2173 }
2174}