Skip to content

Commit 6615a39

Browse files
committed
feat: Disable wal_autocheckpoint
From https://www.sqlite.org/wal.html: > The default strategy is to allow successive write transactions to grow the WAL until the WAL becomes about 1000 pages in size, then to run a checkpoint operation for each subsequent COMMIT until the WAL is reset to be smaller than 1000 pages. By default, the checkpoint will be run automatically by the same thread that does the COMMIT that pushes the WAL over its size limit. This has the effect of causing most COMMIT operations to be very fast but an occasional COMMIT (those that trigger a checkpoint) to be much slower. And while autocheckpoint runs in the `PASSIVE` mode and thus doesn't block concurrent readers and writers, in our design it blocks writers because it's done under `write_mutex` locked and thus may cause the app to stuck for noticeable time. Let's disable autocheckpointing then, we can't rely on it anyway. Instead, run a `TRUNCATE` checkpoint from `inbox_loop()` if the WAL is >= 4K pages and a `PASSIVE` checkpoint otherwise.
1 parent aa8dd72 commit 6615a39

File tree

4 files changed

+30
-9
lines changed

4 files changed

+30
-9
lines changed

src/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ impl Context {
413413

414414
/// Changes encrypted database passphrase.
415415
pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
416-
self.sql.change_passphrase(passphrase).await?;
416+
self.sql.change_passphrase(self, passphrase).await?;
417417
Ok(())
418418
}
419419

src/scheduler.rs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::location;
2626
use crate::log::{LogExt, error, info, warn};
2727
use crate::message::MsgId;
2828
use crate::smtp::{Smtp, send_smtp_messages};
29-
use crate::sql;
29+
use crate::sql::{self, Sql};
3030
use crate::tools::{self, duration_to_str, maybe_add_time_based_warnings, time, time_elapsed};
3131

3232
pub(crate) mod connectivity;
@@ -506,6 +506,11 @@ async fn inbox_fetch_idle(ctx: &Context, imap: &mut Imap, mut session: Session)
506506
last_housekeeping_time.saturating_add(constants::HOUSEKEEPING_PERIOD);
507507
if next_housekeeping_time <= time() {
508508
sql::housekeeping(ctx).await.log_err(ctx).ok();
509+
} else {
510+
let force_truncate = false;
511+
if let Err(err) = Sql::wal_checkpoint(ctx, force_truncate).await {
512+
warn!(ctx, "wal_checkpoint() failed: {err:#}.");
513+
}
509514
}
510515
}
511516
Err(err) => {

src/sql.rs

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -298,7 +298,11 @@ impl Sql {
298298
/// The database must already be encrypted and the passphrase cannot be empty.
299299
/// It is impossible to turn encrypted database into unencrypted
300300
/// and vice versa this way, use import/export for this.
301-
pub async fn change_passphrase(&self, passphrase: String) -> Result<()> {
301+
pub(crate) async fn change_passphrase(
302+
&self,
303+
_context: &Context,
304+
passphrase: String,
305+
) -> Result<()> {
302306
let mut lock = self.pool.write().await;
303307

304308
let pool = lock.take().context("SQL connection pool is not open")?;
@@ -646,8 +650,12 @@ impl Sql {
646650
&self.config_cache
647651
}
648652

649-
/// Runs a checkpoint operation in TRUNCATE mode, so the WAL file is truncated to 0 bytes.
650-
pub(crate) async fn wal_checkpoint(context: &Context) -> Result<()> {
653+
/// Runs a WAL checkpoint operation.
654+
///
655+
/// * `force_truncate` - Force TRUNCATE mode to truncate the WAL file to 0 bytes, otherwise only
656+
/// run PASSIVE mode if the WAL isn't too large. NB: Truncating blocks all db connections for
657+
/// some time.
658+
pub(crate) async fn wal_checkpoint(context: &Context, force_truncate: bool) -> Result<()> {
651659
let t_start = Time::now();
652660
let lock = context.sql.pool.read().await;
653661
let Some(pool) = lock.as_ref() else {
@@ -658,13 +666,19 @@ impl Sql {
658666
// Do as much work as possible without blocking anybody.
659667
let query_only = true;
660668
let conn = pool.get(query_only).await?;
661-
tokio::task::block_in_place(|| {
669+
let pages_total = tokio::task::block_in_place(|| {
662670
// Execute some transaction causing the WAL file to be opened so that the
663671
// `wal_checkpoint()` can proceed, otherwise it fails when called the first time,
664672
// see https://sqlite.org/forum/forumpost/7512d76a05268fc8.
665673
conn.query_row("PRAGMA table_list", [], |_| Ok(()))?;
666-
conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |_| Ok(()))
674+
conn.query_row("PRAGMA wal_checkpoint(PASSIVE)", [], |row| {
675+
let pages_total: i64 = row.get(1)?;
676+
Ok(pages_total)
677+
})
667678
})?;
679+
if !force_truncate && pages_total < 4096 {
680+
return Ok(());
681+
}
668682

669683
// Kick out writers.
670684
const _: () = assert!(Sql::N_DB_CONNECTIONS > 1, "Deadlock possible");
@@ -735,6 +749,7 @@ fn new_connection(path: &Path, passphrase: &str) -> Result<Connection> {
735749
PRAGMA busy_timeout = 0; -- fail immediately
736750
PRAGMA soft_heap_limit = 8388608; -- 8 MiB limit, same as set in Android SQLiteDatabase.
737751
PRAGMA foreign_keys=on;
752+
PRAGMA wal_autocheckpoint=N;
738753
",
739754
)?;
740755

@@ -843,7 +858,8 @@ pub async fn housekeeping(context: &Context) -> Result<()> {
843858
// bigger than 200M) and also make sure we truncate the WAL periodically. Auto-checkponting does
844859
// not normally truncate the WAL (unless the `journal_size_limit` pragma is set), see
845860
// https://www.sqlite.org/wal.html.
846-
if let Err(err) = Sql::wal_checkpoint(context).await {
861+
let force_truncate = true;
862+
if let Err(err) = Sql::wal_checkpoint(context, force_truncate).await {
847863
warn!(context, "wal_checkpoint() failed: {err:#}.");
848864
debug_assert!(false);
849865
}

src/sql/sql_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -263,7 +263,7 @@ async fn test_sql_change_passphrase() -> Result<()> {
263263
sql.open(&t, "foo".to_string())
264264
.await
265265
.context("failed to open the database second time")?;
266-
sql.change_passphrase("bar".to_string())
266+
sql.change_passphrase(&t, "bar".to_string())
267267
.await
268268
.context("failed to change passphrase")?;
269269

0 commit comments

Comments
 (0)