chaintools 0.0.5

work with .chain files in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
// Copyright (c) 2026 Alejandro Gonzales-Irribarren <alejandrxgzi@gmail.com>
// Distributed under the terms of the Apache License, Version 2.0.

use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use chaintools::{Block, OwnedChain, StreamItem, StreamingReader, write_chain_dense};
#[cfg(feature = "parallel")]
use rayon::prelude::ParallelSliceMut;

use super::CliError;

pub(super) const OUTPUT_BUFFER_CAPACITY: usize = 1024 * 1024;
const MAX_OPEN_RUNS: usize = 128;

/// Sort criteria for chain ordering.
///
/// # Variants
///
/// * `Score` - Sort by chain score (descending), tie-breaks by ID
/// * `Id` - Sort by chain ID
/// * `Reference` - Sort by reference sequence name and coordinates
/// * `Query` - Sort by query sequence name and coordinates
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum SortCriterion {
    Score,
    Id,
    Reference,
    Query,
}

/// Container for sorted chain input data.
///
/// # Variants
///
/// * `InMemory` - All chains fit in memory
/// * `Runs` - Chains spilled to temporary files and need merge
pub(super) enum SortedInput {
    InMemory(Vec<OwnedChain>),
    Runs(Vec<TempRun>),
}

/// Represents a temporary run file for external sorting.
///
/// When memory is insufficient, chains are spilled to temporary files
/// that are later merged. Implements automatic cleanup on drop.
///
/// # Fields
///
/// * `path` - Path to the temporary file
pub(super) struct TempRun {
    path: PathBuf,
}

impl TempRun {
    pub(super) fn create(
        dir: &Path,
        prefix: &str,
        next_temp_id: &mut u64,
    ) -> Result<(Self, File), CliError> {
        for _ in 0..1024 {
            let nonce = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_nanos();
            let path = dir.join(format!(
                ".chaintools-sort-{prefix}-{}-{nonce}-{}.tmp",
                std::process::id(),
                *next_temp_id
            ));
            *next_temp_id += 1;

            match OpenOptions::new().write(true).create_new(true).open(&path) {
                Ok(file) => return Ok((Self { path }, file)),
                Err(err) if err.kind() == io::ErrorKind::AlreadyExists => continue,
                Err(err) => return Err(CliError::Io(err)),
            }
        }

        Err(CliError::Message(format!(
            "failed to create temporary {prefix} file in {}",
            dir.display()
        )))
    }
}

impl Drop for TempRun {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.path);
    }
}

/// Accumulates chains and manages sorting with optional spilling.
///
/// Handles in-memory sorting when data fits, and manages temporary file
/// creation when memory budget is exceeded. Supports metadata preservation.
///
/// # Fields
///
/// * `sort_by` - The sort criterion to use
/// * `max_in_memory_bytes` - Maximum bytes to keep in memory before spilling
/// * `temp_dir` - Directory for temporary run files
/// * `next_generated_id` - Counter for generated chain IDs
/// * `metadata` - Preserved metadata lines (comments)
/// * `records` - Chains currently in memory
/// * `runs` - Temporary run files for external sorting
/// * `chunk_bytes` - Estimated memory usage of current records
/// * `next_temp_id` - Counter for temporary file names
pub(super) struct SortAccumulator<'a> {
    sort_by: SortCriterion,
    max_in_memory_bytes: u64,
    temp_dir: &'a Path,
    next_generated_id: u64,
    metadata: Vec<Vec<u8>>,
    records: Vec<OwnedChain>,
    runs: Vec<TempRun>,
    chunk_bytes: u64,
    next_temp_id: u64,
    chains_pushed: u64,
    runs_spilled: u64,
}

impl<'a> SortAccumulator<'a> {
    pub(super) fn new(
        sort_by: SortCriterion,
        max_in_memory_bytes: u64,
        temp_dir: &'a Path,
    ) -> Self {
        Self {
            sort_by,
            max_in_memory_bytes,
            temp_dir,
            next_generated_id: 1,
            metadata: Vec::new(),
            records: Vec::new(),
            runs: Vec::new(),
            chunk_bytes: 0,
            next_temp_id: 0,
            chains_pushed: 0,
            runs_spilled: 0,
        }
    }

    pub(super) fn push_stream<R: BufRead>(
        &mut self,
        reader: &mut StreamingReader<R>,
    ) -> Result<(), CliError> {
        reader.set_next_generated_id(self.next_generated_id);

        while let Some(item) = reader.next_item()? {
            match item {
                StreamItem::MetaLine(line) => self.metadata.push(line),
                StreamItem::Header(header) => {
                    let blocks = reader.read_blocks(header.offset)?;
                    let chain = header.into_chain(blocks);
                    self.chunk_bytes = self
                        .chunk_bytes
                        .saturating_add(estimate_chain_bytes(&chain));
                    self.records.push(chain);
                    self.chains_pushed += 1;

                    if self.chunk_bytes >= self.max_in_memory_bytes && !self.records.is_empty() {
                        let spilled = self.records.len();
                        self.runs.push(spill_records_to_run(
                            &mut self.records,
                            self.sort_by,
                            self.temp_dir,
                            &mut self.next_temp_id,
                        )?);
                        self.runs_spilled += 1;
                        log::debug!(
                            "spilled sorted run #{} ({spilled} chains; memory budget exceeded)",
                            self.runs_spilled
                        );
                        self.chunk_bytes = 0;
                    }
                }
            }
        }

        self.next_generated_id = reader.next_generated_id();
        Ok(())
    }

    pub(super) fn finish(mut self) -> Result<(Vec<Vec<u8>>, SortedInput), CliError> {
        if self.runs.is_empty() {
            log::debug!("sort path: in-memory ({} chains)", self.records.len());
            sort_records(&mut self.records, self.sort_by);
            return Ok((self.metadata, SortedInput::InMemory(self.records)));
        }

        if !self.records.is_empty() {
            let spilled = self.records.len();
            self.runs.push(spill_records_to_run(
                &mut self.records,
                self.sort_by,
                self.temp_dir,
                &mut self.next_temp_id,
            )?);
            self.runs_spilled += 1;
            log::debug!(
                "spilled final sorted run #{} ({spilled} chains)",
                self.runs_spilled
            );
        }

        log::debug!("sort path: external merge of {} runs", self.runs.len());
        let reduced = reduce_runs(
            self.runs,
            self.sort_by,
            self.temp_dir,
            &mut self.next_temp_id,
        )?;
        Ok((self.metadata, SortedInput::Runs(reduced)))
    }

    /// Number of chains read into the accumulator.
    pub(super) fn chains_pushed(&self) -> u64 {
        self.chains_pushed
    }

    /// Number of sorted runs spilled to disk (`0` when the sort stayed fully in
    /// memory).
    pub(super) fn runs_spilled(&self) -> u64 {
        self.runs_spilled
    }
}

/// Emits sorted chains to a writer.
///
/// Writes all chains in sorted order, handling both in-memory and
/// run-based sorted inputs.
///
/// # Arguments
///
/// * `writer` - Output writer
/// * `sorted` - The sorted input (in-memory or runs)
/// * `sort_by` - The sort criterion used
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
pub(super) fn emit_sorted_chains<W: Write>(
    writer: &mut W,
    sorted: SortedInput,
    sort_by: SortCriterion,
) -> Result<(), CliError> {
    match sorted {
        SortedInput::InMemory(records) => {
            for chain in &records {
                write_chain_dense(writer, chain)?;
            }
        }
        SortedInput::Runs(runs) => {
            with_merged_runs(&runs, sort_by, |chain| {
                write_chain_dense(writer, chain).map_err(CliError::from)
            })?;
        }
    }
    Ok(())
}

/// Merges multiple sorted runs and emits chains in order.
///
/// Uses a binary heap to perform a k-way merge of sorted runs,
/// yielding chains in sorted order without loading all data into memory.
///
/// # Arguments
///
/// * `runs` - Temporary run files to merge
/// * `sort_by` - The sort criterion for merging
/// * `emit` - Callback function to receive each sorted chain
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
pub(super) fn with_merged_runs<F>(
    runs: &[TempRun],
    sort_by: SortCriterion,
    mut emit: F,
) -> Result<(), CliError>
where
    F: FnMut(&OwnedChain) -> Result<(), CliError>,
{
    let mut readers = Vec::with_capacity(runs.len());
    let mut heap = BinaryHeap::with_capacity(runs.len());

    for (run_index, run) in runs.iter().enumerate() {
        let mut reader = StreamingReader::from_path(&run.path)?;
        if let Some(chain) = reader.next_chain()? {
            heap.push(MergeHead {
                sort_by,
                run_index,
                chain,
            });
        }
        readers.push(reader);
    }

    while let Some(head) = heap.pop() {
        emit(&head.chain)?;
        if let Some(chain) = readers[head.run_index].next_chain()? {
            heap.push(MergeHead {
                sort_by,
                run_index: head.run_index,
                chain,
            });
        }
    }

    Ok(())
}

/// Writes metadata lines to a writer.
///
/// Writes each preserved metadata line (comment lines starting with #)
/// to the output, adding newline characters.
///
/// # Arguments
///
/// * `writer` - Output writer
/// * `metadata` - Vector of metadata lines to write
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
pub(super) fn write_metadata_lines<W: Write>(
    writer: &mut W,
    metadata: &[Vec<u8>],
) -> Result<(), CliError> {
    for line in metadata {
        writer.write_all(line)?;
        writer.write_all(b"\n")?;
    }
    Ok(())
}

/// Compares two chains according to the sort criterion.
///
/// Provides a comparison function that sorts chains based on the specified
/// criterion, with consistent tie-breaking behavior.
///
/// # Arguments
///
/// * `a` - First chain to compare
/// * `b` - Second chain to compare
/// * `sort_by` - The sort criterion for comparison
///
/// # Output
///
/// Returns `Ordering` indicating the relative order of the chains
pub(super) fn compare_chains(a: &OwnedChain, b: &OwnedChain, sort_by: SortCriterion) -> Ordering {
    match sort_by {
        SortCriterion::Score => compare_score(a, b),
        SortCriterion::Id => compare_id(a, b),
        SortCriterion::Reference => compare_reference(a, b),
        SortCriterion::Query => compare_query(a, b),
    }
}

/// Reduces runs by merging them in batches.
///
/// Continuously merges runs until the number of runs is at or below MAX_OPEN_RUNS.
/// Each merge reads multiple runs and writes a new merged run to disk.
///
/// # Arguments
///
/// * `runs` - Vector of temporary runs to reduce
/// * `sort_by` - Sort criterion for merging
/// * `temp_dir` - Directory for temporary files
/// * `next_temp_id` - Counter for generating unique temp file names
///
/// # Output
///
/// Returns `Ok(Vec<TempRun>)` with reduced runs
fn reduce_runs(
    mut runs: Vec<TempRun>,
    sort_by: SortCriterion,
    temp_dir: &Path,
    next_temp_id: &mut u64,
) -> Result<Vec<TempRun>, CliError> {
    while runs.len() > MAX_OPEN_RUNS {
        log::debug!(
            "reducing {} sorted runs in groups of {MAX_OPEN_RUNS}",
            runs.len()
        );
        let old_runs = std::mem::take(&mut runs);
        let mut next_runs = Vec::new();
        let mut groups = old_runs.into_iter();

        loop {
            let group: Vec<TempRun> = groups.by_ref().take(MAX_OPEN_RUNS).collect();
            if group.is_empty() {
                break;
            }
            let (merged_run, file) = TempRun::create(temp_dir, "merge", next_temp_id)?;
            let writer = BufWriter::with_capacity(OUTPUT_BUFFER_CAPACITY, file);
            write_merged_runs_to_plain(&group, sort_by, writer)?;
            next_runs.push(merged_run);
        }

        runs = next_runs;
    }

    Ok(runs)
}

/// Spills records to a temporary run file.
///
/// Sorts the records, writes them to a temporary file, and returns the TempRun handle.
///
/// # Arguments
///
/// * `records` - Vector of chains to write
/// * `sort_by` - Sort criterion for ordering
/// * `temp_dir` - Directory for temporary files
/// * `next_temp_id` - Counter for generating unique temp file names
///
/// # Output
///
/// Returns `Ok(TempRun)` with the temporary run file handle
fn spill_records_to_run(
    records: &mut Vec<OwnedChain>,
    sort_by: SortCriterion,
    temp_dir: &Path,
    next_temp_id: &mut u64,
) -> Result<TempRun, CliError> {
    let mut chunk = std::mem::take(records);
    sort_records(&mut chunk, sort_by);

    let (run, file) = TempRun::create(temp_dir, "run", next_temp_id)?;
    let mut writer = BufWriter::with_capacity(OUTPUT_BUFFER_CAPACITY, file);
    for chain in &chunk {
        write_chain_dense(&mut writer, chain)?;
    }
    writer.flush()?;
    Ok(run)
}

/// Writes merged runs to a plain text output file.
///
/// Merges multiple runs using heap-based k-way merge and writes sorted chains.
///
/// # Arguments
///
/// * `runs` - Temporary runs to merge
/// * `sort_by` - Sort criterion for merging
/// * `writer` - Output writer
///
/// # Output
///
/// Returns `Ok(())` on success or `Err(CliError)` on failure
fn write_merged_runs_to_plain<W: Write>(
    runs: &[TempRun],
    sort_by: SortCriterion,
    mut writer: W,
) -> Result<(), CliError> {
    with_merged_runs(runs, sort_by, |chain| {
        write_chain_dense(&mut writer, chain).map_err(CliError::from)
    })?;
    writer.flush()?;
    Ok(())
}

/// Estimates memory usage for a chain in bytes.
///
/// Calculates approximate memory footprint including the chain struct, names, and blocks.
///
/// # Arguments
///
/// * `chain` - The chain to estimate
///
/// # Output
///
/// Returns estimated byte size
fn estimate_chain_bytes(chain: &OwnedChain) -> u64 {
    (std::mem::size_of::<OwnedChain>()
        + chain.reference_name.len()
        + chain.query_name.len()
        + chain.blocks.len() * std::mem::size_of::<Block>()) as u64
}

/// Sorts records using parallel sorting.
///
/// Uses Rayon's parallel sort for high-performance sorting when the parallel feature is enabled.
///
/// # Arguments
///
/// * `records` - Mutable slice of chains to sort
/// * `sort_by` - Sort criterion
///
/// # Examples
///
/// ```ignore
/// use chaintools::cli::sort_core::{sort_records, SortCriterion};
///
/// let mut chains = vec![chain1, chain2, chain3];
/// sort_records(&mut chains, SortCriterion::Score);
/// ```
#[cfg(feature = "parallel")]
fn sort_records(records: &mut [OwnedChain], sort_by: SortCriterion) {
    records.par_sort_unstable_by(|a, b| compare_chains(a, b, sort_by));
}

#[cfg(not(feature = "parallel"))]
/// Sorts records using sequential sorting.
///
/// Uses standard sequential sort when the parallel feature is not enabled.
///
/// # Arguments
///
/// * `records` - Mutable slice of chains to sort
/// * `sort_by` - Sort criterion
fn sort_records(records: &mut [OwnedChain], sort_by: SortCriterion) {
    records.sort_unstable_by(|a, b| compare_chains(a, b, sort_by));
}

/// Compares chains by score, with tie-breakers.
fn compare_score(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    b.score
        .cmp(&a.score)
        .then_with(|| compare_tie_breakers(a, b))
}

/// Compares chains by ID, with additional tie-breakers.
fn compare_id(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.id.cmp(&b.id)
        .then_with(|| compare_non_id_tie_breakers(a, b))
}

/// Compares chains by reference name and position.
fn compare_reference(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    compare_reference_primary(a, b).then_with(|| compare_tie_breakers(a, b))
}

/// Compares chains by query name and position.
fn compare_query(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    compare_query_primary(a, b).then_with(|| compare_tie_breakers(a, b))
}

/// Secondary tie-breaker: compares by ID first, then other non-ID fields.
fn compare_tie_breakers(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.id.cmp(&b.id)
        .then_with(|| compare_non_id_tie_breakers(a, b))
}

/// Non-ID tie-breaker: compares reference full, query full, score, then blocks.
fn compare_non_id_tie_breakers(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    compare_reference_full(a, b)
        .then_with(|| compare_query_full(a, b))
        .then_with(|| b.score.cmp(&a.score))
        .then_with(|| compare_blocks(&a.blocks, &b.blocks))
}

/// Primary reference comparison: name then start position.
fn compare_reference_primary(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.reference_name
        .cmp(&b.reference_name)
        .then_with(|| a.reference_start.cmp(&b.reference_start))
}

/// Primary query comparison: name then start position.
fn compare_query_primary(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.query_name
        .cmp(&b.query_name)
        .then_with(|| a.query_start.cmp(&b.query_start))
}

/// Full reference comparison: name, size, strand, start, then end.
fn compare_reference_full(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.reference_name
        .cmp(&b.reference_name)
        .then_with(|| a.reference_size.cmp(&b.reference_size))
        .then_with(|| strand_to_byte(a.reference_strand).cmp(&strand_to_byte(b.reference_strand)))
        .then_with(|| a.reference_start.cmp(&b.reference_start))
        .then_with(|| a.reference_end.cmp(&b.reference_end))
}

/// Full query comparison: name, size, strand, start, then end.
fn compare_query_full(a: &OwnedChain, b: &OwnedChain) -> Ordering {
    a.query_name
        .cmp(&b.query_name)
        .then_with(|| a.query_size.cmp(&b.query_size))
        .then_with(|| strand_to_byte(a.query_strand).cmp(&strand_to_byte(b.query_strand)))
        .then_with(|| a.query_start.cmp(&b.query_start))
        .then_with(|| a.query_end.cmp(&b.query_end))
}

/// Compares block sequences by iterating and comparing size, gaps.
fn compare_blocks(a: &[Block], b: &[Block]) -> Ordering {
    for (lhs, rhs) in a.iter().zip(b.iter()) {
        let cmp = lhs
            .size
            .cmp(&rhs.size)
            .then_with(|| lhs.gap_reference.cmp(&rhs.gap_reference))
            .then_with(|| lhs.gap_query.cmp(&rhs.gap_query));
        if cmp != Ordering::Equal {
            return cmp;
        }
    }
    a.len().cmp(&b.len())
}

/// Merge head for k-way merge algorithm.
///
/// Holds a chain from a run along with metadata for heap-based merging.
///
/// # Fields
///
/// * `sort_by` - Sort criterion for comparison
/// * `run_index` - Index of the run this chain came from
/// * `chain` - The chain data
struct MergeHead {
    sort_by: SortCriterion,
    run_index: usize,
    chain: OwnedChain,
}

impl Ord for MergeHead {
    fn cmp(&self, other: &Self) -> Ordering {
        compare_chains(&other.chain, &self.chain, self.sort_by)
            .then_with(|| other.run_index.cmp(&self.run_index))
    }
}

impl PartialOrd for MergeHead {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for MergeHead {
    fn eq(&self, other: &Self) -> bool {
        self.run_index == other.run_index
            && compare_chains(&self.chain, &other.chain, self.sort_by) == Ordering::Equal
    }
}

impl Eq for MergeHead {}

/// Converts a Strand to a byte representation.
fn strand_to_byte(strand: chaintools::Strand) -> u8 {
    match strand {
        chaintools::Strand::Plus => b'+',
        chaintools::Strand::Minus => b'-',
    }
}