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 {
#[arg(long = "db", value_name = "FILE")]
path: Option<PathBuf>,
#[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 {
ReadOnly,
WriteOnly,
#[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>,
pending_writes: Vec<PendingRow>,
initialized: bool,
}
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")?;
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)
}
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(())
}
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)?;
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 {
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;
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();
let tx = self.conn.transaction_with_behavior(if write {
TransactionBehavior::Immediate
} else {
TransactionBehavior::Deferred
})?;
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(())
}
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)?,
});
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(())
}
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<()> {
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,
_ => {
let pos = u16::try_from(i)?;
n_positions.extend_from_slice(&pos.to_be_bytes());
0b00
}
};
#[expect(clippy::indexing_slicing)]
{
bits[i / 4] |= two_bit << (6 - (i % 4) * 2);
}
}
Ok((bits, n_positions))
}
#[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()
}
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();
(0..10).for_each(|i| store(&mut db, (job / 2) * 10 + i));
});
assert_eq!(count(&path, "alignments"), 40);
}
#[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);
}
#[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());
}
}