Skip to main content

gen_models/
edge.rs

1use std::{
2    collections::{HashMap, HashSet},
3    hash::Hash,
4    rc::Rc,
5};
6
7use gen_core::{
8    HashId, PATH_END_NODE_ID, PATH_START_NODE_ID, Strand, Workspace, calculate_hash, is_terminal,
9    traits::Capnp,
10};
11use gen_graph::{GenGraph, GraphEdge, GraphNode};
12use indexmap::IndexSet;
13use itertools::Itertools;
14use petgraph::algo::kosaraju_scc;
15use rusqlite::{ToSql, params, types::Value};
16use serde::{Deserialize, Serialize};
17use thiserror::Error;
18
19use crate::{
20    ModelSelect,
21    block_group_edge::{AugmentedEdge, BlockGroupEdge},
22    db::{GraphConnection, max_rows_per_batch},
23    errors::NodeError,
24    gen_models_capnp::edge,
25    node::Node,
26    sequence::{Sequence, SequenceError},
27};
28
29#[derive(
30    Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize, Ord, PartialOrd, ModelSelect,
31)]
32#[model_select(table = "edges")]
33pub struct Edge {
34    pub id: HashId,
35    pub source_node_id: HashId,
36    pub source_coordinate: i64,
37    pub source_strand: Strand,
38    pub target_node_id: HashId,
39    pub target_coordinate: i64,
40    pub target_strand: Strand,
41}
42
43impl<'a> Capnp<'a> for Edge {
44    type Builder = edge::Builder<'a>;
45    type Reader = edge::Reader<'a>;
46
47    fn write_capnp(&self, builder: &mut Self::Builder) {
48        builder.set_id(&self.id.0).unwrap();
49        builder.set_source_node_id(&self.source_node_id.0).unwrap();
50        builder.set_source_coordinate(self.source_coordinate);
51        builder.set_source_strand(self.source_strand.into());
52        builder.set_target_node_id(&self.target_node_id.0).unwrap();
53        builder.set_target_coordinate(self.target_coordinate);
54        builder.set_target_strand(self.target_strand.into());
55    }
56
57    fn read_capnp(reader: Self::Reader) -> Self {
58        let id: HashId = reader
59            .get_id()
60            .unwrap()
61            .as_slice()
62            .unwrap()
63            .try_into()
64            .unwrap();
65        let source_node_id = reader
66            .get_source_node_id()
67            .unwrap()
68            .as_slice()
69            .unwrap()
70            .try_into()
71            .unwrap();
72        let source_coordinate = reader.get_source_coordinate();
73        let source_strand = reader.get_source_strand().unwrap().into();
74        let target_node_id = reader
75            .get_target_node_id()
76            .unwrap()
77            .as_slice()
78            .unwrap()
79            .try_into()
80            .unwrap();
81        let target_coordinate = reader.get_target_coordinate();
82        let target_strand = reader.get_target_strand().unwrap().into();
83
84        Edge {
85            id,
86            source_node_id,
87            source_coordinate,
88            source_strand,
89            target_node_id,
90            target_coordinate,
91            target_strand,
92        }
93    }
94}
95
96#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Ord, PartialOrd)]
97pub struct EdgeData {
98    pub source_node_id: HashId,
99    pub source_coordinate: i64,
100    pub source_strand: Strand,
101    pub target_node_id: HashId,
102    pub target_coordinate: i64,
103    pub target_strand: Strand,
104}
105
106impl EdgeData {
107    pub fn id_hash(&self) -> HashId {
108        HashId(calculate_hash(&format!(
109            "{}:{}:{}:{}:{}:{}",
110            self.source_node_id,
111            self.source_coordinate,
112            self.source_strand,
113            self.target_node_id,
114            self.target_coordinate,
115            self.target_strand
116        )))
117    }
118}
119
120impl From<&Edge> for EdgeData {
121    fn from(item: &Edge) -> Self {
122        EdgeData {
123            source_node_id: item.source_node_id,
124            source_coordinate: item.source_coordinate,
125            source_strand: item.source_strand,
126            target_node_id: item.target_node_id,
127            target_coordinate: item.target_coordinate,
128            target_strand: item.target_strand,
129        }
130    }
131}
132
133#[derive(Eq, Hash, PartialEq)]
134pub struct BlockKey {
135    pub node_id: HashId,
136    pub coordinate: i64,
137}
138
139#[derive(Clone, Debug)]
140pub struct GroupBlock {
141    pub id: i64,
142    pub node_id: HashId,
143    sequence: Option<String>,
144    external_sequence: Option<Sequence>,
145    pub start: i64,
146    pub end: i64,
147}
148
149impl GroupBlock {
150    pub fn new(id: i64, node_id: HashId, sequence: &Sequence, start: i64, end: i64) -> Self {
151        if sequence.external_sequence {
152            GroupBlock {
153                id,
154                node_id,
155                sequence: None,
156                external_sequence: Some(sequence.clone()),
157                start,
158                end,
159            }
160        } else {
161            GroupBlock {
162                id,
163                node_id,
164                sequence: Some(sequence.get_sequence(start, end).unwrap()),
165                external_sequence: None,
166                start,
167                end,
168            }
169        }
170    }
171
172    pub fn sequence(&self) -> String {
173        if let Some(sequence) = &self.sequence {
174            sequence.to_string()
175        } else if let Some(sequence) = &self.external_sequence {
176            sequence.get_sequence(self.start, self.end).unwrap()
177        } else {
178            panic!("Sequence or external sequence is not set.")
179        }
180    }
181}
182
183#[derive(Debug, Error, PartialEq)]
184pub enum EdgeError {
185    #[error("Database error: {0}")]
186    DatabaseError(#[from] rusqlite::Error),
187    #[error("Node creation error: {0}")]
188    NodeError(#[from] NodeError),
189    #[error("Sequence error: {0}")]
190    SequenceError(#[from] SequenceError),
191    #[error("Cannot build blocks from starts {starts:?} and ends {ends:?}")]
192    BlockIntervalError {
193        starts: HashSet<i64>,
194        ends: HashSet<i64>,
195    },
196}
197
198impl Edge {
199    #[allow(clippy::too_many_arguments)]
200    #[cfg_attr(
201        all(debug_assertions, feature = "profiling"),
202        tracing::instrument(skip(
203            conn,
204            source_node_id,
205            source_coordinate,
206            source_strand,
207            target_node_id,
208            target_coordinate,
209            target_strand
210        ))
211    )]
212    pub fn create(
213        conn: &GraphConnection,
214        source_node_id: HashId,
215        source_coordinate: i64,
216        source_strand: Strand,
217        target_node_id: HashId,
218        target_coordinate: i64,
219        target_strand: Strand,
220    ) -> Result<Edge, EdgeError> {
221        let hash = EdgeData {
222            source_node_id,
223            source_coordinate,
224            source_strand,
225            target_node_id,
226            target_coordinate,
227            target_strand,
228        }
229        .id_hash();
230        let query = "INSERT INTO edges (id, source_node_id, source_coordinate, source_strand, target_node_id, target_coordinate, target_strand) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7);";
231        let mut stmt = match conn.prepare(query) {
232            Ok(s) => s,
233            Err(e) => return Err(EdgeError::DatabaseError(e)),
234        };
235        match stmt.execute(params![
236            hash,
237            source_node_id,
238            source_coordinate,
239            source_strand,
240            target_node_id,
241            target_coordinate,
242            target_strand
243        ]) {
244            Ok(_) => Ok(Edge {
245                id: hash,
246                source_node_id,
247                source_coordinate,
248                source_strand,
249                target_node_id,
250                target_coordinate,
251                target_strand,
252            }),
253            Err(rusqlite::Error::SqliteFailure(e, _))
254                if e.code == rusqlite::ErrorCode::ConstraintViolation =>
255            {
256                // Edge already exists, return the existing record
257                Ok(Edge {
258                    id: hash,
259                    source_node_id,
260                    source_coordinate,
261                    source_strand,
262                    target_node_id,
263                    target_coordinate,
264                    target_strand,
265                })
266            }
267            Err(e) => Err(EdgeError::DatabaseError(e)),
268        }
269    }
270
271    #[cfg_attr(feature = "profiling", tracing::instrument(skip(conn, edges)))]
272    pub fn bulk_create(conn: &GraphConnection, edges: &[EdgeData]) -> Vec<HashId> {
273        let edge_ids = edges.iter().map(|edge| edge.id_hash()).collect::<Vec<_>>();
274        let batch_size = max_rows_per_batch(conn, 7);
275
276        let query = Edge::select(conn)
277            .query_by_ids(edge_ids.iter().copied())
278            .expect("should load existing edges by id");
279        let existing_edges = query.iter().map(|edge| &edge.id).collect::<HashSet<_>>();
280
281        let mut edges_to_insert = IndexSet::new();
282        for (index, edge) in edge_ids.iter().enumerate() {
283            if !existing_edges.contains(edge) {
284                edges_to_insert.insert(&edges[index]);
285            }
286        }
287
288        for chunk in &edges_to_insert.iter().chunks(batch_size) {
289            let chunk = chunk.collect::<Vec<_>>();
290            let mut sql = String::from(
291                "INSERT INTO edges (id, source_node_id, source_coordinate, source_strand, target_node_id, target_coordinate, target_strand) VALUES ",
292            );
293            for row_index in 0..chunk.len() {
294                if row_index > 0 {
295                    sql.push(',');
296                }
297                sql.push_str("(?, ?, ?, ?, ?, ?, ?)");
298            }
299            let mut params = Vec::with_capacity(chunk.len() * 7);
300            for edge in chunk {
301                params.push(Value::from(edge.id_hash()));
302                params.push(Value::from(edge.source_node_id));
303                params.push(Value::from(edge.source_coordinate));
304                params.push(Value::from(edge.source_strand));
305                params.push(Value::from(edge.target_node_id));
306                params.push(Value::from(edge.target_coordinate));
307                params.push(Value::from(edge.target_strand));
308            }
309            sql.push(';');
310            let mut statement = conn.prepare_cached(&sql).unwrap();
311            statement
312                .execute(rusqlite::params_from_iter(params))
313                .unwrap();
314        }
315        edge_ids
316    }
317
318    pub fn to_data(edge: Edge) -> EdgeData {
319        EdgeData {
320            source_node_id: edge.source_node_id,
321            source_coordinate: edge.source_coordinate,
322            source_strand: edge.source_strand,
323            target_node_id: edge.target_node_id,
324            target_coordinate: edge.target_coordinate,
325            target_strand: edge.target_strand,
326        }
327    }
328
329    pub fn edges_for_block_group_nodes(
330        conn: &GraphConnection,
331        block_group_id: &HashId,
332        node_ids: &[HashId],
333        history_ref: Option<&str>,
334    ) -> Result<Vec<AugmentedEdge>, EdgeError> {
335        if node_ids.is_empty() {
336            return Ok(vec![]);
337        }
338
339        let mut edges = vec![];
340        let batch_size = max_rows_per_batch(conn, 1);
341        let query = format!(
342            "\
343            SELECT
344                e.id,
345                e.source_node_id,
346                e.source_coordinate,
347                e.source_strand,
348                e.target_node_id,
349                e.target_coordinate,
350                e.target_strand,
351                bge.chromosome_index,
352                bge.phased,
353                bge.created_on
354            FROM {} bge
355            JOIN {} e ON e.id = bge.edge_id
356            WHERE bge.block_group_id = :block_group_id
357              AND (e.source_node_id IN rarray(:node_ids) OR e.target_node_id IN rarray(:node_ids))
358            ORDER BY bge.created_on DESC;",
359            BlockGroupEdge::table_name_with_history_ref(history_ref),
360            Self::table_name_with_history_ref(history_ref),
361        );
362
363        for chunk in node_ids.chunks(batch_size) {
364            let values = chunk.iter().copied().map(Value::from).collect::<Vec<_>>();
365            let mut stmt = conn.prepare(&query)?;
366            let node_ids = Rc::new(values);
367            let mut params: Vec<(&str, &dyn ToSql)> = vec![
368                (":block_group_id", block_group_id),
369                (":node_ids", &node_ids),
370            ];
371            if let Some(history_ref) = history_ref.as_ref() {
372                params.push((":history_ref", history_ref));
373            }
374            let rows = stmt.query_map(&params[..], |row| {
375                Ok(AugmentedEdge {
376                    edge: Edge {
377                        id: row.get(0)?,
378                        source_node_id: row.get(1)?,
379                        source_coordinate: row.get(2)?,
380                        source_strand: row.get(3)?,
381                        target_node_id: row.get(4)?,
382                        target_coordinate: row.get(5)?,
383                        target_strand: row.get(6)?,
384                    },
385                    chromosome_index: row.get(7)?,
386                    phased: row.get(8)?,
387                    created_on: row.get(9)?,
388                })
389            })?;
390            for row in rows {
391                edges.push(row?);
392            }
393        }
394
395        Ok(edges)
396    }
397
398    /// Converts input edge coordinates for one backing node into the sequence slices represented
399    /// by `GroupBlock`s.
400    ///
401    /// `blocks_from_edges` calls this after it has collected every coordinate needed by the block
402    /// group. Non-zero intervals carry sequence, while requested zero-width intervals act as
403    /// junctions between adjacent coordinate jumps. Outer junctions cover edge endpoints that have
404    /// no sequence interval on one side, so every input edge still has a concrete graph endpoint.
405    fn get_block_intervals(
406        starts: &HashSet<i64>,
407        ends: &HashSet<i64>,
408        junction_coordinates: &HashSet<i64>,
409    ) -> Result<Vec<(i64, i64)>, EdgeError> {
410        let coordinates = starts.union(ends).sorted().copied().collect::<Vec<_>>();
411        if coordinates.is_empty() {
412            return Err(EdgeError::BlockIntervalError {
413                starts: starts.clone(),
414                ends: ends.clone(),
415            });
416        }
417        if coordinates.len() == 1 {
418            return Ok(vec![(coordinates[0], coordinates[0])]);
419        }
420
421        let mut intervals = Vec::new();
422        for (index, coordinate) in coordinates.iter().copied().enumerate() {
423            let is_first_coordinate = index == 0;
424            let is_last_coordinate = index == coordinates.len() - 1;
425            let needs_outer_junction = (is_first_coordinate && ends.contains(&coordinate))
426                || (is_last_coordinate && starts.contains(&coordinate));
427
428            if junction_coordinates.contains(&coordinate) || needs_outer_junction {
429                intervals.push((coordinate, coordinate));
430            }
431            if let Some(next_coordinate) = coordinates.get(index + 1) {
432                intervals.push((coordinate, *next_coordinate));
433            }
434        }
435
436        Ok(intervals)
437    }
438
439    /// Records a coordinate jump whose endpoints belong to the same backing node.
440    ///
441    /// `blocks_from_edges` calls this for its initial edges and for neighboring edges fetched while
442    /// completing partially described nodes. The source is an outgoing jump coordinate and the
443    /// target is an incoming jump coordinate. Keeping those sets separate lets block generation
444    /// identify where one jump arrives and another leaves.
445    fn record_same_node_jump_coordinates(
446        edge: &Edge,
447        outgoing_coordinates_by_node_id: &mut HashMap<HashId, HashSet<i64>>,
448        incoming_coordinates_by_node_id: &mut HashMap<HashId, HashSet<i64>>,
449    ) {
450        if edge.source_node_id == edge.target_node_id
451            && edge.source_coordinate != edge.target_coordinate
452        {
453            outgoing_coordinates_by_node_id
454                .entry(edge.source_node_id)
455                .or_default()
456                .insert(edge.source_coordinate);
457            incoming_coordinates_by_node_id
458                .entry(edge.target_node_id)
459                .or_default()
460                .insert(edge.target_coordinate);
461        }
462    }
463
464    /// Finds base boundaries that need a shared zero-width position.
465    ///
466    /// In reference `TACG`, deleting `A` spells `TCG`, deleting `C` spells `TAG`, and taking both
467    /// deletions spells `TG`. The empty position `(2,2)` between `A` and `C` connects the deletion
468    /// edges even when no sequence block remains between them:
469    ///
470    /// ```text
471    /// [T] --+--> [A] --+
472    ///       |          |
473    ///       +----------+--> (2,2) --+--> [C] --+
474    ///                               |          |
475    ///                               +----------+--> [G]
476    /// ```
477    fn shared_position_coordinates(edges: &[AugmentedEdge]) -> HashSet<BlockKey> {
478        let mut outgoing_coordinates = HashSet::new();
479        // Same-coordinate edges have a separate projection for connections between adjacent
480        // sequence slices.
481        // Distinct edges identify coordinates that need a shared site.
482        for augmented_edge in edges {
483            let edge = &augmented_edge.edge;
484            if !edge.is_same_coordinate_edge()
485                && !is_terminal(edge.source_node_id)
486                && !is_terminal(edge.target_node_id)
487            {
488                outgoing_coordinates.insert(BlockKey {
489                    node_id: edge.source_node_id,
490                    coordinate: edge.source_coordinate,
491                });
492            }
493        }
494
495        let mut incoming_coordinates = HashSet::new();
496        for augmented_edge in edges {
497            let edge = &augmented_edge.edge;
498            if !is_terminal(edge.target_node_id)
499                && !is_terminal(edge.source_node_id)
500                && !edge.is_same_coordinate_edge()
501                && outgoing_coordinates.contains(&BlockKey {
502                    node_id: edge.target_node_id,
503                    coordinate: edge.target_coordinate,
504                })
505            {
506                incoming_coordinates.insert(BlockKey {
507                    node_id: edge.target_node_id,
508                    coordinate: edge.target_coordinate,
509                });
510            }
511        }
512
513        incoming_coordinates
514    }
515
516    /// Computes the backing-node slices from the stored block group edges.
517    ///
518    /// Graph construction, sequence enumeration, GFA export, and diff reconstruction use this as
519    /// the first half of the edge-to-`GenGraph` pipeline, the second half being the build_graph
520    /// method below. This method gathers coordinates, expands incomplete node descriptions from
521    /// the block group, and calls `get_block_intervals` to construct both blocks with sequences
522    /// and zero-width junction blocks.
523    ///
524    /// In reference `TACG`, deleting `A` gives `TCG`, deleting the adjacent `C` gives `TAG`, and
525    /// both deletions give `TG`. The empty position `(2,2)` between `A` and `C` joins the deletion
526    /// edges. Parenthesized nodes are zero-width positions; bracketed nodes contain sequence:
527    ///
528    /// ```text
529    /// [T] --+--> [A] --+
530    ///       |          |
531    ///       +----------+--> (2,2) --+--> [C] --+
532    ///                               |          |
533    ///                               +----------+--> [G]
534    /// ```
535    ///
536    /// Deleting `A` skips `[A]`, and deleting `C` skips `[C]`. Their shared position joins the two
537    /// edges, so a path can take both deletions without adding a reconstructed bypass edge. A path
538    /// may pass through any number of consecutive zero-width positions before reaching a sequence
539    /// block; these steps consume no sequence.
540    ///
541    /// Consider a substitution of the first base of `TAAT`, changing `T` to `G` while keeping the
542    /// original sequence:
543    ///
544    /// ```text
545    ///                     +--> [T] --+
546    ///                     |          |
547    /// [AC] --> (0,0) -----+--> [G] --+--> [AAT]
548    /// ```
549    ///
550    /// The incoming edge reaches the start of `TAAT`; the substitution leaves that same boundary
551    /// for `[G]`. No `TAAT` bases precede its first `T`, so no nonempty sequence slice ends at that
552    /// boundary for the outgoing edit. `(0,0)` is an empty position at the start of `TAAT`, not a
553    /// graph coordinate, and supplies the shared endpoint. The two paths spell `ACTAAT` and
554    /// `ACGAAT`.
555    ///
556    /// If the input has only the incoming edge from `[AC]` to `TAAT`, fetched neighboring edges
557    /// can reveal the substitution. Include those edges when choosing the zero-width blocks.
558    pub fn blocks_from_edges(
559        conn: &GraphConnection,
560        workspace: &Workspace,
561        block_group_id: &HashId,
562        edges: &[AugmentedEdge],
563        history_ref: Option<&str>,
564    ) -> Result<Vec<GroupBlock>, EdgeError> {
565        let mut node_ids = IndexSet::new();
566        let mut starts_by_node_id: HashMap<HashId, HashSet<i64>> = HashMap::new();
567        let mut ends_by_node_id: HashMap<HashId, HashSet<i64>> = HashMap::new();
568        // A same-node coordinate jump connects positions without consuming the intervening
569        // sequence. Track where jumps leave and arrive so their intersections can become
570        // junctions.
571        let mut outgoing_jump_coordinates_by_node_id: HashMap<HashId, HashSet<i64>> =
572            HashMap::new();
573        let mut incoming_jump_coordinates_by_node_id: HashMap<HashId, HashSet<i64>> =
574            HashMap::new();
575        let mut routing_edges = edges.to_vec();
576        for edge in edges.iter().map(|edge| &edge.edge) {
577            Self::record_same_node_jump_coordinates(
578                edge,
579                &mut outgoing_jump_coordinates_by_node_id,
580                &mut incoming_jump_coordinates_by_node_id,
581            );
582            if !is_terminal(edge.source_node_id) {
583                node_ids.insert(edge.source_node_id);
584            }
585            ends_by_node_id
586                .entry(edge.source_node_id)
587                .or_default()
588                .insert(edge.source_coordinate);
589
590            if !is_terminal(edge.target_node_id) {
591                node_ids.insert(edge.target_node_id);
592            }
593            starts_by_node_id
594                .entry(edge.target_node_id)
595                .or_default()
596                .insert(edge.target_coordinate);
597        }
598
599        let is_incomplete =
600            |node_id: &HashId,
601             starts_by_node_id: &HashMap<HashId, HashSet<i64>>,
602             ends_by_node_id: &HashMap<HashId, HashSet<i64>>| {
603                let has_starts = starts_by_node_id
604                    .get(node_id)
605                    .is_some_and(|starts| !starts.is_empty());
606                let has_ends = ends_by_node_id
607                    .get(node_id)
608                    .is_some_and(|ends| !ends.is_empty());
609                has_starts != has_ends
610            };
611        let mut queried_node_ids = HashSet::new();
612        let mut incomplete_node_ids = node_ids
613            .iter()
614            .copied()
615            .filter(|node_id| is_incomplete(node_id, &starts_by_node_id, &ends_by_node_id))
616            .collect::<Vec<_>>();
617
618        // A caller may provide a graph fragment whose edges mention only one side of a backing
619        // node. Pulling neighboring input edges supplies the missing endpoint coordinates so the
620        // resulting blocks use the same slices as a graph built from the complete block group.
621        while !incomplete_node_ids.is_empty() {
622            queried_node_ids.extend(incomplete_node_ids.iter().copied());
623            let mut next_incomplete_node_ids = HashSet::new();
624
625            let neighboring_edges = Edge::edges_for_block_group_nodes(
626                conn,
627                block_group_id,
628                &incomplete_node_ids,
629                history_ref,
630            )?;
631            for augmented_edge in neighboring_edges {
632                routing_edges.push(augmented_edge.clone());
633                let edge = &augmented_edge.edge;
634                Self::record_same_node_jump_coordinates(
635                    edge,
636                    &mut outgoing_jump_coordinates_by_node_id,
637                    &mut incoming_jump_coordinates_by_node_id,
638                );
639                if !is_terminal(edge.source_node_id) {
640                    node_ids.insert(edge.source_node_id);
641                }
642                ends_by_node_id
643                    .entry(edge.source_node_id)
644                    .or_default()
645                    .insert(edge.source_coordinate);
646
647                if !is_terminal(edge.target_node_id) {
648                    node_ids.insert(edge.target_node_id);
649                }
650                starts_by_node_id
651                    .entry(edge.target_node_id)
652                    .or_default()
653                    .insert(edge.target_coordinate);
654
655                for candidate_node_id in [edge.source_node_id, edge.target_node_id] {
656                    if !is_terminal(candidate_node_id)
657                        && !queried_node_ids.contains(&candidate_node_id)
658                        && is_incomplete(&candidate_node_id, &starts_by_node_id, &ends_by_node_id)
659                    {
660                        next_incomplete_node_ids.insert(candidate_node_id);
661                    }
662                }
663            }
664
665            incomplete_node_ids = next_incomplete_node_ids.into_iter().collect();
666        }
667
668        let node_ids = node_ids.iter().copied().collect::<Vec<HashId>>();
669        let shared_position_coordinates = Self::shared_position_coordinates(&routing_edges);
670        let mut shared_position_coordinates_by_node_id = HashMap::<HashId, HashSet<i64>>::new();
671        for position in shared_position_coordinates {
672            shared_position_coordinates_by_node_id
673                .entry(position.node_id)
674                .or_default()
675                .insert(position.coordinate);
676        }
677        let sequences_by_node_id =
678            Node::get_sequences_by_node_ids(conn, workspace, &node_ids, history_ref);
679
680        let mut blocks = vec![];
681        let mut block_index = 0;
682        // we sort by keys to exploit the external sequence cache which keeps the most recently used
683        // external sequence in memory.
684        for (node_id, sequence) in sequences_by_node_id
685            .iter()
686            .sorted_by_key(|(_node_id, seq)| seq.hash)
687        {
688            let empty_starts = HashSet::new();
689            let empty_ends = HashSet::new();
690            let starts = starts_by_node_id.get(node_id).unwrap_or(&empty_starts);
691            let ends = ends_by_node_id.get(node_id).unwrap_or(&empty_ends);
692            let empty_jumps = HashSet::new();
693            let outgoing_jump_coordinates = outgoing_jump_coordinates_by_node_id
694                .get(node_id)
695                .unwrap_or(&empty_jumps);
696            let incoming_jump_coordinates = incoming_jump_coordinates_by_node_id
697                .get(node_id)
698                .unwrap_or(&empty_jumps);
699            // In `TACG`, the same-node jump deleting `A` arrives at `(2,2)` and the same-node jump
700            // deleting the adjacent `C` leaves from that empty position:
701            //
702            //     [T] --+--> [A] --+
703            //           |          |
704            //           +----------+--> (2,2) --+--> [C] --+
705            //                                   |          |
706            //                                   +----------+--> [G]
707            //
708            // Shared endpoints with other edges are also routing positions. A lone jump connects
709            // sequence blocks directly when neither endpoint needs a junction.
710            let mut junction_coordinates = outgoing_jump_coordinates
711                .intersection(incoming_jump_coordinates)
712                .copied()
713                .collect::<HashSet<_>>();
714            junction_coordinates.extend(outgoing_jump_coordinates.intersection(starts).copied());
715            junction_coordinates.extend(incoming_jump_coordinates.intersection(ends).copied());
716            junction_coordinates.extend(
717                shared_position_coordinates_by_node_id
718                    .get(node_id)
719                    .into_iter()
720                    .flatten()
721                    .copied(),
722            );
723            let block_intervals = Edge::get_block_intervals(starts, ends, &junction_coordinates)?;
724
725            for (start, end) in block_intervals {
726                blocks.push(GroupBlock::new(block_index, *node_id, sequence, start, end));
727                block_index += 1;
728            }
729        }
730
731        // NOTE: We need a dedicated start node and a dedicated end node for the graph formed by the
732        // block group, since different paths in the block group may start or end at different
733        // places on sequences.  These two "start sequence" and "end sequence" blocks will serve
734        // that role.
735        let start_block = GroupBlock::new(
736            block_index + 1,
737            PATH_START_NODE_ID,
738            &Sequence::new().sequence_type("DNA").sequence("").build(),
739            0,
740            0,
741        );
742        blocks.push(start_block);
743        let end_block = GroupBlock::new(
744            block_index + 2,
745            PATH_END_NODE_ID,
746            &Sequence::new().sequence_type("DNA").sequence("").build(),
747            0,
748            0,
749        );
750        blocks.push(end_block);
751        Ok(blocks)
752    }
753
754    /// Checks whether both endpoints use the same node and coordinate.
755    ///
756    /// `block_connections` uses this structural property when connecting blocks around a junction.
757    /// Whether the edge is a real path choice or a reference-healing edit-site marker remains
758    /// separate chromosome-index metadata on `AugmentedEdge`.
759    fn is_same_coordinate_edge(&self) -> bool {
760        self.source_node_id == self.target_node_id
761            && self.source_coordinate == self.target_coordinate
762    }
763
764    /// Selects the blocks that an edge endpoint should connect to.
765    ///
766    /// `block_connections` calls this when an input edge enters or leaves a coordinate. If a
767    /// junction exists, the edge connects to it and traversal continues from there. Otherwise the
768    /// edge connects directly to the sequence block.
769    fn select_junction_or_sequence_blocks<'a>(blocks: &[&'a GroupBlock]) -> Vec<&'a GroupBlock> {
770        let junctions = blocks
771            .iter()
772            .copied()
773            .filter(|block| block.start == block.end)
774            .collect::<Vec<_>>();
775        if junctions.is_empty() {
776            blocks.to_vec()
777        } else {
778            junctions
779        }
780    }
781
782    /// Builds connections for a same-coordinate edge.
783    ///
784    /// At a junction, the source lookup contains the sequence block ending at the coordinate and
785    /// the junction, while the target lookup contains the junction and the sequence block starting
786    /// there. `block_connections` calls this to produce the deliberate `sequence -> junction` and
787    /// `junction -> sequence` connections without adding a junction self-loop. With no junction,
788    /// the Cartesian product keeps the direct connection between sequence blocks.
789    ///
790    /// For reference `TACG`, `[A]` and `[C]` meet at offset `2`:
791    ///
792    /// ```text
793    /// without a junction:  [A] ---> [C]
794    ///
795    /// with a junction:     [A] ---> (2,2) ---> [C]
796    /// ```
797    ///
798    /// The same-coordinate edge therefore preserves the same route after the junction is
799    /// introduced without creating `(2,2) -> (2,2)`.
800    fn same_coordinate_block_connections<'a>(
801        source_blocks: &[&'a GroupBlock],
802        target_blocks: &[&'a GroupBlock],
803    ) -> Vec<(&'a GroupBlock, &'a GroupBlock)> {
804        let source_junctions = source_blocks
805            .iter()
806            .copied()
807            .filter(|block| block.start == block.end)
808            .collect::<Vec<_>>();
809        let target_junctions = target_blocks
810            .iter()
811            .copied()
812            .filter(|block| block.start == block.end)
813            .collect::<Vec<_>>();
814
815        if source_junctions.is_empty() && target_junctions.is_empty() {
816            return source_blocks
817                .iter()
818                .copied()
819                .cartesian_product(target_blocks.iter().copied())
820                .collect();
821        }
822
823        let source_sequence_blocks = source_blocks
824            .iter()
825            .copied()
826            .filter(|block| block.start != block.end);
827        let target_sequence_blocks = target_blocks
828            .iter()
829            .copied()
830            .filter(|block| block.start != block.end);
831
832        // Sequence ending at the coordinate enters the junction, and sequence starting there
833        // leaves it. If neither side has real sequence, there is no connection to add.
834        source_sequence_blocks
835            .cartesian_product(target_junctions)
836            .chain(
837                source_junctions
838                    .into_iter()
839                    .cartesian_product(target_sequence_blocks),
840            )
841            .collect()
842    }
843
844    /// Returns the graph links represented by one stored edge.
845    ///
846    /// In `TACG`, deleting `A` gives `TCG`, deleting the adjacent `C` gives `TAG`, and taking both
847    /// deletions gives `TG`. The first deletion jumps from after `T` to the boundary between `A`
848    /// and `C`; the second leaves from that same boundary. The empty position lets the deletions
849    /// combine without consuming either deleted base:
850    ///
851    /// ```text
852    /// [T] --+--> [A] --+
853    ///       |          |
854    ///       +----------+--> (2,2) --+--> [C] --+
855    ///                               |          |
856    ///                               +----------+--> [G]
857    /// ```
858    ///
859    /// `(2,2)` is the empty position between `A` and `C`. Edges connecting adjacent sequence
860    /// slices at the same coordinate pass through such positions without adding a self-loop.
861    ///
862    /// If an edit starts at a shared boundary or a deletion jump stays within one sequence node,
863    /// keep the sequence slice as a source alongside any zero-width position. For deleting `C` in
864    /// `TACG`, `[A]` can reach `[G]` directly or through `(2,2)`. The direct route remains available
865    /// if the connection between adjacent sequence slices is filtered out. A deletion jump also
866    /// keeps possible target slices unless its target boundary is shared. These graph links
867    /// represent one stored edge, not new stored edges.
868    ///
869    /// Both delete-`C` links below keep the same stored edge identity:
870    ///
871    /// ```text
872    /// [A] --+-- delete C -----------------------------+
873    ///       |                                         |
874    ///       +-- reference --> (2,2) -- delete C ------+--> [G]
875    /// ```
876    fn block_connections<'a>(
877        &self,
878        source_blocks: &[&'a GroupBlock],
879        target_blocks: &[&'a GroupBlock],
880        source_is_shared_position: bool,
881        target_is_shared_position: bool,
882    ) -> Vec<(&'a GroupBlock, &'a GroupBlock)> {
883        if self.is_same_coordinate_edge() {
884            return Self::same_coordinate_block_connections(source_blocks, target_blocks);
885        }
886
887        let same_node_jump = self.source_node_id == self.target_node_id;
888        let source_blocks = if source_is_shared_position || same_node_jump {
889            source_blocks.to_vec()
890        } else {
891            Self::select_junction_or_sequence_blocks(source_blocks)
892        };
893        let target_blocks = if target_is_shared_position {
894            target_blocks
895                .iter()
896                .copied()
897                .filter(|block| block.start == block.end)
898                .collect()
899        } else if same_node_jump {
900            target_blocks.to_vec()
901        } else {
902            Self::select_junction_or_sequence_blocks(target_blocks)
903        };
904        source_blocks
905            .into_iter()
906            .cartesian_product(target_blocks)
907            .collect()
908    }
909
910    /// Computes a `GenGraph` from augmented edges and their computed blocks.
911    ///
912    /// `BlockGroup::get_graph`, sequence enumeration, and graph export call this after
913    /// `blocks_from_edges`. The returned node-pair map retains the input `Edge` responsible for
914    /// each projected graph edge so downstream consumers can recover edge provenance.
915    ///
916    /// Junctions and `PRESERVE_EDIT_SITE_CHROMOSOME_INDEX` have independent jobs:
917    ///
918    /// - A junction is a generated zero-width graph node. It gives adjacent edges a shared endpoint
919    ///   so edges can link to the site of an edit instead of requiring a sequence to link to.
920    ///   This occurs in places such as deleting the first base of a node, or adjacent deletions.
921    /// - `PRESERVE_EDIT_SITE_CHROMOSOME_INDEX` is metadata on an `AugmentedEdge`. It identifies a
922    ///   reference-healing connection. Importantly, these are in the database whereas junctions
923    ///   are in the built graph only.
924    ///
925    /// When a marked same-coordinate edge meets a junction, one input edge can produce two
926    /// in-memory graph connections:
927    ///
928    /// ```text
929    /// [ATA] -- reference --> (3,3) -- reference --> [CG]
930    ///                           0 bases
931    /// ```
932    ///
933    /// `(3,3)` is the generated node. The reference labels represent copied chromosome-index
934    /// metadata on the projected connections; neither connection is added to the database.
935    ///
936    /// One stored edge may produce several graph links. Each link keeps the edge's ID and metadata;
937    /// the pair map retains the original `Edge`, so pruning recognizes the links as one edit.
938    pub fn build_graph(
939        edges: &[AugmentedEdge],
940        blocks: &[GroupBlock],
941    ) -> (GenGraph, HashMap<(i64, i64), Edge>) {
942        let shared_position_coordinates = Self::shared_position_coordinates(edges);
943        let graph_node_for_block = |block: &GroupBlock| GraphNode {
944            node_id: block.node_id,
945            sequence_start: block.start,
946            sequence_end: block.end,
947        };
948        // Input edge sources resolve to blocks ending at their coordinate, and targets resolve to
949        // blocks starting there. A junction belongs to both indexes, which lets one edge arrive at
950        // it and the next edge leave from it.
951        let blocks_by_start = blocks
952            .iter()
953            .map(|block| {
954                (
955                    BlockKey {
956                        node_id: block.node_id,
957                        coordinate: block.start,
958                    },
959                    block,
960                )
961            })
962            .into_group_map();
963        let blocks_by_end = blocks
964            .iter()
965            .map(|block| {
966                (
967                    BlockKey {
968                        node_id: block.node_id,
969                        coordinate: block.end,
970                    },
971                    block,
972                )
973            })
974            .into_group_map();
975
976        let mut graph = GenGraph::new();
977        let mut edges_by_node_pair = HashMap::new();
978        let mut position_exit_projections = Vec::new();
979        let graph_edge_for = |augmented_edge: &AugmentedEdge| GraphEdge {
980            edge_id: augmented_edge.edge.id,
981            source_strand: augmented_edge.edge.source_strand,
982            target_strand: augmented_edge.edge.target_strand,
983            chromosome_index: augmented_edge.chromosome_index,
984            phased: augmented_edge.phased,
985            created_on: augmented_edge.created_on,
986        };
987        for block in blocks {
988            graph.add_node(graph_node_for_block(block));
989        }
990        for (edge_index, augmented_edge) in edges.iter().enumerate() {
991            let edge = &augmented_edge.edge;
992            let source_key = BlockKey {
993                node_id: edge.source_node_id,
994                coordinate: edge.source_coordinate,
995            };
996            let source_blocks = blocks_by_end.get(&source_key);
997            let target_key = BlockKey {
998                node_id: edge.target_node_id,
999                coordinate: edge.target_coordinate,
1000            };
1001            let target_blocks = blocks_by_start.get(&target_key);
1002
1003            if let Some(source_blocks) = source_blocks
1004                && let Some(target_blocks) = target_blocks
1005            {
1006                // A coordinate may match both a sequence block and a junction. When connecting
1007                // to junctions, multiple edges may be needed to fully represent the graph.
1008                // `block_connections` orchestrates this.
1009                let source_is_shared_position = shared_position_coordinates.contains(&source_key);
1010                let target_is_shared_position = shared_position_coordinates.contains(&target_key);
1011                let connections = edge.block_connections(
1012                    source_blocks,
1013                    target_blocks,
1014                    source_is_shared_position,
1015                    target_is_shared_position,
1016                );
1017                for (source_block, target_block) in &connections {
1018                    let source_node = graph_node_for_block(source_block);
1019                    let target_node = graph_node_for_block(target_block);
1020                    let graph_edge = graph_edge_for(augmented_edge);
1021                    if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1022                        existing_edges.push(graph_edge);
1023                    } else {
1024                        graph.add_edge(source_node, target_node, vec![graph_edge]);
1025                    }
1026                    edges_by_node_pair.insert((source_block.id, target_block.id), edge.clone());
1027                }
1028
1029                if target_is_shared_position && !edge.is_same_coordinate_edge() {
1030                    let target_sequences = target_blocks
1031                        .iter()
1032                        .copied()
1033                        .filter(|block| block.start != block.end)
1034                        .collect::<Vec<_>>();
1035                    for (source_block, position_block) in connections
1036                        .iter()
1037                        .filter(|(_, target_block)| target_block.start == target_block.end)
1038                    {
1039                        for target_sequence in &target_sequences {
1040                            position_exit_projections.push((
1041                                *source_block,
1042                                *position_block,
1043                                *target_sequence,
1044                                edge_index,
1045                            ));
1046                        }
1047                    }
1048                }
1049            }
1050        }
1051
1052        // With no possible cycle-exit links, there is nothing to check.
1053        if position_exit_projections.is_empty() {
1054            return (graph, edges_by_node_pair);
1055        }
1056
1057        // Another edit can split inserted `GG` into `[G]` slices `0..1` and `1..2`; a partial
1058        // graph fragment can discover this cut from a neighboring edge. If the connection between
1059        // adjacent sequence slices is filtered or absent, supplied edges still give
1060        // `(3,3) -> [G](0..1)` and `[G](1..2) -> (3,3)`, but omit the middle `[G] -> [G]` link.
1061        // The intact `[GG]` cycle shown below has no such gap and needs no temporary link.
1062        //
1063        // For SCC classification only, the loop skips zero-width blocks and matches positive-
1064        // length slices on the same node when one ends where the next begins (here, offset `1`).
1065        // It adds the missing `[G] -> [G]` link without stored edge metadata, then records the
1066        // pair for removal. These links let the cycle check see the return across both slices:
1067        //
1068        //               +--> [G] (0..1) -- temporary connection --> [G] (1..2) --+
1069        //               |                                                        |
1070        // [ATA] --> (3,3) <------------------------------------------------------+
1071        let mut continuity_edges = Vec::new();
1072        for source_block in blocks.iter().filter(|block| block.start != block.end) {
1073            let next_block_key = BlockKey {
1074                node_id: source_block.node_id,
1075                coordinate: source_block.end,
1076            };
1077            if let Some(target_blocks) = blocks_by_start.get(&next_block_key) {
1078                for target_block in target_blocks
1079                    .iter()
1080                    .filter(|block| block.start != block.end)
1081                {
1082                    let source_node = graph_node_for_block(source_block);
1083                    let target_node = graph_node_for_block(target_block);
1084                    if !graph.contains_edge(source_node, target_node) {
1085                        graph.add_edge(source_node, target_node, Vec::new());
1086                        continuity_edges.push((source_node, target_node));
1087                    }
1088                }
1089            }
1090        }
1091
1092        // Use the graph with adjacent sequence slices connected to decide whether a candidate
1093        // returns to its position.
1094        let component_by_node = kosaraju_scc(&graph)
1095            .into_iter()
1096            .enumerate()
1097            .flat_map(|(component, nodes)| nodes.into_iter().map(move |node| (node, component)))
1098            .collect::<HashMap<_, _>>();
1099        // The SCCs use those temporary links. Remove them in reverse insertion order before
1100        // applying real exit projections, restoring the stored-edge graph and its edge ordering.
1101        for (source_node, target_node) in continuity_edges.into_iter().rev() {
1102            graph.remove_edge(source_node, target_node);
1103        }
1104
1105        // In intact reference `ATACG`, inserting `GG` between `[ATA]` and `[CG]` spells `ATAGGCG`.
1106        // For the candidate below, `source_block` is `[GG]`, `position_block` is `(3,3)`, and
1107        // `target_block` is `[CG]`. If `[GG]` and `(3,3)` are in the same SCC, the return path
1108        // exists, so this adds the real `[GG] -> [CG]` projection using the return edge's metadata.
1109        // The original cycle remains:
1110        //
1111        //               +----> [GG] ---+
1112        //               |              |
1113        // [ATA] --> (3,3) <------------+
1114        //               |              |
1115        //               +--------------+--> [CG]
1116        //
1117        // This happens for all insertions that do not replace bases -- such as inserting
1118        // "AAA" at m123:10-10.
1119        // An acyclic route gets no shortcut: it could bypass a touching edit and restore a
1120        // replaced reference base, such as the first `T` in `TAAT` after `T` becomes `G`.
1121        for (source_block, position_block, target_block, edge_index) in position_exit_projections {
1122            let source_node = graph_node_for_block(source_block);
1123            let position_node = graph_node_for_block(position_block);
1124            let target_node = graph_node_for_block(target_block);
1125            if component_by_node.get(&source_node) != component_by_node.get(&position_node) {
1126                continue;
1127            }
1128
1129            let augmented_edge = &edges[edge_index];
1130            let edge = &augmented_edge.edge;
1131            let graph_edge = graph_edge_for(augmented_edge);
1132            if let Some(existing_edges) = graph.edge_weight_mut(source_node, target_node) {
1133                existing_edges.push(graph_edge);
1134            } else {
1135                graph.add_edge(source_node, target_node, vec![graph_edge]);
1136            }
1137            edges_by_node_pair.insert((source_block.id, target_block.id), edge.clone());
1138        }
1139
1140        (graph, edges_by_node_pair)
1141    }
1142
1143    pub fn is_start_edge(&self) -> bool {
1144        self.source_node_id == PATH_START_NODE_ID
1145    }
1146
1147    pub fn is_end_edge(&self) -> bool {
1148        self.target_node_id == PATH_END_NODE_ID
1149    }
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154    // Note this useful idiom: importing names from outer (for mod tests) scope.
1155    use gen_core::PathBlock;
1156
1157    use super::*;
1158    use crate::{
1159        block_group::{BlockGroup, BlockGroupChange},
1160        block_group_edge::{BlockGroupEdge, BlockGroupEdgeData},
1161        collection::Collection,
1162        region::ResolvedGenRegion,
1163        sequence::Sequence,
1164        test_helpers::{get_connection, setup_block_group, test_workspace},
1165    };
1166
1167    fn get_block_boundaries(
1168        source_edges: Option<&Vec<&Edge>>,
1169        target_edges: Option<&Vec<&Edge>>,
1170    ) -> Vec<i64> {
1171        let mut block_boundary_coordinates = HashSet::new();
1172        if let Some(actual_source_edges) = source_edges {
1173            for source_edge in actual_source_edges {
1174                block_boundary_coordinates.insert(source_edge.source_coordinate);
1175            }
1176        }
1177        if let Some(actual_target_edges) = target_edges {
1178            for target_edge in actual_target_edges {
1179                block_boundary_coordinates.insert(target_edge.target_coordinate);
1180            }
1181        }
1182
1183        block_boundary_coordinates
1184            .into_iter()
1185            .sorted_by(|c1, c2| Ord::cmp(&c1, &c2))
1186            .collect::<Vec<i64>>()
1187    }
1188
1189    fn group_block(id: i64, node_id: HashId, start: i64, end: i64) -> GroupBlock {
1190        GroupBlock {
1191            id,
1192            node_id,
1193            sequence: Some(String::new()),
1194            external_sequence: None,
1195            start,
1196            end,
1197        }
1198    }
1199
1200    fn augmented_edge(
1201        id: &str,
1202        source_node_id: HashId,
1203        source_coordinate: i64,
1204        target_node_id: HashId,
1205        target_coordinate: i64,
1206    ) -> AugmentedEdge {
1207        AugmentedEdge {
1208            edge: Edge {
1209                id: HashId::convert_str(id),
1210                source_node_id,
1211                source_coordinate,
1212                source_strand: Strand::Forward,
1213                target_node_id,
1214                target_coordinate,
1215                target_strand: Strand::Forward,
1216            },
1217            chromosome_index: 0,
1218            phased: 0,
1219            created_on: 0,
1220        }
1221    }
1222
1223    fn graph_node(block: &GroupBlock) -> GraphNode {
1224        GraphNode {
1225            node_id: block.node_id,
1226            sequence_start: block.start,
1227            sequence_end: block.end,
1228        }
1229    }
1230
1231    #[test]
1232    fn test_get_block_intervals_splits_sorted_unique_coordinates() {
1233        let starts = HashSet::from([5, 0, 5]);
1234        let ends = HashSet::from([10, 3]);
1235
1236        let intervals = Edge::get_block_intervals(&starts, &ends, &HashSet::new()).unwrap();
1237
1238        assert_eq!(intervals, vec![(0, 3), (3, 5), (5, 10)]);
1239    }
1240
1241    #[test]
1242    fn test_get_block_intervals_single_coordinate_creates_anchor_block() {
1243        let starts = HashSet::from([3]);
1244        let ends = HashSet::new();
1245
1246        let intervals = Edge::get_block_intervals(&starts, &ends, &HashSet::new()).unwrap();
1247
1248        assert_eq!(intervals, vec![(3, 3)]);
1249    }
1250
1251    #[test]
1252    fn test_get_block_intervals_adds_outer_junctions() {
1253        let starts = HashSet::from([0, 2, 4]);
1254        let ends = HashSet::from([0, 2, 4]);
1255
1256        let intervals = Edge::get_block_intervals(&starts, &ends, &HashSet::new()).unwrap();
1257
1258        assert_eq!(intervals, vec![(0, 0), (0, 2), (2, 4), (4, 4)]);
1259    }
1260
1261    #[test]
1262    fn test_get_block_intervals_adds_requested_interior_junction() {
1263        let starts = HashSet::from([0, 2, 4]);
1264        let ends = HashSet::from([0, 2, 4]);
1265        let junction_coordinates = HashSet::from([2]);
1266
1267        let intervals = Edge::get_block_intervals(&starts, &ends, &junction_coordinates).unwrap();
1268
1269        assert_eq!(intervals, vec![(0, 0), (0, 2), (2, 2), (2, 4), (4, 4)]);
1270    }
1271
1272    #[test]
1273    fn test_get_block_intervals_errors_without_coordinates() {
1274        assert!(matches!(
1275            Edge::get_block_intervals(&HashSet::new(), &HashSet::new(), &HashSet::new()),
1276            Err(EdgeError::BlockIntervalError { .. })
1277        ));
1278    }
1279
1280    #[test]
1281    fn test_build_graph_routes_incoming_edge_to_junction() {
1282        let source_node_id = HashId::convert_str("incoming-source");
1283        let target_node_id = HashId::convert_str("incoming-target");
1284        let blocks = vec![
1285            group_block(0, source_node_id, 0, 3),
1286            group_block(1, target_node_id, 0, 0),
1287            group_block(2, target_node_id, 0, 1),
1288        ];
1289        let edges = vec![augmented_edge(
1290            "incoming-edge",
1291            source_node_id,
1292            3,
1293            target_node_id,
1294            0,
1295        )];
1296
1297        let (graph, _) = Edge::build_graph(&edges, &blocks);
1298
1299        assert!(
1300            graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[1])),
1301            "incoming edge should terminate at the junction"
1302        );
1303        assert!(
1304            !graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[2])),
1305            "incoming edge should not bypass the junction"
1306        );
1307        assert_eq!(graph.edge_count(), 1, "should project one block edge");
1308    }
1309
1310    #[test]
1311    fn test_build_graph_routes_outgoing_edge_from_junction() {
1312        let source_node_id = HashId::convert_str("outgoing-source");
1313        let target_node_id = HashId::convert_str("outgoing-target");
1314        let blocks = vec![
1315            group_block(0, source_node_id, 0, 1),
1316            group_block(1, source_node_id, 1, 1),
1317            group_block(2, target_node_id, 0, 2),
1318        ];
1319        let edges = vec![augmented_edge(
1320            "outgoing-edge",
1321            source_node_id,
1322            1,
1323            target_node_id,
1324            0,
1325        )];
1326
1327        let (graph, _) = Edge::build_graph(&edges, &blocks);
1328
1329        assert!(
1330            graph.contains_edge(graph_node(&blocks[1]), graph_node(&blocks[2])),
1331            "outgoing edge should originate at the junction"
1332        );
1333        assert!(
1334            !graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[2])),
1335            "outgoing edge should not bypass the junction"
1336        );
1337        assert_eq!(graph.edge_count(), 1, "should create one block edge");
1338    }
1339
1340    #[test]
1341    fn test_build_graph_creates_same_coordinate_edge_from_start_junction() {
1342        let node_id = HashId::convert_str("same-coordinate-node");
1343        let blocks = vec![group_block(0, node_id, 0, 0), group_block(1, node_id, 0, 1)];
1344        let edges = vec![augmented_edge(
1345            "same-coordinate-edge",
1346            node_id,
1347            0,
1348            node_id,
1349            0,
1350        )];
1351
1352        let (graph, _) = Edge::build_graph(&edges, &blocks);
1353
1354        assert!(
1355            graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[1])),
1356            "same-coordinate edge should connect the junction to adjacent sequence"
1357        );
1358        assert!(
1359            !graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[0])),
1360            "same-coordinate edge should not add a redundant junction self-loop"
1361        );
1362        assert_eq!(graph.edge_count(), 1, "should create one block edge");
1363    }
1364
1365    #[test]
1366    fn test_build_graph_creates_same_coordinate_edge_into_end_junction() {
1367        let node_id = HashId::convert_str("ending-same-coordinate-node");
1368        let blocks = vec![group_block(0, node_id, 0, 1), group_block(1, node_id, 1, 1)];
1369        let edges = vec![augmented_edge(
1370            "ending-same-coordinate-edge",
1371            node_id,
1372            1,
1373            node_id,
1374            1,
1375        )];
1376
1377        let (graph, _) = Edge::build_graph(&edges, &blocks);
1378
1379        assert!(
1380            graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[1])),
1381            "same-coordinate edge should connect adjacent sequence into the junction"
1382        );
1383        assert!(
1384            !graph.contains_edge(graph_node(&blocks[1]), graph_node(&blocks[1])),
1385            "same-coordinate edge should not add a redundant junction self-loop"
1386        );
1387        assert_eq!(graph.edge_count(), 1, "should create one block edge");
1388    }
1389
1390    #[test]
1391    fn test_build_graph_creates_same_coordinate_edge_without_junction_directly() {
1392        let node_id = HashId::convert_str("interior-same-coordinate-node");
1393        let blocks = vec![group_block(0, node_id, 0, 1), group_block(1, node_id, 1, 2)];
1394        let edges = vec![augmented_edge(
1395            "interior-same-coordinate-edge",
1396            node_id,
1397            1,
1398            node_id,
1399            1,
1400        )];
1401
1402        let (graph, _) = Edge::build_graph(&edges, &blocks);
1403
1404        assert!(
1405            graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[1])),
1406            "same-coordinate edge should directly connect sequence blocks without a junction"
1407        );
1408        assert_eq!(graph.edge_count(), 1, "should create one block edge");
1409    }
1410
1411    #[test]
1412    fn test_build_graph_omits_same_coordinate_edge_without_adjacent_sequence() {
1413        let node_id = HashId::convert_str("isolated-junction");
1414        let blocks = vec![group_block(0, node_id, 0, 0)];
1415        let edges = vec![augmented_edge("isolated-edge", node_id, 0, node_id, 0)];
1416
1417        let (graph, edges_by_node_pair) = Edge::build_graph(&edges, &blocks);
1418
1419        assert!(
1420            !graph.contains_edge(graph_node(&blocks[0]), graph_node(&blocks[0])),
1421            "a junction without adjacent sequence should not create a graph self-loop"
1422        );
1423        assert_eq!(graph.edge_count(), 0, "should not create a block edge");
1424        assert!(
1425            edges_by_node_pair.is_empty(),
1426            "omitted self-loop should not have a block-pair mapping"
1427        );
1428    }
1429
1430    #[test]
1431    fn test_bulk_create() {
1432        let conn = &mut get_connection(None).unwrap();
1433        Collection::create(conn, "test collection").unwrap();
1434        let sequence1 = Sequence::new()
1435            .sequence_type("DNA")
1436            .sequence("ATCGATCG")
1437            .save(conn)
1438            .unwrap();
1439        let node1_id = Node::create(conn, &sequence1.hash, &HashId::convert_str("1")).unwrap();
1440        let edge1 = EdgeData {
1441            source_node_id: PATH_START_NODE_ID,
1442            source_coordinate: -1,
1443            source_strand: Strand::Forward,
1444            target_node_id: node1_id,
1445            target_coordinate: 1,
1446            target_strand: Strand::Forward,
1447        };
1448        let sequence2 = Sequence::new()
1449            .sequence_type("DNA")
1450            .sequence("AAAAAAAA")
1451            .save(conn)
1452            .unwrap();
1453        let node2_id = Node::create(conn, &sequence2.hash, &HashId::convert_str("2")).unwrap();
1454        let edge2 = EdgeData {
1455            source_node_id: node1_id,
1456            source_coordinate: 2,
1457            source_strand: Strand::Forward,
1458            target_node_id: node2_id,
1459            target_coordinate: 3,
1460            target_strand: Strand::Forward,
1461        };
1462        let edge3 = EdgeData {
1463            source_node_id: node2_id,
1464            source_coordinate: 4,
1465            source_strand: Strand::Forward,
1466            target_node_id: PATH_END_NODE_ID,
1467            target_coordinate: -1,
1468            target_strand: Strand::Forward,
1469        };
1470
1471        let edge_ids = Edge::bulk_create(conn, &[edge1, edge2, edge3]);
1472        assert_eq!(edge_ids.len(), 3);
1473        let edges = Edge::select(conn)
1474            .query_by_ids(edge_ids)
1475            .expect("should load edges by id");
1476        assert_eq!(edges.len(), 3);
1477
1478        let edges_by_source_node_id = edges
1479            .into_iter()
1480            .map(|edge| (edge.source_node_id, edge))
1481            .collect::<HashMap<_, Edge>>();
1482
1483        let edge_result1 = edges_by_source_node_id.get(&PATH_START_NODE_ID).unwrap();
1484        assert_eq!(edge_result1.source_coordinate, -1);
1485        assert_eq!(edge_result1.target_node_id, node1_id);
1486        assert_eq!(edge_result1.target_coordinate, 1);
1487        let edge_result2 = edges_by_source_node_id.get(&node1_id).unwrap();
1488        assert_eq!(edge_result2.source_coordinate, 2);
1489        assert_eq!(edge_result2.target_node_id, node2_id);
1490        assert_eq!(edge_result2.target_coordinate, 3);
1491        let edge_result3 = edges_by_source_node_id.get(&node2_id).unwrap();
1492        assert_eq!(edge_result3.source_coordinate, 4);
1493        assert_eq!(edge_result3.target_node_id, PATH_END_NODE_ID);
1494        assert_eq!(edge_result3.target_coordinate, -1);
1495    }
1496
1497    #[test]
1498    fn test_bulk_create_returns_edges_in_order() {
1499        let conn = &mut get_connection(None).unwrap();
1500        Collection::create(conn, "test collection").unwrap();
1501        let sequence1 = Sequence::new()
1502            .sequence_type("DNA")
1503            .sequence("ATCGATCG")
1504            .save(conn)
1505            .unwrap();
1506        let node1_id = Node::create(conn, &sequence1.hash, &HashId::convert_str("1")).unwrap();
1507        let edge1 = EdgeData {
1508            source_node_id: PATH_START_NODE_ID,
1509            source_coordinate: -1,
1510            source_strand: Strand::Forward,
1511            target_node_id: node1_id,
1512            target_coordinate: 1,
1513            target_strand: Strand::Forward,
1514        };
1515        let sequence2 = Sequence::new()
1516            .sequence_type("DNA")
1517            .sequence("AAAAAAAA")
1518            .save(conn)
1519            .unwrap();
1520        let node2_id = Node::create(conn, &sequence2.hash, &HashId::convert_str("2")).unwrap();
1521        let edge2 = EdgeData {
1522            source_node_id: node1_id,
1523            source_coordinate: 2,
1524            source_strand: Strand::Forward,
1525            target_node_id: node2_id,
1526            target_coordinate: 3,
1527            target_strand: Strand::Forward,
1528        };
1529        let edge3 = EdgeData {
1530            source_node_id: node2_id,
1531            source_coordinate: 4,
1532            source_strand: Strand::Forward,
1533            target_node_id: PATH_END_NODE_ID,
1534            target_coordinate: -1,
1535            target_strand: Strand::Forward,
1536        };
1537
1538        let edges = vec![edge2, edge3];
1539        let edge_ids1 = Edge::bulk_create(conn, &edges);
1540        assert_eq!(edge_ids1.len(), 2);
1541        for (index, id) in edge_ids1.iter().enumerate() {
1542            let edge = Edge::select(conn)
1543                .get_by_id(*id)
1544                .expect("should query edge")
1545                .expect("should find edge");
1546            assert_eq!(EdgeData::from(&edge), edges[index]);
1547        }
1548
1549        let edges = vec![edge1, edge2, edge3];
1550        let edge_ids2 = Edge::bulk_create(conn, &edges);
1551        assert_eq!(edge_ids2[1], edge_ids1[0]);
1552        assert_eq!(edge_ids2[2], edge_ids1[1]);
1553        assert_eq!(edge_ids2.len(), 3);
1554        for (index, id) in edge_ids2.iter().enumerate() {
1555            let edge = Edge::select(conn)
1556                .get_by_id(*id)
1557                .expect("should query edge")
1558                .expect("should find edge");
1559            assert_eq!(EdgeData::from(&edge), edges[index]);
1560        }
1561    }
1562
1563    #[test]
1564    fn test_edges_for_block_group_nodes_filters_by_block_group_and_node_ids() {
1565        let conn = get_connection(None).unwrap();
1566        Collection::get_or_create(&conn, "test").unwrap();
1567        crate::sample::Sample::get_or_create(
1568            &conn,
1569            crate::sample::NewSample {
1570                name: "test",
1571                ..Default::default()
1572            },
1573        )
1574        .unwrap();
1575        let bg = BlockGroup::create(
1576            &conn,
1577            crate::block_group::NewBlockGroup {
1578                collection_name: "test",
1579                sample_name: "test",
1580                name: "query-bg",
1581                ..Default::default()
1582            },
1583        )
1584        .unwrap();
1585        let other_bg = BlockGroup::create(
1586            &conn,
1587            crate::block_group::NewBlockGroup {
1588                collection_name: "test",
1589                sample_name: "test",
1590                name: "other-bg",
1591                ..Default::default()
1592            },
1593        )
1594        .unwrap();
1595
1596        let seq_a = Sequence::new()
1597            .sequence_type("DNA")
1598            .sequence("AAA")
1599            .save(&conn)
1600            .unwrap();
1601        let seq_b = Sequence::new()
1602            .sequence_type("DNA")
1603            .sequence("CCC")
1604            .save(&conn)
1605            .unwrap();
1606        let seq_c = Sequence::new()
1607            .sequence_type("DNA")
1608            .sequence("GGG")
1609            .save(&conn)
1610            .unwrap();
1611        let n_a = Node::create(&conn, &seq_a.hash, &HashId::convert_str("node-a")).unwrap();
1612        let n_b = Node::create(&conn, &seq_b.hash, &HashId::convert_str("node-b")).unwrap();
1613        let n_c = Node::create(&conn, &seq_c.hash, &HashId::convert_str("node-c")).unwrap();
1614
1615        let source_match =
1616            Edge::create(&conn, n_a, 3, Strand::Forward, n_b, 0, Strand::Forward).unwrap();
1617        let target_match =
1618            Edge::create(&conn, n_c, 3, Strand::Forward, n_a, 0, Strand::Forward).unwrap();
1619        let no_match =
1620            Edge::create(&conn, n_b, 3, Strand::Forward, n_c, 0, Strand::Forward).unwrap();
1621        let other_bg_match = Edge::create(
1622            &conn,
1623            PATH_START_NODE_ID,
1624            -1,
1625            Strand::Forward,
1626            n_a,
1627            0,
1628            Strand::Forward,
1629        )
1630        .unwrap();
1631
1632        let block_group_edges = [source_match.clone(), target_match.clone(), no_match.clone()]
1633            .iter()
1634            .map(|edge| BlockGroupEdgeData {
1635                block_group_id: bg.id,
1636                edge_id: edge.id,
1637                chromosome_index: 0,
1638                phased: 0,
1639            })
1640            .chain(std::iter::once(BlockGroupEdgeData {
1641                block_group_id: other_bg.id,
1642                edge_id: other_bg_match.id,
1643                chromosome_index: 0,
1644                phased: 0,
1645            }))
1646            .collect::<Vec<_>>();
1647        BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1648
1649        let edges = Edge::edges_for_block_group_nodes(&conn, &bg.id, &[n_a], None).unwrap();
1650        let edge_ids = edges
1651            .iter()
1652            .map(|augmented_edge| augmented_edge.edge.id)
1653            .collect::<HashSet<_>>();
1654
1655        assert_eq!(edge_ids.len(), 2);
1656        assert!(edge_ids.contains(&source_match.id));
1657        assert!(edge_ids.contains(&target_match.id));
1658        assert!(!edge_ids.contains(&no_match.id));
1659        assert!(!edge_ids.contains(&other_bg_match.id));
1660    }
1661
1662    #[test]
1663    fn test_blocks_from_edges_branched_graph() {
1664        // Branched graph: {AAA,GGG} → TTT → {CCC,ATC}
1665        // TTT has 2 incoming edges and 2 outgoing edges.
1666        // All sequences are length 3.
1667        let conn = get_connection(None).unwrap();
1668        Collection::get_or_create(&conn, "test").unwrap();
1669        crate::sample::Sample::get_or_create(
1670            &conn,
1671            crate::sample::NewSample {
1672                name: "test",
1673                ..Default::default()
1674            },
1675        )
1676        .unwrap();
1677        let bg = BlockGroup::create(
1678            &conn,
1679            crate::block_group::NewBlockGroup {
1680                collection_name: "test",
1681                sample_name: "test",
1682                name: "branched",
1683                ..Default::default()
1684            },
1685        )
1686        .unwrap();
1687
1688        let seq_aaa = Sequence::new()
1689            .sequence_type("DNA")
1690            .sequence("AAA")
1691            .save(&conn)
1692            .unwrap();
1693        let seq_ggg = Sequence::new()
1694            .sequence_type("DNA")
1695            .sequence("GGG")
1696            .save(&conn)
1697            .unwrap();
1698        let seq_ttt = Sequence::new()
1699            .sequence_type("DNA")
1700            .sequence("TTT")
1701            .save(&conn)
1702            .unwrap();
1703        let seq_ccc = Sequence::new()
1704            .sequence_type("DNA")
1705            .sequence("CCC")
1706            .save(&conn)
1707            .unwrap();
1708        let seq_atc = Sequence::new()
1709            .sequence_type("DNA")
1710            .sequence("ATC")
1711            .save(&conn)
1712            .unwrap();
1713
1714        let n_aaa = Node::create(&conn, &seq_aaa.hash, &HashId::convert_str("node-aaa")).unwrap();
1715        let n_ggg = Node::create(&conn, &seq_ggg.hash, &HashId::convert_str("node-ggg")).unwrap();
1716        let n_ttt = Node::create(&conn, &seq_ttt.hash, &HashId::convert_str("node-ttt")).unwrap();
1717        let n_ccc = Node::create(&conn, &seq_ccc.hash, &HashId::convert_str("node-ccc")).unwrap();
1718        let n_atc = Node::create(&conn, &seq_atc.hash, &HashId::convert_str("node-atc")).unwrap();
1719
1720        let e_start_aaa = Edge::create(
1721            &conn,
1722            PATH_START_NODE_ID,
1723            -1,
1724            Strand::Forward,
1725            n_aaa,
1726            0,
1727            Strand::Forward,
1728        )
1729        .unwrap();
1730        let e_start_ggg = Edge::create(
1731            &conn,
1732            PATH_START_NODE_ID,
1733            -1,
1734            Strand::Forward,
1735            n_ggg,
1736            0,
1737            Strand::Forward,
1738        )
1739        .unwrap();
1740        // Edges: AAA→TTT, GGG→TTT, TTT→CCC, TTT→ATC
1741        let e_aaa_ttt =
1742            Edge::create(&conn, n_aaa, 3, Strand::Forward, n_ttt, 0, Strand::Forward).unwrap();
1743        let e_ggg_ttt =
1744            Edge::create(&conn, n_ggg, 3, Strand::Forward, n_ttt, 0, Strand::Forward).unwrap();
1745        let e_ttt_ccc =
1746            Edge::create(&conn, n_ttt, 3, Strand::Forward, n_ccc, 0, Strand::Forward).unwrap();
1747        let e_ttt_atc =
1748            Edge::create(&conn, n_ttt, 3, Strand::Forward, n_atc, 0, Strand::Forward).unwrap();
1749        let e_ccc_end = Edge::create(
1750            &conn,
1751            n_ccc,
1752            3,
1753            Strand::Forward,
1754            PATH_END_NODE_ID,
1755            -1,
1756            Strand::Forward,
1757        )
1758        .unwrap();
1759        let e_atc_end = Edge::create(
1760            &conn,
1761            n_atc,
1762            3,
1763            Strand::Forward,
1764            PATH_END_NODE_ID,
1765            -1,
1766            Strand::Forward,
1767        )
1768        .unwrap();
1769
1770        let block_group_edges = [
1771            e_start_aaa.clone(),
1772            e_start_ggg.clone(),
1773            e_aaa_ttt.clone(),
1774            e_ggg_ttt.clone(),
1775            e_ttt_ccc.clone(),
1776            e_ttt_atc.clone(),
1777            e_ccc_end.clone(),
1778            e_atc_end.clone(),
1779        ]
1780        .iter()
1781        .map(|edge| BlockGroupEdgeData {
1782            block_group_id: bg.id,
1783            edge_id: edge.id,
1784            chromosome_index: 0,
1785            phased: 0,
1786        })
1787        .collect::<Vec<_>>();
1788        BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1789
1790        let augmented_edges = vec![
1791            AugmentedEdge {
1792                edge: e_aaa_ttt,
1793                chromosome_index: 0,
1794                phased: 0,
1795                created_on: 0,
1796            },
1797            AugmentedEdge {
1798                edge: e_ggg_ttt,
1799                chromosome_index: 0,
1800                phased: 0,
1801                created_on: 0,
1802            },
1803            AugmentedEdge {
1804                edge: e_ttt_ccc,
1805                chromosome_index: 0,
1806                phased: 0,
1807                created_on: 0,
1808            },
1809            AugmentedEdge {
1810                edge: e_ttt_atc,
1811                chromosome_index: 0,
1812                phased: 0,
1813                created_on: 0,
1814            },
1815        ];
1816
1817        let blocks =
1818            Edge::blocks_from_edges(&conn, test_workspace(), &bg.id, &augmented_edges, None)
1819                .unwrap();
1820
1821        // 5 non-terminal nodes: AAA, GGG, TTT, CCC, ATC
1822        // 2 terminal blocks: START, END
1823        // Total: 7
1824        assert_eq!(
1825            blocks.len(),
1826            7,
1827            "expected 7 blocks (5 nodes + 2 terminals), got {}",
1828            blocks.len()
1829        );
1830
1831        // Verify all 5 non-terminal nodes have blocks
1832        let block_node_ids: Vec<HashId> = blocks
1833            .iter()
1834            .filter(|b| {
1835                b.node_id != gen_core::PATH_START_NODE_ID && b.node_id != gen_core::PATH_END_NODE_ID
1836            })
1837            .map(|b| b.node_id)
1838            .collect();
1839        assert!(block_node_ids.contains(&n_aaa), "AAA block missing");
1840        assert!(block_node_ids.contains(&n_ggg), "GGG block missing");
1841        assert!(block_node_ids.contains(&n_ttt), "TTT block missing");
1842        assert!(block_node_ids.contains(&n_ccc), "CCC block missing");
1843        assert!(block_node_ids.contains(&n_atc), "ATC block missing");
1844
1845        // Verify TTT block has correct boundaries (0..3)
1846        let ttt_block = blocks.iter().find(|b| b.node_id == n_ttt).unwrap();
1847        assert_eq!(ttt_block.start, 0, "TTT block start should be 0");
1848        assert_eq!(ttt_block.end, 3, "TTT block end should be 3");
1849
1850        // Verify AAA block has correct boundaries (0..3)
1851        let aaa_block = blocks.iter().find(|b| b.node_id == n_aaa).unwrap();
1852        assert_eq!(aaa_block.start, 0, "AAA block start should be 0");
1853        assert_eq!(aaa_block.end, 3, "AAA block end should be 3");
1854
1855        // Verify CCC block has correct boundaries (0..3)
1856        let ccc_block = blocks.iter().find(|b| b.node_id == n_ccc).unwrap();
1857        assert_eq!(ccc_block.start, 0, "CCC block start should be 0");
1858        assert_eq!(ccc_block.end, 3, "CCC block end should be 3");
1859
1860        // Verify ATC block has correct boundaries (0..3)
1861        let atc_block = blocks.iter().find(|b| b.node_id == n_atc).unwrap();
1862        assert_eq!(atc_block.start, 0, "ATC block start should be 0");
1863        assert_eq!(atc_block.end, 3, "ATC block end should be 3");
1864    }
1865
1866    #[test]
1867    fn test_blocks_from_edges_uses_edge_coordinates_not_backing_sequence_length() {
1868        // This test ensures we do not use sequence_start or sequence_end to get coordinates by making
1869        // a test case where the graph has no nodes that are the sequence length. This was leading to
1870        // technically incorrect behavior by adding blocks of [0, sequence_length] when that was just
1871        // a happy coincidence it worked
1872        let conn = get_connection(None).unwrap();
1873        Collection::get_or_create(&conn, "test").unwrap();
1874        crate::sample::Sample::get_or_create(
1875            &conn,
1876            crate::sample::NewSample {
1877                name: "test",
1878                ..Default::default()
1879            },
1880        )
1881        .unwrap();
1882        let bg = BlockGroup::create(
1883            &conn,
1884            crate::block_group::NewBlockGroup {
1885                collection_name: "test",
1886                sample_name: "test",
1887                name: "slice",
1888                ..Default::default()
1889            },
1890        )
1891        .unwrap();
1892
1893        let backing_sequence = Sequence::new()
1894            .sequence_type("DNA")
1895            .sequence("AAATTT")
1896            .save(&conn)
1897            .unwrap();
1898        let node_id =
1899            Node::create(&conn, &backing_sequence.hash, &HashId::convert_str("slice")).unwrap();
1900
1901        let into_slice = Edge::create(
1902            &conn,
1903            PATH_START_NODE_ID,
1904            -1,
1905            Strand::Forward,
1906            node_id,
1907            3,
1908            Strand::Forward,
1909        )
1910        .unwrap();
1911        let out_of_slice = Edge::create(
1912            &conn,
1913            node_id,
1914            4,
1915            Strand::Forward,
1916            PATH_END_NODE_ID,
1917            -1,
1918            Strand::Forward,
1919        )
1920        .unwrap();
1921        let block_group_edges = [into_slice.clone(), out_of_slice.clone()]
1922            .iter()
1923            .map(|edge| BlockGroupEdgeData {
1924                block_group_id: bg.id,
1925                edge_id: edge.id,
1926                chromosome_index: 0,
1927                phased: 0,
1928            })
1929            .collect::<Vec<_>>();
1930        BlockGroupEdge::bulk_create(&conn, &block_group_edges);
1931
1932        let augmented_edges = vec![
1933            AugmentedEdge {
1934                edge: into_slice,
1935                chromosome_index: 0,
1936                phased: 0,
1937                created_on: 0,
1938            },
1939            AugmentedEdge {
1940                edge: out_of_slice,
1941                chromosome_index: 0,
1942                phased: 0,
1943                created_on: 0,
1944            },
1945        ];
1946
1947        let blocks =
1948            Edge::blocks_from_edges(&conn, test_workspace(), &bg.id, &augmented_edges, None)
1949                .unwrap();
1950        let node_blocks = blocks
1951            .iter()
1952            .filter(|block| block.node_id == node_id)
1953            .collect::<Vec<_>>();
1954
1955        assert_eq!(
1956            node_blocks.len(),
1957            1,
1958            "expected one edge-delimited block, got {node_blocks:?}"
1959        );
1960        assert_eq!(node_blocks[0].start, 3);
1961        assert_eq!(node_blocks[0].end, 4);
1962    }
1963
1964    #[test]
1965    fn test_blocks_from_edges_does_not_treat_asymmetric_boundaries_as_incomplete() {
1966        // It's possible that the passed in set of edges is deliberately incomplete.
1967        // This asserts we do not expand the graph if node information is present.
1968        let conn = get_connection(None).unwrap();
1969        Collection::get_or_create(&conn, "test").unwrap();
1970        crate::sample::Sample::get_or_create(
1971            &conn,
1972            crate::sample::NewSample {
1973                name: "test",
1974                ..Default::default()
1975            },
1976        )
1977        .unwrap();
1978        let bg = BlockGroup::create(
1979            &conn,
1980            crate::block_group::NewBlockGroup {
1981                collection_name: "test",
1982                sample_name: "test",
1983                name: "asymmetric",
1984                ..Default::default()
1985            },
1986        )
1987        .unwrap();
1988
1989        let seq_src = Sequence::new()
1990            .sequence_type("DNA")
1991            .sequence("AAA")
1992            .save(&conn)
1993            .unwrap();
1994        let seq_mid = Sequence::new()
1995            .sequence_type("DNA")
1996            .sequence("AAACCCGGG")
1997            .save(&conn)
1998            .unwrap();
1999        let seq_a = Sequence::new()
2000            .sequence_type("DNA")
2001            .sequence("CCC")
2002            .save(&conn)
2003            .unwrap();
2004        let seq_b = Sequence::new()
2005            .sequence_type("DNA")
2006            .sequence("GGG")
2007            .save(&conn)
2008            .unwrap();
2009        let seq_extra = Sequence::new()
2010            .sequence_type("DNA")
2011            .sequence("TTT")
2012            .save(&conn)
2013            .unwrap();
2014
2015        let n_src = Node::create(&conn, &seq_src.hash, &HashId::convert_str("node-src")).unwrap();
2016        let n_mid = Node::create(&conn, &seq_mid.hash, &HashId::convert_str("node-mid")).unwrap();
2017        let n_a = Node::create(&conn, &seq_a.hash, &HashId::convert_str("node-a")).unwrap();
2018        let n_b = Node::create(&conn, &seq_b.hash, &HashId::convert_str("node-b")).unwrap();
2019        let n_extra =
2020            Node::create(&conn, &seq_extra.hash, &HashId::convert_str("node-extra")).unwrap();
2021
2022        let e_src_mid =
2023            Edge::create(&conn, n_src, 3, Strand::Forward, n_mid, 0, Strand::Forward).unwrap();
2024        let e_mid_a =
2025            Edge::create(&conn, n_mid, 3, Strand::Forward, n_a, 0, Strand::Forward).unwrap();
2026        let e_mid_b =
2027            Edge::create(&conn, n_mid, 6, Strand::Forward, n_b, 0, Strand::Forward).unwrap();
2028        // We exclude this edge from graph construction
2029        let e_mid_extra = Edge::create(
2030            &conn,
2031            n_mid,
2032            9,
2033            Strand::Forward,
2034            n_extra,
2035            0,
2036            Strand::Forward,
2037        )
2038        .unwrap();
2039
2040        let block_group_edges = [
2041            e_src_mid.clone(),
2042            e_mid_a.clone(),
2043            e_mid_b.clone(),
2044            e_mid_extra,
2045        ]
2046        .iter()
2047        .map(|edge| BlockGroupEdgeData {
2048            block_group_id: bg.id,
2049            edge_id: edge.id,
2050            chromosome_index: 0,
2051            phased: 0,
2052        })
2053        .collect::<Vec<_>>();
2054        BlockGroupEdge::bulk_create(&conn, &block_group_edges);
2055
2056        let augmented_edges = vec![
2057            AugmentedEdge {
2058                edge: e_src_mid,
2059                chromosome_index: 0,
2060                phased: 0,
2061                created_on: 0,
2062            },
2063            AugmentedEdge {
2064                edge: e_mid_a,
2065                chromosome_index: 0,
2066                phased: 0,
2067                created_on: 0,
2068            },
2069            AugmentedEdge {
2070                edge: e_mid_b,
2071                chromosome_index: 0,
2072                phased: 0,
2073                created_on: 0,
2074            },
2075        ];
2076
2077        let blocks =
2078            Edge::blocks_from_edges(&conn, test_workspace(), &bg.id, &augmented_edges, None)
2079                .unwrap();
2080        let mid_intervals = blocks
2081            .iter()
2082            .filter(|block| block.node_id == n_mid)
2083            .map(|block| (block.start, block.end))
2084            .collect::<Vec<_>>();
2085
2086        assert_eq!(mid_intervals, vec![(0, 3), (3, 6)]);
2087        assert!(!blocks.iter().any(|block| block.node_id == n_extra));
2088    }
2089
2090    #[test]
2091    fn test_blocks_from_edges_resolves_incomplete_nodes_created_by_lookup() {
2092        // If a node is present as just a source or sink node, ensure we look it up to
2093        // accurately add it to the graph.
2094        let conn = get_connection(None).unwrap();
2095        Collection::get_or_create(&conn, "test").unwrap();
2096        crate::sample::Sample::get_or_create(
2097            &conn,
2098            crate::sample::NewSample {
2099                name: "test",
2100                ..Default::default()
2101            },
2102        )
2103        .unwrap();
2104        let bg = BlockGroup::create(
2105            &conn,
2106            crate::block_group::NewBlockGroup {
2107                collection_name: "test",
2108                sample_name: "test",
2109                name: "recursive-incomplete",
2110                ..Default::default()
2111            },
2112        )
2113        .unwrap();
2114
2115        let seq_a = Sequence::new()
2116            .sequence_type("DNA")
2117            .sequence("AAA")
2118            .save(&conn)
2119            .unwrap();
2120        let seq_b = Sequence::new()
2121            .sequence_type("DNA")
2122            .sequence("BBB")
2123            .save(&conn)
2124            .unwrap();
2125        let seq_c = Sequence::new()
2126            .sequence_type("DNA")
2127            .sequence("CCC")
2128            .save(&conn)
2129            .unwrap();
2130        let seq_d = Sequence::new()
2131            .sequence_type("DNA")
2132            .sequence("DDD")
2133            .save(&conn)
2134            .unwrap();
2135
2136        let n_a = Node::create(&conn, &seq_a.hash, &HashId::convert_str("node-a")).unwrap();
2137        let n_b = Node::create(&conn, &seq_b.hash, &HashId::convert_str("node-b")).unwrap();
2138        let n_c = Node::create(&conn, &seq_c.hash, &HashId::convert_str("node-c")).unwrap();
2139        let n_d = Node::create(&conn, &seq_d.hash, &HashId::convert_str("node-d")).unwrap();
2140
2141        let e_a_b = Edge::create(&conn, n_a, 3, Strand::Forward, n_b, 0, Strand::Forward).unwrap();
2142        let e_b_c = Edge::create(&conn, n_b, 3, Strand::Forward, n_c, 0, Strand::Forward).unwrap();
2143        let e_c_d = Edge::create(&conn, n_c, 3, Strand::Forward, n_d, 0, Strand::Forward).unwrap();
2144
2145        let block_group_edges = [e_a_b.clone(), e_b_c.clone(), e_c_d.clone()]
2146            .iter()
2147            .map(|edge| BlockGroupEdgeData {
2148                block_group_id: bg.id,
2149                edge_id: edge.id,
2150                chromosome_index: 0,
2151                phased: 0,
2152            })
2153            .collect::<Vec<_>>();
2154        BlockGroupEdge::bulk_create(&conn, &block_group_edges);
2155
2156        let blocks = Edge::blocks_from_edges(
2157            &conn,
2158            test_workspace(),
2159            &bg.id,
2160            &[AugmentedEdge {
2161                edge: e_a_b,
2162                chromosome_index: 0,
2163                phased: 0,
2164                created_on: 0,
2165            }],
2166            None,
2167        )
2168        .unwrap();
2169
2170        let b_block = blocks.iter().find(|block| block.node_id == n_b).unwrap();
2171        assert_eq!(b_block.start, 0);
2172        assert_eq!(b_block.end, 3);
2173
2174        let c_block = blocks.iter().find(|block| block.node_id == n_c).unwrap();
2175        assert_eq!(c_block.start, 0);
2176        assert_eq!(c_block.end, 3);
2177    }
2178
2179    #[test]
2180    fn test_bulk_create_with_existing_edge() {
2181        let conn = &mut get_connection(None).unwrap();
2182        Collection::create(conn, "test collection").unwrap();
2183        let sequence1 = Sequence::new()
2184            .sequence_type("DNA")
2185            .sequence("ATCGATCG")
2186            .save(conn)
2187            .unwrap();
2188        let node1_id = Node::create(conn, &sequence1.hash, &HashId::convert_str("1")).unwrap();
2189        // NOTE: Create one edge ahead of time to confirm an existing row ID gets returned in the bulk create
2190        let existing_edge = Edge::create(
2191            conn,
2192            PATH_START_NODE_ID,
2193            -1,
2194            Strand::Forward,
2195            node1_id,
2196            1,
2197            Strand::Forward,
2198        )
2199        .unwrap();
2200        assert_eq!(existing_edge.source_node_id, PATH_START_NODE_ID);
2201        assert_eq!(existing_edge.source_coordinate, -1);
2202        assert_eq!(existing_edge.target_node_id, node1_id);
2203        assert_eq!(existing_edge.target_coordinate, 1);
2204
2205        let edge1 = EdgeData {
2206            source_coordinate: -1,
2207            source_node_id: PATH_START_NODE_ID,
2208            source_strand: Strand::Forward,
2209            target_node_id: node1_id,
2210            target_coordinate: 1,
2211            target_strand: Strand::Forward,
2212        };
2213        let sequence2 = Sequence::new()
2214            .sequence_type("DNA")
2215            .sequence("AAAAAAAA")
2216            .save(conn)
2217            .unwrap();
2218        let node2_id = Node::create(conn, &sequence2.hash, &HashId::convert_str("2")).unwrap();
2219        let edge2 = EdgeData {
2220            source_node_id: node1_id,
2221            source_coordinate: 2,
2222            source_strand: Strand::Forward,
2223            target_node_id: node2_id,
2224            target_coordinate: 3,
2225            target_strand: Strand::Forward,
2226        };
2227        let edge3 = EdgeData {
2228            source_node_id: node2_id,
2229            source_coordinate: 4,
2230            source_strand: Strand::Forward,
2231            target_node_id: PATH_END_NODE_ID,
2232            target_coordinate: -1,
2233            target_strand: Strand::Forward,
2234        };
2235
2236        let edge_ids = Edge::bulk_create(conn, &[edge1, edge2, edge3]);
2237        assert_eq!(edge_ids.len(), 3);
2238        let edges = Edge::select(conn)
2239            .query_by_ids(edge_ids)
2240            .expect("should load edges by id");
2241        assert_eq!(edges.len(), 3);
2242
2243        let edges_by_source_node_id = edges
2244            .into_iter()
2245            .map(|edge| (edge.source_node_id, edge))
2246            .collect::<HashMap<_, Edge>>();
2247
2248        let edge_result1 = edges_by_source_node_id.get(&PATH_START_NODE_ID).unwrap();
2249
2250        assert_eq!(edge_result1.id, existing_edge.id);
2251
2252        assert_eq!(edge_result1.source_coordinate, -1);
2253        assert_eq!(edge_result1.target_node_id, node1_id);
2254        assert_eq!(edge_result1.target_coordinate, 1);
2255        let edge_result2 = edges_by_source_node_id.get(&node1_id).unwrap();
2256        assert_eq!(edge_result2.source_coordinate, 2);
2257        assert_eq!(edge_result2.target_node_id, node2_id);
2258        assert_eq!(edge_result2.target_coordinate, 3);
2259        let edge_result3 = edges_by_source_node_id.get(&node2_id).unwrap();
2260        assert_eq!(edge_result3.source_coordinate, 4);
2261        assert_eq!(edge_result3.target_node_id, PATH_END_NODE_ID);
2262        assert_eq!(edge_result3.target_coordinate, -1);
2263    }
2264
2265    #[test]
2266    fn test_edge_data_id_hash_matches_edge_create() {
2267        let conn = &mut get_connection(None).unwrap();
2268        Collection::create(conn, "test collection").unwrap();
2269        let sequence = Sequence::new()
2270            .sequence_type("DNA")
2271            .sequence("ATCGATCG")
2272            .save(conn)
2273            .unwrap();
2274        let node_id = Node::create(conn, &sequence.hash, &HashId::convert_str("target")).unwrap();
2275        let edge = EdgeData {
2276            source_node_id: HashId::convert_str("source"),
2277            source_coordinate: -12_345,
2278            source_strand: Strand::Reverse,
2279            target_node_id: node_id,
2280            target_coordinate: 67_890,
2281            target_strand: Strand::ImportantButUnknown,
2282        };
2283
2284        let created_edge = Edge::create(
2285            conn,
2286            edge.source_node_id,
2287            edge.source_coordinate,
2288            edge.source_strand,
2289            edge.target_node_id,
2290            edge.target_coordinate,
2291            edge.target_strand,
2292        )
2293        .expect("should create edge with xxhash-derived id");
2294
2295        assert_eq!(edge.id_hash(), created_edge.id);
2296    }
2297
2298    #[test]
2299    fn test_duplicate_edge_creation_is_idempotent_by_primary_key() {
2300        let conn = get_connection(None).expect("should create graph connection");
2301        let edge = EdgeData {
2302            source_node_id: PATH_START_NODE_ID,
2303            source_coordinate: -1,
2304            source_strand: Strand::Forward,
2305            target_node_id: PATH_END_NODE_ID,
2306            target_coordinate: 0,
2307            target_strand: Strand::Forward,
2308        };
2309
2310        let first = Edge::create(
2311            &conn,
2312            edge.source_node_id,
2313            edge.source_coordinate,
2314            edge.source_strand,
2315            edge.target_node_id,
2316            edge.target_coordinate,
2317            edge.target_strand,
2318        )
2319        .expect("should create edge");
2320        let duplicate = Edge::create(
2321            &conn,
2322            edge.source_node_id,
2323            edge.source_coordinate,
2324            edge.source_strand,
2325            edge.target_node_id,
2326            edge.target_coordinate,
2327            edge.target_strand,
2328        )
2329        .expect("should treat the duplicate edge as existing");
2330
2331        assert_eq!(first.id, edge.id_hash());
2332        assert_eq!(duplicate.id, first.id);
2333        assert_eq!(Edge::all(&conn).expect("should load edges").len(), 1);
2334    }
2335
2336    #[test]
2337    fn test_blocks_from_edges() {
2338        let conn = get_connection(None).unwrap();
2339        let (block_group_id, path) = setup_block_group(&conn);
2340
2341        let edges = BlockGroupEdge::edges_for_block_group(&conn, &block_group_id, None);
2342        let blocks =
2343            Edge::blocks_from_edges(&conn, test_workspace(), &block_group_id, &edges, None)
2344                .unwrap();
2345
2346        // 4 actual sequences: 10-length ones of all A, all T, all C, all G
2347        // 2 terminal node blocks (start/end)
2348        // 6 total
2349        assert_eq!(blocks.len(), 6);
2350
2351        let insert_sequence = Sequence::new()
2352            .sequence_type("DNA")
2353            .sequence("NNNN")
2354            .save(&conn)
2355            .unwrap();
2356        let insert_node_id =
2357            Node::create(&conn, &insert_sequence.hash, &HashId::convert_str("1")).unwrap();
2358        let insert = PathBlock {
2359            node_id: insert_node_id,
2360            block_sequence: insert_sequence.get_sequence(0, 4).unwrap(),
2361            sequence_start: 0,
2362            sequence_end: 4,
2363            path_start: 7,
2364            path_end: 15,
2365            strand: Strand::Forward,
2366        };
2367        let region = ResolvedGenRegion::from_path(&conn, &path, 7, 15).unwrap();
2368        let change = BlockGroupChange {
2369            region,
2370            path_accession: None,
2371            block: insert,
2372            chromosome_index: 0,
2373            phased: 0,
2374            preserve_edge: true,
2375        };
2376        BlockGroup::insert_change(&conn, test_workspace(), &change).unwrap();
2377        let mut edges = BlockGroupEdge::edges_for_block_group(&conn, &block_group_id, None);
2378
2379        let blocks =
2380            Edge::blocks_from_edges(&conn, test_workspace(), &block_group_id, &edges, None)
2381                .unwrap();
2382
2383        // 2 10-length sequences of all C, all G
2384        // 1 inserted NNNN sequence
2385        // 4 split blocks (A and T sequences were split) resulting from the inserted sequence
2386        // 2 terminal node blocks (start/end)
2387        // 9 total
2388        assert_eq!(blocks.len(), 9);
2389
2390        // Confirm that ordering doesn't matter
2391        edges.reverse();
2392        let blocks =
2393            Edge::blocks_from_edges(&conn, test_workspace(), &block_group_id, &edges, None)
2394                .unwrap();
2395
2396        // 2 10-length sequences of all C, all G
2397        // 1 inserted NNNN sequence
2398        // 4 split blocks (A and T sequences were split) resulting from the inserted sequence
2399        // 2 terminal node blocks (start/end)
2400        // 9 total
2401        assert_eq!(blocks.len(), 9);
2402    }
2403
2404    #[test]
2405    fn test_get_block_boundaries() {
2406        let conn = get_connection(None).unwrap();
2407        let template_sequence = Sequence::new()
2408            .sequence_type("DNA")
2409            .sequence("AAAAAAAAAA")
2410            .save(&conn)
2411            .unwrap();
2412        let template_node_id =
2413            Node::create(&conn, &template_sequence.hash, &HashId::convert_str("1")).unwrap();
2414
2415        let insert_sequence = Sequence::new()
2416            .sequence_type("DNA")
2417            .sequence("NNNN")
2418            .save(&conn)
2419            .unwrap();
2420        let insert_node_id =
2421            Node::create(&conn, &insert_sequence.hash, &HashId::convert_str("2")).unwrap();
2422
2423        let edge1 = Edge::create(
2424            &conn,
2425            template_node_id,
2426            2,
2427            Strand::Forward,
2428            insert_node_id,
2429            0,
2430            Strand::Forward,
2431        )
2432        .unwrap();
2433        let edge2 = Edge::create(
2434            &conn,
2435            insert_node_id,
2436            4,
2437            Strand::Forward,
2438            template_node_id,
2439            3,
2440            Strand::Forward,
2441        )
2442        .unwrap();
2443
2444        let boundaries = get_block_boundaries(Some(&vec![&edge1]), Some(&vec![&edge2]));
2445        assert_eq!(boundaries, vec![2, 3]);
2446    }
2447
2448    #[test]
2449    fn test_get_block_boundaries_with_two_original_sequences() {
2450        let conn = get_connection(None).unwrap();
2451        let template_sequence1 = Sequence::new()
2452            .sequence_type("DNA")
2453            .sequence("AAAAAAAAAA")
2454            .save(&conn)
2455            .unwrap();
2456        let template1_node_id =
2457            Node::create(&conn, &template_sequence1.hash, &HashId::convert_str("1")).unwrap();
2458
2459        let template_sequence2 = Sequence::new()
2460            .sequence_type("DNA")
2461            .sequence("TTTTTTTTTT")
2462            .save(&conn)
2463            .unwrap();
2464        let template2_node_id =
2465            Node::create(&conn, &template_sequence2.hash, &HashId::convert_str("2")).unwrap();
2466
2467        let insert_sequence = Sequence::new()
2468            .sequence_type("DNA")
2469            .sequence("NNNN")
2470            .save(&conn)
2471            .unwrap();
2472        let insert_node_id =
2473            Node::create(&conn, &insert_sequence.hash, &HashId::convert_str("3")).unwrap();
2474
2475        let edge1 = Edge::create(
2476            &conn,
2477            template1_node_id,
2478            2,
2479            Strand::Forward,
2480            insert_node_id,
2481            0,
2482            Strand::Forward,
2483        )
2484        .unwrap();
2485        let edge2 = Edge::create(
2486            &conn,
2487            insert_node_id,
2488            4,
2489            Strand::Forward,
2490            template2_node_id,
2491            3,
2492            Strand::Forward,
2493        )
2494        .unwrap();
2495
2496        let outgoing_boundaries = get_block_boundaries(Some(&vec![&edge1]), None);
2497        assert_eq!(outgoing_boundaries, vec![2]);
2498        let incoming_boundaries = get_block_boundaries(None, Some(&vec![&edge2]));
2499        assert_eq!(incoming_boundaries, vec![3]);
2500    }
2501
2502    #[test]
2503    fn test_edge_capnp_serialization() {
2504        use capnp::message::TypedBuilder;
2505
2506        let edge = Edge {
2507            id: HashId::pad_str(789),
2508            source_node_id: HashId::convert_str("1"),
2509            source_coordinate: 10,
2510            source_strand: Strand::Forward,
2511            target_node_id: HashId::convert_str("2"),
2512            target_coordinate: 20,
2513            target_strand: Strand::Reverse,
2514        };
2515
2516        let mut message = TypedBuilder::<edge::Owned>::new_default();
2517        let mut root = message.init_root();
2518        edge.write_capnp(&mut root);
2519
2520        let deserialized = Edge::read_capnp(root.into_reader());
2521        assert_eq!(edge, deserialized);
2522    }
2523}