Skip to main content

gen_diff/
graph.rs

1//! Builds a connected, renderable graph describing changes between two states.
2//!
3//! This module is the graph-construction half of `gen-diff`.
4//! [`crate::operations`] uses Dolt's table-diff functions to find affected block
5//! groups, edges, and nodes and associate those rows with operations. This module
6//! handles the boundary normalization, input construction, and graph unification.
7//! The resulting graph is consumed by the CLI, patch preview, GenHub, and the
8//! diff TUI to show unchanged context together with added, removed, and modified
9//! graph elements.
10//!
11//! # Source and target terminology
12//!
13//! At a merge boundary, the **source** is the branch the changes are coming
14//! from and the **target** is the branch they are being merged into. The
15//! historical names in this crate use `source` and `target` differently:
16//! `source_ref` is the graph's comparison baseline and `target_ref` is the
17//! changed state being displayed. Consequently, a caller showing “merge source
18//! branch into target branch” passes the merge target as the first/internal
19//! source endpoint and the merge source as the second/internal target endpoint.
20//! This is the source/target swap visible in merge-oriented callers.
21//!
22//! The same distinction applies to `source_block_group` and
23//! `target_block_group` in [`BlockGroupDiff`]. They record whether the requested
24//! block-group ID exists in the baseline and changed database states,
25//! respectively; they do not identify the incoming and receiving branches of a
26//! merge. Source/target on a [`GraphEdge`] is a third, unrelated use: it is only
27//! the direction of that edge.
28//!
29//! # Block-group membership and effective graph snapshots
30//!
31//! Every block group, including one created for a child sample, owns a complete
32//! set of `block_group_edges`. Copied memberships are stored as rows belonging
33//! to the child block group, and its parent relationship is recorded separately
34//! by `parent_block_group_id`. The child graph therefore does not need its
35//! parent in order to load or reconstruct its stored state.
36//!
37//! A parent is selected only to make an added or removed child graph
38//! biologically meaningful. The changed rows would show a child's entire graph
39//! being removed or created. Thus, comparing to the parent shows the edits that
40//! introduced in the child. `build_block_group_comparison` therefore
41//! keeps two concepts separate:
42//!
43//! - `source_block_group` and `target_block_group` preserve actual membership
44//!   of the requested ID and determine whether the block group is added,
45//!   removed, or modified.
46//! - `source_effective_block_group_id` and
47//!   `target_effective_block_group_id` select the graph used for display. When
48//!   the requested ID is absent, this may be the child's parent ID.
49//!
50//! The corresponding effective history ref comes from the endpoint where the
51//! selected row is known to exist. Thus a target-only child uses its own graph
52//! at `target_ref` and its parent graph at that same endpoint as the source
53//! baseline; a source-only child uses the symmetric source-side pair. This
54//! selection affects only the rendered graph. It never fills in the missing
55//! `source_block_group` or `target_block_group`.
56//!
57//! Dolt's copied `block_group_edges` rows contain enough information to
58//! reconstruct a new child's graph from the table diff. The effective parent is
59//! not a workaround for incomplete diff rows. It supplies the inherited
60//! comparison baseline, and `effective_edge_changes_for_source` filters copied
61//! memberships that Dolt reports as added but that already exist in that
62//! selected parent graph.
63//!
64//! # Graph-building approach
65//!
66//! Graph construction has three steps:
67//!
68//! 1. Load the selected endpoint edge sets and convert edge coordinates into
69//!    [`GraphNode`] sequence slices. Coordinates are slices of the backing
70//!    sequence, not positions in graph space.
71//! 2. Split both sides at the union of their slice boundaries. For example,
72//!    `N[0..10]` on one side and `N[0..4] + N[4..10]` on the other become the
73//!    same two comparison units. Real path edges are retained,
74//!    persistence-only edit-site marker edges are omitted, and neutral
75//!    continuation edges reconnect slices that belong to one covered span.
76//! 3. Union the normalized endpoint graphs into a [`DiffGenGraph`]. Presence
77//!    and Dolt operation metadata determine each node's and edge's
78//!    [`DiffChange`]. Start/end nodes and unchanged context remain in the result
79//!    because the renderer needs a connected graph for layout.
80//!
81//! Loading both endpoint edge sets makes path membership and marker filtering
82//! straightforward. An alternative is to load the baseline once and apply the
83//! `block_group_edges` diff rows to reconstruct the changed graph; the copied
84//! child rows are sufficient for that and it may be preferable if endpoint
85//! loading becomes a measured bottleneck. Another alternative is a literal
86//! database-membership diff with an empty missing side, but that intentionally
87//! gives up the lineage-aware view. The current effective-ID/ref variables could
88//! also be replaced by an explicit endpoint-snapshot struct resolved once
89//! upstream; that would preserve the behavior while making the storage choice
90//! less indirect.
91
92use std::collections::{HashMap, HashSet};
93
94use gen_core::{
95    DoltHashId, HashId, NO_CHROMOSOME_INDEX, PATH_END_NODE_ID, PATH_START_NODE_ID,
96    PRESERVE_EDIT_SITE_CHROMOSOME_INDEX, Strand, is_terminal,
97};
98use gen_graph::{GenGraph, GraphEdge, GraphNode};
99use gen_models::{
100    block_group::BlockGroup,
101    block_group_edge::{AugmentedEdge, BlockGroupEdge},
102    db::GraphConnection,
103};
104use petgraph::graphmap::DiGraphMap;
105
106use crate::operations::{BlockGroupEdgeChange, BlockGroupEdgeKey, NodeChange, OperationDiffError};
107
108#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
109pub enum DiffChangeKind {
110    Unchanged,
111    Added,
112    Removed,
113    Modified,
114}
115
116/// Records whether an input edge came from storage or graph normalization.
117///
118/// An explicit edge represents path topology stored for a block group, so its
119/// presence is explicitly introduced. A continuation edge is created only to
120/// reconnect adjacent slices after a shared comparison boundary splits a stored
121/// span. This lets us mark these edges as not part of a diff.
122#[derive(Clone, Copy, Debug, Eq, PartialEq)]
123enum EdgeOrigin {
124    /// A real path edge loaded from the block group's stored edge membership.
125    Explicit,
126    /// A synthetic connection between slices of one originally continuous span.
127    Continuation,
128}
129
130#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
131pub struct DiffChange {
132    pub kind: DiffChangeKind,
133    pub operation: Option<DoltHashId>,
134}
135
136impl DiffChange {
137    /// Creates the neutral annotation used for graph elements shared by both endpoints.
138    ///
139    /// Input builders and merge helpers use this constructor so unchanged
140    /// context has neither a change kind nor misleading operation attribution.
141    pub const fn unchanged() -> Self {
142        Self {
143            kind: DiffChangeKind::Unchanged,
144            operation: None,
145        }
146    }
147
148    /// Creates an annotation from the change kind and attribution collected from Dolt.
149    ///
150    /// Input-graph construction uses this common constructor before the source
151    /// and target annotations are consolidated into the rendered diff graph.
152    pub const fn new(kind: DiffChangeKind, operation: Option<DoltHashId>) -> Self {
153        Self { kind, operation }
154    }
155
156    /// Returns explicit attribution or the comparison's fallback operation.
157    ///
158    /// Change-merging code uses this when every rendered change must be tied to
159    /// an operation even if the table-diff row did not provide one.
160    pub fn operation_or(self, default_operation: DoltHashId) -> DoltHashId {
161        self.operation.unwrap_or(default_operation)
162    }
163}
164
165#[derive(Clone, Debug)]
166pub struct BlockGroupDiff {
167    pub id: HashId,
168    pub source_block_group: Option<BlockGroup>,
169    pub target_block_group: Option<BlockGroup>,
170    pub graph: DiffGenGraph,
171}
172
173/// Describes how a block group differs between the comparison endpoints.
174///
175/// This is computed from block-group membership at the source and target. It is
176/// intentionally distinct from [`DiffChangeKind`], which describes individual
177/// graph elements and can therefore also be unchanged.
178#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
179pub enum BlockGroupChangeKind {
180    Added,
181    Removed,
182    Modified,
183}
184
185impl BlockGroupDiff {
186    /// Returns the block group's change classification for this comparison.
187    ///
188    /// `None` indicates an invalid diff with no block group at either endpoint.
189    /// The classification is derived rather than stored so it cannot disagree
190    /// with `source_block_group` and `target_block_group`. CLI and TUI views use
191    /// the result to label the complete block-group diff.
192    pub const fn change_kind(&self) -> Option<BlockGroupChangeKind> {
193        match (
194            self.source_block_group.is_some(),
195            self.target_block_group.is_some(),
196        ) {
197            (false, true) => Some(BlockGroupChangeKind::Added),
198            (true, false) => Some(BlockGroupChangeKind::Removed),
199            (true, true) => Some(BlockGroupChangeKind::Modified),
200            (false, false) => None,
201        }
202    }
203}
204
205#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
206pub struct DiffGraphNode {
207    pub node: GraphNode,
208    pub change: DiffChange,
209}
210
211#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
212pub struct DiffGraphEdge {
213    pub edge: GraphEdge,
214    pub change: DiffChange,
215}
216
217pub type DiffGenGraph = DiGraphMap<DiffGraphNode, Vec<DiffGraphEdge>>;
218
219pub struct DiffGenGraphRef<'a>(pub &'a DiffGenGraph);
220
221impl<'a> From<&'a DiffGenGraph> for DiffGenGraphRef<'a> {
222    /// Wraps a borrowed diff graph for conversion without cloning its topology.
223    ///
224    /// Generic graph consumers use this adapter before stripping diff
225    /// annotations through the `GenGraph` conversion.
226    fn from(graph: &'a DiffGenGraph) -> Self {
227        Self(graph)
228    }
229}
230
231impl<'a> From<DiffGenGraphRef<'a>> for GenGraph {
232    /// Projects a diff graph into the ordinary graph shape used by layout code.
233    ///
234    /// The conversion keeps nodes and edges but deliberately drops change
235    /// annotations; the diff TUI uses the resulting `GenGraph` for layout while
236    /// retaining the annotated graph for styling.
237    fn from(val: DiffGenGraphRef<'a>) -> Self {
238        let mut graph = GenGraph::new();
239        for node in val.0.nodes() {
240            graph.add_node(node.node);
241        }
242        for (src, dest, edges) in val.0.all_edges() {
243            let mapped_edges = edges.iter().map(|edge| edge.edge).collect::<Vec<_>>();
244            graph.add_edge(src.node, dest.node, mapped_edges);
245        }
246        graph
247    }
248}
249
250impl From<DiffGraphNode> for GraphNode {
251    /// Removes a node's diff annotation for consumers that only need graph topology.
252    ///
253    /// Conversion and rendering helpers use this projection instead of
254    /// duplicating field access at each generic-graph boundary.
255    fn from(node: DiffGraphNode) -> Self {
256        node.node
257    }
258}
259
260impl From<DiffGraphEdge> for GraphEdge {
261    /// Removes an edge's diff annotation for consumers that only need graph topology.
262    ///
263    /// Conversion and rendering helpers use this projection when passing diff
264    /// edges through APIs written for ordinary graph edges.
265    fn from(edge: DiffGraphEdge) -> Self {
266        edge.edge
267    }
268}
269
270pub(crate) struct BlockGroupDiffInputs<'a> {
271    pub(crate) source_ref: &'a str,
272    pub(crate) target_ref: &'a str,
273    pub(crate) default_operation: DoltHashId,
274    pub(crate) edge_changes_by_block_group: &'a HashMap<HashId, Vec<BlockGroupEdgeChange>>,
275    pub(crate) block_group_operations_by_id: &'a HashMap<HashId, HashSet<DoltHashId>>,
276    pub(crate) node_changes: &'a [NodeChange],
277}
278
279/// When carrying out a diff based purely on edges.
280pub(crate) struct EdgeDiffInput<'a> {
281    edges: &'a [AugmentedEdge],
282    spans: HashSet<GraphNode>,
283    node_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
284    edge_operations_by_id: Option<&'a HashMap<HashId, DoltHashId>>,
285}
286
287impl<'a> EdgeDiffInput<'a> {
288    /// Creates an input whose changes have no operation attribution.
289    pub(crate) fn unattributed(edges: &'a [AugmentedEdge]) -> Self {
290        Self {
291            edges,
292            spans: spans_from_edges(edges),
293            node_operations_by_id: None,
294            edge_operations_by_id: None,
295        }
296    }
297
298    /// Attaches operation attribution after callers have used the cached spans.
299    pub(crate) fn with_attribution(
300        mut self,
301        node_operations_by_id: &'a HashMap<HashId, DoltHashId>,
302        edge_operations_by_id: &'a HashMap<HashId, DoltHashId>,
303    ) -> Self {
304        self.node_operations_by_id = Some(node_operations_by_id);
305        self.edge_operations_by_id = Some(edge_operations_by_id);
306        self
307    }
308
309    /// Returns the cached sequence spans represented by this input's edges.
310    pub(crate) fn spans(&self) -> &HashSet<GraphNode> {
311        &self.spans
312    }
313}
314
315/// Builds the renderable diff for one block group identified by table-diff discovery.
316///
317/// `build_dolt_operation_diff` calls this once per affected block group. It
318/// resolves normalized endpoint input graphs, unifies them, and omits a
319/// source-and-target block group when the resulting graph has no visible
320/// changes, avoiding empty entries in command and TUI output.
321pub(crate) fn build_block_group_diff(
322    graph_conn: &GraphConnection,
323    block_group_id: HashId,
324    inputs: &BlockGroupDiffInputs<'_>,
325) -> Result<Option<BlockGroupDiff>, OperationDiffError> {
326    let Some(comparison) = build_block_group_comparison(graph_conn, block_group_id, inputs)? else {
327        return Ok(None);
328    };
329    if !diff_graph_has_changes(&comparison.graph)
330        && comparison.source_block_group.is_some()
331        && comparison.target_block_group.is_some()
332    {
333        return Ok(None);
334    }
335
336    Ok(Some(BlockGroupDiff {
337        id: block_group_id,
338        source_block_group: comparison.source_block_group,
339        target_block_group: comparison.target_block_group,
340        graph: comparison.graph,
341    }))
342}
343
344/// Builds a comparable graph while retaining block-group endpoint membership.
345///
346/// `build_block_group_diff` uses this preparation step to keep endpoint
347/// membership separate from the lineage-aware graph chosen for display. It
348/// loads complete endpoint edges, filters copied child memberships, aligns
349/// sequence-slice boundaries, and attaches Dolt operation attribution because
350/// the unified builder needs matching graph units and real path membership.
351fn build_block_group_comparison(
352    graph_conn: &GraphConnection,
353    block_group_id: HashId,
354    inputs: &BlockGroupDiffInputs<'_>,
355) -> Result<Option<BlockGroupComparison>, OperationDiffError> {
356    let target_block_group =
357        BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.target_ref)).ok();
358    let source_block_group =
359        BlockGroup::get_by_id(graph_conn, &block_group_id, Some(inputs.source_ref)).ok();
360    if source_block_group.is_none() && target_block_group.is_none() {
361        return Ok(None);
362    }
363    // Added or removed child block groups only exist on one endpoint. The
364    // opposite endpoint is represented by the child's parent so the diff
365    // compares the child graph against the graph it diverged from.
366    let source_parent_block_group_id = target_block_group
367        .as_ref()
368        .and_then(|block_group| block_group.parent_block_group_id);
369    let target_parent_block_group_id = source_block_group
370        .as_ref()
371        .and_then(|block_group| block_group.parent_block_group_id);
372    let source_effective_block_group_id = source_block_group
373        .as_ref()
374        .map(|block_group| block_group.id)
375        .or(source_parent_block_group_id);
376    let target_effective_block_group_id = target_block_group
377        .as_ref()
378        .map(|block_group| block_group.id)
379        .or(target_parent_block_group_id);
380    // When the block group exists on the endpoint, read it from that endpoint's
381    // ref. When it does not, the effective id is the parent id discovered from
382    // the other endpoint's child row, so the parent must be read from that
383    // endpoint's ref instead.
384    let source_effective_history_ref = if source_block_group.is_some() {
385        Some(inputs.source_ref)
386    } else {
387        Some(inputs.target_ref)
388    };
389    let target_effective_history_ref = if target_block_group.is_some() {
390        Some(inputs.target_ref)
391    } else {
392        Some(inputs.source_ref)
393    };
394    // Load both endpoint edge sets directly instead of replaying diff rows over
395    // the source. Diff rows are still useful for attribution, but they are not
396    // a complete graph description:
397    //
398    //   new sample with no sequence edits:
399    //     source(parent):  start -> A -> end
400    //     target(child):   start -> A -> end
401    //
402    // The copied child edges may have the same edge keys as the parent, so
403    // replaying only changed keys can make the target look empty and hide the
404    // created sample. Endpoint reads keep presence-only samples visible.
405    //
406    //   insertion/deletion edits:
407    //     source: A -> B
408    //     target: A -> I -> B, plus internal edit-site marker edges
409    //
410    // The target endpoint tells us which path edges are real graph choices and
411    // lets the input builder filter marker edges before rendering.
412    let source_edges = load_block_group_edges(
413        graph_conn,
414        source_effective_block_group_id,
415        source_effective_history_ref,
416    );
417    let raw_block_group_edge_changes = inputs
418        .edge_changes_by_block_group
419        .get(&block_group_id)
420        .map(Vec::as_slice)
421        .unwrap_or(&[]);
422    let block_group_edge_changes =
423        effective_edge_changes_for_source(&source_edges, raw_block_group_edge_changes);
424    let target_edges = load_block_group_edges(
425        graph_conn,
426        target_effective_block_group_id,
427        target_effective_history_ref,
428    );
429    let source_input = EdgeDiffInput::unattributed(&source_edges);
430    let target_input = EdgeDiffInput::unattributed(&target_edges);
431    let operation_change_lookup = collect_input_operation_changes(
432        block_group_id,
433        inputs,
434        &block_group_edge_changes,
435        source_input.spans(),
436        target_input.spans(),
437    );
438    let graph = build_diff_graph_from_edges(
439        source_input.with_attribution(
440            &operation_change_lookup.source_node_operation_by_id,
441            &operation_change_lookup.source_edge_operation_by_id,
442        ),
443        target_input.with_attribution(
444            &operation_change_lookup.target_node_operation_by_id,
445            &operation_change_lookup.target_edge_operation_by_id,
446        ),
447        Some(inputs.default_operation),
448    );
449
450    Ok(Some(BlockGroupComparison {
451        source_block_group,
452        target_block_group,
453        graph,
454    }))
455}
456
457/// Loads all augmented path edges for an optional block group at one history ref.
458///
459/// `build_block_group_comparison` uses an empty vector for a genuinely missing
460/// endpoint and a complete edge set otherwise. Centralizing that choice keeps
461/// absence handling out of the span and input-graph builders.
462fn load_block_group_edges(
463    graph_conn: &GraphConnection,
464    block_group_id: Option<HashId>,
465    history_ref: Option<&str>,
466) -> Vec<AugmentedEdge> {
467    block_group_id.map_or_else(Vec::new, |block_group_id| {
468        BlockGroupEdge::edges_for_block_group(graph_conn, &block_group_id, history_ref)
469    })
470}
471
472/// Builds a graph diff from two complete edge sets.
473///
474/// Both inputs use one shared sequence-boundary plan so their normalized
475/// `GraphNode` slices are directly comparable. Callers may attach operation
476/// attribution to either input; elements present only in the query are added,
477/// while elements present only in the base are removed.
478pub(crate) fn build_diff_graph_from_edges(
479    base: EdgeDiffInput<'_>,
480    query: EdgeDiffInput<'_>,
481    default_operation: Option<DoltHashId>,
482) -> DiffGenGraph {
483    let (base_nodes, query_nodes) = split_nodes_at_shared_boundaries(base.spans(), query.spans());
484    // This is a failback case where no operations are provided. Edge sets can be input directly
485    // to get a diff from and not have operations associated with the changes.
486    let no_operations = HashMap::new();
487    let base_graph = build_diff_input_graph(
488        base_nodes,
489        base.spans(),
490        base.edges,
491        base.node_operations_by_id.unwrap_or(&no_operations),
492        base.edge_operations_by_id.unwrap_or(&no_operations),
493    );
494    let query_graph = build_diff_input_graph(
495        query_nodes,
496        query.spans(),
497        query.edges,
498        query.node_operations_by_id.unwrap_or(&no_operations),
499        query.edge_operations_by_id.unwrap_or(&no_operations),
500    );
501    build_unified_diff_graph(&base_graph, &query_graph, default_operation)
502}
503
504/// Derives the sequence slices covered by an endpoint's path edges.
505///
506/// This methods exists because blocks_from_edges because loads sequences, which
507/// can add quite a bit of overhead.
508fn spans_from_edges(edges: &[AugmentedEdge]) -> HashSet<GraphNode> {
509    // A diff graph node only needs a backing node id and a sequence slice. Do
510    // not call Edge::blocks_from_edges here: that query fetches sequence text
511    // so GroupBlock::sequence can work, but the diff graph resolves sequence
512    // text later through the regular GraphNode rendering path.
513    //
514    //   endpoint edges:
515    //     start -> A@0
516    //     A@10 -> end
517    //
518    //   edge-derived span:
519    //     A[0..10]
520    //
521    // Keeping this as edge-derived spans lets edge attribution stay attached
522    // until the graph builder has both the display nodes and real path edges.
523    let mut starts_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
524    let mut ends_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
525    for edge in edges.iter().map(|edge| &edge.edge) {
526        if !is_terminal(edge.source_node_id) {
527            ends_by_node_id
528                .entry(edge.source_node_id)
529                .or_default()
530                .insert(edge.source_coordinate);
531        }
532        if !is_terminal(edge.target_node_id) {
533            starts_by_node_id
534                .entry(edge.target_node_id)
535                .or_default()
536                .insert(edge.target_coordinate);
537        }
538    }
539
540    let mut node_ids = starts_by_node_id.keys().copied().collect::<HashSet<_>>();
541    node_ids.extend(ends_by_node_id.keys().copied());
542    let mut spans = HashSet::new();
543    for node_id in node_ids {
544        let empty_starts = HashSet::new();
545        let empty_ends = HashSet::new();
546        let starts = starts_by_node_id.get(&node_id).unwrap_or(&empty_starts);
547        let ends = ends_by_node_id.get(&node_id).unwrap_or(&empty_ends);
548        for (sequence_start, sequence_end) in coordinate_spans(starts, ends) {
549            spans.insert(GraphNode {
550                node_id,
551                sequence_start,
552                sequence_end,
553            });
554        }
555    }
556    spans
557}
558
559/// Turns observed entry and exit coordinates into ordered sequence intervals.
560///
561/// `spans_from_edges` uses adjacent coordinates rather than graph-space
562/// positions because `GraphNode` ranges slice the backing sequence. The
563/// resulting intervals are the endpoint-local spans later split at shared
564/// source/target boundaries.
565fn coordinate_spans(starts: &HashSet<i64>, ends: &HashSet<i64>) -> Vec<(i64, i64)> {
566    let mut coordinates = starts.union(ends).copied().collect::<Vec<_>>();
567    coordinates.sort();
568    coordinates.dedup();
569    if coordinates.len() <= 1 {
570        return coordinates
571            .first()
572            .copied()
573            .map(|coordinate| vec![(coordinate, coordinate)])
574            .unwrap_or_default();
575    }
576    coordinates
577        .windows(2)
578        .map(|window| (window[0], window[1]))
579        .collect()
580}
581
582/// Normalizes endpoint nodes to the same sequence-slice boundaries.
583///
584/// See `split_spans_at_boundaries` for a real explanation of what this does.
585/// It essentially converts nodes so they can be compared across graphs, such as
586/// the source graph having N[0:10] and target having N[0-3] -> N[6-10]. This converts
587/// it to: N[0-3], N[3-6], N[6-10] so additions/removals can be properly described
588fn split_nodes_at_shared_boundaries(
589    source_spans: &HashSet<GraphNode>,
590    target_spans: &HashSet<GraphNode>,
591) -> (HashSet<GraphNode>, HashSet<GraphNode>) {
592    let boundaries_by_node_id = collect_shared_boundaries(source_spans, target_spans);
593    (
594        split_spans_at_boundaries(source_spans, &boundaries_by_node_id),
595        split_spans_at_boundaries(target_spans, &boundaries_by_node_id),
596    )
597}
598
599/// Collects every endpoint boundary for each backing sequence node.
600///
601/// `split_nodes_at_shared_boundaries` uses this union as the shared cut
602/// plan, ensuring source-only and target-only boundaries are applied
603/// symmetrically before graph elements are classified.
604fn collect_shared_boundaries(
605    source_spans: &HashSet<GraphNode>,
606    target_spans: &HashSet<GraphNode>,
607) -> HashMap<HashId, HashSet<i64>> {
608    let mut boundaries_by_node_id = HashMap::new();
609    for span in source_spans.iter().chain(target_spans) {
610        let boundaries = boundaries_by_node_id
611            .entry(span.node_id)
612            .or_insert_with(HashSet::new);
613        boundaries.insert(span.sequence_start);
614        boundaries.insert(span.sequence_end);
615    }
616    boundaries_by_node_id
617}
618
619/// Splits existing endpoint spans according to the shared boundary plan.
620///
621/// The normalization step uses this helper to divide only sequence already
622/// present in that endpoint; it never fills gaps. That preserves membership
623/// while giving `build_unified_diff_graph` equal-sized units to mark as added,
624/// removed, or unchanged.
625fn split_spans_at_boundaries(
626    spans: &HashSet<GraphNode>,
627    boundaries_by_node_id: &HashMap<HashId, HashSet<i64>>,
628) -> HashSet<GraphNode> {
629    let mut nodes = HashSet::new();
630    for span in spans {
631        // Split both endpoint graphs on the union of observed edge boundaries
632        // for each backing node. GraphNode coordinates are sequence slices, not
633        // path coordinates, so this only divides already-present sequence spans.
634        //
635        //   source before VCF edit:
636        //     [0................................34]
637        //
638        //   target after deletion/insertion:
639        //     [0..3] [4..10] [10..............34] and inserted [AGA]
640        //
641        //   source display nodes:
642        //     [0..3] [3..4] [4..10] [10.......34]
643        //
644        // Without this split, the deleted [3..4] base is hidden inside a large
645        // source block and cannot be colored as removed.
646        if span.sequence_start == span.sequence_end {
647            nodes.insert(*span);
648            continue;
649        }
650        let mut boundaries = boundaries_by_node_id
651            .get(&span.node_id)
652            .into_iter()
653            .flat_map(|boundaries| boundaries.iter())
654            .filter(|coordinate| {
655                **coordinate >= span.sequence_start && **coordinate <= span.sequence_end
656            })
657            .copied()
658            .collect::<Vec<_>>();
659        boundaries.sort();
660        boundaries.dedup();
661        if boundaries.len() < 2 {
662            nodes.insert(*span);
663            continue;
664        }
665        for window in boundaries.windows(2) {
666            let sequence_start = window[0];
667            let sequence_end = window[1];
668            if sequence_start == sequence_end {
669                continue;
670            }
671            nodes.insert(GraphNode {
672                node_id: span.node_id,
673                sequence_start,
674                sequence_end,
675            });
676        }
677    }
678    nodes
679}
680
681/// Removes copied child-edge changes already represented by the effective source graph.
682///
683/// `build_block_group_comparison` uses this filter when a missing child
684/// endpoint is displayed through its parent. Dolt reports the child's copied
685/// memberships as additions, but suppressing keys already in that parent keeps
686/// inherited paths from receiving false change attribution.
687fn effective_edge_changes_for_source(
688    source_edges: &[AugmentedEdge],
689    edge_changes: &[BlockGroupEdgeChange],
690) -> Vec<BlockGroupEdgeChange> {
691    let source_edge_keys = source_edges
692        .iter()
693        .map(BlockGroupEdgeKey::from)
694        .collect::<HashSet<_>>();
695    edge_changes
696        .iter()
697        .copied()
698        .filter(
699            |edge_change| match (edge_change.old_key, edge_change.new_key) {
700                (None, Some(new_key)) => !source_edge_keys.contains(&new_key),
701                (Some(old_key), None) => source_edge_keys.contains(&old_key),
702                (Some(old_key), Some(new_key)) => {
703                    source_edge_keys.contains(&old_key) || !source_edge_keys.contains(&new_key)
704                }
705                (None, None) => false,
706            },
707        )
708        .collect()
709}
710
711/// Builds endpoint-specific operation attribution for nodes and edges in each input graph.
712///
713/// `build_block_group_comparison` attaches this lookup to both edge inputs.
714/// It intersects Dolt changes with the block group's represented operations and
715/// endpoint membership so unrelated table rows do not color this graph.
716fn collect_input_operation_changes(
717    block_group_id: HashId,
718    inputs: &BlockGroupDiffInputs<'_>,
719    changed_edge_ids: &[BlockGroupEdgeChange],
720    source_spans: &HashSet<GraphNode>,
721    target_spans: &HashSet<GraphNode>,
722) -> InputOperationChangeLookup {
723    let mut change_lookup = InputOperationChangeLookup::default();
724    let Some(block_group_operations) = inputs.block_group_operations_by_id.get(&block_group_id)
725    else {
726        return change_lookup;
727    };
728    let source_node_ids = span_node_ids(source_spans);
729    let target_node_ids = span_node_ids(target_spans);
730    for node_change in inputs.node_changes {
731        if let (Some(old_node_id), Some(operation)) =
732            (node_change.old_node_id(), node_change.old_operation())
733            && block_group_operations.contains(&operation)
734            && source_node_ids.contains(&old_node_id)
735            && !target_node_ids.contains(&old_node_id)
736        {
737            change_lookup
738                .source_node_operation_by_id
739                .insert(old_node_id, operation);
740        }
741        if let (Some(new_node_id), Some(operation)) =
742            (node_change.new_node_id(), node_change.new_operation())
743            && block_group_operations.contains(&operation)
744            && target_node_ids.contains(&new_node_id)
745            && !source_node_ids.contains(&new_node_id)
746        {
747            change_lookup
748                .target_node_operation_by_id
749                .insert(new_node_id, operation);
750        }
751    }
752
753    for changed_edge_id in changed_edge_ids {
754        if let (Some(old_edge_id), Some(operation)) = (
755            changed_edge_id.old_edge_id(),
756            changed_edge_id.old_operation(),
757        ) {
758            change_lookup
759                .source_edge_operation_by_id
760                .insert(old_edge_id, operation);
761        }
762        if let (Some(new_edge_id), Some(operation)) = (
763            changed_edge_id.new_edge_id(),
764            changed_edge_id.new_operation(),
765        ) {
766            change_lookup
767                .target_edge_operation_by_id
768                .insert(new_edge_id, operation);
769        }
770    }
771    change_lookup
772}
773
774/// Extracts non-terminal backing node IDs from an input's sequence spans.
775///
776/// `collect_input_operation_changes` uses these sets to attribute a node
777/// only when its membership actually changes between the two endpoint graphs.
778fn span_node_ids(spans: &HashSet<GraphNode>) -> HashSet<HashId> {
779    spans
780        .iter()
781        .filter(|span| !is_terminal(span.node_id))
782        .map(|span| span.node_id)
783        .collect()
784}
785
786/// Unifies normalized inputs into the connected graph rendered as a diff.
787///
788/// Combines both inputs into one graph, marking nodes and edges as added,
789/// removed, modified, or unchanged. Unchanged nodes and edges, including the
790/// start and end nodes, remain so the CLI and TUI can display changes in
791/// context.
792pub(crate) fn build_unified_diff_graph(
793    source_graph: &DiffInputGraph,
794    target_graph: &DiffInputGraph,
795    default_operation: Option<DoltHashId>,
796) -> DiffGenGraph {
797    let merged_nodes = source_graph
798        .nodes()
799        .chain(target_graph.nodes())
800        .collect::<HashSet<_>>();
801
802    let merged_edge_keys = source_graph
803        .edges()
804        .map(|(edge_key, _)| edge_key)
805        .chain(target_graph.edges().map(|(edge_key, _)| edge_key))
806        .collect::<HashSet<_>>();
807    let mut diff_graph = DiffGenGraph::new();
808    for node in merged_nodes {
809        diff_graph.add_node(diff_graph_node(
810            node,
811            source_graph,
812            target_graph,
813            default_operation,
814        ));
815    }
816
817    let mut merged_edges_by_node_pair = HashMap::<(GraphNode, GraphNode), Vec<GraphEdgeKey>>::new();
818    for edge_key in merged_edge_keys {
819        merged_edges_by_node_pair
820            .entry((edge_key.source, edge_key.target))
821            .or_default()
822            .push(edge_key);
823    }
824    let mut merged_edge_pairs = merged_edges_by_node_pair.into_iter().collect::<Vec<_>>();
825    merged_edge_pairs.sort_by_key(|((source, target), _)| (*source, *target));
826    for ((source, target), edge_keys) in merged_edge_pairs {
827        let source_node = diff_graph_node(source, source_graph, target_graph, default_operation);
828        let target_node = diff_graph_node(target, source_graph, target_graph, default_operation);
829        let diff_edges = edge_keys
830            .iter()
831            .copied()
832            .map(|edge_key| DiffGraphEdge {
833                edge: graph_edge_for_key(source_graph, target_graph, edge_key),
834                change: merge_input_edge_changes(
835                    source_graph.edge_metadata(edge_key),
836                    target_graph.edge_metadata(edge_key),
837                    default_operation,
838                ),
839            })
840            .collect::<Vec<_>>();
841        diff_graph.add_edge(source_node, target_node, diff_edges);
842    }
843
844    diff_graph
845}
846
847/// Reports whether a unified graph contains any visible node or edge change.
848///
849/// `build_block_group_diff` uses this scan to omit modified block groups whose
850/// table rows normalize to unchanged graph content, while still retaining
851/// membership-only additions and removals.
852fn diff_graph_has_changes(graph: &DiffGenGraph) -> bool {
853    graph
854        .nodes()
855        .any(|node| node.change.kind != DiffChangeKind::Unchanged)
856        || graph.all_edges().any(|(_, _, edges)| {
857            edges
858                .iter()
859                .any(|edge| edge.change.kind != DiffChangeKind::Unchanged)
860        })
861}
862
863/// Creates one unified node by reconciling its endpoint annotations.
864///
865/// `build_unified_diff_graph` calls this for every normalized node and for edge
866/// endpoints. Using one helper guarantees that topology keys and displayed node
867/// styling share the same presence and attribution rules.
868fn diff_graph_node(
869    node: GraphNode,
870    source_graph: &DiffInputGraph,
871    target_graph: &DiffInputGraph,
872    default_operation: Option<DoltHashId>,
873) -> DiffGraphNode {
874    let source_change = source_graph.node_change(node);
875    let target_change = target_graph.node_change(node);
876    DiffGraphNode {
877        node,
878        change: merge_input_changes(source_change, target_change, default_operation),
879    }
880}
881
882/// Retrieves the concrete edge represented by a merged identity key.
883///
884/// `build_unified_diff_graph` prefers the target copy so current metadata is
885/// rendered, then falls back to the source for removed edges. The key was
886/// collected from one of those inputs, so absence from both is an invariant
887/// violation.
888fn graph_edge_for_key(
889    source_graph: &DiffInputGraph,
890    target_graph: &DiffInputGraph,
891    edge_key: GraphEdgeKey,
892) -> GraphEdge {
893    target_graph
894        .edge(edge_key)
895        .or_else(|| source_graph.edge(edge_key))
896        .expect("should contain graph edge for merged diff key")
897}
898
899/// Reconciles source and target presence plus attribution for one graph element.
900///
901/// Unified-node construction and the default edge path use this function.
902/// Presence on only one side determines addition or removal; elements on both
903/// sides become modified only when either input carries change metadata, which
904/// keeps shared layout context neutral.
905fn merge_input_changes(
906    source_change: Option<DiffChange>,
907    target_change: Option<DiffChange>,
908    default_operation: Option<DoltHashId>,
909) -> DiffChange {
910    match (source_change, target_change) {
911        (None, None) => DiffChange::unchanged(),
912        (None, Some(change)) => changed(DiffChangeKind::Added, change.operation, default_operation),
913        (Some(change), None) => {
914            changed(DiffChangeKind::Removed, change.operation, default_operation)
915        }
916        (Some(source_change), Some(target_change))
917            if source_change.kind == DiffChangeKind::Removed =>
918        {
919            changed(
920                DiffChangeKind::Removed,
921                source_change.operation.or(target_change.operation),
922                default_operation,
923            )
924        }
925        (Some(source_change), Some(target_change))
926            if target_change.kind == DiffChangeKind::Added =>
927        {
928            changed(
929                DiffChangeKind::Added,
930                target_change.operation.or(source_change.operation),
931                default_operation,
932            )
933        }
934        (Some(source_change), Some(target_change))
935            if source_change.operation.is_some()
936                || target_change.operation.is_some()
937                || source_change.kind != DiffChangeKind::Unchanged
938                || target_change.kind != DiffChangeKind::Unchanged =>
939        {
940            changed(
941                DiffChangeKind::Modified,
942                target_change.operation.or(source_change.operation),
943                default_operation,
944            )
945        }
946        (Some(_), Some(_)) => DiffChange::unchanged(),
947    }
948}
949
950/// Applies edge-specific reconciliation on top of the general input rules.
951///
952/// Continuation edges reconnect slices split during normalization, so they
953/// stay unchanged. Explicit edges present in only one input are added or
954/// removed.
955fn merge_input_edge_changes(
956    source_metadata: Option<DiffInputEdgeMetadata>,
957    target_metadata: Option<DiffInputEdgeMetadata>,
958    default_operation: Option<DoltHashId>,
959) -> DiffChange {
960    if source_metadata
961        .into_iter()
962        .chain(target_metadata)
963        .any(|metadata| metadata.origin == EdgeOrigin::Continuation)
964    {
965        return DiffChange::unchanged();
966    }
967    let source_change = source_metadata.map(|metadata| metadata.change);
968    let target_change = target_metadata.map(|metadata| metadata.change);
969    merge_input_changes(source_change, target_change, default_operation)
970}
971
972/// Creates an attributed non-neutral change, filling missing Dolt attribution.
973///
974/// Input and edge merge helpers use the comparison's default operation so
975/// every colored element can be grouped by operation in downstream views.
976fn changed(
977    kind: DiffChangeKind,
978    operation: Option<DoltHashId>,
979    default_operation: Option<DoltHashId>,
980) -> DiffChange {
981    DiffChange::new(kind, operation.or(default_operation))
982}
983
984/// Builds one endpoint's connected diff input from normalized nodes.
985///
986/// Builds one input for the diff. It connects sequence slices using explicit
987/// edges and skips edges that are due to normalization, etc. If present, nodes
988/// and edges are attributed to an operation.
989pub(crate) fn build_diff_input_graph(
990    mut input_nodes: HashSet<GraphNode>,
991    continuation_spans: &HashSet<GraphNode>,
992    input_edges: &[AugmentedEdge],
993    node_operations_by_id: &HashMap<HashId, DoltHashId>,
994    edge_operations_by_id: &HashMap<HashId, DoltHashId>,
995) -> DiffInputGraph {
996    let mut graph = GenGraph::new();
997    let mut node_changes = HashMap::new();
998    let mut edge_metadata = HashMap::new();
999
1000    input_nodes.insert(path_start_graph_node());
1001    input_nodes.insert(path_end_graph_node());
1002    for node in &input_nodes {
1003        graph.add_node(*node);
1004        node_changes.insert(
1005            *node,
1006            node_operations_by_id
1007                .get(&node.node_id)
1008                .map_or_else(DiffChange::unchanged, |operation| {
1009                    DiffChange::new(DiffChangeKind::Modified, Some(*operation))
1010                }),
1011        );
1012    }
1013
1014    let blocks_by_start = input_nodes
1015        .iter()
1016        .map(|node| ((node.node_id, node.sequence_start), *node))
1017        .collect::<HashMap<_, _>>();
1018    let blocks_by_end = input_nodes
1019        .iter()
1020        .map(|node| ((node.node_id, node.sequence_end), *node))
1021        .collect::<HashMap<_, _>>();
1022
1023    for augmented_edge in input_edges {
1024        // Edit-site marker edges preserve coordinates for later graph
1025        // operations. They are not path choices, so rendering them as diff
1026        // edges makes inserted/deleted sequence look unchanged.
1027        if augmented_edge.chromosome_index == PRESERVE_EDIT_SITE_CHROMOSOME_INDEX {
1028            continue;
1029        }
1030        let source_node = blocks_by_end
1031            .get(&(
1032                augmented_edge.edge.source_node_id,
1033                augmented_edge.edge.source_coordinate,
1034            ))
1035            .copied();
1036        let target_node = blocks_by_start
1037            .get(&(
1038                augmented_edge.edge.target_node_id,
1039                augmented_edge.edge.target_coordinate,
1040            ))
1041            .copied();
1042        if let (Some(source_node), Some(target_node)) = (source_node, target_node) {
1043            let graph_edge = GraphEdge {
1044                edge_id: augmented_edge.edge.id,
1045                source_strand: augmented_edge.edge.source_strand,
1046                target_strand: augmented_edge.edge.target_strand,
1047                chromosome_index: augmented_edge.chromosome_index,
1048                phased: augmented_edge.phased,
1049                created_on: augmented_edge.created_on,
1050            };
1051            if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1052                existing_edges.push(graph_edge);
1053            } else {
1054                graph.add_edge(source_node, target_node, vec![graph_edge]);
1055            }
1056            edge_metadata.insert(
1057                GraphEdgeKey::new(source_node, target_node, graph_edge),
1058                DiffInputEdgeMetadata {
1059                    change: edge_operations_by_id
1060                        .get(&graph_edge.edge_id)
1061                        .map_or_else(DiffChange::unchanged, |operation| {
1062                            DiffChange::new(DiffChangeKind::Modified, Some(*operation))
1063                        }),
1064                    origin: EdgeOrigin::Explicit,
1065                },
1066            );
1067        }
1068    }
1069
1070    add_continuation_edges(
1071        &input_nodes,
1072        continuation_spans,
1073        &mut graph,
1074        &mut edge_metadata,
1075    );
1076    remove_unconnected_input_nodes(&mut graph, &mut node_changes);
1077
1078    DiffInputGraph {
1079        graph,
1080        node_changes,
1081        edge_metadata,
1082    }
1083}
1084
1085/// Returns the canonical start terminal used in every input and unified graph.
1086///
1087/// The input builder and graph-layout tests use this shared value so endpoint
1088/// graphs remain connected to the same synthetic path boundary.
1089pub(crate) fn path_start_graph_node() -> GraphNode {
1090    GraphNode {
1091        node_id: PATH_START_NODE_ID,
1092        sequence_start: 0,
1093        sequence_end: 0,
1094    }
1095}
1096
1097/// Returns the canonical end terminal used in every input and unified graph.
1098///
1099/// The input builder and graph-layout tests use this shared value so endpoint
1100/// graphs remain connected to the same synthetic path boundary.
1101pub(crate) fn path_end_graph_node() -> GraphNode {
1102    GraphNode {
1103        node_id: PATH_END_NODE_ID,
1104        sequence_start: 0,
1105        sequence_end: 0,
1106    }
1107}
1108
1109/// Reconnects normalized slices that came from one continuous endpoint span.
1110///
1111/// `build_diff_input_graph` invokes this after mapping explicit edges.
1112/// It adds neutral synthetic edges only between adjacent slices covered by the
1113/// same original span, preserving renderable connectivity without bridging
1114/// genuine deletions or endpoint gaps.
1115fn add_continuation_edges(
1116    input_nodes: &HashSet<GraphNode>,
1117    continuation_spans: &HashSet<GraphNode>,
1118    graph: &mut GenGraph,
1119    edge_metadata: &mut HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
1120) {
1121    for span in continuation_spans {
1122        // Delayed block construction starts from the endpoint edges and keeps
1123        // each endpoint's real covered spans separate before splitting them
1124        // into display nodes. Add neutral continuation edges only inside a
1125        // span that exists in this endpoint:
1126        //
1127        //   endpoint span [0..10] split to [0..3] [3..4] [4..10]
1128        //     add grey continuations 0..3 -> 3..4 -> 4..10
1129        //
1130        //   endpoint spans [0..3] and [4..10]
1131        //     do not synthesize 0..3 -> 3..4 -> 4..10
1132        //
1133        // This is the point where the graph knows enough to split display
1134        // nodes without asking a second question about whether a boundary came
1135        // from the source or target path.
1136        if is_terminal(span.node_id) || span.sequence_start == span.sequence_end {
1137            continue;
1138        }
1139        let mut nodes = input_nodes
1140            .iter()
1141            .copied()
1142            .filter(|node| {
1143                node.node_id == span.node_id
1144                    && node.sequence_start >= span.sequence_start
1145                    && node.sequence_end <= span.sequence_end
1146            })
1147            .collect::<Vec<_>>();
1148        nodes.sort_by_key(|node| (node.sequence_start, node.sequence_end));
1149        for window in nodes.windows(2) {
1150            let source_node = window[0];
1151            let target_node = window[1];
1152            if source_node.sequence_end != target_node.sequence_start {
1153                continue;
1154            }
1155            let synthetic_edge = GraphEdge {
1156                edge_id: HashId::convert_str(&format!(
1157                    "diff-continuation:{}:{}:{}:{}:{}",
1158                    span.node_id,
1159                    source_node.sequence_start,
1160                    source_node.sequence_end,
1161                    target_node.sequence_start,
1162                    target_node.sequence_end
1163                )),
1164                source_strand: Strand::Forward,
1165                target_strand: Strand::Forward,
1166                chromosome_index: NO_CHROMOSOME_INDEX,
1167                phased: 0,
1168                created_on: 0,
1169            };
1170            if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1171                if existing_edges.contains(&synthetic_edge) {
1172                    continue;
1173                }
1174                existing_edges.push(synthetic_edge);
1175            } else {
1176                graph.add_edge(source_node, target_node, vec![synthetic_edge]);
1177            }
1178            edge_metadata.insert(
1179                GraphEdgeKey::new(source_node, target_node, synthetic_edge),
1180                DiffInputEdgeMetadata {
1181                    change: DiffChange::unchanged(),
1182                    origin: EdgeOrigin::Continuation,
1183                },
1184            );
1185        }
1186    }
1187}
1188
1189/// Removes non-terminal slices that no mapped or continuation edge reaches.
1190///
1191/// `build_diff_input_graph` uses this cleanup after edge construction.
1192/// Coordinate normalization can produce candidate slices unsupported by actual
1193/// endpoint topology; pruning them keeps the unified graph from displaying
1194/// isolated artifacts while retaining terminal anchors.
1195fn remove_unconnected_input_nodes(
1196    graph: &mut GenGraph,
1197    node_changes: &mut HashMap<GraphNode, DiffChange>,
1198) {
1199    let mut connected_nodes = HashSet::new();
1200    for (source, target, _) in graph.all_edges() {
1201        connected_nodes.insert(source);
1202        connected_nodes.insert(target);
1203    }
1204    let disconnected_nodes = graph
1205        .nodes()
1206        .filter(|node| !is_terminal(node.node_id) && !connected_nodes.contains(node))
1207        .collect::<Vec<_>>();
1208    for node in disconnected_nodes {
1209        graph.remove_node(node);
1210        node_changes.remove(&node);
1211    }
1212}
1213
1214#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
1215pub(crate) struct GraphEdgeKey {
1216    source: GraphNode,
1217    target: GraphNode,
1218    edge_id: HashId,
1219    source_strand: Strand,
1220    target_strand: Strand,
1221    chromosome_index: i64,
1222    phased: i64,
1223}
1224
1225impl GraphEdgeKey {
1226    /// Creates the stable edge identity used to union and annotate endpoint graphs.
1227    ///
1228    /// Input construction and continuation-edge insertion use this key instead
1229    /// of the full stored record so volatile `created_on` metadata does not
1230    /// turn an otherwise identical connection into a structural diff.
1231    pub(crate) fn new(source: GraphNode, target: GraphNode, edge: GraphEdge) -> Self {
1232        Self {
1233            source,
1234            target,
1235            edge_id: edge.edge_id,
1236            source_strand: edge.source_strand,
1237            target_strand: edge.target_strand,
1238            chromosome_index: edge.chromosome_index,
1239            phased: edge.phased,
1240        }
1241    }
1242
1243    /// Tests whether a concrete edge has the structural identity represented by this key.
1244    ///
1245    /// `DiffInputGraph::edge` uses this after selecting a node pair because a
1246    /// `GenGraph` edge weight may contain multiple parallel edges.
1247    fn matches_edge(self, edge: GraphEdge) -> bool {
1248        self.edge_id == edge.edge_id
1249            && self.source_strand == edge.source_strand
1250            && self.target_strand == edge.target_strand
1251            && self.chromosome_index == edge.chromosome_index
1252            && self.phased == edge.phased
1253    }
1254}
1255
1256struct BlockGroupComparison {
1257    source_block_group: Option<BlockGroup>,
1258    target_block_group: Option<BlockGroup>,
1259    graph: DiffGenGraph,
1260}
1261
1262pub(crate) struct DiffInputGraph {
1263    graph: GenGraph,
1264    node_changes: HashMap<GraphNode, DiffChange>,
1265    edge_metadata: HashMap<GraphEdgeKey, DiffInputEdgeMetadata>,
1266}
1267
1268/// Keeps an edge's displayed change separate from why the input contains it.
1269///
1270/// Stores an input edge's change annotation and origin. During comparison,
1271/// the origin tells us whether to mark a missing explicit edge as added or
1272/// removed, or leave a synthetic continuation unchanged.
1273#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1274pub(crate) struct DiffInputEdgeMetadata {
1275    change: DiffChange,
1276    origin: EdgeOrigin,
1277}
1278
1279impl DiffInputGraph {
1280    /// Iterates over the graph nodes present in this endpoint.
1281    fn nodes(&self) -> impl Iterator<Item = GraphNode> + '_ {
1282        self.node_changes.keys().copied()
1283    }
1284
1285    /// Returns this endpoint's annotation for a node when it is present.
1286    fn node_change(&self, node: GraphNode) -> Option<DiffChange> {
1287        self.node_changes.get(&node).copied()
1288    }
1289
1290    /// Iterates over stable edge keys and their input metadata.
1291    fn edges(&self) -> impl Iterator<Item = (GraphEdgeKey, DiffInputEdgeMetadata)> + '_ {
1292        self.edge_metadata
1293            .iter()
1294            .map(|(edge_key, metadata)| (*edge_key, *metadata))
1295    }
1296
1297    /// Returns this endpoint's metadata for an edge when it is present.
1298    fn edge_metadata(&self, edge_key: GraphEdgeKey) -> Option<DiffInputEdgeMetadata> {
1299        self.edge_metadata.get(&edge_key).copied()
1300    }
1301
1302    /// Returns the concrete graph edge represented by a stable key.
1303    fn edge(&self, edge_key: GraphEdgeKey) -> Option<GraphEdge> {
1304        self.graph
1305            .edge_weight(edge_key.source, edge_key.target)?
1306            .iter()
1307            .copied()
1308            .find(|edge| edge_key.matches_edge(*edge))
1309    }
1310}
1311
1312#[cfg(test)]
1313impl DiffInputGraph {
1314    /// Exposes input topology to reconstruction tests without exposing its maps.
1315    pub(crate) const fn graph(&self) -> &GenGraph {
1316        &self.graph
1317    }
1318}
1319
1320#[derive(Debug, Default)]
1321struct InputOperationChangeLookup {
1322    source_node_operation_by_id: HashMap<HashId, DoltHashId>,
1323    target_node_operation_by_id: HashMap<HashId, DoltHashId>,
1324    source_edge_operation_by_id: HashMap<HashId, DoltHashId>,
1325    target_edge_operation_by_id: HashMap<HashId, DoltHashId>,
1326}
1327
1328#[cfg(test)]
1329mod tests {
1330    use gen_models::edge::Edge;
1331
1332    use super::*;
1333
1334    fn topology_test_edge(source: HashId, target: HashId, source_coordinate: i64) -> AugmentedEdge {
1335        AugmentedEdge {
1336            edge: Edge {
1337                id: HashId::convert_str(&format!("{source}-{source_coordinate}-{target}")),
1338                source_node_id: source,
1339                source_coordinate,
1340                source_strand: Strand::Forward,
1341                target_node_id: target,
1342                target_coordinate: 0,
1343                target_strand: Strand::Forward,
1344            },
1345            chromosome_index: 0,
1346            phased: 0,
1347            created_on: 0,
1348        }
1349    }
1350
1351    #[test]
1352    fn test_tracks_added_edge() {
1353        // Simple graph like
1354        // source -> {a,b} -> end
1355        // adds a connection where a->b. Ensure we can track that new edge.
1356        let node_a = HashId::convert_str("topology-a");
1357        let node_b = HashId::convert_str("topology-b");
1358        // Only the base includes the extra A -> B connection.
1359        let query_edges = vec![
1360            topology_test_edge(PATH_START_NODE_ID, node_a, 0),
1361            topology_test_edge(node_a, PATH_END_NODE_ID, 10),
1362            topology_test_edge(PATH_START_NODE_ID, node_b, 0),
1363            topology_test_edge(node_b, PATH_END_NODE_ID, 10),
1364        ];
1365        let connection = topology_test_edge(node_a, node_b, 10);
1366        let mut base_edges = query_edges.clone();
1367        base_edges.push(connection.clone());
1368        for (base, query, expected) in [
1369            (&base_edges, &query_edges, DiffChangeKind::Removed),
1370            (&query_edges, &base_edges, DiffChangeKind::Added),
1371        ] {
1372            let graph = build_diff_graph_from_edges(
1373                EdgeDiffInput::unattributed(base),
1374                EdgeDiffInput::unattributed(query),
1375                None,
1376            );
1377            assert!(
1378                graph
1379                    .nodes()
1380                    .all(|node| node.change.kind == DiffChangeKind::Unchanged)
1381            );
1382            let change = graph
1383                .all_edges()
1384                .flat_map(|(_, _, edges)| edges)
1385                .find(|edge| edge.edge.edge_id == connection.edge.id)
1386                .expect("should retain the differing explicit connection")
1387                .change;
1388            assert_eq!(
1389                change.kind, expected,
1390                "explicit membership must determine edge changes even when both nodes survive"
1391            );
1392            assert_eq!(change.operation, None);
1393        }
1394    }
1395
1396    #[test]
1397    fn test_tracks_chromosome_index_changes_for_diploids() {
1398        // Simple graph: source -> a -> end.
1399        // One input has two source -> a edges, one per chromosome.
1400        // Ensure the extra edge is Added/Removed while the shared edge stays unchanged.
1401        let node = HashId::convert_str("parallel-node");
1402        let query_edges = vec![
1403            topology_test_edge(PATH_START_NODE_ID, node, 0),
1404            topology_test_edge(node, PATH_END_NODE_ID, 10),
1405        ];
1406        let mut parallel = query_edges[0].clone();
1407        parallel.chromosome_index = 1;
1408        let mut base_edges = query_edges.clone();
1409        base_edges.push(parallel);
1410        for (base, query, expected) in [
1411            (&base_edges, &query_edges, DiffChangeKind::Removed),
1412            (&query_edges, &base_edges, DiffChangeKind::Added),
1413        ] {
1414            let graph = build_diff_graph_from_edges(
1415                EdgeDiffInput::unattributed(base),
1416                EdgeDiffInput::unattributed(query),
1417                None,
1418            );
1419            let parallel_change = graph
1420                .all_edges()
1421                .flat_map(|(_, _, edges)| edges)
1422                .find(|edge| edge.edge.chromosome_index == 1)
1423                .expect("should retain the differing parallel edge")
1424                .change;
1425            assert_eq!(
1426                parallel_change.kind, expected,
1427                "parallel membership differences must remain visible alongside shared edges"
1428            );
1429            assert_eq!(parallel_change.operation, None);
1430            let shared_change = graph
1431                .all_edges()
1432                .flat_map(|(_, _, edges)| edges)
1433                .find(|edge| {
1434                    edge.edge.edge_id == query_edges[0].edge.id
1435                        && edge.edge.chromosome_index == query_edges[0].chromosome_index
1436                })
1437                .expect("should retain the shared parallel edge")
1438                .change;
1439            assert_eq!(shared_change.kind, DiffChangeKind::Unchanged);
1440            assert_eq!(shared_change.operation, None);
1441        }
1442    }
1443
1444    #[test]
1445    fn test_operation_attribution() {
1446        // Simple graph: source -> {a,b} -> end.
1447        // The query adds a -> b with an associated operation.
1448        // Ensure the new edge is Added and retains that operation.
1449        let node_a = HashId::convert_str("attributed-topology-a");
1450        let node_b = HashId::convert_str("attributed-topology-b");
1451        let base_edges = vec![
1452            topology_test_edge(PATH_START_NODE_ID, node_a, 0),
1453            topology_test_edge(node_a, PATH_END_NODE_ID, 10),
1454            topology_test_edge(PATH_START_NODE_ID, node_b, 0),
1455            topology_test_edge(node_b, PATH_END_NODE_ID, 10),
1456        ];
1457        let connection = topology_test_edge(node_a, node_b, 10);
1458        let mut query_edges = base_edges.clone();
1459        query_edges.push(connection.clone());
1460        let operation = DoltHashId([9; 20]);
1461        let edge_operations = HashMap::from([(connection.edge.id, operation)]);
1462        let graph = build_diff_graph_from_edges(
1463            EdgeDiffInput::unattributed(&base_edges)
1464                .with_attribution(&HashMap::new(), &HashMap::new()),
1465            EdgeDiffInput::unattributed(&query_edges)
1466                .with_attribution(&HashMap::new(), &edge_operations),
1467            None,
1468        );
1469        let change = graph
1470            .all_edges()
1471            .flat_map(|(_, _, edges)| edges)
1472            .find(|edge| edge.edge.edge_id == connection.edge.id)
1473            .expect("should retain the added explicit connection")
1474            .change;
1475        assert_eq!(change.kind, DiffChangeKind::Added);
1476        assert_eq!(change.operation, Some(operation));
1477    }
1478
1479    #[test]
1480    fn test_continuation_is_neutral() {
1481        // One input:   source -> a[0..10] -> end
1482        // Other input: source -> {a[0..5], a[5..10]} -> end
1483        // Normalization splits the continuous span and connects a[0..5] -> a[5..10].
1484        // Ensure this synthetic connection stays neutral in either comparison direction.
1485        let node = HashId::convert_str("continuation-node");
1486        let continuous_edges = vec![
1487            topology_test_edge(PATH_START_NODE_ID, node, 0),
1488            topology_test_edge(node, PATH_END_NODE_ID, 10),
1489        ];
1490        let split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
1491        let split_end = topology_test_edge(node, PATH_END_NODE_ID, 5);
1492        let mut second_split_start = topology_test_edge(PATH_START_NODE_ID, node, 0);
1493        second_split_start.edge.id = HashId::convert_str("continuation-second-start");
1494        second_split_start.edge.target_coordinate = 5;
1495        let second_split_end = topology_test_edge(node, PATH_END_NODE_ID, 10);
1496        let split_edges = vec![split_start, split_end, second_split_start, second_split_end];
1497        let first_slice = GraphNode {
1498            node_id: node,
1499            sequence_start: 0,
1500            sequence_end: 5,
1501        };
1502        let second_slice = GraphNode {
1503            node_id: node,
1504            sequence_start: 5,
1505            sequence_end: 10,
1506        };
1507
1508        for (base, query) in [
1509            (&continuous_edges, &split_edges),
1510            (&split_edges, &continuous_edges),
1511        ] {
1512            let graph = build_diff_graph_from_edges(
1513                EdgeDiffInput::unattributed(base),
1514                EdgeDiffInput::unattributed(query),
1515                None,
1516            );
1517            let continuation_edges = graph
1518                .all_edges()
1519                .find_map(|(source, target, edges)| {
1520                    (source.node == first_slice && target.node == second_slice).then_some(edges)
1521                })
1522                .expect("should retain the normalization continuation");
1523            assert!(
1524                continuation_edges
1525                    .iter()
1526                    .all(|edge| edge.change.kind == DiffChangeKind::Unchanged)
1527            );
1528            assert!(
1529                continuation_edges
1530                    .iter()
1531                    .all(|edge| edge.change.operation.is_none())
1532            );
1533        }
1534    }
1535
1536    fn block_group(id: i64) -> BlockGroup {
1537        BlockGroup {
1538            id: HashId::pad_str(id),
1539            collection_name: "collection".to_string(),
1540            sample_name: "sample".to_string(),
1541            name: "block-group".to_string(),
1542            created_on: 0,
1543            parent_block_group_id: None,
1544            is_default: false,
1545        }
1546    }
1547
1548    #[test]
1549    fn test_block_group_change_kind_is_derived_from_endpoint_membership() {
1550        let block_group = block_group(1);
1551        let block_group_id = block_group.id;
1552        let diff = |source_block_group, target_block_group| BlockGroupDiff {
1553            id: block_group_id,
1554            source_block_group,
1555            target_block_group,
1556            graph: DiffGenGraph::new(),
1557        };
1558
1559        assert_eq!(
1560            diff(None, Some(block_group.clone())).change_kind(),
1561            Some(BlockGroupChangeKind::Added)
1562        );
1563        assert_eq!(
1564            diff(Some(block_group.clone()), None).change_kind(),
1565            Some(BlockGroupChangeKind::Removed)
1566        );
1567        assert_eq!(
1568            diff(Some(block_group.clone()), Some(block_group)).change_kind(),
1569            Some(BlockGroupChangeKind::Modified)
1570        );
1571        assert_eq!(diff(None, None).change_kind(), None);
1572    }
1573
1574    #[test]
1575    fn test_split_nodes_at_shared_boundaries_exposes_removed_slice() {
1576        let node_id = HashId::convert_str("reference-node");
1577        let source_spans = HashSet::from([GraphNode {
1578            node_id,
1579            sequence_start: 0,
1580            sequence_end: 10,
1581        }]);
1582        let target_spans = HashSet::from([
1583            GraphNode {
1584                node_id,
1585                sequence_start: 0,
1586                sequence_end: 3,
1587            },
1588            GraphNode {
1589                node_id,
1590                sequence_start: 5,
1591                sequence_end: 10,
1592            },
1593        ]);
1594
1595        let (source_nodes, target_nodes) =
1596            split_nodes_at_shared_boundaries(&source_spans, &target_spans);
1597        let removed_slice = GraphNode {
1598            node_id,
1599            sequence_start: 3,
1600            sequence_end: 5,
1601        };
1602
1603        assert_eq!(
1604            source_nodes,
1605            HashSet::from([
1606                GraphNode {
1607                    node_id,
1608                    sequence_start: 0,
1609                    sequence_end: 3,
1610                },
1611                removed_slice,
1612                GraphNode {
1613                    node_id,
1614                    sequence_start: 5,
1615                    sequence_end: 10,
1616                },
1617            ])
1618        );
1619        assert_eq!(target_nodes, target_spans);
1620        assert!(source_nodes.contains(&removed_slice));
1621        assert!(!target_nodes.contains(&removed_slice));
1622    }
1623
1624    #[test]
1625    fn diff_graph_to_gen_graph_maps_nodes_and_edges() {
1626        let node_a = DiffGraphNode {
1627            node: GraphNode {
1628                node_id: HashId::pad_str(1),
1629                sequence_start: 0,
1630                sequence_end: 5,
1631            },
1632            change: DiffChange {
1633                kind: DiffChangeKind::Added,
1634                operation: Some(DoltHashId([10; 20])),
1635            },
1636        };
1637        let node_b = DiffGraphNode {
1638            node: GraphNode {
1639                node_id: HashId::pad_str(2),
1640                sequence_start: 5,
1641                sequence_end: 10,
1642            },
1643            change: DiffChange::unchanged(),
1644        };
1645        let mut diff_graph = DiffGenGraph::new();
1646        diff_graph.add_node(node_a);
1647        diff_graph.add_node(node_b);
1648        let edge = DiffGraphEdge {
1649            edge: GraphEdge {
1650                edge_id: HashId::pad_str(9),
1651                source_strand: Strand::Forward,
1652                target_strand: Strand::Forward,
1653                chromosome_index: 0,
1654                phased: 0,
1655                created_on: 0,
1656            },
1657            change: DiffChange {
1658                kind: DiffChangeKind::Added,
1659                operation: Some(DoltHashId([10; 20])),
1660            },
1661        };
1662        diff_graph.add_edge(node_a, node_b, vec![edge]);
1663
1664        let graph: GenGraph = DiffGenGraphRef(&diff_graph).into();
1665        assert_eq!(graph.nodes().count(), 2);
1666        assert_eq!(graph.all_edges().count(), 1);
1667        let weights = graph
1668            .all_edges()
1669            .next()
1670            .map(|(_, _, edges)| edges.clone())
1671            .expect("graph edge");
1672        assert_eq!(weights, vec![edge.edge]);
1673    }
1674}