Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# climateData (development version)

- Reading the bundled tile index (`latestHistoricalYear()`, the tile lookup in `ClimateNA_useTiles()`) no longer
writes `-wal`/`-shm` files into the installed package folder. Read-only `ClimateNA_sql()` connections open the
file with SQLite's `immutable=1`, and the bundled index is shipped in rollback-journal mode instead of WAL.

- `latestHistoricalYear()` and the tile lookup in `ClimateNA_useTiles()` open the bundled tile index read-only
and set the SQLite busy timeout before any other statement. Before, many processes opening it together
(e.g. parallel hindcast jobs parsing fireSense modules on NFS) could fail with "database is locked".
Expand Down
32 changes: 27 additions & 5 deletions R/ClimateNA_createTiles.R
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,20 @@ ClimateNA_path <- function(dataPath, tile = NULL, type = NULL, msy = NULL, gcm =
})()
}

#' SQLite `file:` URI that opens `dbfile` immutably
#'
#' POSIX paths give `file:///home/...`; Windows paths give `file:///C:/...` (backslashes become `/`, the
#' drive colon stays). The rest of the path is percent-encoded.
#'
#' @keywords internal
sqlite_immutable_uri <- function(dbfile) {
path <- gsub("\\", "/", normalizePath(dbfile, winslash = "/", mustWork = FALSE), fixed = TRUE)
drive <- if (grepl("^[A-Za-z]:", path)) substr(path, 1L, 2L) else ""
rest <- substring(path, nchar(drive) + 1L)
rest <- gsub("%2F", "/", utils::URLencode(rest, reserved = TRUE), fixed = TRUE)
paste0("file://", if (nzchar(drive)) "/", drive, rest, "?immutable=1")
}

#' @keywords internal
#' @importFrom DBI dbExecute
#' @importFrom RSQLite dbConnect SQLite
Expand All @@ -92,23 +106,31 @@ sqlite_connect_db <- function(dbfile, readonly = FALSE) {
## builds a library containing only this package's Depends/Imports/LinkingTo.
## climateData therefore declares hms in its own Imports: the requirement is
## real and RSQLite does not state it correctly.
## A read-only connection opens the file with SQLite's `immutable=1` URI parameter: SQLite then takes no
## locks and creates no `-wal`/`-shm` files, so reading never writes beside the database (e.g. into the
## installed package folder, which may be read-only or shared). Use it only for a file nobody is changing.
## RSQLite hands a `file:` URI straight to SQLite, so no extra flag is needed beyond `SQLITE_RO`.
dbname <- if (isTRUE(readonly)) sqlite_immutable_uri(dbfile) else dbfile

db <- RSQLite::dbConnect(
drv = RSQLite::SQLite(),
dbname = dbfile,
dbname = dbname,
## `synchronous = NULL`: dbConnect would otherwise run `PRAGMA synchronous` before any busy timeout
## is set, which fails at once with "database is locked" when other processes have the file open.
synchronous = NULL,
flags = if (isTRUE(readonly)) RSQLite::SQLITE_RO else RSQLite::SQLITE_RWC,
extended_types = TRUE ## for DATETIME -- see note above re: hms
)

## must come first: every statement below waits (ms) for a lock instead of failing at once
DBI::dbExecute(db, "PRAGMA busy_timeout = 60000")

if (!isTRUE(readonly)) {
## must come first: every statement below waits (ms) for a lock instead of failing at once
DBI::dbExecute(db, "PRAGMA busy_timeout = 60000")
DBI::dbExecute(db, "PRAGMA synchronous = normal")
if (isTRUE(newDb)) {
DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency
## WAL allows concurrent writers while building. Switch back to `journal_mode = DELETE` before the
## file is shipped in inst/extdata (see data-raw/06-archive_fingerprints.R): a WAL file creates
## `-wal`/`-shm` files beside it even when only read.
DBI::dbExecute(db, "PRAGMA journal_mode = WAL")
}
}

Expand Down
1 change: 1 addition & 0 deletions data-raw/06-archive_fingerprints.R
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ db <- sqlite_connect_db(wrkngDBfile)
n <- .archivesUpsert(db, fingerprints)
message(n, " fingerprints written; ", sum(is.na(fingerprints$verified)), " zips not verified")
DBI::dbExecute(db, "PRAGMA wal_checkpoint(TRUNCATE)")
DBI::dbExecute(db, "PRAGMA journal_mode = DELETE") ## ship in rollback-journal mode: reading a WAL file writes -wal/-shm beside it
DBI::dbDisconnect(db)
stopifnot(!file.exists(paste0(wrkngDBfile, "-wal")) || file.size(paste0(wrkngDBfile, "-wal")) == 0)

Expand Down
Binary file modified inst/extdata/ClimateNA_tiles.sqlite
Binary file not shown.
13 changes: 13 additions & 0 deletions man/sqlite_immutable_uri.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions tests/testthat/helper-sqlite.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
## A copy of the shipped tile index in its own temporary folder (removed when the calling test ends),
## so a test can tell whether anything else appears beside it.
dbCopy <- function(env = parent.frame()) {
d <- tempfile("extdata")
dir.create(d)
f <- file.path(d, "ClimateNA_tiles.sqlite")
file.copy(ClimateNA_tiles_sqlite(), f)
withr::defer({
Sys.chmod(d, "755")
unlink(d, recursive = TRUE)
}, envir = env)
f
}
33 changes: 23 additions & 10 deletions tests/testthat/test-sqliteConcurrency.R
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,6 @@

skip_on_os("windows") ## uses forked workers

dbCopy <- function() {
f <- tempfile(fileext = ".sqlite")
file.copy(ClimateNA_tiles_sqlite(), f)
f
}

test_that("parallel latestHistoricalYear() calls on one database do not fail", {
f <- dbCopy()
on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE)
Expand Down Expand Up @@ -50,23 +44,42 @@ test_that("a read-only lookup neither writes nor creates tables", {
expect_false(DBI::dbExistsTable(con, "future_normals"))
})

test_that("a lookup waits for a lock held by another process instead of failing", {
test_that("writing connections wait for each other's lock; an immutable read does not", {
f <- dbCopy()
on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE)
## rollback-journal mode, where a writer's lock blocks readers
## rollback-journal mode, as shipped, where a writer's lock blocks other connections
con <- DBI::dbConnect(RSQLite::SQLite(), f)
DBI::dbExecute(con, "PRAGMA journal_mode = DELETE")
DBI::dbDisconnect(con)
testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f)
nRows <- function() {
d <- ClimateNA_sql(f, "historical", readonly = TRUE)
on.exit(DBI::dbDisconnect(d[["db"]]))
nrow(dplyr::collect(d[["df"]]))
}
nBefore <- nRows()

holder <- parallel::mcparallel({
con <- DBI::dbConnect(RSQLite::SQLite(), f)
DBI::dbExecute(con, "BEGIN EXCLUSIVE")
Sys.sleep(2)
Sys.sleep(3)
DBI::dbExecute(con, "COMMIT")
DBI::dbDisconnect(con)
})
Sys.sleep(0.5) ## let the holder take its lock
expect_no_error(latestHistoricalYear())

## the immutable read ignores the lock: it neither waits nor fails
t0 <- Sys.time()
expect_no_error(yr <- latestHistoricalYear())
expect_lt(as.numeric(difftime(Sys.time(), t0, units = "secs")), 2)

## a second writing connection waits for the lock (busy_timeout) instead of failing, then writes
t0 <- Sys.time()
w <- ClimateNA_sql(f, "historical")
expect_no_error(DBI::dbExecute(w[["db"]], "DELETE FROM historical WHERE rowid = (SELECT max(rowid) FROM historical)"))
DBI::dbDisconnect(w[["db"]])
expect_gt(as.numeric(difftime(Sys.time(), t0, units = "secs")), 1)
parallel::mccollect(holder)

expect_identical(nRows(), nBefore - 1L)
})
51 changes: 51 additions & 0 deletions tests/testthat/test-sqliteReadOnlyNoWrites.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
## Reading the shipped tile index must not write anything beside it (no -wal/-shm files, no change to the
## database file), also when the folder is read-only (read-only installs, hard-linked or shared libraries).

dbState <- function(f) {
list(files = list.files(dirname(f), all.files = TRUE, no.. = TRUE),
size = file.size(f), mtime = file.mtime(f), md5 = unname(tools::md5sum(f)))
}

lookup <- function() {
dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical", readonly = TRUE)
on.exit(DBI::dbDisconnect(dbdf[["db"]]), add = TRUE)
dplyr::collect(dplyr::arrange(dplyr::filter(dbdf[["df"]], tileid <= 20L), rowid))
}

test_that("the shipped tile index is not in WAL mode", {
con <- DBI::dbConnect(RSQLite::SQLite(), dbCopy(), flags = RSQLite::SQLITE_RO)
on.exit(DBI::dbDisconnect(con))
expect_identical(DBI::dbGetQuery(con, "PRAGMA journal_mode")[[1]], "delete")
})

test_that("read-only lookups write nothing beside the database", {
f <- dbCopy()
testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f)
before <- dbState(f)
res <- lookup()
yr <- latestHistoricalYear()
expect_identical(dbState(f), before)
expect_gt(nrow(res), 0L)
expect_true(is.numeric(yr) || is.integer(yr))
})

test_that("read-only lookups work in a read-only folder and give the same rows", {
f <- dbCopy()
testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f)
expected <- lookup()
expectedYr <- latestHistoricalYear()
Sys.chmod(dirname(f), "555")
before <- dbState(f)
expect_identical(lookup(), expected)
expect_identical(latestHistoricalYear(), expectedYr)
expect_identical(dbState(f), before)

## Windows ignores folder modes, and root can write anywhere: then only the assertions above ran
skip_if(file.access(dirname(f), 2) == 0, "cannot make a folder read-only here (Windows or root)")
})

test_that("the immutable URI is built for POSIX and Windows paths", {
expect_identical(sqlite_immutable_uri("C:\\Users\\a b\\x.sqlite"), "file:///C:/Users/a%20b/x.sqlite?immutable=1")
skip_on_os("windows") ## normalizePath() adds a drive letter to a POSIX path
expect_identical(sqlite_immutable_uri("/home/a b/x#.sqlite"), "file:///home/a%20b/x%23.sqlite?immutable=1")
})
Loading