Bound the checkpoint after a removed key to a short wait, once per sign-out

Store::truncate_wal ran PRAGMA wal_checkpoint(TRUNCATE) with the connection's
busy timeout of five seconds. A checkpoint that truncates holds the writer lock
of the log while it waits for readers, so a reader that kept a snapshot made
every removed row cost the whole timeout with the store's mutex held, and other
writers failed with "database is locked" meanwhile. KeyStore::sign_out removes
up to four rows (the synced copies, the device key, the record) and ran the
checkpoint after each: 20 s and failing writers in the gate's probe.

- truncate_wal now sets a busy timeout of 150 ms (CHECKPOINT_WAIT) around the
  pragma and restores the timeout the connection had (read back with PRAGMA
  busy_timeout, so a value set by a caller survives) whatever the checkpoint
  returned. A blocked checkpoint still leaves the delete standing and warns.
- SqliteKeyStore overrides sign_out: the trait's own steps run on a private
  SignOutPass whose remove deletes the row and notes it, and the sign-out
  truncates the log once after its last step (also when a step failed, the
  removals before it have happened). KeyStore::remove on its own still
  truncates after the row it removed.
- The three sentences that said the bytes "stay in the log until the next
  checkpoint" (keystore.rs, Store::truncate_wal, docs/architecture.md) are
  corrected: they go when a later checkpoint truncates the log, later writes
  overwrite those frames, or the last connection closes and the log is deleted.

Tests: with a raw connection holding a read snapshot, a sign-out with four
removals returns in about 170 ms (it took 20 s) while a writer on another
connection with a one-second busy timeout writes throughout without an error
(it got "database is locked" nineteen times), and the next removal after the
reader is gone truncates the log again; a unit test shows a blocked
truncate_wal returns in under a second, leaves the log, and restores a
non-default busy timeout, and that the same call truncates once the reader is
gone. Both tests fail on the previous code.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Sonnet 5.5 committed 2026-10-20 10:21:49 +03:00
1 parent 2e026a043c
commit 0ac4095143
4 files changed
+225 -33

No files matched your search

+78 -19
View File
@@ -43,12 +43,16 @@
//!
//! The rows are private keys, so a removed row is not left behind in the file:
//! every connection sets `secure_delete`, which makes SQLite overwrite what it
//! deletes, and [`KeyStore::remove`] (which is how a sign-out deletes a key)
//! truncates the write-ahead log after it, as [`Store::delete_identity`] does,
//! so that the frame of the log that held the page with the key is gone too. A
//! checkpoint that another connection blocks cannot truncate; the removal still
//! succeeds and a warning says that the bytes stay in the log until the next
//! checkpoint (`Store::truncate_wal`).
//! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as
//! [`Store::delete_identity`] does, so that the frame of the log that held the
//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with
//! `remove`, truncates the log once, after its last step, not after each
//! removal. The checkpoint waits for another connection for a moment at most
//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it,
//! and then the removal still succeeds and a warning says that the deleted
//! bytes may stay in the log file, until a later checkpoint truncates the log,
//! later writes overwrite those frames, or the last connection to the database
//! closes and the log is deleted.
//!
//! The device key is never a synced copy. The account record names the Voelin key
//! that is the installation's device key, and [`KeyStore::sign_out`] deletes
@@ -68,6 +72,7 @@
//! lines.
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
use rusqlite::params;
@@ -75,8 +80,8 @@ use rusqlite::types::ValueRef;
use tsclientlib::Identity;
use voelin_identity::migrate::SELECT_ACCOUNT_COLUMNS;
use voelin_identity::{
AccountBinding, BlobError, IdentityBlob, IdentityInfo, KIND_ACCOUNT, KIND_TEAMSPEAK,
KIND_VOELIN, KeyStore, KeyStoreError,
AccountBinding, BlobError, DeviceKeyChoice, IdentityBlob, IdentityInfo, KIND_ACCOUNT,
KIND_TEAMSPEAK, KIND_VOELIN, KeyStore, KeyStoreError, SignOut, Uid,
};
use crate::{Error, Result, Store};
@@ -118,7 +123,8 @@ const PUT: &str = "INSERT INTO identities
/// access to the TeamSpeak methods of the same connection.
///
/// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as
/// `voelin-identity` defines them, on top of the five methods here.
/// `voelin-identity` defines them, on top of the five methods here; the
/// sign-out only truncates the write-ahead log once, at its end.
pub struct SqliteKeyStore {
store: Mutex<Store>,
}
@@ -238,18 +244,71 @@ impl KeyStore for SqliteKeyStore {
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
let store = self.lock();
let removed = store
.db
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
.map_err(backend)?
.execute(params![kind, uid])
.map_err(backend)?;
if removed > 0 {
// The row may be a key (a sign-out removes them one by one through
// this method): leave nothing of it in the log either.
let removed = delete_row(&store, kind, uid)?;
if removed {
// The row may be a key: leave nothing of it in the log either.
store.truncate_wal();
}
Ok(removed > 0)
Ok(removed)
}
/// The trait's sign-out, with the log truncated once after its last step
/// instead of after each of its removals: it removes up to a handful of
/// rows, and a checkpoint that another connection blocks costs a moment
/// (`Store::truncate_wal`) each time. The steps are the trait's own; they
/// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves
/// the checkpoint to this method.
fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult<SignOut> {
let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) };
let outcome = KeyStore::sign_out(&pass, account, device_key);
// Also after a failure: the removals before it have happened.
if pass.deleted.load(Ordering::Relaxed) {
self.lock().truncate_wal();
}
outcome
}
}
/// Delete the row of this `(kind, uid)`: whether there was one. The rows are
/// overwritten (`secure_delete`); the log is the caller's to truncate.
fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult<bool> {
let removed = store
.db
.prepare_cached("DELETE FROM identities WHERE kind = ?1 AND uid = ?2")
.map_err(backend)?
.execute(params![kind, uid])
.map_err(backend)?;
Ok(removed > 0)
}
/// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same
/// rows, but `remove` only notes that it deleted something, so that the sign-out
/// truncates the log once at its end.
struct SignOutPass<'a> {
store: &'a SqliteKeyStore,
/// Whether a row was deleted.
deleted: AtomicBool,
}
impl KeyStore for SignOutPass<'_> {
fn list(&self) -> KsResult<Vec<IdentityInfo>> {
self.store.list()
}
fn get(&self, kind: &str, uid: &str) -> KsResult<Option<IdentityBlob>> {
self.store.get(kind, uid)
}
fn put(&self, blob: &IdentityBlob) -> KsResult<()> {
self.store.put(blob)
}
fn remove(&self, kind: &str, uid: &str) -> KsResult<bool> {
let removed = delete_row(&self.store.lock(), kind, uid)?;
if removed {
self.deleted.store(true, Ordering::Relaxed);
}
Ok(removed)
}
}
+73 -9
View File
@@ -1,6 +1,7 @@
//! The SQLite database.
use std::path::Path;
use std::time::Duration;
use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use serde::de::DeserializeOwned;
@@ -237,6 +238,12 @@ impl Bookmark {
}
}
/// How long the checkpoint that follows the deletion of a key waits for another
/// connection ([`Store::truncate_wal`]). Short on purpose: the connection's own
/// busy timeout is seconds, and the checkpoint holds the writer lock while it
/// waits.
const CHECKPOINT_WAIT: Duration = Duration::from_millis(150);
pub struct Store {
pub(crate) db: Connection,
}
@@ -429,16 +436,22 @@ impl Store {
/// deleted.
///
/// It is best effort, because the delete it follows has happened and a
/// sign-out must still finish: a checkpoint that cannot complete (another
/// connection keeps reading an old snapshot for as long as the busy timeout)
/// or fails leaves the bytes in the log until the next checkpoint, and a
/// warning says so. It does nothing to a database that is not in WAL mode
/// and does not overwrite what was deleted before `secure_delete` was on
/// (`VACUUM` does).
/// sign-out must still finish. A checkpoint that cannot complete (another
/// connection keeps reading an old snapshot) or fails leaves the bytes in
/// the log file, and a warning says so; they go when a later checkpoint
/// truncates the log, when later writes overwrite those frames, or when the
/// last connection to the database closes and the log is deleted. It does
/// nothing to a database that is not in WAL mode and does not overwrite what
/// was deleted before `secure_delete` was on (`VACUUM` does).
///
/// It waits for another connection for [`CHECKPOINT_WAIT`] at most, not for
/// the busy timeout of the connection: while a checkpoint that truncates
/// waits for readers it holds the writer lock of the log, so every other
/// writer would wait with it, and fail with "database is locked" when its
/// own timeout is shorter than the wait. The timeout the connection had is
/// restored before this returns.
pub(crate) fn truncate_wal(&self) {
let blocked =
self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0));
match blocked {
match self.checkpoint_truncate() {
Ok(0) => {}
Ok(_) => tracing::warn!(
"a deleted key may stay in the write-ahead log: another connection blocked the checkpoint"
@@ -450,6 +463,20 @@ impl Store {
}
}
/// `PRAGMA wal_checkpoint(TRUNCATE)` under [`CHECKPOINT_WAIT`]: whether
/// another connection blocked it (`1`) or not (`0`).
fn checkpoint_truncate(&self) -> rusqlite::Result<i64> {
let previous: i64 = self.db.pragma_query_value(None, "busy_timeout", |r| r.get(0))?;
let previous = Duration::from_millis(u64::try_from(previous).unwrap_or_default());
self.db.busy_timeout(CHECKPOINT_WAIT)?;
let blocked =
self.db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |r| r.get::<_, i64>(0));
if let Err(error) = self.db.busy_timeout(previous) {
tracing::warn!(%error, "the busy timeout of the connection could not be restored");
}
blocked
}
// Bookmarks
pub fn add_bookmark(&self, bookmark: &Bookmark) -> Result<i64> {
@@ -588,6 +615,43 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_blocked_checkpoint_waits_briefly_and_leaves_the_busy_timeout_as_it_was() {
let dir = scratch_dir("blocked-checkpoint");
let path = dir.join("client.db");
let wal = dir.join("client.db-wal");
let store = Store::open(&path).unwrap();
store.add_identity("first", &Identity::create(), IdentityOrigin::User).unwrap();
// A reader whose snapshot is older than the last write keeps the log
// from being reset.
let reader = Connection::open(&path).unwrap();
reader.execute_batch("BEGIN").unwrap();
reader.query_row("SELECT count(*) FROM identities", [], |r| r.get::<_, i64>(0)).unwrap();
store.add_identity("second", &Identity::create(), IdentityOrigin::User).unwrap();
// A value that is not the default, so that restoring a constant would show.
let timeout = |store: &Store| -> i64 {
store.db.pragma_query_value(None, "busy_timeout", |r| r.get(0)).unwrap()
};
store.db.busy_timeout(Duration::from_millis(2345)).unwrap();
let started = std::time::Instant::now();
store.truncate_wal();
let elapsed = started.elapsed();
assert!(elapsed < Duration::from_secs(1), "the checkpoint waited {elapsed:?}");
assert!(std::fs::metadata(&wal).unwrap().len() > 0, "the reader should block the reset");
assert_eq!(timeout(&store), 2345);
// Without the reader the same call resets the log.
reader.execute_batch("COMMIT").unwrap();
store.truncate_wal();
assert_eq!(std::fs::metadata(&wal).unwrap().len(), 0);
assert_eq!(timeout(&store), 2345);
drop(reader);
drop(store);
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn the_default_identity() {
let store = Store::open_in_memory().unwrap();
+64 -1
View File
@@ -19,7 +19,8 @@
//! last section.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use rusqlite::{Connection, params};
use tsclientlib::Identity;
@@ -1542,6 +1543,68 @@ fn removing_through_the_key_store_leaves_no_key_behind_either() {
assert!(!store.remove(KIND_VOELIN, &device.uid).unwrap());
}
#[test]
fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer() {
// A connection that keeps a read snapshot (a long query of the UI, a backup)
// keeps the checkpoint that truncates the log from finishing. The sign-out
// still deletes and warns that the bytes may stay in the log, and it waits
// for the checkpoint a moment, not for the busy timeout of five seconds once
// per removed row. While the checkpoint waits it holds the writer lock of the
// log, so a second connection that writes meanwhile must get through.
let scratch = Scratch::new("blocked-checkpoint");
let store = SqliteKeyStore::open(&scratch.db()).unwrap();
store.put_voelin_key(&key()).unwrap();
store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap();
for copy in [fresh_teamspeak(binding()), fresh_teamspeak(binding())] {
store.put(&copy).unwrap();
}
// The snapshot is older than every removal below.
let reader = Connection::open(scratch.db()).unwrap();
reader.execute_batch("BEGIN").unwrap();
let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap();
assert_eq!(rows, 4);
let stop = AtomicBool::new(false);
let (done, elapsed, writes, errors) = std::thread::scope(|scope| {
let writer = scope.spawn(|| {
// Its own connection, which gives up on a lock after one second.
let db = Connection::open(scratch.db()).unwrap();
db.busy_timeout(Duration::from_secs(1)).unwrap();
let sql = "INSERT OR REPLACE INTO settings (key, value) VALUES ('probe', ?1)";
let (mut writes, mut errors) = (0, Vec::new());
while !stop.load(Ordering::Relaxed) {
match db.execute(sql, [writes.to_string()]) {
Ok(_) => writes += 1,
Err(error) => errors.push(error.to_string()),
}
std::thread::sleep(Duration::from_millis(5));
}
(writes, errors)
});
let started = Instant::now();
let done = store.sign_out(&binding().account, DeviceKeyChoice::Auto);
let elapsed = started.elapsed();
stop.store(true, Ordering::Relaxed);
let (writes, errors) = writer.join().unwrap();
(done.unwrap(), elapsed, writes, errors)
});
// Four removals: the two copies, the device key the client made, the record.
assert_eq!(done.removed.len(), 4, "{done:?}");
assert!(store.list().unwrap().is_empty());
assert!(writes > 0, "the writer never ran");
assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}");
assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}");
// Nothing is lost by the wait: once the reader is gone, the next removal
// truncates the log.
reader.execute_batch("COMMIT").unwrap();
store.put_voelin_key(&key()).unwrap();
assert!(store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap());
assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again");
}
// -------------------------------------- the device key is never a synced copy
//
// `KeyStore::sign_out` deletes everything bound with `synced = true` in its