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