diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index a2a6200a9..8242a5a79 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -21,7 +21,7 @@ jobs: WSL-R-CMD-check: if: "! contains(github.event.head_commit.message, '[ci skip]')" runs-on: windows-latest - timeout-minutes: 240 + timeout-minutes: 200 name: windows-latest-WSL2 @@ -29,6 +29,7 @@ jobs: R_REMOTES_NO_ERRORS_FROM_WARNINGS: true GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true + TESTTHAT_PARALLEL: false CMDSTANR_OPENCL_TESTS: true steps: diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 5329657c8..a49746769 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -27,6 +27,7 @@ jobs: R-CMD-check: if: "! contains(github.event.head_commit.message, '[ci skip]')" runs-on: ${{ matrix.config.os }} + timeout-minutes: 150 name: ${{ matrix.config.os }} (${{ matrix.config.r }}) @@ -50,6 +51,7 @@ jobs: R_REMOTES_NO_ERRORS_FROM_WARNINGS: true GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true + TESTTHAT_CPUS: ${{ (matrix.config.os == 'macOS-latest' || matrix.config.os == 'macos-26') && 3 || 4 }} CMDSTANR_OPENCL_TESTS: ${{ matrix.config.opencl }} CMDSTAN_TEST_TARBALL_URL: ${{ github.event.inputs.tarball_url }} PKG_SYSREQS_DB_UPDATE_TIMEOUT: 30s @@ -165,15 +167,20 @@ jobs: - name: Install cmdstan run: | cmdstanr::check_cmdstan_toolchain() + cpp_options <- list() + if (Sys.info()[["sysname"]] == "Linux") { + cpp_options <- list("CPPFLAGS_SUNDIALS += -fPIC") + } tarball_url <- Sys.getenv("CMDSTAN_TEST_TARBALL_URL") if (nzchar(tarball_url)) { cmdstanr::install_cmdstan( cores = 2, overwrite = TRUE, - release_url = tarball_url + release_url = tarball_url, + cpp_options = cpp_options ) } else { - cmdstanr::install_cmdstan(cores = 2) + cmdstanr::install_cmdstan(cores = 2, cpp_options = cpp_options) } shell: Rscript {0} diff --git a/.github/workflows/Test-coverage.yaml b/.github/workflows/Test-coverage.yaml index ae1851317..ab41c4517 100644 --- a/.github/workflows/Test-coverage.yaml +++ b/.github/workflows/Test-coverage.yaml @@ -22,6 +22,7 @@ jobs: test-coverage: if: "! contains(github.event.head_commit.message, '[ci skip]')" runs-on: ${{ matrix.config.os }} + timeout-minutes: 150 name: ${{ matrix.config.os }} @@ -34,6 +35,7 @@ jobs: env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true + TESTTHAT_CPUS: 4 steps: - name: cmdstan env vars @@ -54,7 +56,11 @@ jobs: - name: Install cmdstan run: | cmdstanr::check_cmdstan_toolchain() - cmdstanr::install_cmdstan(cores = 2) + cpp_options <- list() + if (Sys.info()[["sysname"]] == "Linux") { + cpp_options <- list("CPPFLAGS_SUNDIALS += -fPIC") + } + cmdstanr::install_cmdstan(cores = 2, cpp_options = cpp_options) shell: Rscript {0} - name: Test coverage (Linux) diff --git a/DESCRIPTION b/DESCRIPTION index c73a30d97..0682e3f17 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -61,6 +61,7 @@ Imports: withr (>= 2.5.0) Suggests: bayesplot, + filelock, ggplot2, knitr (>= 1.37), loo (>= 2.0.0), @@ -73,4 +74,7 @@ Suggests: vctrs VignetteBuilder: knitr Config/testthat/edition: 3 +Config/testthat/parallel: true +Config/testthat/start-first: install, model-compile, fit-mcmc, + model-methods, model-rebuild, fit-shared Config/roxygen2/version: 8.1.1 diff --git a/R/utils.R b/R/utils.R index db166d68d..0d6196468 100644 --- a/R/utils.R +++ b/R/utils.R @@ -766,7 +766,14 @@ check_file_exists <- function(files, access = "", ...) { .wsl_check_exists <- function(path, is_dir = TRUE, access = "") { path_check <- processx::run( command = "wsl", - args = c("ls", "-la", wsl_safe_path(path)), + args = c( + "--exec", + "sh", + "-c", + 'ls -la "$1" && id -un', + "cmdstanr", + wsl_safe_path(path) + ), error_on_status = FALSE ) @@ -782,14 +789,8 @@ check_file_exists <- function(files, access = "", ...) { path_metadata <- strsplit(path_check$stdout, split = "\n", fixed = TRUE)[[1]] - wsl_user <- processx::run( - command = "wsl", - args = c("echo", "$USER"), - error_on_status = FALSE - )$stdout - wsl_user <- gsub("\n", "", wsl_user, fixed = TRUE) - - path_metadata <- grep(wsl_user, path_metadata, value = TRUE) + wsl_user <- utils::tail(path_metadata, 1) + path_metadata <- grep(wsl_user, utils::head(path_metadata, -1), value = TRUE) if (!is.null(access)) { path_permissions <- strsplit(path_metadata, " ", fixed = TRUE)[[1]][1] diff --git a/tests/testthat/README.md b/tests/testthat/README.md index e23666ef9..0f93db579 100644 --- a/tests/testthat/README.md +++ b/tests/testthat/README.md @@ -32,8 +32,17 @@ in `helper-mock-cli.R` stands in for `make` and for the executable's `info` call, so a test can go through the build code without a compiler. `mock_cmdstan_model()` wraps it and removes the stand-in executable and its record when the calling frame ends, so a later real compile of the same -program does not find them. `setup.R` removes everything but the `.stan` -files under `resources/stan/` before and after a run. +program does not find them. + +The full suite runs in parallel unless `TESTTHAT_PARALLEL=false`, with +`TESTTHAT_CPUS` workers, so files must not depend on each other or on the order +they run in. Each worker has its own copy of `resources/stan/` in +`tempdir()/stan`, which `setup.R` cleans of everything but the `.stan` files +before and after a run. Before the workers start, the first one to take a lock +in `setup.R` builds the precompiled headers and main objects that all of them +share in the CmdStan installation. A test that changes the installation +(`make/local`, `bin/`, a rebuild) calls `local_private_cmdstan()`, or +`local_cmdstan_make_local()`, which calls it, to work on a per-worker copy. `test-install.R` installs CmdStan from source, so it can be convenient to run single tests from it with the `desc` argument of `test_file()` rather than the diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index adb868421..c71c99a60 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -165,14 +165,81 @@ local_make_local_backup <- function(envir = parent.frame()) { invisible(NULL) } -# Write cpp_options to the make/local of the current CmdStan installation and -# restore its original contents (or absence) when `envir` exits. Called at the -# top level of a test file, the restore runs after all tests in that file. +# Switch to this worker's private CmdStan copy and write cpp_options to its +# make/local. When `envir` exits, restore the original make/local (or its +# absence) and switch back to the shared installation. Called at the top level +# of a test file, the whole file runs on the private copy. local_cmdstan_make_local <- function( cpp_options, envir = parent.frame(), append = TRUE ) { + local_private_cmdstan(envir = envir) local_make_local_backup(envir = envir) cmdstan_make_local(cpp_options = cpp_options, append = append) } + +private_cmdstan <- new.env(parent = emptyenv()) + +copy_cmdstan <- function(from, to) { + if (os_is_wsl()) { + wsl_compatible_run( + command = "cp", + args = c("-a", wsl_safe_path(from), wsl_safe_path(to)) + ) + return(invisible(TRUE)) + } + if (os_is_windows()) { + status <- system2( + "robocopy", + c( + shQuote(from), + shQuote(to), + "/E", + "/MT:16", + "/NFL", + "/NDL", + "/NJH", + "/NJS", + "/NP" + ), + stdout = FALSE + ) + failed <- status >= 8 + } else { + status <- system2("cp", c("-a", shQuote(from), shQuote(to))) + failed <- status != 0 + } + if (failed) { + stop("Could not copy '", from, "' to '", to, "'.", call. = FALSE) + } + invisible(TRUE) +} + +local_build_tempdir <- function(envir = parent.frame()) { + if (!os_is_wsl()) { + return(withr::local_tempdir("cmdstan-private-", .local_envir = envir)) + } + wsl_dir <- wsl_tempdir() + withr::defer( + wsl_compatible_run(command = "rm", args = c("-rf", wsl_dir)), + envir = envir + ) + wsl_safe_path(wsl_dir, revert = TRUE) +} + +# Point cmdstan_path() at this worker's private copy of the installation, made +# on first use, until `envir` exits. The copy is deleted at worker teardown. +local_private_cmdstan <- function(envir = parent.frame()) { + shared <- cmdstan_path() + if (is.null(private_cmdstan$path)) { + to <- file.path( + local_build_tempdir(testthat::teardown_env()), + basename(shared) + ) + copy_cmdstan(shared, to) + private_cmdstan$path <- to + } + suppressMessages(set_cmdstan_path(private_cmdstan$path)) + withr::defer(suppressMessages(set_cmdstan_path(shared)), envir = envir) +} diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index 7213c0027..8609a5061 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -6,7 +6,10 @@ testing_data <- function(name) { } } testing_stan_file <- function(name) { - test_path("resources", "stan", paste0(name, ".stan")) + stan_fixture(paste0(name, ".stan")) +} +stan_fixture <- function(...) { + file.path(tempdir(), "stan", ...) } local_include_model_with_spaces <- function(.local_envir = parent.frame()) { diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 4e7ea3c58..46b0ca74b 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -1,9 +1,18 @@ -# CI runners have four cores, so run two chains at a time +# Each worker runs two chains at a time; CI runs up to four workers. options(mc.cores = 2) +stan_dir <- stan_fixture() +dir.create(stan_dir, recursive = TRUE, showWarnings = FALSE) +file.copy( + list.files(test_path("resources", "stan"), full.names = TRUE), + stan_dir, + recursive = TRUE, + overwrite = TRUE +) + cleanup_stan_artifacts <- function() { all_files_in_stan <- list.files( - test_path("resources", "stan"), + stan_dir, full.names = TRUE, recursive = TRUE ) @@ -18,3 +27,49 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) + +# Build what every worker would otherwise build at once in the shared +# installation: the -fPIC SUNDIALS flag, and the precompiled headers and main +# objects for plain and threaded models. Concurrent builds corrupt these files, +# so the first worker to take the lock builds them and the rest wait. +if (identical(Sys.getenv("NOT_CRAN"), "true")) { + local({ + message("Preparing CmdStan in ", cmdstan_path(), " for the tests") + lock_dir <- tools::R_user_dir("cmdstanr", "cache") + dir.create(lock_dir, recursive = TRUE, showWarnings = FALSE) + lock <- filelock::lock(file.path(lock_dir, "test-warm-up.lock")) + withr::defer(filelock::unlock(lock)) + + # Workers killed during teardown leave their CmdStan copies behind + stale <- Sys.glob( + file.path(dirname(tempdir()), "Rtmp*", "cmdstan-private-*") + ) + unlink(stale[file.mtime(stale) < Sys.time() - 86400], recursive = TRUE) + + withr::with_options( + list(mc.cores = parallel::detectCores()), + check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), FALSE) + ) + for (make_args in list(character(), "STAN_THREADS=true")) { + flags <- c("PRECOMPILED_MODEL_HEADER", "CMDSTAN_MAIN_O") + output <- run_make( + c("-s", make_args, paste0("print-", flags)), + quiet = TRUE + )$stdout + header <- parse_make_print_flag(flags[1], output) + main_o <- parse_make_print_flag(flags[2], output) + targets <- c( + header, + sub("\\.hpp\\.gch$", ".d", header), + main_o, + sub("\\.o$", ".d", main_o) + ) + targets <- targets[nzchar(targets)] + # make fails on Windows when a target is already built + missing <- targets[!file.exists(file.path(cmdstan_path(), targets))] + if (length(missing) > 0) { + run_make(c("-j2", missing, make_args), quiet = TRUE) + } + } + }) +} diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index a96f27d48..13ed586ed 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -5,14 +5,15 @@ if (!nzchar(cmdstan_test_tarball_url)) { cmdstan_test_tarball_url <- NULL } -test_that("install_cmdstan() successfully installs cmdstan", { - dir <- withr::local_tempdir() +test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { + build_cores <- min(parallel::detectCores(), 4) + dir <- local_build_tempdir() withr::defer(set_cmdstan_path()) expect_message( expect_output( install_cmdstan( dir = dir, - cores = 2, + cores = build_cores, quiet = FALSE, overwrite = TRUE, release_url = cmdstan_test_tarball_url, @@ -24,6 +25,11 @@ test_that("install_cmdstan() successfully installs cmdstan", { "CmdStan path set", fixed = TRUE ) + expect_output( + rebuild_cmdstan(dir = cmdstan_path(), cores = build_cores), + paste0("CmdStan v", cmdstan_version(), " built"), + fixed = TRUE + ) }) test_that("install_cmdstan() errors if installation already exists", { @@ -133,7 +139,7 @@ test_that("install_cmdstan() errors if invalid version or URL", { test_that("install_cmdstan() installs from release_url", { skip_if(!is.null(cmdstan_test_tarball_url)) - dir <- withr::local_tempdir() + dir <- local_build_tempdir() url <- paste0( "https://github.com/stan-dev/cmdstan/releases/download/", "v2.37.0/cmdstan-2.37.0.tar.gz" @@ -211,15 +217,6 @@ test_that("check_cmdstan_toolchain() reports what is missing on Unix", { expect_error(check_cmdstan_toolchain(), err_msg_cpp, fixed = TRUE) }) -test_that("clean and rebuild works", { - set_cmdstan_path() - expect_output( - rebuild_cmdstan(cores = 2), - paste0("CmdStan v", cmdstan_version(), " built"), - fixed = TRUE - ) -}) - test_that("github_download_url constructs correct url", { expect_equal( github_download_url("FOO"), @@ -391,7 +388,7 @@ test_that("download_with_retries() drops GITHUB_PAT after auth failure", { }) test_that("install_cmdstan() installs from release_file", { - dir <- withr::local_tempdir() + dir <- local_build_tempdir() destfile <- file.path(withr::local_tempdir(), "cmdstan-2.37.0.tar.gz") download_with_retries( paste0( @@ -777,6 +774,7 @@ test_that("install_cmdstan() rejects a non-logical copy_make_local", { }) test_that("cmdstan_make_local() works", { + local_private_cmdstan() # Backup only, cmdstan_make_local() is the thing being tested. local_make_local_backup() diff --git a/tests/testthat/test-knitr.R b/tests/testthat/test-knitr.R index 38b10fa66..4cd8d60e9 100644 --- a/tests/testthat/test-knitr.R +++ b/tests/testthat/test-knitr.R @@ -12,10 +12,10 @@ test_that("eng_cmdstan works", { skip_if_not_installed("knitr") code <- " parameters { - real y; + real knitr_y; } model { - y ~ std_normal(); + knitr_y ~ std_normal(); } " opts <- knitr::opts_chunk$merge(list( diff --git a/tests/testthat/test-model-compile.R b/tests/testthat/test-model-compile.R index c9f6f8048..c38b7dd0c 100644 --- a/tests/testthat/test-model-compile.R +++ b/tests/testthat/test-model-compile.R @@ -43,7 +43,7 @@ test_that("compiling works with spaces in path", { stan_file <- testing_stan_file("bernoulli") stan_model_with_spaces <- testing_stan_file("folder spaces/bernoulli spaces") - dir_with_spaces <- test_path("resources", "stan", "folder spaces") + dir_with_spaces <- stan_fixture("folder spaces") if (!file.exists(dir_with_spaces)) { dir.create(dir_with_spaces) } @@ -73,7 +73,7 @@ test_that("compilation works with include_paths", { cmdstan_model( stan_file = stan_program_w_include, quiet = TRUE, - include_paths = test_path("resources", "stan"), + include_paths = stan_fixture(), force_recompile = TRUE ) ) @@ -555,7 +555,7 @@ test_that("check_syntax() works with include_paths on compiled model", { mod_w_include <- cmdstan_model( stan_file = stan_program_w_include, - include_paths = test_path("resources", "stan") + include_paths = stan_fixture() ) expect_true(mod_w_include$check_syntax()) }) @@ -1025,7 +1025,7 @@ test_that("format() works with include_paths on compiled model", { mod_w_include <- cmdstan_model( stan_file = stan_program_w_include, - include_paths = test_path("resources", "stan") + include_paths = stan_fixture() ) expect_output( mod_w_include$format(), diff --git a/tests/testthat/test-model-methods.R b/tests/testthat/test-model-methods.R index a27aa9169..66bf9b20a 100644 --- a/tests/testthat/test-model-methods.R +++ b/tests/testthat/test-model-methods.R @@ -199,9 +199,15 @@ test_that("model methods don't export Stan Math's autodiff stack", { getLoadedDLLs() ) expect_gt(length(dlls), 0) - for (dll in dlls) { - expect_false(is.loaded(instance, PACKAGE = dll[["name"]])) - } + expect_false( + any( + vapply( + dlls, + function(dll) is.loaded(instance, PACKAGE = dll[["name"]]), + logical(1) + ) + ) + ) }) test_that("Model methods environments are independent", { diff --git a/tests/testthat/test-model-rebuild-rules.R b/tests/testthat/test-model-rebuild-rules.R index 315c21f71..c9ece1857 100644 --- a/tests/testthat/test-model-rebuild-rules.R +++ b/tests/testthat/test-model-rebuild-rules.R @@ -607,8 +607,8 @@ test_that("filename-in-msg supplied unnamed is not added again", { expect_match(hpp, "published.stan", fixed = TRUE) }) -# Writes the shared installation's make/local, so it runs last and once. test_that("an edited make/local rebuilds", { + local_private_cmdstan() stan_file <- local_bernoulli() mocked(expect_mock_compile(cmdstan_model(stan_file))) diff --git a/tests/testthat/test-model-rebuild.R b/tests/testthat/test-model-rebuild.R index c818f746e..9e151d80f 100644 --- a/tests/testthat/test-model-rebuild.R +++ b/tests/testthat/test-model-rebuild.R @@ -4,7 +4,7 @@ set_cmdstan_path() # A fresh copy of a resources/stan/ program (with its include file, for # bernoulli_include) in its own directory, so a build never touches the -# shared copy under resources/stan/. +# per-worker copy under tempdir()/stan. local_program <- function(name = "bernoulli", .local_envir = parent.frame()) { dir <- withr::local_tempdir(.local_envir = .local_envir) file.copy(testing_stan_file(name), dir) diff --git a/tests/testthat/test-path.R b/tests/testthat/test-path.R index 4f273bd45..5f433a52c 100644 --- a/tests/testthat/test-path.R +++ b/tests/testthat/test-path.R @@ -16,6 +16,24 @@ test_that("Setting path works and confirms with message", { expect_equal(.cmdstanr$PATH, PATH) }) +test_that("WSL file checks handle quoted paths, missing paths, and permissions", { + skip_if_not(os_is_wsl()) + dir <- withr::local_tempdir() + path <- file.path(dir, "file with 'quotes'.txt") + writeLines("test", path) + + expect_true(check_dir_exists(dir, access = "rwx")) + expect_true(check_file_exists(path, access = "r")) + expect_match(check_dir_exists(file.path(dir, "missing")), "does not exist") + expect_match(check_file_exists(paste0(path, "-missing")), "does not exist") + + dir <- local_build_tempdir() + path <- file.path(dir, "unreadable.txt") + writeLines("test", path) + wsl_compatible_run(command = "chmod", args = c("000", wsl_safe_path(path))) + expect_match(check_file_exists(path, access = "r"), "access permission r") +}) + test_that("Setting bad path leads to warning (can't find directory)", { unset_cmdstan_path() expect_null(.cmdstanr$PATH) diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index 3d5deca12..e3fb2e424 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -175,6 +175,7 @@ test_that("check_ebfmi and computing ebfmi works", { # cmdstan utilities ------------------------------------------------------- test_that("cmdstan_summary works if bin/stansummary deleted file", { + local_private_cmdstan() delete_and_run <- function() { file.remove(file.path(cmdstan_path(), "bin", cmdstan_ext("stansummary"))) fit_mcmc$cmdstan_summary() @@ -183,6 +184,7 @@ test_that("cmdstan_summary works if bin/stansummary deleted file", { }) test_that("cmdstan_diagnose works if bin/diagnose deleted file", { + local_private_cmdstan() delete_and_run <- function() { file.remove(file.path(cmdstan_path(), "bin", cmdstan_ext("diagnose"))) fit_mcmc$cmdstan_diagnose() @@ -639,6 +641,7 @@ test_that("make_shell_quote() survives Make expansion and shell splitting (#1230 }) test_that("local_make_local_backup() heals residue and nests", { + local_private_cmdstan() make_local_path <- file.path(cmdstan_path(), "make", "local") original <- if (file.exists(make_local_path)) { readBin(make_local_path, "raw", file.size(make_local_path))