twitcher 0.8.2

Find template switch mutations in genomic data
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
use std::{
    fmt::Display,
    path::{Path, PathBuf},
    time::Duration,
};

use anyhow::Context;
use clap::ValueEnum;
use itertools::Itertools;
use rusqlite::{Connection, OpenFlags, OptionalExtension, TransactionBehavior};
use tracing::{error, warn};

use crate::common::aligner::{
    AlignerSelectorDescription, AlignmentKey,
    result::{AlignmentFailure, SoftFailureReason, TwitcherAlignment},
};

const DB_SCHEMA_VERSION: i32 = 3;
const DB_TABLES: [DbTableSpec; 2] = [
    DbTableSpec {
        name: "configurations",
        colunms: &[
            ["id", "INTEGER PRIMARY KEY AUTOINCREMENT"],
            ["reference", "TEXT NOT NULL"],
            ["aligner", "BLOB NOT NULL"],
            ["created_at", "TEXT NOT NULL DEFAULT (datetime('now'))"],
        ],
        extra: None,
    },
    DbTableSpec {
        name: "alignments",
        colunms: &[
            ["id", "INTEGER PRIMARY KEY AUTOINCREMENT"],
            [
                "config_id",
                "INTEGER NOT NULL REFERENCES configurations(id)",
            ],
            ["reference_region", "TEXT NOT NULL"],
            ["ref_offset", "INTEGER NOT NULL"],
            ["ref_limit", "INTEGER NOT NULL"],
            ["query_offset", "INTEGER NOT NULL"],
            ["query_limit", "INTEGER NOT NULL"],
            ["query_seq", "BLOB NOT NULL"],
            ["query_seq_n_pos", "BLOB NOT NULL"],
            ["query_seq_len", "INTEGER NOT NULL"],
            ["memory_allowance", "INTEGER NOT NULL"],
            ["timeout_ns", "INTEGER NOT NULL"],
            ["result", "BLOB NOT NULL"],
        ],
        extra: Some(
            "UNIQUE(config_id, reference_region, ref_offset, ref_limit, query_offset, query_limit, query_seq, query_seq_n_pos, query_seq_len)",
        ),
    },
];

const MAX_PENDING_WRITES: usize = 1024;

#[derive(Debug)]
struct DbTableSpec {
    name: &'static str,
    colunms: &'static [[&'static str; 2]],
    extra: Option<&'static str>,
}

#[derive(clap::Args, Debug, Default)]
#[command(next_help_heading = "Alignment cache")]
pub struct CliDatabaseArgs {
    /// Path to a database file (sqlite) used as a persistent cache of alignment results. Results are keyed
    /// by the aligner configuration and the aligned sequences, so a rerun with the same settings
    /// reuses them instead of recomputing. The file is created if it does not exist. Several
    /// twitcher processes on the same machine may use the same file at the same time.
    #[arg(long = "db", value_name = "FILE")]
    path: Option<PathBuf>,

    /// How to use the cache file given with --db.
    #[arg(
        long = "db-mode",
        value_name = "MODE",
        default_value_t,
        requires = "path"
    )]
    mode: DbMode,
}

#[derive(clap::ValueEnum, Debug, Clone, Copy, Default, PartialEq, Eq)]
enum DbMode {
    /// Reuse cached alignments, but do not store newly computed ones.
    ReadOnly,
    /// Store newly computed alignments, but do not reuse cached ones (recomputes everything).
    WriteOnly,
    /// Reuse cached alignments and store newly computed ones.
    #[default]
    ReadWrite,
}

impl DbMode {
    const fn is_read(self) -> bool {
        matches!(self, Self::ReadOnly | Self::ReadWrite)
    }
    const fn is_write(self) -> bool {
        matches!(self, Self::WriteOnly | Self::ReadWrite)
    }
}

impl Display for DbMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if let Some(pv) = self.to_possible_value() {
            write!(f, "{}", pv.get_name())
        } else {
            write!(f, "unknown")
        }
    }
}

pub struct Database {
    conn: Connection,
    mode: DbMode,
    config_id: Option<u32>,
    /// Rows not yet committed, kept until a commit succeeds so that a busy database only delays them.
    pending_writes: Vec<PendingRow>,
    initialized: bool,
}

/// One row of the `alignments` table, minus the `config_id`, already converted so that a flush can
/// only fail on the database itself.
struct PendingRow {
    reference_region: String,
    ref_offset: isize,
    ref_limit: isize,
    query_offset: isize,
    query_limit: isize,
    query_seq: Vec<u8>,
    query_seq_n_pos: Vec<u8>,
    query_seq_len: isize,
    memory_allowance: i64,
    timeout_ns: i64,
    result: Vec<u8>,
}

impl TryFrom<&CliDatabaseArgs> for Option<Database> {
    type Error = anyhow::Error;
    fn try_from(args: &CliDatabaseArgs) -> anyhow::Result<Self> {
        let Some(path) = &args.path else {
            return Ok(None);
        };
        let mut conn = if args.mode.is_write() {
            let conn = Connection::open(path)
                .with_context(|| format!("Cannot open database {}", path.display()))?;
            enable_wal(&conn).context("Cannot switch database to WAL mode")?;
            // In WAL mode, commits then survive a crash of this process but not of the OS, and
            // need no fsync.
            conn.pragma_update(None, "synchronous", "NORMAL")
                .context("Cannot configure database")?;
            conn
        } else {
            open_read_only(path)
                .with_context(|| format!("Cannot open database {}", path.display()))?
        };
        Database::check_or_init_schema(&mut conn, args.mode)
            .context("Cannot set up database tables")?;
        Ok(Some(Database {
            conn,
            mode: args.mode,
            config_id: None,
            pending_writes: Vec::new(),
            initialized: false,
        }))
    }
}

pub struct StaticAlignmentKey<'a> {
    pub reference_name: &'a str,
    pub aligner_config: AlignerSelectorDescription,
}

fn to_timeout_ns(t: Option<Duration>) -> i64 {
    t.and_then(|d| d.as_nanos().try_into().ok()).unwrap_or(-1)
}

/// Switch the database to write-ahead logging, so that readers and the writer do not block each
/// other. This is persistent and a no-op for a file already in WAL mode, but switching a new file
/// needs an exclusive lock, which sqlite does not wait for with the busy handler; when several jobs
/// open a new file at the same time, retry for a while. If it never succeeds, the database still
/// works in rollback journal mode, only with more lock contention.
fn enable_wal(conn: &Connection) -> rusqlite::Result<()> {
    const ATTEMPTS: usize = 50;
    for _ in 0..ATTEMPTS {
        match conn
            .pragma_update_and_check(None, "journal_mode", "WAL", |row| row.get::<_, String>(0))
        {
            Ok(mode) if mode.eq_ignore_ascii_case("wal") => return Ok(()),
            Ok(_) => {}
            Err(e) if e.sqlite_error_code() == Some(rusqlite::ErrorCode::DatabaseBusy) => {}
            Err(e) => return Err(e),
        }
        std::thread::sleep(Duration::from_millis(100));
    }
    warn!("Could not switch the database to WAL mode, continuing in rollback journal mode");
    Ok(())
}

/// Open `path` without writing to it. A database in WAL mode still needs to create its `-shm` file
/// next to it; if that is not possible (e.g. a shared cache in a directory this job cannot write
/// to), fall back to opening it as immutable, which ignores the `-wal` file and assumes that nobody
/// writes to it in the meantime.
fn open_read_only(path: &Path) -> rusqlite::Result<Connection> {
    let flags = OpenFlags::SQLITE_OPEN_READ_ONLY
        | OpenFlags::SQLITE_OPEN_URI
        | OpenFlags::SQLITE_OPEN_NO_MUTEX;
    let conn = Connection::open_with_flags(path, flags)?;
    // Opening is lazy, only the first read shows whether the file can actually be read.
    match conn.pragma_query_value(None, "user_version", |row| row.get::<_, i32>(0)) {
        Ok(_) => Ok(conn),
        Err(e) => {
            warn!(
                "Cannot read database {} normally ({e}), opening it as immutable instead",
                path.display()
            );
            let path = path.to_string_lossy();
            let escaped = path
                .replace('%', "%25")
                .replace('?', "%3f")
                .replace('#', "%23");
            Connection::open_with_flags(format!("file:{escaped}?immutable=1"), flags)
        }
    }
}

impl Database {
    /// Create the tables in a new database, or check them in an existing one. Runs in one
    /// transaction, so that jobs which open a new database at the same time take turns: the first
    /// one creates the tables, the others find them.
    fn check_or_init_schema(conn: &mut Connection, mode: DbMode) -> anyhow::Result<()> {
        let behavior = if mode.is_write() {
            TransactionBehavior::Immediate
        } else {
            TransactionBehavior::Deferred
        };
        let tx = conn.transaction_with_behavior(behavior)?;
        let version: i32 = tx.pragma_query_value(None, "user_version", |row| row.get(0))?;
        let objects: i64 =
            tx.query_row("SELECT COUNT(*) FROM sqlite_master", [], |row| row.get(0))?;
        match version {
            DB_SCHEMA_VERSION => Self::check_tables(&tx)?,
            0 if objects == 0 && mode.is_write() => {
                Self::init_tables(&tx)?;
                tx.pragma_update(None, "user_version", DB_SCHEMA_VERSION)?;
            }
            0 if objects == 0 => {
                anyhow::bail!("The database file is empty, and read-only was specified.")
            }
            v => anyhow::bail!(
                "The database file has schema version {v}, but this version of twitcher needs version {DB_SCHEMA_VERSION}."
            ),
        }
        tx.commit()?;
        Ok(())
    }

    fn init_tables(conn: &Connection) -> Result<(), rusqlite::Error> {
        for table in &DB_TABLES {
            let name = table.name;
            // cursed
            let columns = table
                .colunms
                .iter()
                .map(|s| s.iter().join(" "))
                .chain(table.extra.map(str::to_string))
                .join(",\n");
            let query = format!(
                "CREATE TABLE {name} (
                    {columns}
                )"
            );
            conn.execute(&query, ())?;
        }
        Ok(())
    }

    fn check_tables(conn: &Connection) -> anyhow::Result<()> {
        for table in &DB_TABLES {
            let exists: bool = conn.query_row(
                "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name=?1",
                [table.name],
                |row| row.get::<_, i64>(0),
            )? > 0;

            if !exists {
                anyhow::bail!("Required table '{}' does not exist", table.name);
            }

            let mut stmt = conn.prepare(&format!("PRAGMA table_info({})", table.name))?;
            let actual_columns: Vec<String> = stmt
                .query_map([], |row| row.get::<_, String>(1))?
                .filter_map(Result::ok)
                .collect();

            for &[col, _] in table.colunms {
                if !actual_columns.iter().any(|c| c == col) {
                    anyhow::bail!("Table '{}' is missing required column '{col}'", table.name);
                }
            }
        }
        Ok(())
    }

    pub fn init_with_config(&mut self, key: &StaticAlignmentKey) -> anyhow::Result<()> {
        let write = self.mode.is_write();
        // Immediate: jobs starting at the same time take turns, so a second one finds the
        // configuration the first one inserted instead of inserting a duplicate.
        let tx = self.conn.transaction_with_behavior(if write {
            TransactionBehavior::Immediate
        } else {
            TransactionBehavior::Deferred
        })?;
        // Databases written by earlier versions may hold duplicates; always pick the same one.
        let existing_config: Option<u32> = tx
            .query_row(
                "SELECT id FROM configurations WHERE reference = ? AND aligner = ? ORDER BY id LIMIT 1",
                (key.reference_name, &key.aligner_config),
                |row| row.get(0),
            )
            .optional()?;

        let config_id = if existing_config.is_some() {
            existing_config
        } else if write {
            Some(tx.query_one(
                "INSERT INTO configurations (reference, aligner) VALUES (?, ?) RETURNING id",
                (key.reference_name, &key.aligner_config),
                |row| row.get(0),
            )?)
        } else {
            warn!(
                "read-only database, but no existing data matches the configuration of this execution"
            );
            None
        };
        tx.commit()?;

        self.config_id = config_id;
        self.initialized = true;
        Ok(())
    }

    /// Stop using the database for the rest of the run: lookups miss and results are not stored.
    pub fn disable(&mut self) {
        self.config_id = None;
        self.initialized = true;
    }

    pub const fn needs_init(&self) -> bool {
        !self.initialized
    }

    pub fn lookup(
        &self,
        key: &AlignmentKey,
        memory: usize,
        timeout: Option<Duration>,
    ) -> anyhow::Result<Option<TwitcherAlignment>> {
        if !self.initialized {
            anyhow::bail!("DB needs to be initialized before first use");
        }
        if !self.mode.is_read() {
            return Ok(None);
        }
        let Some(cid) = self.config_id else {
            return Ok(None);
        };
        let (qry_seq, qry_ns) = compress_sequence(&key.query_sequence)?;
        let row: Option<(Vec<u8>, i64, i64)> = self
            .conn
            .query_one(
                "SELECT result, memory_allowance, timeout_ns FROM alignments
                 WHERE config_id = ?
                   AND reference_region = ?
                   AND ref_offset = ? AND ref_limit = ?
                   AND query_offset = ? AND query_limit = ?
                   AND query_seq = ? AND query_seq_n_pos = ? AND query_seq_len = ?",
                (
                    cid,
                    key.reference_region.to_string(),
                    isize::try_from(key.alignment_ranges.reference_offset())?,
                    isize::try_from(key.alignment_ranges.reference_limit())?,
                    isize::try_from(key.alignment_ranges.query_offset())?,
                    isize::try_from(key.alignment_ranges.query_limit())?,
                    qry_seq,
                    qry_ns,
                    isize::try_from(key.query_sequence.len())?,
                ),
                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
            )
            .optional()?;

        if let Some((bytes, stored_memory, stored_timeout_ns)) = row {
            let result: TwitcherAlignment = rmp_serde::from_slice(&bytes)?;
            let current_timeout_ns = to_timeout_ns(timeout);
            let retry_timeout = match (stored_timeout_ns, current_timeout_ns) {
                (-1, _) => false,
                (_, -1) => true,
                (s, c) => c > s,
            };
            match &result.outcome {
                Err(AlignmentFailure::SoftFailure {
                    reason: SoftFailureReason::OutOfMemory,
                }) if i64::try_from(memory)? > stored_memory => return Ok(None),
                Err(AlignmentFailure::SoftFailure {
                    reason: SoftFailureReason::Timeout(_),
                }) if retry_timeout => return Ok(None),
                _ => {}
            }
            Ok(Some(result))
        } else {
            Ok(None)
        }
    }

    pub fn store(
        &mut self,
        key: &AlignmentKey,
        result: &TwitcherAlignment,
        memory: usize,
        timeout: Option<Duration>,
    ) -> anyhow::Result<()> {
        if !self.initialized {
            anyhow::bail!("DB needs to be initialized before first use");
        }
        if !self.mode.is_write() || self.config_id.is_none() {
            return Ok(());
        }

        let (query_seq, query_seq_n_pos) = compress_sequence(&key.query_sequence)?;
        self.pending_writes.push(PendingRow {
            reference_region: key.reference_region.to_string(),
            ref_offset: isize::try_from(key.alignment_ranges.reference_offset())?,
            ref_limit: isize::try_from(key.alignment_ranges.reference_limit())?,
            query_offset: isize::try_from(key.alignment_ranges.query_offset())?,
            query_limit: isize::try_from(key.alignment_ranges.query_limit())?,
            query_seq,
            query_seq_n_pos,
            query_seq_len: isize::try_from(key.query_sequence.len())?,
            memory_allowance: i64::try_from(memory)?,
            timeout_ns: to_timeout_ns(timeout),
            result: rmp_serde::to_vec(result)?,
        });

        // Commit every result right away: keeps it safe when the process is killed and makes it
        // visible to concurrent jobs; with `synchronous = NORMAL` a commit is cheap compared to an
        // alignment. Failed rows stay pending and are retried with the next one.
        let pending = self.pending_writes.len();
        if let Err(e) = self.flush_writes() {
            warn!("Could not write {pending} alignment(s) to the database: {e}");
        }

        Ok(())
    }

    /// Commit all pending rows. They are only removed once the commit succeeded, or once too many
    /// have piled up.
    fn flush_writes(&mut self) -> anyhow::Result<()> {
        if self.pending_writes.is_empty() {
            return Ok(());
        }
        let config_id = self.config_id.context("We should have a config id here!")?;

        if let Err(e) = Self::write_rows(&mut self.conn, config_id, &self.pending_writes) {
            if self.pending_writes.len() >= MAX_PENDING_WRITES {
                error!(
                    "Giving up on writing {} alignment(s) to the database",
                    self.pending_writes.len()
                );
                self.pending_writes.clear();
            }
            return Err(e.into());
        }
        self.pending_writes.clear();
        Ok(())
    }

    fn write_rows(
        conn: &mut Connection,
        config_id: u32,
        rows: &[PendingRow],
    ) -> rusqlite::Result<()> {
        // Immediate: wait for the write lock (up to the busy timeout) right away, instead of
        // failing when a read lock cannot be upgraded.
        let tx = conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
        for row in rows {
            tx.execute(
                "INSERT OR REPLACE INTO alignments
                    (config_id, reference_region, ref_offset, ref_limit,
                     query_offset, query_limit, query_seq, query_seq_n_pos,
                     query_seq_len, memory_allowance, timeout_ns, result)
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                (
                    config_id,
                    &row.reference_region,
                    row.ref_offset,
                    row.ref_limit,
                    row.query_offset,
                    row.query_limit,
                    &row.query_seq,
                    &row.query_seq_n_pos,
                    row.query_seq_len,
                    row.memory_allowance,
                    row.timeout_ns,
                    &row.result,
                ),
            )?;
        }
        tx.commit()
    }
}

impl Drop for Database {
    fn drop(&mut self) {
        if let Err(e) = self.flush_writes() {
            error!(
                "Could not write {} alignment(s) to the database before exiting: {e}",
                self.pending_writes.len()
            );
        }
    }
}

fn compress_sequence(seq: &[u8]) -> anyhow::Result<(Vec<u8>, Vec<u8>)> {
    let mut bits: Vec<u8> = vec![0u8; seq.len().div_ceil(4)];
    let mut n_positions: Vec<u8> = Vec::new();

    for (i, &base) in seq.iter().enumerate() {
        let two_bit = match base {
            b'A' | b'a' => 0b00,
            b'C' | b'c' => 0b01,
            b'G' | b'g' => 0b10,
            b'T' | b't' => 0b11,
            _ => {
                // N or anything else: record position, write 0
                let pos = u16::try_from(i)?;
                n_positions.extend_from_slice(&pos.to_be_bytes());
                0b00
            }
        };
        #[expect(clippy::indexing_slicing)]
        {
            // Soundness
            // 1. bits[i/4] is valid because i/4 == i.div_floor(4) < seq.len().div_floor(4) <= seq.len().div_ceil(4) == bit.len()
            // 2. (6 - (i % 4) * 2) is one of 6, 4, 2, 0, and two_bit has only the the two least significant bits set.
            bits[i / 4] |= two_bit << (6 - (i % 4) * 2);
        }
    }

    Ok((bits, n_positions))
}

/// Concurrent use of one database file. Every `Database` owns its own `Connection`, and sqlite
/// coordinates connections within one process just as it coordinates processes, so threads that
/// each open the file stand in for parallel twitcher jobs sharing one `--db`.
#[cfg(test)]
mod concurrency_tests {
    use std::{
        path::Path,
        sync::{Arc, Barrier},
        thread,
        time::Duration,
    };

    use lib_tsalign::a_star_aligner::alignment_geometry::{AlignmentCoordinates, AlignmentRange};

    use super::{CliDatabaseArgs, Database, DbMode, StaticAlignmentKey};
    use crate::common::{
        aligner::{
            AlignmentKey,
            exec_stats::{ExecStats, MemoryUsage},
            result::{AlignmentFailure, SoftFailureReason, TwitcherAlignment},
        },
        contig::ContigName,
        coords::{GenomePosition, GenomeRegion},
    };

    const JOBS: usize = 8;
    const MEMORY: usize = 1 << 30;

    fn open(path: &Path, mode: DbMode) -> anyhow::Result<Database> {
        let args = CliDatabaseArgs {
            path: Some(path.to_path_buf()),
            mode,
        };
        Ok(Option::<Database>::try_from(&args)?.expect("path was given"))
    }

    fn open_init(path: &Path, mode: DbMode) -> anyhow::Result<Database> {
        let mut db = open(path, mode)?;
        db.init_with_config(&StaticAlignmentKey {
            reference_name: "ref.fa",
            aligner_config: b"aligner".to_vec(),
        })?;
        Ok(db)
    }

    fn key(i: usize) -> AlignmentKey {
        AlignmentKey {
            reference_region: GenomeRegion::new_bounded(
                GenomePosition::new_0(ContigName::new(b"chr1"), 1000 * i),
                10,
            ),
            alignment_ranges: AlignmentRange::new_offset_limit(
                AlignmentCoordinates::new(0, 0),
                AlignmentCoordinates::new(10, 10),
            ),
            query_sequence: Arc::from(&b"ACGTACGTAC"[..]),
        }
    }

    fn result() -> TwitcherAlignment {
        TwitcherAlignment::new(
            Err(AlignmentFailure::SoftFailure {
                reason: SoftFailureReason::Other(String::new()),
            }),
            ExecStats {
                wall: Duration::ZERO,
                memory: MemoryUsage::default(),
                memory_limit: MEMORY,
            },
        )
    }

    fn store(db: &mut Database, i: usize) {
        db.store(&key(i), &result(), MEMORY, None).unwrap();
    }

    fn is_cached(db: &Database, i: usize) -> bool {
        db.lookup(&key(i), MEMORY, None).unwrap().is_some()
    }

    fn count(path: &Path, table: &str) -> i64 {
        rusqlite::Connection::open(path)
            .unwrap()
            .query_row(&format!("SELECT COUNT(*) FROM {table}"), [], |r| r.get(0))
            .unwrap()
    }

    /// Run `f` on `JOBS` threads released together.
    fn race<T: Send + 'static>(f: impl Fn(usize) -> T + Send + Sync + 'static) -> Vec<T> {
        let barrier = Arc::new(Barrier::new(JOBS));
        let f = Arc::new(f);
        let handles: Vec<_> = (0..JOBS)
            .map(|i| {
                let (barrier, f) = (barrier.clone(), f.clone());
                thread::spawn(move || {
                    barrier.wait();
                    f(i)
                })
            })
            .collect();
        handles.into_iter().map(|h| h.join().unwrap()).collect()
    }

    #[test]
    fn jobs_creating_the_same_file_all_succeed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("new.db");
        let p = path.clone();
        for result in race(move |_| open_init(&p, DbMode::ReadWrite).map(drop)) {
            result.unwrap();
        }
        assert_eq!(count(&path, "configurations"), 1);
    }

    #[test]
    fn concurrent_writers_lose_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("writers.db");
        drop(open(&path, DbMode::ReadWrite).unwrap());
        let p = path.clone();
        race(move |job| {
            let mut db = open_init(&p, DbMode::ReadWrite).unwrap();
            // Every key is written by two jobs.
            (0..10).for_each(|i| store(&mut db, (job / 2) * 10 + i));
        });
        assert_eq!(count(&path, "alignments"), 40);
    }

    /// Databases written by earlier versions may hold duplicate configurations; every job must
    /// pick the same one.
    #[test]
    fn duplicate_configurations_resolve_to_the_first() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("dup.db");
        drop(open(&path, DbMode::ReadWrite).unwrap());
        rusqlite::Connection::open(&path)
            .unwrap()
            .execute_batch(
                "INSERT INTO configurations (reference, aligner) VALUES ('ref.fa', x'616c69676e6572');
                 INSERT INTO configurations (reference, aligner) VALUES ('ref.fa', x'616c69676e6572');",
            )
            .unwrap();
        assert_eq!(
            open_init(&path, DbMode::ReadWrite).unwrap().config_id,
            Some(1)
        );
    }

    #[test]
    fn results_are_visible_to_other_jobs_without_flush_on_exit() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("visible.db");
        let mut writer = open_init(&path, DbMode::ReadWrite).unwrap();
        let reader = open_init(&path, DbMode::ReadWrite).unwrap();
        store(&mut writer, 0);
        assert!(is_cached(&reader, 0));
        #[expect(clippy::mem_forget, reason = "simulates a killed process")]
        std::mem::forget(writer);
        assert_eq!(count(&path, "alignments"), 1);
    }

    #[test]
    fn writes_blocked_by_another_job_are_retried() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("busy.db");
        let mut db = open_init(&path, DbMode::ReadWrite).unwrap();
        db.conn.busy_timeout(Duration::from_millis(10)).unwrap();

        let blocker = rusqlite::Connection::open(&path).unwrap();
        blocker.execute_batch("BEGIN IMMEDIATE").unwrap();
        store(&mut db, 0);
        assert_eq!(db.pending_writes.len(), 1);
        blocker.execute_batch("COMMIT").unwrap();

        store(&mut db, 1);
        assert!(db.pending_writes.is_empty());
        assert_eq!(count(&path, "alignments"), 2);
    }

    /// A shared cache in a directory this job cannot write to (no `-shm` file possible).
    #[test]
    fn read_only_works_in_unwritable_directory() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("shared.db");
        store(&mut open_init(&path, DbMode::ReadWrite).unwrap(), 0);
        let mode = |m| std::fs::Permissions::from_mode(m);
        std::fs::set_permissions(dir.path(), mode(0o555)).unwrap();

        let cached = open_init(&path, DbMode::ReadOnly).map(|db| is_cached(&db, 0));
        std::fs::set_permissions(dir.path(), mode(0o755)).unwrap();
        assert!(cached.unwrap());
    }
}