Skip to content

Commit 02c0366

Browse files
committed
disklayer_sqlite: Commit the cache flush transaction
Commit the WAL transaction with synchronous set to FULL. The transaction was previously rolled back on drop, so sync_cache could return success without syncing cached writes. Start writable connections in NORMAL mode to avoid a WAL sync on each write. Restore the original mode even when the flush fails. Test initialization on new and reopened disks. Verify that the WAL commit is visible and runs with synchronous set to FULL. Check that a rejected commit reports an error without changing the mode or preventing a later flush. Signed-off-by: Anatol Belski <anbelski@linux.microsoft.com>
1 parent 66bdba0 commit 02c0366

3 files changed

Lines changed: 135 additions & 4 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1869,6 +1869,7 @@ dependencies = [
18691869
"serde_json",
18701870
"storage_tests",
18711871
"tempfile",
1872+
"test_with_tracing",
18721873
"tracing",
18731874
"vm_resource",
18741875
]

‎vm/devices/storage/disklayer_sqlite/Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,9 @@ tracing.workspace = true
3737

3838
[dev-dependencies]
3939
pal_async.workspace = true
40+
rusqlite = { workspace = true, features = ["hooks"] }
4041
storage_tests.workspace = true
42+
test_with_tracing.workspace = true
4143

4244
# Building SQLite from source needs a C toolchain for the target, which the
4345
# macOS cross-compile lint job does not have. That job only lints and never

‎vm/devices/storage/disklayer_sqlite/src/lib.rs‎

Lines changed: 132 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -224,6 +224,10 @@ impl SqliteDiskLayer {
224224
serde_json::from_str(&data)?
225225
};
226226

227+
if !read_only {
228+
conn.pragma_update(None, "synchronous", "NORMAL")?;
229+
}
230+
227231
Ok(SqliteDiskLayer {
228232
conn: Arc::new(Mutex::new(conn)),
229233
meta,
@@ -377,14 +381,17 @@ impl LayerIo for SqliteDiskLayer {
377381
unblock({
378382
let mut conn = self.conn.clone().lock_owned().await;
379383
move || -> rusqlite::Result<()> {
384+
let previous_mode: u32 =
385+
conn.pragma_query_value(None, "synchronous", |row| row.get(0))?;
380386
// https://sqlite-users.sqlite.narkive.com/LX75NOma/forcing-a-manual-fsync-in-wal-normal-mode
381387
conn.pragma_update(None, "synchronous", "FULL")?;
382-
{
388+
let flush_result = (|| {
383389
let tx = conn.transaction()?;
384390
tx.pragma_update(None, "user_version", "0")?;
385-
}
386-
conn.pragma_update(None, "synchronous", "NORMAL")?;
387-
Ok(())
391+
tx.commit()
392+
})();
393+
let restore_result = conn.pragma_update(None, "synchronous", previous_mode);
394+
flush_result.and(restore_result)
388395
}
389396
})
390397
.await
@@ -585,10 +592,22 @@ mod tests {
585592
use crate::FormatParams;
586593
use crate::SqliteDiskLayer;
587594
use disk_backend::Disk;
595+
use disk_backend::DiskError;
588596
use disk_layered::DiskLayer;
589597
use disk_layered::LayerConfiguration;
598+
use disk_layered::LayerIo;
590599
use disk_layered::LayeredDisk;
600+
use guestmem::GuestMemory;
591601
use pal_async::async_test;
602+
use rusqlite::Connection;
603+
use rusqlite::hooks::AuthAction;
604+
use rusqlite::hooks::AuthContext;
605+
use rusqlite::hooks::Authorization;
606+
use scsi_buffers::OwnedRequestBuffers;
607+
use std::sync::Arc;
608+
use std::sync::atomic::AtomicBool;
609+
use std::sync::atomic::Ordering;
610+
use test_with_tracing::test;
592611

593612
const SECTOR_SIZE: u32 = 512;
594613
const DISK_SIZE: u64 = 1024 * 1024;
@@ -632,4 +651,113 @@ mod tests {
632651
let dir = tempfile::tempdir().unwrap();
633652
storage_tests::sector_range::test_layer_sector_range(&new_layer(&dir)).await;
634653
}
654+
655+
#[async_test]
656+
async fn writable_connection_starts_in_normal_mode() {
657+
let dir = tempfile::tempdir().unwrap();
658+
let layer = new_layer(&dir);
659+
for layer in [
660+
layer,
661+
SqliteDiskLayer::new(&dir.path().join("test.dbhd"), false, None).unwrap(),
662+
] {
663+
let mode: u32 = layer
664+
.conn
665+
.lock()
666+
.await
667+
.pragma_query_value(None, "synchronous", |row| row.get(0))
668+
.unwrap();
669+
assert_eq!(mode, 1, "expected synchronous=NORMAL");
670+
}
671+
}
672+
673+
#[async_test]
674+
async fn sync_cache_commits_wal_transaction() {
675+
let dir = tempfile::tempdir().unwrap();
676+
let layer = new_layer(&dir);
677+
let synchronous_full = Arc::new(AtomicBool::new(false));
678+
{
679+
let conn = layer.conn.lock().await;
680+
conn.pragma_update(None, "synchronous", "NORMAL").unwrap();
681+
let synchronous_full = synchronous_full.clone();
682+
// The commit hook cannot query this connection. Track mode changes
683+
// through the authorizer as SQLite prepares each PRAGMA assignment.
684+
conn.authorizer(Some(move |ctx: AuthContext<'_>| {
685+
if let AuthAction::Pragma {
686+
pragma_name,
687+
pragma_value: Some(value),
688+
} = ctx.action
689+
&& pragma_name.eq_ignore_ascii_case("synchronous")
690+
{
691+
synchronous_full.store(
692+
value.eq_ignore_ascii_case("FULL") || value == "2",
693+
Ordering::Relaxed,
694+
);
695+
}
696+
Authorization::Allow
697+
}));
698+
}
699+
let observer = Connection::open(dir.path().join("test.dbhd")).unwrap();
700+
let mem = GuestMemory::allocate(SECTOR_SIZE as usize);
701+
let buffers = OwnedRequestBuffers::linear(0, SECTOR_SIZE as usize, false);
702+
703+
for pattern in [0x5a, 0xa5] {
704+
mem.write_at(0, &[pattern; SECTOR_SIZE as usize]).unwrap();
705+
layer.write(&buffers.buffer(&mem), 7, false).await.unwrap();
706+
let before: u32 = observer
707+
.pragma_query_value(None, "data_version", |row| row.get(0))
708+
.unwrap();
709+
710+
let synchronous_full = synchronous_full.clone();
711+
layer
712+
.conn
713+
.lock()
714+
.await
715+
.commit_hook(Some(move || !synchronous_full.load(Ordering::Relaxed)));
716+
layer
717+
.sync_cache()
718+
.await
719+
.expect("cache flush must commit with synchronous=FULL");
720+
layer.conn.lock().await.commit_hook(None::<fn() -> bool>);
721+
722+
let after: u32 = observer
723+
.pragma_query_value(None, "data_version", |row| row.get(0))
724+
.unwrap();
725+
assert_ne!(
726+
before, after,
727+
"cache flush did not commit a WAL transaction"
728+
);
729+
}
730+
}
731+
732+
#[async_test]
733+
async fn sync_cache_reports_commit_error() {
734+
let dir = tempfile::tempdir().unwrap();
735+
let layer = new_layer(&dir);
736+
for (mode, expected) in [("NORMAL", 1), ("FULL", 2)] {
737+
{
738+
let conn = layer.conn.lock().await;
739+
conn.pragma_update(None, "synchronous", mode).unwrap();
740+
conn.commit_hook(Some(|| true));
741+
}
742+
743+
assert!(matches!(layer.sync_cache().await, Err(DiskError::Io(_))));
744+
745+
layer.conn.lock().await.commit_hook(None::<fn() -> bool>);
746+
for flush_succeeded in [false, true] {
747+
if flush_succeeded {
748+
layer.sync_cache().await.unwrap();
749+
}
750+
let synchronous: u32 = layer
751+
.conn
752+
.lock()
753+
.await
754+
.pragma_query_value(None, "synchronous", |row| row.get(0))
755+
.unwrap();
756+
assert_eq!(
757+
synchronous, expected,
758+
"expected synchronous={mode} after flush (success={flush_succeeded})"
759+
);
760+
}
761+
}
762+
}
635763
}

0 commit comments

Comments
 (0)