diff --git a/NEWS.md b/NEWS.md index c346d5a..f2fc9a9 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,10 @@ # climateData (development version) +- `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". + `ClimateNA_sql()` gets a `readonly` argument; writing connections set WAL only when they create the file. + - Solar radiation variables now use the ClimateNA v7.60+ names: `rsds` (annual; was `MAR`), `rsds_wt`, `rsds_sp`, `rsds_sm`, `rsds_at` (seasonal; were `Rad_*`) and `rsds01`-`rsds12` (monthly; were `Rad01`-`Rad12`). ClimateNA v7.60 (April 2025) replaced its RAD variables with rsds, based on CHELSA. Only the historical diff --git a/R/ClimateNA_createTiles.R b/R/ClimateNA_createTiles.R index dc95f91..3e77095 100644 --- a/R/ClimateNA_createTiles.R +++ b/R/ClimateNA_createTiles.R @@ -78,8 +78,8 @@ ClimateNA_path <- function(dataPath, tile = NULL, type = NULL, msy = NULL, gcm = #' @keywords internal #' @importFrom DBI dbExecute #' @importFrom RSQLite dbConnect SQLite -sqlite_connect_db <- function(dbfile) { - firstRun <- file.exists(dbfile) +sqlite_connect_db <- function(dbfile, readonly = FALSE) { + newDb <- !file.exists(dbfile) ## `extended_types = TRUE` makes RSQLite return DATETIME columns as hms / ## POSIXct, which requires the `hms` package AT RUNTIME. RSQLite declares hms @@ -95,13 +95,21 @@ sqlite_connect_db <- function(dbfile) { db <- RSQLite::dbConnect( drv = RSQLite::SQLite(), dbname = dbfile, - synchronous = "normal", + ## `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 ) - if (isTRUE(firstRun)) { - DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency - DBI::dbExecute(db, "PRAGMA busy_timeout = 60000") ## set busy timeout (ms); allows concurrency. + ## 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)) { + DBI::dbExecute(db, "PRAGMA synchronous = normal") + if (isTRUE(newDb)) { + DBI::dbExecute(db, "PRAGMA journal_mode = WAL") ## using WAL allows concurrency + } } return(db) @@ -113,6 +121,9 @@ sqlite_connect_db <- function(dbfile) { #' #' @template ClimateNA_type #' +#' @param readonly logical. If `TRUE`, open the database read-only (it is never written to, and a missing +#' table is not created). Use for lookups, so that many processes can read one database at once. +#' #' @return named list containing: #' - `db`, the database connection; #' - `df`, a lazy `tbl_dbi` object (see `dbplyr`). @@ -125,8 +136,8 @@ sqlite_connect_db <- function(dbfile) { #' @rdname ClimateNA_sql ## dplyr::tbl() on a DBI connection needs dbplyr at run time (dplyr's check_dbplyr() stops without it), so ## dbplyr is an Import: without it every tile lookup fails, as R CMD check without Suggests showed. -ClimateNA_sql <- function(dbfile, type) { - db <- sqlite_connect_db(dbfile) +ClimateNA_sql <- function(dbfile, type, readonly = FALSE) { + db <- sqlite_connect_db(dbfile, readonly = readonly) df_template <- switch( type, @@ -182,7 +193,7 @@ ClimateNA_sql <- function(dbfile, type) { tbl <- type - if (!DBI::dbExistsTable(db, tbl)) { + if (!isTRUE(readonly) && !DBI::dbExistsTable(db, tbl)) { DBI::dbCreateTable(db, tbl, df_template) } diff --git a/R/ClimateNA_useTiles.R b/R/ClimateNA_useTiles.R index b61a4d8..5c5f29e 100644 --- a/R/ClimateNA_useTiles.R +++ b/R/ClimateNA_useTiles.R @@ -56,7 +56,7 @@ getClimateTable <- function( stopifnot(!is.null(years)) } - dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), type) + dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), type, readonly = TRUE) climate_db <- dbdf[["db"]] climate_df <- dbdf[["df"]] on.exit(DBI::dbDisconnect(climate_db), add = TRUE) diff --git a/R/latestHistoricalYear.R b/R/latestHistoricalYear.R index 4aca213..242c8ef 100644 --- a/R/latestHistoricalYear.R +++ b/R/latestHistoricalYear.R @@ -18,7 +18,7 @@ #' @examples #' latestHistoricalYear() latestHistoricalYear <- function(tile = NULL, msy = "MSY") { - dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical") + dbdf <- ClimateNA_sql(ClimateNA_tiles_sqlite(), "historical", readonly = TRUE) on.exit(DBI::dbDisconnect(dbdf[["db"]]), add = TRUE) climate_df <- dplyr::filter(dbdf[["df"]], msy %in% !!msy) |> diff --git a/man/ClimateNA_sql.Rd b/man/ClimateNA_sql.Rd index 26dafc6..b035e02 100644 --- a/man/ClimateNA_sql.Rd +++ b/man/ClimateNA_sql.Rd @@ -5,7 +5,7 @@ \alias{checksums_sql} \title{Connect to ClimateNA tile and checksums database} \usage{ -ClimateNA_sql(dbfile, type) +ClimateNA_sql(dbfile, type, readonly = FALSE) checksums_sql(dbfile, type) } @@ -14,6 +14,9 @@ checksums_sql(dbfile, type) \item{type}{character. denotes the table in the sqlite database to access. one of 'historical', 'future', 'historical_normals', or 'future_normals'.} + +\item{readonly}{logical. If \code{TRUE}, open the database read-only (it is never written to, and a missing +table is not created). Use for lookups, so that many processes can read one database at once.} } \value{ named list containing: diff --git a/tests/testthat/test-sqliteConcurrency.R b/tests/testthat/test-sqliteConcurrency.R new file mode 100644 index 0000000..bc553cf --- /dev/null +++ b/tests/testthat/test-sqliteConcurrency.R @@ -0,0 +1,72 @@ +## latestHistoricalYear() and the tile lookup run in many processes at once (every parse of a +## fireSense module calls it). They must only read the index, so concurrent opens must not fail with +## "database is locked". + +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) + testthat::local_mocked_bindings(ClimateNA_tiles_sqlite = function() f) + expected <- latestHistoricalYear() + + ## R CMD check caps forked workers at 2 (_R_CHECK_LIMIT_CORES_) + nWorkers <- if (nzchar(Sys.getenv("_R_CHECK_LIMIT_CORES_"))) 2L else 8L + res <- parallel::mclapply(seq_len(nWorkers), function(i) { + t0 <- Sys.time() + out <- character() + while (difftime(Sys.time(), t0, units = "secs") < 10) { + r <- tryCatch(identical(latestHistoricalYear(), expected), error = function(e) conditionMessage(e)) + if (!isTRUE(r)) out <- c(out, as.character(r)) + } + out + }, mc.cores = nWorkers) + + errs <- unlist(res) + expect_identical(unique(errs), character(0), info = paste(head(errs, 3), collapse = "; ")) +}) + +test_that("a read-only lookup neither writes nor creates tables", { + f <- dbCopy() + on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) + + dbdf <- ClimateNA_sql(f, "historical", readonly = TRUE) + expect_error(DBI::dbExecute(dbdf[["db"]], "DELETE FROM historical"), "readonly") + DBI::dbDisconnect(dbdf[["db"]]) + + ## a table that does not exist is not created on a read path + con <- DBI::dbConnect(RSQLite::SQLite(), f) + DBI::dbExecute(con, "DROP TABLE IF EXISTS future_normals") + DBI::dbDisconnect(con) + expect_error(ClimateNA_sql(f, "future_normals", readonly = TRUE)) + con <- DBI::dbConnect(RSQLite::SQLite(), f) + on.exit(DBI::dbDisconnect(con), add = TRUE) + expect_false(DBI::dbExistsTable(con, "future_normals")) +}) + +test_that("a lookup waits for a lock held by another process instead of failing", { + f <- dbCopy() + on.exit(unlink(paste0(f, c("", "-wal", "-shm"))), add = TRUE) + ## rollback-journal mode, where a writer's lock blocks readers + 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) + + holder <- parallel::mcparallel({ + con <- DBI::dbConnect(RSQLite::SQLite(), f) + DBI::dbExecute(con, "BEGIN EXCLUSIVE") + Sys.sleep(2) + DBI::dbExecute(con, "COMMIT") + DBI::dbDisconnect(con) + }) + Sys.sleep(0.5) ## let the holder take its lock + expect_no_error(latestHistoricalYear()) + parallel::mccollect(holder) +})