From ba7dbbfe491d978494ee0c4ded830130d22134b2 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Tue, 13 Oct 2026 11:22:07 -0700 Subject: [PATCH 01/32] Trying to parallelize tests --- DESCRIPTION | 2 ++ tests/testthat/helper-models.R | 5 ++++- tests/testthat/setup.R | 16 +++++++++++++++- tests/testthat/test-install.R | 8 ++++++-- tests/testthat/test-model-compile.R | 8 ++++---- tests/testthat/test-path.R | 3 ++- 6 files changed, 33 insertions(+), 9 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index c73a30d97..4c824456a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -73,4 +73,6 @@ Suggests: vctrs VignetteBuilder: knitr Config/testthat/edition: 3 +Config/testthat/parallel: true +Config/testthat/start-first: test-install.R Config/roxygen2/version: 8.1.1 diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index 7d55b2aac..0077d6f18 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..b05870386 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -1,9 +1,17 @@ # CI runners have four cores, so run two chains at a time options(mc.cores = 2) +stan_dir <- file.path(tempdir(), "stan") +dir.create(stan_dir, recursive = TRUE, showWarnings = FALSE) +file.copy( + list.files(test_path("resources", "stan"), full.names = TRUE), + stan_dir, + recursive = TRUE +) + cleanup_stan_artifacts <- function() { all_files_in_stan <- list.files( - test_path("resources", "stan"), + stan_dir, full.names = TRUE, recursive = TRUE ) @@ -18,3 +26,9 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) + +shared_cmdstan <- cmdstan_path() +worker_cmdstan <- file.path(tempdir(), "cmdstan", basename(shared_cmdstan)) +dir.create(dirname(worker_cmdstan), recursive = TRUE, showWarnings = FALSE) +file.copy(shared_cmdstan, dirname(worker_cmdstan), recursive = TRUE) +Sys.setenv(CMDSTAN = worker_cmdstan) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 87579c8bd..a411a997a 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -161,9 +161,13 @@ test_that("check_cmdstan_toolchain() reports what is missing on Unix", { }) test_that("clean and rebuild works", { - set_cmdstan_path() + dir <- withr::local_tempdir() + withr::defer(set_cmdstan_path()) + install_cmdstan(dir = dir, cores = 2, quiet = TRUE, overwrite = TRUE, + release_url = cmdstan_test_tarball_url, + wsl = os_is_wsl()) expect_output( - rebuild_cmdstan(cores = 2), + rebuild_cmdstan(dir = cmdstan_path(), cores = 2), paste0("CmdStan v", cmdstan_version(), " built"), fixed = TRUE ) diff --git a/tests/testthat/test-model-compile.R b/tests/testthat/test-model-compile.R index 449d766f7..93c4279c6 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) } @@ -68,7 +68,7 @@ test_that("compilation works with include_paths", { mod_w_include <- expect_compilation( cmdstan_model(stan_file = stan_program_w_include, quiet = TRUE, - include_paths = test_path("resources", "stan"), + include_paths = stan_fixture(), force_recompile = TRUE) ) expect_equal( @@ -520,7 +520,7 @@ test_that("check_syntax() works with include_paths on compiled model", { stan_program_w_include <- testing_stan_file("bernoulli_include") 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()) }) @@ -980,7 +980,7 @@ test_that("format() works with include_paths on compiled model", { stan_program_w_include <- testing_stan_file("bernoulli_include") 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(), "#include ", diff --git a/tests/testthat/test-path.R b/tests/testthat/test-path.R index d491e5e10..cf6e703cc 100644 --- a/tests/testthat/test-path.R +++ b/tests/testthat/test-path.R @@ -1,5 +1,6 @@ skip_on_cran() +worker_cmdstan <- Sys.getenv("CMDSTAN") Sys.unsetenv("CMDSTAN") PATH <- absolute_path(set_cmdstan_path()) VERSION <- cmdstan_version() @@ -312,5 +313,5 @@ test_that("is_release_candidate() works", { }) # cleanup ----------------------------------------------------------------- -Sys.unsetenv("CMDSTAN") +Sys.setenv(CMDSTAN = worker_cmdstan) unset_cmdstan_path() From 6c8d5fc3a7bed5a79409580d709340b477205470 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Tue, 13 Oct 2026 17:47:25 -0700 Subject: [PATCH 02/32] Serial WSL, fixed timestamps and recompile --- .github/workflows/R-CMD-check-wsl.yaml | 1 + DESCRIPTION | 2 +- tests/testthat/setup.R | 18 +++++++++++++----- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index a2a6200a9..ea816dce4 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -76,6 +76,7 @@ jobs: - uses: r-lib/actions/check-r-package@v2 env: _R_CHECK_CRAN_INCOMING_: false + TESTTHAT_PARALLEL: false - name: Show testthat output if: always() diff --git a/DESCRIPTION b/DESCRIPTION index 4c824456a..9387a05fa 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -74,5 +74,5 @@ Suggests: VignetteBuilder: knitr Config/testthat/edition: 3 Config/testthat/parallel: true -Config/testthat/start-first: test-install.R +Config/testthat/start-first: install Config/roxygen2/version: 8.1.1 diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index b05870386..151852f84 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -27,8 +27,16 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) -shared_cmdstan <- cmdstan_path() -worker_cmdstan <- file.path(tempdir(), "cmdstan", basename(shared_cmdstan)) -dir.create(dirname(worker_cmdstan), recursive = TRUE, showWarnings = FALSE) -file.copy(shared_cmdstan, dirname(worker_cmdstan), recursive = TRUE) -Sys.setenv(CMDSTAN = worker_cmdstan) +if (!os_is_wsl()) { + shared_cmdstan <- cmdstan_path() + worker_cmdstan <- file.path(tempdir(), "cmdstan", basename(shared_cmdstan)) + dir.create(dirname(worker_cmdstan), recursive = TRUE, showWarnings = FALSE) + file.copy( + shared_cmdstan, + dirname(worker_cmdstan), + recursive = TRUE, + copy.date = TRUE + ) + Sys.setenv(CMDSTAN = worker_cmdstan) + suppressMessages(set_cmdstan_path()) +} From 7fa9b60cce08bf72cb1af9a9fec58ed94cd21a69 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Tue, 13 Oct 2026 20:39:47 -0700 Subject: [PATCH 03/32] Speed up parallel tests --- DESCRIPTION | 5 ++++- tests/testthat.R | 4 ++++ tests/testthat/setup.R | 19 +++++++++++++------ tests/testthat/test-install.R | 20 ++++++-------------- 4 files changed, 27 insertions(+), 21 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 9387a05fa..ddd5d0ba0 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -74,5 +74,8 @@ Suggests: VignetteBuilder: knitr Config/testthat/edition: 3 Config/testthat/parallel: true -Config/testthat/start-first: install +Config/testthat/start-first: install, model-compile, model-rebuild, + fit-shared, fit-mcmc, model-sample, model-variables, model-methods, + fit-init, csv, failed-chains, model-init, model-expose-functions, + threads, model-diagnose Config/roxygen2/version: 8.1.1 diff --git a/tests/testthat.R b/tests/testthat.R index d32cadb01..76933e949 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -1,4 +1,8 @@ library(testthat) library(cmdstanr) +if (identical(Sys.getenv("NOT_CRAN"), "true") && !nzchar(Sys.getenv("TESTTHAT_CPUS"))) { + Sys.setenv(TESTTHAT_CPUS = parallel::detectCores()) +} + test_check("cmdstanr") diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 151852f84..7101bd8c4 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -31,12 +31,19 @@ if (!os_is_wsl()) { shared_cmdstan <- cmdstan_path() worker_cmdstan <- file.path(tempdir(), "cmdstan", basename(shared_cmdstan)) dir.create(dirname(worker_cmdstan), recursive = TRUE, showWarnings = FALSE) - file.copy( - shared_cmdstan, - dirname(worker_cmdstan), - recursive = TRUE, - copy.date = TRUE - ) + if (os_is_windows()) { + system2( + "robocopy", + c( + shQuote(shared_cmdstan), + shQuote(worker_cmdstan), + "/E", "/MT:16", "/NFL", "/NDL", "/NJH", "/NJS", "/NP" + ), + stdout = FALSE + ) + } else { + system2("cp", c("-a", shQuote(shared_cmdstan), shQuote(worker_cmdstan))) + } Sys.setenv(CMDSTAN = worker_cmdstan) suppressMessages(set_cmdstan_path()) } diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index a411a997a..7e9cc3b17 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -5,7 +5,7 @@ if (!nzchar(cmdstan_test_tarball_url)) { cmdstan_test_tarball_url <- NULL } -test_that("install_cmdstan() successfully installs cmdstan", { +test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { dir <- withr::local_tempdir() withr::defer(set_cmdstan_path()) expect_message( @@ -19,6 +19,11 @@ test_that("install_cmdstan() successfully installs cmdstan", { "CmdStan path set", fixed = TRUE ) + expect_output( + rebuild_cmdstan(dir = cmdstan_path(), cores = 2), + paste0("CmdStan v", cmdstan_version(), " built"), + fixed = TRUE + ) }) test_that("install_cmdstan() errors if installation already exists", { @@ -160,19 +165,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", { - dir <- withr::local_tempdir() - withr::defer(set_cmdstan_path()) - install_cmdstan(dir = dir, cores = 2, quiet = TRUE, overwrite = TRUE, - release_url = cmdstan_test_tarball_url, - wsl = os_is_wsl()) - expect_output( - rebuild_cmdstan(dir = cmdstan_path(), cores = 2), - paste0("CmdStan v", cmdstan_version(), " built"), - fixed = TRUE - ) -}) - test_that("github_download_url constructs correct url", { expect_equal( github_download_url("FOO"), From 0b708d40b424ba2d4601ad6f4ed329b1b9fd32c5 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Wed, 14 Oct 2026 04:31:03 -0700 Subject: [PATCH 04/32] Speed up parallel tests Share one CmdStan, prebuild precompiled headers once, cache compiled fixtures across workers, and merge the install and rebuild tests. --- tests/testthat.R | 40 +++++++++++++++++-- tests/testthat/helper-envvars-and-paths.R | 33 +++++++++++++++ tests/testthat/helper-models.R | 38 +++++++++++++++++- tests/testthat/setup.R | 21 ---------- tests/testthat/test-failed-chains.R | 6 +-- tests/testthat/test-fit-shared.R | 6 +-- tests/testthat/test-install.R | 1 + tests/testthat/test-installation-check.R | 4 +- .../testthat/test-model-compile-user_header.R | 2 +- tests/testthat/test-model-rebuild-rules.R | 2 +- tests/testthat/test-path.R | 3 +- tests/testthat/test-utils.R | 1 + 12 files changed, 117 insertions(+), 40 deletions(-) diff --git a/tests/testthat.R b/tests/testthat.R index 76933e949..bfea03144 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -1,8 +1,42 @@ library(testthat) library(cmdstanr) -if (identical(Sys.getenv("NOT_CRAN"), "true") && !nzchar(Sys.getenv("TESTTHAT_CPUS"))) { - Sys.setenv(TESTTHAT_CPUS = parallel::detectCores()) +prebuild_precompiled_headers <- function() { + variants <- list(character(), "STAN_THREADS=true") + headers <- vapply(variants, function(make_args) { + header <- cmdstanr:::get_cmdstan_flags( + "PRECOMPILED_MODEL_HEADER", make_args = make_args + ) + gsub("\"", "", header, fixed = TRUE) + }, "") + missing <- nzchar(headers) & !file.exists(headers) + if (any(missing)) { + targets <- sub("^.*/(stan/src/stan/model/)", "\\1", headers) + cluster <- parallel::makeCluster(sum(missing)) + on.exit(parallel::stopCluster(cluster)) + parallel::clusterMap( + cluster, + function(target, make_args) { + cmdstanr:::run_make(c(target, make_args), quiet = TRUE) + }, + targets[missing], variants[missing] + ) + } } -test_check("cmdstanr") +shared <- NULL +if (identical(Sys.getenv("NOT_CRAN"), "true") && + !identical(Sys.getenv("TESTTHAT_PARALLEL"), "false")) { + shared <- tempfile("cmdstanr-tests-") + dir.create(shared) + Sys.setenv(CMDSTANR_TEST_SHARED = shared) + if (!nzchar(Sys.getenv("TESTTHAT_CPUS"))) { + Sys.setenv(TESTTHAT_CPUS = min(parallel::detectCores(), 4)) + } + prebuild_precompiled_headers() +} + +tryCatch( + test_check("cmdstanr"), + finally = if (!is.null(shared)) unlink(shared, recursive = TRUE) +) diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 7c71d98e7..7f2038115 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -173,6 +173,39 @@ local_make_local_backup <- function(envir = parent.frame()) { # top level of a test file, the restore runs after all tests in that file. 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) } + +copy_cmdstan_tree <- function(from, to) { + if (os_is_windows()) { + system2( + "robocopy", + c( + shQuote(from), + shQuote(to), + "/E", "/MT:16", "/NFL", "/NDL", "/NJH", "/NJS", "/NP" + ), + stdout = FALSE + ) + } else { + system2("cp", c("-a", shQuote(from), shQuote(to))) + } +} + +private_cmdstan <- new.env(parent = emptyenv()) + +local_private_cmdstan <- function(envir = parent.frame()) { + if (os_is_wsl()) { + return(invisible()) + } + shared <- cmdstan_path() + if (is.null(private_cmdstan$path)) { + private_cmdstan$path <- file.path(tempfile("cmdstan-"), basename(shared)) + dir.create(dirname(private_cmdstan$path)) + copy_cmdstan_tree(shared, private_cmdstan$path) + } + 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 0077d6f18..1555e08a2 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -35,8 +35,42 @@ cmdstan_example_file <- function() { file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan") } -testing_model <- function(name) { - cmdstan_model(stan_file = testing_stan_file(name)) +test_run_dir <- function() { + dir <- Sys.getenv("CMDSTANR_TEST_SHARED") + if (nzchar(dir)) dir else NULL +} + +with_test_lock <- function(key, code, timeout = 900) { + lock <- file.path(test_run_dir(), paste0(key, ".lock")) + deadline <- Sys.time() + timeout + while (!dir.create(lock, showWarnings = FALSE) && Sys.time() < deadline) { + Sys.sleep(0.25) + } + on.exit(unlink(lock, recursive = TRUE)) + force(code) +} + +testing_model <- function(name, ...) { + stan_file <- testing_stan_file(name) + if (is.null(test_run_dir())) { + return(cmdstan_model(stan_file = stan_file, ...)) + } + exe <- executable_path(stan_file) + files <- c(exe, build_record_path(exe)) + variant <- rlang::hash(list(cmdstan_path(), rlang::hash_file(stan_file), ...)) + cache <- file.path(test_run_dir(), variant) + with_test_lock(variant, { + if (dir.exists(cache)) { + file.copy( + file.path(cache, basename(files)), dirname(exe), + overwrite = TRUE, copy.date = TRUE + ) + } + mod <- cmdstan_model(stan_file = stan_file, ...) + dir.create(cache, showWarnings = FALSE) + file.copy(files, cache, overwrite = TRUE, copy.date = TRUE) + mod + }) } testing_fit <- diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 7101bd8c4..d86996218 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -26,24 +26,3 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) - -if (!os_is_wsl()) { - shared_cmdstan <- cmdstan_path() - worker_cmdstan <- file.path(tempdir(), "cmdstan", basename(shared_cmdstan)) - dir.create(dirname(worker_cmdstan), recursive = TRUE, showWarnings = FALSE) - if (os_is_windows()) { - system2( - "robocopy", - c( - shQuote(shared_cmdstan), - shQuote(worker_cmdstan), - "/E", "/MT:16", "/NFL", "/NDL", "/NJH", "/NJS", "/NP" - ), - stdout = FALSE - ) - } else { - system2("cp", c("-a", shQuote(shared_cmdstan), shQuote(worker_cmdstan))) - } - Sys.setenv(CMDSTAN = worker_cmdstan) - suppressMessages(set_cmdstan_path()) -} diff --git a/tests/testthat/test-failed-chains.R b/tests/testthat/test-failed-chains.R index cd31e7ce3..b20258056 100644 --- a/tests/testthat/test-failed-chains.R +++ b/tests/testthat/test-failed-chains.R @@ -1,11 +1,9 @@ skip_on_cran() set_cmdstan_path() -stan_program <- testing_stan_file("chain_fails") -stan_program_init_warnings <- testing_stan_file("init_warnings") -mod <- cmdstan_model(stan_file = stan_program) -mod_init_warnings <- cmdstan_model(stan_file = stan_program_init_warnings) +mod <- testing_model("chain_fails") +mod_init_warnings <- testing_model("init_warnings") make_all_fail <- function(x) { utils::capture.output( diff --git a/tests/testthat/test-fit-shared.R b/tests/testthat/test-fit-shared.R index 80941b8d8..8632ee94e 100644 --- a/tests/testthat/test-fit-shared.R +++ b/tests/testthat/test-fit-shared.R @@ -546,10 +546,9 @@ test_that("sampling works with explicit and inferred include paths containing sp }) test_that("CmdStanModel created with exe_file works", { - stan_program <- testing_stan_file("bernoulli") data_list <- testing_data("bernoulli") - mod <- cmdstan_model(stan_file = stan_program) + mod <- testing_model("bernoulli") mod_exe <- cmdstan_model(exe_file = mod$exe_file()) utils::capture.output( @@ -584,10 +583,9 @@ test_that("CmdStanModel created with exe_file works", { ) expect_equal(fit_sample$draws(), fit_sample_exe$draws()) - stan_ppc_program <- testing_stan_file("bernoulli_ppc") data_ppc_list <- testing_data("bernoulli_ppc") - mod_bern_ppc <- cmdstan_model(stan_file = stan_ppc_program) + mod_bern_ppc <- testing_model("bernoulli_ppc") mod_bern_ppc_exe <- cmdstan_model(exe_file = mod_bern_ppc$exe_file()) utils::capture.output( diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 7e9cc3b17..58d7a3d00 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -632,6 +632,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-installation-check.R b/tests/testthat/test-installation-check.R index 9d6abbd40..7c5719b00 100644 --- a/tests/testthat/test-installation-check.R +++ b/tests/testthat/test-installation-check.R @@ -31,14 +31,14 @@ test_that("a model is not built when the selected installation is gone", { }) test_that("check_syntax() and format() error naming the gone installation", { - mod <- cmdstan_model(stan_program) + mod <- testing_model("bernoulli") gone <- local_gone_installation() expect_error(mod$check_syntax(), gone, fixed = TRUE) expect_error(mod$format(), gone, fixed = TRUE) }) test_that("variables() works with the installation gone while variables_stan_file() does not", { - mod <- cmdstan_model(stan_program) + mod <- testing_model("bernoulli") gone <- local_gone_installation() expect_no_error(mod$variables()) expect_error(variables_stan_file(stan_program), gone, fixed = TRUE) diff --git a/tests/testthat/test-model-compile-user_header.R b/tests/testthat/test-model-compile-user_header.R index a429df4fc..58c6df572 100644 --- a/tests/testthat/test-model-compile-user_header.R +++ b/tests/testthat/test-model-compile-user_header.R @@ -71,7 +71,7 @@ test_that("cmdstan_model() records a user header", { }) test_that("cmdstan_model() honours an explicit user_header = NULL", { - model <- cmdstan_model(testing_stan_file("bernoulli"), user_header = NULL) + model <- testing_model("bernoulli", user_header = NULL) expect_null(model$user_header()) }) diff --git a/tests/testthat/test-model-rebuild-rules.R b/tests/testthat/test-model-rebuild-rules.R index 174a188c0..97c6e865d 100644 --- a/tests/testthat/test-model-rebuild-rules.R +++ b/tests/testthat/test-model-rebuild-rules.R @@ -523,8 +523,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-path.R b/tests/testthat/test-path.R index cf6e703cc..d491e5e10 100644 --- a/tests/testthat/test-path.R +++ b/tests/testthat/test-path.R @@ -1,6 +1,5 @@ skip_on_cran() -worker_cmdstan <- Sys.getenv("CMDSTAN") Sys.unsetenv("CMDSTAN") PATH <- absolute_path(set_cmdstan_path()) VERSION <- cmdstan_version() @@ -313,5 +312,5 @@ test_that("is_release_candidate() works", { }) # cleanup ----------------------------------------------------------------- -Sys.setenv(CMDSTAN = worker_cmdstan) +Sys.unsetenv("CMDSTAN") unset_cmdstan_path() diff --git a/tests/testthat/test-utils.R b/tests/testthat/test-utils.R index 8b7959a88..0515da1f4 100644 --- a/tests/testthat/test-utils.R +++ b/tests/testthat/test-utils.R @@ -550,6 +550,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)) From 52585c06098562d03e02e1bfa63d37ed751e9897 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Wed, 14 Oct 2026 06:17:14 -0700 Subject: [PATCH 05/32] Resolve precompiled header names inside the build environment The prebuild stripped only double quotes from the header path, so on Unix make got a target with a trailing quote, and on Windows R 4.1 the name came from a make run without the toolchain PATH. --- tests/testthat.R | 58 ++++++++++++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/tests/testthat.R b/tests/testthat.R index bfea03144..9f7fcfab7 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -3,25 +3,45 @@ library(cmdstanr) prebuild_precompiled_headers <- function() { variants <- list(character(), "STAN_THREADS=true") - headers <- vapply(variants, function(make_args) { - header <- cmdstanr:::get_cmdstan_flags( - "PRECOMPILED_MODEL_HEADER", make_args = make_args - ) - gsub("\"", "", header, fixed = TRUE) - }, "") - missing <- nzchar(headers) & !file.exists(headers) - if (any(missing)) { - targets <- sub("^.*/(stan/src/stan/model/)", "\\1", headers) - cluster <- parallel::makeCluster(sum(missing)) - on.exit(parallel::stopCluster(cluster)) - parallel::clusterMap( - cluster, - function(target, make_args) { - cmdstanr:::run_make(c(target, make_args), quiet = TRUE) - }, - targets[missing], variants[missing] - ) - } + cluster <- parallel::makeCluster(length(variants), outfile = "") + on.exit(parallel::stopCluster(cluster)) + parallel::clusterApply( + cluster, + variants, + function(make_args) { + output <- character() + tryCatch( + withCallingHandlers( + { + printed <- cmdstanr:::run_make( + c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), + quiet = TRUE + )$stdout + line <- grep( + "^PRECOMPILED_MODEL_HEADER", trimws(strsplit(printed, "\n")[[1]]), + value = TRUE + ) + header <- trimws(sub("^PRECOMPILED_MODEL_HEADER\\s*=", "", line)) + if ( + length(header) == 1 && nzchar(header) && + !file.exists(file.path(cmdstanr::cmdstan_path(), header)) + ) { + cmdstanr:::run_make(c(header, make_args), quiet = TRUE) + } + }, + message = function(m) { + output <<- c(output, conditionMessage(m)) + invokeRestart("muffleMessage") + } + ), + error = function(e) { + message(paste(c(output, conditionMessage(e)), collapse = "\n")) + } + ) + invisible() + } + ) + invisible() } shared <- NULL From 8f71f31b7f015fc5a0eb5342351c48bc42c2c1d7 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Wed, 14 Oct 2026 06:50:23 -0700 Subject: [PATCH 06/32] Give the knitr test a Stan program no other file writes Its cache = FALSE case writes into the worker's tempdir under a content hash, so a file that compiled the same program earlier on that worker made the build a no-op. --- tests/testthat/test-knitr.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/testthat/test-knitr.R b/tests/testthat/test-knitr.R index 588f19c23..4d67353c7 100644 --- a/tests/testthat/test-knitr.R +++ b/tests/testthat/test-knitr.R @@ -9,10 +9,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( From 8b6d41524aedc14575d0238811377324e7a17218 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Wed, 14 Oct 2026 07:38:46 -0700 Subject: [PATCH 07/32] Add -fPIC to SUNDIALS once before workers start On Linux the first model-methods or expose-functions call appended -fPIC to make/local and rebuilt the shared CmdStan, deleting objects other workers were linking against. --- tests/testthat.R | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/tests/testthat.R b/tests/testthat.R index 9f7fcfab7..a67a1f38b 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -44,6 +44,16 @@ prebuild_precompiled_headers <- function() { invisible() } +ensure_sundials_fpic <- function() { + withr::with_options( + list(mc.cores = min(parallel::detectCores(), 4)), + cmdstanr:::check_sundials_fpic( + cmdstanr:::get_cmdstan_flags("CPPFLAGS_SUNDIALS"), + verbose = FALSE + ) + ) +} + shared <- NULL if (identical(Sys.getenv("NOT_CRAN"), "true") && !identical(Sys.getenv("TESTTHAT_PARALLEL"), "false")) { @@ -53,6 +63,7 @@ if (identical(Sys.getenv("NOT_CRAN"), "true") && if (!nzchar(Sys.getenv("TESTTHAT_CPUS"))) { Sys.setenv(TESTTHAT_CPUS = min(parallel::detectCores(), 4)) } + ensure_sundials_fpic() prebuild_precompiled_headers() } From 411bd4af353700a2e51eb7eeb2c3d35cc7b7e9e2 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 10:50:54 -0700 Subject: [PATCH 08/32] Another attempt at speeding up; building using up to four cores; attempting to speed up WSL tests --- .github/workflows/R-CMD-check-wsl.yaml | 1 - .github/workflows/R-CMD-check.yaml | 11 +++++++++-- tests/testthat.R | 2 ++ tests/testthat/helper-envvars-and-paths.R | 22 ++++++++++++++++------ tests/testthat/test-install.R | 5 +++-- 5 files changed, 30 insertions(+), 11 deletions(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index ea816dce4..a2a6200a9 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -76,7 +76,6 @@ jobs: - uses: r-lib/actions/check-r-package@v2 env: _R_CHECK_CRAN_INCOMING_: false - TESTTHAT_PARALLEL: false - name: Show testthat output if: always() diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index 4c203e8f6..cb0eae71b 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -136,15 +136,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} @@ -156,6 +161,8 @@ jobs: shell: Rscript {0} - uses: r-lib/actions/check-r-package@v2 + with: + args: 'c("--no-manual", "--as-cran", "--no-build-vignettes")' env: _R_CHECK_CRAN_INCOMING_: false _R_CHECK_FORCE_SUGGESTS_: ${{ matrix.config.r == '4.1' && 'false' || 'true' }} diff --git a/tests/testthat.R b/tests/testthat.R index a67a1f38b..9304c13a9 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -10,6 +10,7 @@ prebuild_precompiled_headers <- function() { variants, function(make_args) { output <- character() + # jarl-ignore internal_function: deliberate use of internals tryCatch( withCallingHandlers( { @@ -45,6 +46,7 @@ prebuild_precompiled_headers <- function() { } ensure_sundials_fpic <- function() { + # jarl-ignore internal_function: deliberate use of internals withr::with_options( list(mc.cores = min(parallel::detectCores(), 4)), cmdstanr:::check_sundials_fpic( diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 3a64eed89..212813e27 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -179,7 +179,12 @@ local_cmdstan_make_local <- function( } copy_cmdstan_tree <- function(from, to) { - if (os_is_windows()) { + if (os_is_wsl()) { + wsl_compatible_run( + command = "cp", + args = c("-a", wsl_safe_path(from), wsl_safe_path(to)) + ) + } else if (os_is_windows()) { system2( "robocopy", c( @@ -197,13 +202,18 @@ copy_cmdstan_tree <- function(from, to) { private_cmdstan <- new.env(parent = emptyenv()) local_private_cmdstan <- function(envir = parent.frame()) { - if (os_is_wsl()) { - return(invisible()) - } shared <- cmdstan_path() if (is.null(private_cmdstan$path)) { - private_cmdstan$path <- file.path(tempfile("cmdstan-"), basename(shared)) - dir.create(dirname(private_cmdstan$path)) + root <- tempfile("cmdstan-") + if (os_is_wsl()) { + root <- file.path(dirname(dirname(shared)), basename(root)) + withr::defer( + unlink(root, recursive = TRUE, force = TRUE), + testthat::teardown_env() + ) + } + private_cmdstan$path <- file.path(root, basename(shared)) + dir.create(root) copy_cmdstan_tree(shared, private_cmdstan$path) } suppressMessages(set_cmdstan_path(private_cmdstan$path)) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 810b40094..b241a035e 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -6,13 +6,14 @@ if (!nzchar(cmdstan_test_tarball_url)) { } test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { + build_cores <- min(parallel::detectCores(), 4) dir <- withr::local_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, @@ -25,7 +26,7 @@ test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() fixed = TRUE ) expect_output( - rebuild_cmdstan(dir = cmdstan_path(), cores = 2), + rebuild_cmdstan(dir = cmdstan_path(), cores = build_cores), paste0("CmdStan v", cmdstan_version(), " built"), fixed = TRUE ) From 11cee57c776f13abc592c5f463b1b3a34f350c9e Mon Sep 17 00:00:00 2001 From: Visruth Srimath Kandali Date: Thu, 15 Oct 2026 10:52:18 -0700 Subject: [PATCH 09/32] Apply batched suggestions from code review Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> --- tests/testthat.R | 14 +++++++++----- tests/testthat/helper-envvars-and-paths.R | 8 +++++++- tests/testthat/helper-models.R | 6 ++++-- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/tests/testthat.R b/tests/testthat.R index 9304c13a9..0c7c8846b 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -19,13 +19,15 @@ prebuild_precompiled_headers <- function() { quiet = TRUE )$stdout line <- grep( - "^PRECOMPILED_MODEL_HEADER", trimws(strsplit(printed, "\n")[[1]]), + "^PRECOMPILED_MODEL_HEADER", + trimws(strsplit(printed, "\n")[[1]]), value = TRUE ) header <- trimws(sub("^PRECOMPILED_MODEL_HEADER\\s*=", "", line)) if ( - length(header) == 1 && nzchar(header) && - !file.exists(file.path(cmdstanr::cmdstan_path(), header)) + length(header) == 1 && + nzchar(header) && + !file.exists(file.path(cmdstanr::cmdstan_path(), header)) ) { cmdstanr:::run_make(c(header, make_args), quiet = TRUE) } @@ -57,8 +59,10 @@ ensure_sundials_fpic <- function() { } shared <- NULL -if (identical(Sys.getenv("NOT_CRAN"), "true") && - !identical(Sys.getenv("TESTTHAT_PARALLEL"), "false")) { +if ( + identical(Sys.getenv("NOT_CRAN"), "true") && + !identical(Sys.getenv("TESTTHAT_PARALLEL"), "false") +) { shared <- tempfile("cmdstanr-tests-") dir.create(shared) Sys.setenv(CMDSTANR_TEST_SHARED = shared) diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 212813e27..858488a07 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -190,7 +190,13 @@ copy_cmdstan_tree <- function(from, to) { c( shQuote(from), shQuote(to), - "/E", "/MT:16", "/NFL", "/NDL", "/NJH", "/NJS", "/NP" + "/E", + "/MT:16", + "/NFL", + "/NDL", + "/NJH", + "/NJS", + "/NP" ), stdout = FALSE ) diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index 9d485c238..3af5298fc 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -62,8 +62,10 @@ testing_model <- function(name, ...) { with_test_lock(variant, { if (dir.exists(cache)) { file.copy( - file.path(cache, basename(files)), dirname(exe), - overwrite = TRUE, copy.date = TRUE + file.path(cache, basename(files)), + dirname(exe), + overwrite = TRUE, + copy.date = TRUE ) } mod <- cmdstan_model(stan_file = stan_file, ...) From bcf430325e3b4484188cd0241150671894896fa9 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 11:08:04 -0700 Subject: [PATCH 10/32] Added dep on filelock --- DESCRIPTION | 1 + tests/testthat/helper-models.R | 11 +++++------ 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index ddd5d0ba0..b61b91840 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), diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index 3af5298fc..6b861bdb4 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -41,12 +41,11 @@ test_run_dir <- function() { } with_test_lock <- function(key, code, timeout = 900) { - lock <- file.path(test_run_dir(), paste0(key, ".lock")) - deadline <- Sys.time() + timeout - while (!dir.create(lock, showWarnings = FALSE) && Sys.time() < deadline) { - Sys.sleep(0.25) - } - on.exit(unlink(lock, recursive = TRUE)) + lock <- filelock::lock( + file.path(test_run_dir(), paste0(key, ".lock")), + timeout = timeout * 1000 + ) + on.exit(if (!is.null(lock)) filelock::unlock(lock)) force(code) } From 55c05e90cc6183f5efdcb51326a0c4ee001f8866 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 12:29:48 -0700 Subject: [PATCH 11/32] Moved test tesup to setup.R --- .github/workflows/R-CMD-check-wsl.yaml | 1 + .github/workflows/R-CMD-check.yaml | 3 +- .github/workflows/Test-coverage.yaml | 1 + DESCRIPTION | 1 + tests/testthat.R | 77 +-------------------- tests/testthat/helper-models.R | 3 + tests/testthat/setup.R | 92 +++++++++++++++++++++++++- 7 files changed, 99 insertions(+), 79 deletions(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index a2a6200a9..a7b5f59a1 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -29,6 +29,7 @@ jobs: R_REMOTES_NO_ERRORS_FROM_WARNINGS: true GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true + TESTTHAT_CPUS: 4 CMDSTANR_OPENCL_TESTS: true steps: diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index cb0eae71b..d0f3a2432 100644 --- a/.github/workflows/R-CMD-check.yaml +++ b/.github/workflows/R-CMD-check.yaml @@ -50,6 +50,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 @@ -161,8 +162,6 @@ jobs: shell: Rscript {0} - uses: r-lib/actions/check-r-package@v2 - with: - args: 'c("--no-manual", "--as-cran", "--no-build-vignettes")' env: _R_CHECK_CRAN_INCOMING_: false _R_CHECK_FORCE_SUGGESTS_: ${{ matrix.config.r == '4.1' && 'false' || 'true' }} diff --git a/.github/workflows/Test-coverage.yaml b/.github/workflows/Test-coverage.yaml index ae1851317..bcbe7fb2e 100644 --- a/.github/workflows/Test-coverage.yaml +++ b/.github/workflows/Test-coverage.yaml @@ -34,6 +34,7 @@ jobs: env: GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true + TESTTHAT_CPUS: 4 steps: - name: cmdstan env vars diff --git a/DESCRIPTION b/DESCRIPTION index b61b91840..6b47ab46b 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -66,6 +66,7 @@ Suggests: knitr (>= 1.37), loo (>= 2.0.0), progressr, + ps, qs2, Rcpp, RcppParallel, diff --git a/tests/testthat.R b/tests/testthat.R index 0c7c8846b..d32cadb01 100644 --- a/tests/testthat.R +++ b/tests/testthat.R @@ -1,79 +1,4 @@ library(testthat) library(cmdstanr) -prebuild_precompiled_headers <- function() { - variants <- list(character(), "STAN_THREADS=true") - cluster <- parallel::makeCluster(length(variants), outfile = "") - on.exit(parallel::stopCluster(cluster)) - parallel::clusterApply( - cluster, - variants, - function(make_args) { - output <- character() - # jarl-ignore internal_function: deliberate use of internals - tryCatch( - withCallingHandlers( - { - printed <- cmdstanr:::run_make( - c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), - quiet = TRUE - )$stdout - line <- grep( - "^PRECOMPILED_MODEL_HEADER", - trimws(strsplit(printed, "\n")[[1]]), - value = TRUE - ) - header <- trimws(sub("^PRECOMPILED_MODEL_HEADER\\s*=", "", line)) - if ( - length(header) == 1 && - nzchar(header) && - !file.exists(file.path(cmdstanr::cmdstan_path(), header)) - ) { - cmdstanr:::run_make(c(header, make_args), quiet = TRUE) - } - }, - message = function(m) { - output <<- c(output, conditionMessage(m)) - invokeRestart("muffleMessage") - } - ), - error = function(e) { - message(paste(c(output, conditionMessage(e)), collapse = "\n")) - } - ) - invisible() - } - ) - invisible() -} - -ensure_sundials_fpic <- function() { - # jarl-ignore internal_function: deliberate use of internals - withr::with_options( - list(mc.cores = min(parallel::detectCores(), 4)), - cmdstanr:::check_sundials_fpic( - cmdstanr:::get_cmdstan_flags("CPPFLAGS_SUNDIALS"), - verbose = FALSE - ) - ) -} - -shared <- NULL -if ( - identical(Sys.getenv("NOT_CRAN"), "true") && - !identical(Sys.getenv("TESTTHAT_PARALLEL"), "false") -) { - shared <- tempfile("cmdstanr-tests-") - dir.create(shared) - Sys.setenv(CMDSTANR_TEST_SHARED = shared) - if (!nzchar(Sys.getenv("TESTTHAT_CPUS"))) { - Sys.setenv(TESTTHAT_CPUS = min(parallel::detectCores(), 4)) - } - ensure_sundials_fpic() - prebuild_precompiled_headers() -} - -tryCatch( - test_check("cmdstanr"), - finally = if (!is.null(shared)) unlink(shared, recursive = TRUE) -) +test_check("cmdstanr") diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index 6b861bdb4..ae77972f4 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -41,6 +41,9 @@ test_run_dir <- function() { } with_test_lock <- function(key, code, timeout = 900) { + if (is.null(test_run_dir())) { + return(force(code)) + } lock <- filelock::lock( file.path(test_run_dir(), paste0(key, ".lock")), timeout = timeout * 1000 diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index d86996218..7d415d990 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -6,7 +6,8 @@ dir.create(stan_dir, recursive = TRUE, showWarnings = FALSE) file.copy( list.files(test_path("resources", "stan"), full.names = TRUE), stan_dir, - recursive = TRUE + recursive = TRUE, + overwrite = TRUE ) cleanup_stan_artifacts <- function() { @@ -26,3 +27,92 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) + +ensure_sundials_fpic <- function() { + with_test_lock("sundials-fpic", { + withr::with_options( + list(mc.cores = min(parallel::detectCores(), 4)), + check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), verbose = FALSE) + ) + }) +} + +precompiled_header_path <- function(make_args) { + printed <- run_make( + c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), + quiet = TRUE + )$stdout + line <- grep( + "^PRECOMPILED_MODEL_HEADER", + trimws(strsplit(printed, "\n")[[1]]), + value = TRUE + ) + header <- trimws(sub("^PRECOMPILED_MODEL_HEADER[[:space:]]*=", "", line)) + if (length(header) != 1 || !nzchar(header)) { + return(NULL) + } + file.path(cmdstan_path(), header) +} + +build_precompiled_header <- function(make_args, timeout) { + header_path <- precompiled_header_path(make_args) + if (is.null(header_path) || file.exists(header_path)) { + return(TRUE) + } + lock <- NULL + if (!is.null(test_run_dir())) { + lock <- filelock::lock( + file.path(test_run_dir(), paste0("pch-", rlang::hash(make_args), ".lock")), + timeout = timeout + ) + if (is.null(lock)) { + return(FALSE) + } + on.exit(filelock::unlock(lock)) + } + if (!file.exists(header_path)) { + run_make(c(basename(header_path), make_args), quiet = TRUE) + } + TRUE +} + +ensure_precompiled_headers <- function() { + pending <- list(character(), "STAN_THREADS=true") + for (timeout in c(0, -1)) { + built <- vapply(pending, build_precompiled_header, logical(1), timeout) + pending <- pending[!built] + } +} + +remove_dead_run_dirs <- function(root) { + for (dir in Sys.glob(file.path(root, "cmdstanr-tests-*"))) { + pid <- as.integer(sub("^cmdstanr-tests-", "", basename(dir))) + alive <- tryCatch( + ps::ps_is_running(ps::ps_handle(pid)), + error = function(e) FALSE + ) + if (!alive) { + unlink(dir, recursive = TRUE) + } + } +} + +if (identical(Sys.getenv("NOT_CRAN"), "true")) { + if ( + identical(Sys.getenv("CALLR_IS_RUNNING"), "true") && + !nzchar(Sys.getenv("CMDSTANR_TEST_SHARED")) + ) { + root <- dirname(tempdir()) + remove_dead_run_dirs(root) + run_dir <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) + dir.create(run_dir, showWarnings = FALSE) + Sys.setenv(CMDSTANR_TEST_SHARED = run_dir) + } + tryCatch( + { + ensure_sundials_fpic() + ensure_precompiled_headers() + }, + error = function(e) message(conditionMessage(e)) + ) +} From d7a9df042207a61f79b40993bdf2543159b85e2d Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 15:41:18 -0700 Subject: [PATCH 12/32] Use a directory lock again, fix WSL toolchain test, wrap long lines --- DESCRIPTION | 1 - tests/testthat/helper-models.R | 25 ++++++++++++++++++++----- tests/testthat/setup.R | 14 +++++++------- tests/testthat/test-install.R | 4 ++++ 4 files changed, 31 insertions(+), 13 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index 6b47ab46b..1ea733b87 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -61,7 +61,6 @@ Imports: withr (>= 2.5.0) Suggests: bayesplot, - filelock, ggplot2, knitr (>= 1.37), loo (>= 2.0.0), diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index ae77972f4..0054cf360 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -40,15 +40,30 @@ test_run_dir <- function() { if (nzchar(dir)) dir else NULL } +acquire_test_lock <- function(key, timeout = 900) { + lock <- file.path(test_run_dir(), paste0(key, ".lock")) + deadline <- Sys.time() + timeout + while (!dir.create(lock, showWarnings = FALSE)) { + if (Sys.time() >= deadline) { + return(NULL) + } + Sys.sleep(0.25) + } + lock +} + +release_test_lock <- function(lock) { + if (!is.null(lock)) { + unlink(lock, recursive = TRUE) + } +} + with_test_lock <- function(key, code, timeout = 900) { if (is.null(test_run_dir())) { return(force(code)) } - lock <- filelock::lock( - file.path(test_run_dir(), paste0(key, ".lock")), - timeout = timeout * 1000 - ) - on.exit(if (!is.null(lock)) filelock::unlock(lock)) + lock <- acquire_test_lock(key, timeout) + on.exit(release_test_lock(lock)) force(code) } diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 7d415d990..882d4845b 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -32,7 +32,10 @@ ensure_sundials_fpic <- function() { with_test_lock("sundials-fpic", { withr::with_options( list(mc.cores = min(parallel::detectCores(), 4)), - check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), verbose = FALSE) + check_sundials_fpic( + get_cmdstan_flags("CPPFLAGS_SUNDIALS"), + verbose = FALSE + ) ) }) } @@ -61,14 +64,11 @@ build_precompiled_header <- function(make_args, timeout) { } lock <- NULL if (!is.null(test_run_dir())) { - lock <- filelock::lock( - file.path(test_run_dir(), paste0("pch-", rlang::hash(make_args), ".lock")), - timeout = timeout - ) + lock <- acquire_test_lock(paste0("pch-", rlang::hash(make_args)), timeout) if (is.null(lock)) { return(FALSE) } - on.exit(filelock::unlock(lock)) + on.exit(release_test_lock(lock)) } if (!file.exists(header_path)) { run_make(c(basename(header_path), make_args), quiet = TRUE) @@ -78,7 +78,7 @@ build_precompiled_header <- function(make_args, timeout) { ensure_precompiled_headers <- function() { pending <- list(character(), "STAN_THREADS=true") - for (timeout in c(0, -1)) { + for (timeout in c(0, 900)) { built <- vapply(pending, build_precompiled_header, logical(1), timeout) pending <- pending[!built] } diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index b241a035e..103ca628c 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -1490,6 +1490,10 @@ test_that("toolchain_PATH_env_var() rejects unsafe toolchain paths", { test_that("check_cmdstan_toolchain() stops with no Windows toolchain", { skip_if(!os_is_windows()) + old_wsl <- .cmdstanr$WSL + .cmdstanr$WSL <- FALSE + withr::defer(.cmdstanr$WSL <- old_wsl) + withr::local_envvar(CMDSTANR_USE_WSL = NA) local_mocked_bindings(toolchain_PATH_env_var = function() NULL) expect_snapshot(error = TRUE, check_cmdstan_toolchain()) }) From 38b02f9aa5d8ca13c8a680b258c03b1113695666 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 17:09:37 -0700 Subject: [PATCH 13/32] Take the WSL flag from the CmdStan path when making a private copy --- tests/testthat/helper-envvars-and-paths.R | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 858488a07..2374d925c 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -209,6 +209,7 @@ private_cmdstan <- new.env(parent = emptyenv()) local_private_cmdstan <- function(envir = parent.frame()) { shared <- cmdstan_path() + .cmdstanr$WSL <- grepl("//wsl$", shared, fixed = TRUE) if (is.null(private_cmdstan$path)) { root <- tempfile("cmdstan-") if (os_is_wsl()) { From 8d2154c235c5c073801c0a54cb107636559c9bd4 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Thu, 15 Oct 2026 19:32:53 -0700 Subject: [PATCH 14/32] Run a test early --- DESCRIPTION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/DESCRIPTION b/DESCRIPTION index 1ea733b87..f3a8627f6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -78,5 +78,5 @@ Config/testthat/parallel: true Config/testthat/start-first: install, model-compile, model-rebuild, fit-shared, fit-mcmc, model-sample, model-variables, model-methods, fit-init, csv, failed-chains, model-init, model-expose-functions, - threads, model-diagnose + threads, model-diagnose, tuple-complex Config/roxygen2/version: 8.1.1 From 68a638b71e86a8ab3c6ebc2c24e3372dc889f4a3 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 00:16:11 -0700 Subject: [PATCH 15/32] Small formatting changes --- tests/testthat/helper-envvars-and-paths.R | 53 +++++---- tests/testthat/helper-models.R | 23 +--- tests/testthat/setup.R | 131 ++++++++++------------ tests/testthat/test-install.R | 9 +- 4 files changed, 94 insertions(+), 122 deletions(-) diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 2374d925c..ac0a756a9 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -178,33 +178,6 @@ local_cmdstan_make_local <- function( cmdstan_make_local(cpp_options = cpp_options, append = append) } -copy_cmdstan_tree <- function(from, to) { - if (os_is_wsl()) { - wsl_compatible_run( - command = "cp", - args = c("-a", wsl_safe_path(from), wsl_safe_path(to)) - ) - } else if (os_is_windows()) { - system2( - "robocopy", - c( - shQuote(from), - shQuote(to), - "/E", - "/MT:16", - "/NFL", - "/NDL", - "/NJH", - "/NJS", - "/NP" - ), - stdout = FALSE - ) - } else { - system2("cp", c("-a", shQuote(from), shQuote(to))) - } -} - private_cmdstan <- new.env(parent = emptyenv()) local_private_cmdstan <- function(envir = parent.frame()) { @@ -221,7 +194,31 @@ local_private_cmdstan <- function(envir = parent.frame()) { } private_cmdstan$path <- file.path(root, basename(shared)) dir.create(root) - copy_cmdstan_tree(shared, private_cmdstan$path) + to <- private_cmdstan$path + if (os_is_wsl()) { + wsl_compatible_run( + command = "cp", + args = c("-a", wsl_safe_path(shared), wsl_safe_path(to)) + ) + } else if (os_is_windows()) { + system2( + "robocopy", + c( + shQuote(shared), + shQuote(to), + "/E", + "/MT:16", + "/NFL", + "/NDL", + "/NJH", + "/NJS", + "/NP" + ), + stdout = FALSE + ) + } else { + system2("cp", c("-a", shQuote(shared), shQuote(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 0054cf360..e4ce3c540 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -40,30 +40,19 @@ test_run_dir <- function() { if (nzchar(dir)) dir else NULL } -acquire_test_lock <- function(key, timeout = 900) { +with_test_lock <- function(key, code, timeout = 900, on_timeout = code) { + if (is.null(test_run_dir())) { + return(force(code)) + } lock <- file.path(test_run_dir(), paste0(key, ".lock")) deadline <- Sys.time() + timeout while (!dir.create(lock, showWarnings = FALSE)) { if (Sys.time() >= deadline) { - return(NULL) + return(on_timeout) } Sys.sleep(0.25) } - lock -} - -release_test_lock <- function(lock) { - if (!is.null(lock)) { - unlink(lock, recursive = TRUE) - } -} - -with_test_lock <- function(key, code, timeout = 900) { - if (is.null(test_run_dir())) { - return(force(code)) - } - lock <- acquire_test_lock(key, timeout) - on.exit(release_test_lock(lock)) + on.exit(unlink(lock, recursive = TRUE)) force(code) } diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 882d4845b..fe71150c8 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -28,90 +28,77 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) -ensure_sundials_fpic <- function() { - with_test_lock("sundials-fpic", { - withr::with_options( - list(mc.cores = min(parallel::detectCores(), 4)), - check_sundials_fpic( - get_cmdstan_flags("CPPFLAGS_SUNDIALS"), - verbose = FALSE - ) - ) - }) -} - -precompiled_header_path <- function(make_args) { - printed <- run_make( - c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), - quiet = TRUE - )$stdout - line <- grep( - "^PRECOMPILED_MODEL_HEADER", - trimws(strsplit(printed, "\n")[[1]]), - value = TRUE - ) - header <- trimws(sub("^PRECOMPILED_MODEL_HEADER[[:space:]]*=", "", line)) - if (length(header) != 1 || !nzchar(header)) { - return(NULL) - } - file.path(cmdstan_path(), header) -} - -build_precompiled_header <- function(make_args, timeout) { - header_path <- precompiled_header_path(make_args) - if (is.null(header_path) || file.exists(header_path)) { - return(TRUE) - } - lock <- NULL - if (!is.null(test_run_dir())) { - lock <- acquire_test_lock(paste0("pch-", rlang::hash(make_args)), timeout) - if (is.null(lock)) { - return(FALSE) - } - on.exit(release_test_lock(lock)) - } - if (!file.exists(header_path)) { - run_make(c(basename(header_path), make_args), quiet = TRUE) - } - TRUE -} - -ensure_precompiled_headers <- function() { - pending <- list(character(), "STAN_THREADS=true") - for (timeout in c(0, 900)) { - built <- vapply(pending, build_precompiled_header, logical(1), timeout) - pending <- pending[!built] - } -} - -remove_dead_run_dirs <- function(root) { - for (dir in Sys.glob(file.path(root, "cmdstanr-tests-*"))) { - pid <- as.integer(sub("^cmdstanr-tests-", "", basename(dir))) - alive <- tryCatch( - ps::ps_is_running(ps::ps_handle(pid)), - error = function(e) FALSE - ) - if (!alive) { - unlink(dir, recursive = TRUE) - } - } -} - if (identical(Sys.getenv("NOT_CRAN"), "true")) { if ( identical(Sys.getenv("CALLR_IS_RUNNING"), "true") && !nzchar(Sys.getenv("CMDSTANR_TEST_SHARED")) ) { root <- dirname(tempdir()) - remove_dead_run_dirs(root) + for (dir in Sys.glob(file.path(root, "cmdstanr-tests-*"))) { + pid <- as.integer(sub("^cmdstanr-tests-", "", basename(dir))) + alive <- tryCatch( + ps::ps_is_running(ps::ps_handle(pid)), + error = function(e) FALSE + ) + if (!alive) { + unlink(dir, recursive = TRUE) + } + } run_dir <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) dir.create(run_dir, showWarnings = FALSE) Sys.setenv(CMDSTANR_TEST_SHARED = run_dir) } tryCatch( { - ensure_sundials_fpic() - ensure_precompiled_headers() + with_test_lock("sundials-fpic", { + withr::with_options( + list(mc.cores = min(parallel::detectCores(), 4)), + check_sundials_fpic( + get_cmdstan_flags("CPPFLAGS_SUNDIALS"), + verbose = FALSE + ) + ) + }) + pending <- list(character(), "STAN_THREADS=true") + for (timeout in c(0, 900)) { + built <- vapply( + pending, + function(make_args) { + printed <- run_make( + c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), + quiet = TRUE + )$stdout + line <- grep( + "^PRECOMPILED_MODEL_HEADER", + trimws(readLines(textConnection(printed))), + value = TRUE + ) + header <- trimws( + sub("^PRECOMPILED_MODEL_HEADER[[:space:]]*=", "", line) + ) + if (length(header) != 1 || !nzchar(header)) { + return(TRUE) + } + header_path <- file.path(cmdstan_path(), header) + if (file.exists(header_path)) { + return(TRUE) + } + with_test_lock( + paste0("pch-", rlang::hash(make_args)), + { + if (!file.exists(header_path)) { + run_make(c(basename(header_path), make_args), quiet = TRUE) + } + TRUE + }, + timeout, + on_timeout = FALSE + ) + }, + logical(1) + ) + pending <- pending[!built] + } }, error = function(e) message(conditionMessage(e)) ) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 103ca628c..0ffb4a2d8 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -1490,11 +1490,10 @@ test_that("toolchain_PATH_env_var() rejects unsafe toolchain paths", { test_that("check_cmdstan_toolchain() stops with no Windows toolchain", { skip_if(!os_is_windows()) - old_wsl <- .cmdstanr$WSL - .cmdstanr$WSL <- FALSE - withr::defer(.cmdstanr$WSL <- old_wsl) - withr::local_envvar(CMDSTANR_USE_WSL = NA) - local_mocked_bindings(toolchain_PATH_env_var = function() NULL) + local_mocked_bindings( + os_is_wsl = function() FALSE, + toolchain_PATH_env_var = function() NULL + ) expect_snapshot(error = TRUE, check_cmdstan_toolchain()) }) From 1692ffc8e38e20fe5bcfdef78ab006f107780194 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 11:55:16 -0700 Subject: [PATCH 16/32] Simplify the CmdStan prebuild in the test setup --- tests/testthat/helper-models.R | 8 +-- tests/testthat/setup.R | 89 +++++++++------------------------- 2 files changed, 27 insertions(+), 70 deletions(-) diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index e4ce3c540..ca8d50b82 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -40,20 +40,20 @@ test_run_dir <- function() { if (nzchar(dir)) dir else NULL } -with_test_lock <- function(key, code, timeout = 900, on_timeout = code) { +with_test_lock <- function(key, code, timeout = 900) { if (is.null(test_run_dir())) { - return(force(code)) + return(code) } lock <- file.path(test_run_dir(), paste0(key, ".lock")) deadline <- Sys.time() + timeout while (!dir.create(lock, showWarnings = FALSE)) { if (Sys.time() >= deadline) { - return(on_timeout) + return(code) } Sys.sleep(0.25) } on.exit(unlink(lock, recursive = TRUE)) - force(code) + code } testing_model <- function(name, ...) { diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index fe71150c8..f79fde45a 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -29,77 +29,34 @@ cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) if (identical(Sys.getenv("NOT_CRAN"), "true")) { - if ( - identical(Sys.getenv("CALLR_IS_RUNNING"), "true") && - !nzchar(Sys.getenv("CMDSTANR_TEST_SHARED")) - ) { + if (identical(Sys.getenv("CALLR_IS_RUNNING"), "true")) { root <- dirname(tempdir()) - for (dir in Sys.glob(file.path(root, "cmdstanr-tests-*"))) { - pid <- as.integer(sub("^cmdstanr-tests-", "", basename(dir))) - alive <- tryCatch( - ps::ps_is_running(ps::ps_handle(pid)), - error = function(e) FALSE - ) - if (!alive) { - unlink(dir, recursive = TRUE) - } - } + runs <- Sys.glob(file.path(root, "cmdstanr-tests-*")) + run_pids <- as.integer(sub("^cmdstanr-tests-", "", basename(runs))) + unlink(runs[!run_pids %in% ps::ps_pids()], recursive = TRUE) run_dir <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) dir.create(run_dir, showWarnings = FALSE) Sys.setenv(CMDSTANR_TEST_SHARED = run_dir) } - tryCatch( - { - with_test_lock("sundials-fpic", { - withr::with_options( - list(mc.cores = min(parallel::detectCores(), 4)), - check_sundials_fpic( - get_cmdstan_flags("CPPFLAGS_SUNDIALS"), - verbose = FALSE - ) - ) - }) - pending <- list(character(), "STAN_THREADS=true") - for (timeout in c(0, 900)) { - built <- vapply( - pending, - function(make_args) { - printed <- run_make( - c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), - quiet = TRUE - )$stdout - line <- grep( - "^PRECOMPILED_MODEL_HEADER", - trimws(readLines(textConnection(printed))), - value = TRUE - ) - header <- trimws( - sub("^PRECOMPILED_MODEL_HEADER[[:space:]]*=", "", line) - ) - if (length(header) != 1 || !nzchar(header)) { - return(TRUE) - } - header_path <- file.path(cmdstan_path(), header) - if (file.exists(header_path)) { - return(TRUE) - } - with_test_lock( - paste0("pch-", rlang::hash(make_args)), - { - if (!file.exists(header_path)) { - run_make(c(basename(header_path), make_args), quiet = TRUE) - } - TRUE - }, - timeout, - on_timeout = FALSE - ) - }, - logical(1) + with_test_lock("prebuild", { + 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")) { + header <- trimws( + sub( + ".*=", + "", + run_make( + c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), + quiet = TRUE + )$stdout ) - pending <- pending[!built] + ) + if (nzchar(header) && !file.exists(file.path(cmdstan_path(), header))) { + run_make(c(basename(header), make_args), quiet = TRUE) } - }, - error = function(e) message(conditionMessage(e)) - ) + } + }) } From 0c0c881c56135c43c1e2b3a3f0a2e9aee9c0628e Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 12:25:19 -0700 Subject: [PATCH 17/32] Build the precompiled headers from their full make target --- tests/testthat/setup.R | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index f79fde45a..5e0c13538 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -55,7 +55,7 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { ) ) if (nzchar(header) && !file.exists(file.path(cmdstan_path(), header))) { - run_make(c(basename(header), make_args), quiet = TRUE) + run_make(c(header, make_args), quiet = TRUE) } } }) From 589d855f921fd01383d6a30152b412afbd1331a8 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 15:49:02 -0700 Subject: [PATCH 18/32] Trying filelock again --- DESCRIPTION | 1 + tests/testthat/helper-models.R | 49 ++++++++++++---------------------- tests/testthat/setup.R | 37 +++++++++---------------- 3 files changed, 31 insertions(+), 56 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index f3a8627f6..e16450879 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), diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index ca8d50b82..ae8a1997e 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -35,45 +35,30 @@ cmdstan_example_file <- function() { file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan") } -test_run_dir <- function() { - dir <- Sys.getenv("CMDSTANR_TEST_SHARED") - if (nzchar(dir)) dir else NULL -} - -with_test_lock <- function(key, code, timeout = 900) { - if (is.null(test_run_dir())) { - return(code) - } - lock <- file.path(test_run_dir(), paste0(key, ".lock")) - deadline <- Sys.time() + timeout - while (!dir.create(lock, showWarnings = FALSE)) { - if (Sys.time() >= deadline) { - return(code) - } - Sys.sleep(0.25) - } - on.exit(unlink(lock, recursive = TRUE)) +with_test_lock <- function(key, code) { + lock <- filelock::lock( + file.path( + Sys.getenv("CMDSTANR_TEST_SHARED"), + paste0(key, ".lock") + ) + ) + on.exit(filelock::unlock(lock)) code } testing_model <- function(name, ...) { stan_file <- testing_stan_file(name) - if (is.null(test_run_dir())) { - return(cmdstan_model(stan_file = stan_file, ...)) - } exe <- executable_path(stan_file) files <- c(exe, build_record_path(exe)) - variant <- rlang::hash(list(cmdstan_path(), rlang::hash_file(stan_file), ...)) - cache <- file.path(test_run_dir(), variant) - with_test_lock(variant, { - if (dir.exists(cache)) { - file.copy( - file.path(cache, basename(files)), - dirname(exe), - overwrite = TRUE, - copy.date = TRUE - ) - } + key <- rlang::hash(list(cmdstan_path(), rlang::hash_file(stan_file), ...)) + cache <- file.path(Sys.getenv("CMDSTANR_TEST_SHARED"), key) + with_test_lock(key, { + file.copy( + file.path(cache, basename(files)), + dirname(exe), + overwrite = TRUE, + copy.date = TRUE + ) mod <- cmdstan_model(stan_file = stan_file, ...) dir.create(cache, showWarnings = FALSE) file.copy(files, cache, overwrite = TRUE, copy.date = TRUE) diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 5e0c13538..d3d65ec21 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -28,35 +28,24 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) +shared <- tempdir() +if (identical(Sys.getenv("CALLR_IS_RUNNING"), "true")) { + root <- dirname(tempdir()) + runs <- list.files(root, "^cmdstanr-tests-", full.names = TRUE) + alive <- paste0("cmdstanr-tests-", ps::ps_pids()) + unlink(runs[!basename(runs) %in% alive], recursive = TRUE) + shared <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) + dir.create(shared, showWarnings = FALSE) +} +Sys.setenv(CMDSTANR_TEST_SHARED = shared) + if (identical(Sys.getenv("NOT_CRAN"), "true")) { - if (identical(Sys.getenv("CALLR_IS_RUNNING"), "true")) { - root <- dirname(tempdir()) - runs <- Sys.glob(file.path(root, "cmdstanr-tests-*")) - run_pids <- as.integer(sub("^cmdstanr-tests-", "", basename(runs))) - unlink(runs[!run_pids %in% ps::ps_pids()], recursive = TRUE) - run_dir <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) - dir.create(run_dir, showWarnings = FALSE) - Sys.setenv(CMDSTANR_TEST_SHARED = run_dir) - } with_test_lock("prebuild", { 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")) { - header <- trimws( - sub( - ".*=", - "", - run_make( - c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), - quiet = TRUE - )$stdout - ) - ) - if (nzchar(header) && !file.exists(file.path(cmdstan_path(), header))) { - run_make(c(header, make_args), quiet = TRUE) - } - } + testing_model("bernoulli") + testing_model("bernoulli", cpp_options = list(stan_threads = TRUE)) }) } From 5d12deb5d1bdcb7348d5c055263fbcc13830a8d2 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 20:11:54 -0700 Subject: [PATCH 19/32] Warm up cmdstan once instead of sharing compile cache --- DESCRIPTION | 1 - tests/testthat/helper-models.R | 31 ++--------------- tests/testthat/setup.R | 34 +++++++++---------- .../testthat/test-model-compile-user_header.R | 2 +- 4 files changed, 19 insertions(+), 49 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index e16450879..325e9c6c3 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -66,7 +66,6 @@ Suggests: knitr (>= 1.37), loo (>= 2.0.0), progressr, - ps, qs2, Rcpp, RcppParallel, diff --git a/tests/testthat/helper-models.R b/tests/testthat/helper-models.R index ae8a1997e..8609a5061 100644 --- a/tests/testthat/helper-models.R +++ b/tests/testthat/helper-models.R @@ -35,35 +35,8 @@ cmdstan_example_file <- function() { file.path(cmdstan_path(), "examples", "bernoulli", "bernoulli.stan") } -with_test_lock <- function(key, code) { - lock <- filelock::lock( - file.path( - Sys.getenv("CMDSTANR_TEST_SHARED"), - paste0(key, ".lock") - ) - ) - on.exit(filelock::unlock(lock)) - code -} - -testing_model <- function(name, ...) { - stan_file <- testing_stan_file(name) - exe <- executable_path(stan_file) - files <- c(exe, build_record_path(exe)) - key <- rlang::hash(list(cmdstan_path(), rlang::hash_file(stan_file), ...)) - cache <- file.path(Sys.getenv("CMDSTANR_TEST_SHARED"), key) - with_test_lock(key, { - file.copy( - file.path(cache, basename(files)), - dirname(exe), - overwrite = TRUE, - copy.date = TRUE - ) - mod <- cmdstan_model(stan_file = stan_file, ...) - dir.create(cache, showWarnings = FALSE) - file.copy(files, cache, overwrite = TRUE, copy.date = TRUE) - mod - }) +testing_model <- function(name) { + cmdstan_model(stan_file = testing_stan_file(name)) } testing_fit <- diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index d3d65ec21..3a896e79c 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -28,24 +28,22 @@ cleanup_stan_artifacts <- function() { cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) -shared <- tempdir() -if (identical(Sys.getenv("CALLR_IS_RUNNING"), "true")) { - root <- dirname(tempdir()) - runs <- list.files(root, "^cmdstanr-tests-", full.names = TRUE) - alive <- paste0("cmdstanr-tests-", ps::ps_pids()) - unlink(runs[!basename(runs) %in% alive], recursive = TRUE) - shared <- file.path(root, paste0("cmdstanr-tests-", ps::ps_ppid())) - dir.create(shared, showWarnings = FALSE) -} -Sys.setenv(CMDSTANR_TEST_SHARED = shared) - if (identical(Sys.getenv("NOT_CRAN"), "true")) { - with_test_lock("prebuild", { - withr::with_options( - list(mc.cores = parallel::detectCores()), - check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), FALSE) + warmup <- file.path(dirname(tempdir()), "cmdstanr-warmup") + dir.create(warmup, showWarnings = FALSE) + lock <- filelock::lock(file.path(warmup, "lock")) + withr::with_options( + list(mc.cores = parallel::detectCores()), + check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), FALSE) + ) + for (threads in c(FALSE, TRUE)) { + dir <- file.path(warmup, threads) + dir.create(dir, showWarnings = FALSE) + cmdstan_model( + testing_stan_file("bernoulli"), + dir = dir, + cpp_options = list(stan_threads = threads) ) - testing_model("bernoulli") - testing_model("bernoulli", cpp_options = list(stan_threads = TRUE)) - }) + } + filelock::unlock(lock) } diff --git a/tests/testthat/test-model-compile-user_header.R b/tests/testthat/test-model-compile-user_header.R index c8a7d7667..dc0e9b1bf 100644 --- a/tests/testthat/test-model-compile-user_header.R +++ b/tests/testthat/test-model-compile-user_header.R @@ -72,7 +72,7 @@ test_that("cmdstan_model() records a user header", { }) test_that("cmdstan_model() honours an explicit user_header = NULL", { - model <- testing_model("bernoulli", user_header = NULL) + model <- cmdstan_model(testing_stan_file("bernoulli"), user_header = NULL) expect_null(model$user_header()) }) From 0d93d7aa9fea4796d2a08776e355c8b8d465ff50 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 21:51:39 -0700 Subject: [PATCH 20/32] Prebuild only the precompiled headers in the test warm-up --- tests/testthat/setup.R | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 3a896e79c..97d0673b3 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -36,14 +36,18 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { list(mc.cores = parallel::detectCores()), check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), FALSE) ) - for (threads in c(FALSE, TRUE)) { - dir <- file.path(warmup, threads) - dir.create(dir, showWarnings = FALSE) - cmdstan_model( - testing_stan_file("bernoulli"), - dir = dir, - cpp_options = list(stan_threads = threads) + for (make_args in list(character(), "STAN_THREADS=true")) { + header <- trimws( + sub( + ".*=", + "", + run_make( + c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), + quiet = TRUE + )$stdout + ) ) + run_make(c(header, make_args), quiet = TRUE) } filelock::unlock(lock) } From e5a202e92c55929a86d19c2fddf1609883d4c73a Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 16 Oct 2026 22:04:32 -0700 Subject: [PATCH 21/32] Only build the precompiled headers when they are missing --- tests/testthat/setup.R | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 97d0673b3..750a1b9d4 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -47,7 +47,9 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { )$stdout ) ) - run_make(c(header, make_args), quiet = TRUE) + if (nzchar(header) && !file.exists(file.path(cmdstan_path(), header))) { + run_make(c(header, make_args), quiet = TRUE) + } } filelock::unlock(lock) } From cc193a56ec42f1ca7993853417781a0d8bd85b7f Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Sat, 17 Oct 2026 09:02:52 -0700 Subject: [PATCH 22/32] Run the WSL tests with three workers --- .github/workflows/R-CMD-check-wsl.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index a7b5f59a1..d4a8f7410 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -29,7 +29,7 @@ jobs: R_REMOTES_NO_ERRORS_FROM_WARNINGS: true GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true - TESTTHAT_CPUS: 4 + TESTTHAT_CPUS: 3 CMDSTANR_OPENCL_TESTS: true steps: From 4fbbd83b07a459fa85f18e48e8d9a9753a2c9974 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 23 Oct 2026 16:52:45 -0700 Subject: [PATCH 23/32] Addressed some review comments --- .github/workflows/Test-coverage.yaml | 6 +- DESCRIPTION | 6 +- tests/testthat/README.md | 9 ++- tests/testthat/helper-envvars-and-paths.R | 92 +++++++++++++---------- tests/testthat/setup.R | 65 ++++++++++------ tests/testthat/test-failed-chains.R | 6 +- tests/testthat/test-fit-shared.R | 6 +- tests/testthat/test-install.R | 7 +- tests/testthat/test-installation-check.R | 4 +- tests/testthat/test-model-rebuild.R | 2 +- tests/testthat/test-utils.R | 2 + 11 files changed, 125 insertions(+), 80 deletions(-) diff --git a/.github/workflows/Test-coverage.yaml b/.github/workflows/Test-coverage.yaml index bcbe7fb2e..a4c360fb3 100644 --- a/.github/workflows/Test-coverage.yaml +++ b/.github/workflows/Test-coverage.yaml @@ -55,7 +55,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 325e9c6c3..0682e3f17 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -75,8 +75,6 @@ Suggests: VignetteBuilder: knitr Config/testthat/edition: 3 Config/testthat/parallel: true -Config/testthat/start-first: install, model-compile, model-rebuild, - fit-shared, fit-mcmc, model-sample, model-variables, model-methods, - fit-init, csv, failed-chains, model-init, model-expose-functions, - threads, model-diagnose, tuple-complex +Config/testthat/start-first: install, model-compile, fit-mcmc, + model-methods, model-rebuild, fit-shared Config/roxygen2/version: 8.1.1 diff --git a/tests/testthat/README.md b/tests/testthat/README.md index e23666ef9..1a2203065 100644 --- a/tests/testthat/README.md +++ b/tests/testthat/README.md @@ -32,8 +32,13 @@ 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 suite runs in parallel when `TESTTHAT_CPUS` is set, 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`. A test that changes the CmdStan +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 ac0a756a9..01c851565 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -165,9 +165,6 @@ 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. local_cmdstan_make_local <- function( cpp_options, envir = parent.frame(), @@ -180,45 +177,62 @@ local_cmdstan_make_local <- function( 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(.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) +} + local_private_cmdstan <- function(envir = parent.frame()) { shared <- cmdstan_path() - .cmdstanr$WSL <- grepl("//wsl$", shared, fixed = TRUE) if (is.null(private_cmdstan$path)) { - root <- tempfile("cmdstan-") - if (os_is_wsl()) { - root <- file.path(dirname(dirname(shared)), basename(root)) - withr::defer( - unlink(root, recursive = TRUE, force = TRUE), - testthat::teardown_env() - ) - } - private_cmdstan$path <- file.path(root, basename(shared)) - dir.create(root) - to <- private_cmdstan$path - if (os_is_wsl()) { - wsl_compatible_run( - command = "cp", - args = c("-a", wsl_safe_path(shared), wsl_safe_path(to)) - ) - } else if (os_is_windows()) { - system2( - "robocopy", - c( - shQuote(shared), - shQuote(to), - "/E", - "/MT:16", - "/NFL", - "/NDL", - "/NJH", - "/NJS", - "/NP" - ), - stdout = FALSE - ) - } else { - system2("cp", c("-a", shQuote(shared), shQuote(to))) - } + 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/setup.R b/tests/testthat/setup.R index 750a1b9d4..317ce49bf 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -1,7 +1,13 @@ -# CI runners have four cores, so run two chains at a time +# With NOT_CRAN=true, the first worker to get the lock prepares the CmdStan +# installation once, so parallel workers do not build in it at the same time: +# it adds -fPIC to make/local and rebuilds CmdStan if Linux needs it, then +# builds the precompiled headers and main objects, with and without threads. +# Tests that change the installation use a per-worker copy (see +# local_private_cmdstan()). Each worker runs two chains at a time, so four +# workers sample eight chains at once. options(mc.cores = 2) -stan_dir <- file.path(tempdir(), "stan") +stan_dir <- stan_fixture() dir.create(stan_dir, recursive = TRUE, showWarnings = FALSE) file.copy( list.files(test_path("resources", "stan"), full.names = TRUE), @@ -29,27 +35,42 @@ cleanup_stan_artifacts() withr::defer(cleanup_stan_artifacts(), testthat::teardown_env()) if (identical(Sys.getenv("NOT_CRAN"), "true")) { - warmup <- file.path(dirname(tempdir()), "cmdstanr-warmup") - dir.create(warmup, showWarnings = FALSE) - lock <- filelock::lock(file.path(warmup, "lock")) - 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")) { - header <- trimws( - sub( - ".*=", - "", - run_make( - c("-s", make_args, "print-PRECOMPILED_MODEL_HEADER"), - quiet = TRUE - )$stdout + 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)) + + make_variable <- function(make_args, name) { + trimws( + sub( + ".*=", + "", + run_make( + c("-s", make_args, paste0("print-", name)), + quiet = TRUE + )$stdout + ) ) + } + withr::with_options( + list(mc.cores = parallel::detectCores()), + check_sundials_fpic(get_cmdstan_flags("CPPFLAGS_SUNDIALS"), FALSE) ) - if (nzchar(header) && !file.exists(file.path(cmdstan_path(), header))) { - run_make(c(header, make_args), quiet = TRUE) + for (make_args in list(character(), "STAN_THREADS=true")) { + header <- make_variable(make_args, "PRECOMPILED_MODEL_HEADER") + main_o <- make_variable(make_args, "CMDSTAN_MAIN_O") + targets <- c( + header, + sub("\\.hpp\\.gch$", ".d", header), + main_o, + sub("\\.o$", ".d", main_o) + ) + targets <- targets[nzchar(targets)] + if (length(targets) > 0) { + run_make(c(targets, make_args), quiet = TRUE) + } } - } - filelock::unlock(lock) + }) } diff --git a/tests/testthat/test-failed-chains.R b/tests/testthat/test-failed-chains.R index 0020a2567..92ca8c8c2 100644 --- a/tests/testthat/test-failed-chains.R +++ b/tests/testthat/test-failed-chains.R @@ -1,9 +1,11 @@ skip_on_cran() set_cmdstan_path() +stan_program <- testing_stan_file("chain_fails") +stan_program_init_warnings <- testing_stan_file("init_warnings") -mod <- testing_model("chain_fails") -mod_init_warnings <- testing_model("init_warnings") +mod <- cmdstan_model(stan_file = stan_program) +mod_init_warnings <- cmdstan_model(stan_file = stan_program_init_warnings) make_all_fail <- function(x) { utils::capture.output( diff --git a/tests/testthat/test-fit-shared.R b/tests/testthat/test-fit-shared.R index 28557fb2d..fb6431681 100644 --- a/tests/testthat/test-fit-shared.R +++ b/tests/testthat/test-fit-shared.R @@ -690,9 +690,10 @@ test_that("sampling works with explicit and inferred include paths containing sp }) test_that("CmdStanModel created with exe_file works", { + stan_program <- testing_stan_file("bernoulli") data_list <- testing_data("bernoulli") - mod <- testing_model("bernoulli") + mod <- cmdstan_model(stan_file = stan_program) mod_exe <- cmdstan_model(exe_file = mod$exe_file()) utils::capture.output( @@ -727,9 +728,10 @@ test_that("CmdStanModel created with exe_file works", { ) expect_equal(fit_sample$draws(), fit_sample_exe$draws()) + stan_ppc_program <- testing_stan_file("bernoulli_ppc") data_ppc_list <- testing_data("bernoulli_ppc") - mod_bern_ppc <- testing_model("bernoulli_ppc") + mod_bern_ppc <- cmdstan_model(stan_file = stan_ppc_program) mod_bern_ppc_exe <- cmdstan_model(exe_file = mod_bern_ppc$exe_file()) utils::capture.output( diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index c74a85000..0c6c5b218 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -7,7 +7,7 @@ if (!nzchar(cmdstan_test_tarball_url)) { test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { build_cores <- min(parallel::detectCores(), 4) - dir <- withr::local_tempdir() + dir <- local_build_tempdir() withr::defer(set_cmdstan_path()) expect_message( expect_output( @@ -1637,10 +1637,7 @@ test_that("toolchain_PATH_env_var() rejects unsafe toolchain paths", { test_that("check_cmdstan_toolchain() stops with no Windows toolchain", { skip_if(!os_is_windows() || os_is_wsl()) - local_mocked_bindings( - os_is_wsl = function() FALSE, - toolchain_PATH_env_var = function() NULL - ) + local_mocked_bindings(toolchain_PATH_env_var = function() NULL) expect_snapshot(error = TRUE, check_cmdstan_toolchain()) }) diff --git a/tests/testthat/test-installation-check.R b/tests/testthat/test-installation-check.R index e886cd5cd..ed86fa970 100644 --- a/tests/testthat/test-installation-check.R +++ b/tests/testthat/test-installation-check.R @@ -32,14 +32,14 @@ test_that("a model is not built when the selected installation is gone", { }) test_that("check_syntax() and format() error naming the gone installation", { - mod <- testing_model("bernoulli") + mod <- cmdstan_model(stan_program) gone <- local_gone_installation() expect_error(mod$check_syntax(), gone, fixed = TRUE) expect_error(mod$format(), gone, fixed = TRUE) }) test_that("variables() works with the installation gone while variables_stan_file() does not", { - mod <- testing_model("bernoulli") + mod <- cmdstan_model(stan_program) gone <- local_gone_installation() expect_no_error(mod$variables()) expect_error(variables_stan_file(stan_program), gone, fixed = TRUE) 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-utils.R b/tests/testthat/test-utils.R index a3bbcd7bf..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() From 711cc10ef348d88330c482fe8595eac0f4cd3343 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 23 Oct 2026 17:20:29 -0700 Subject: [PATCH 24/32] Only build missing CmdStan targets in the test warm-up --- tests/testthat/setup.R | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 317ce49bf..681639c54 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -68,8 +68,9 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { sub("\\.o$", ".d", main_o) ) targets <- targets[nzchar(targets)] - if (length(targets) > 0) { - run_make(c(targets, make_args), quiet = TRUE) + missing <- targets[!file.exists(file.path(cmdstan_path(), targets))] + if (length(missing) > 0) { + run_make(c(missing, make_args), quiet = TRUE) } } }) From 928f2a842ffd425fe13bbbb5d096d88d1f652d7b Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Fri, 23 Oct 2026 20:58:41 -0700 Subject: [PATCH 25/32] Build with two cores on WSL and count autodiff-stack check once --- tests/testthat/test-install.R | 2 +- tests/testthat/test-model-methods.R | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 0c6c5b218..841584eb2 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -6,7 +6,7 @@ if (!nzchar(cmdstan_test_tarball_url)) { } test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { - build_cores <- min(parallel::detectCores(), 4) + build_cores <- min(parallel::detectCores(), if (os_is_wsl()) 2 else 4) dir <- local_build_tempdir() withr::defer(set_cmdstan_path()) expect_message( 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", { From b966bd2237f2a1741e696916c2466ba71d9d81ee Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Sat, 24 Oct 2026 03:31:25 -0700 Subject: [PATCH 26/32] Install CmdStan in the Windows temp directory again in the WSL install test --- tests/testthat/test-install.R | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index 841584eb2..b5a756d49 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -6,8 +6,8 @@ if (!nzchar(cmdstan_test_tarball_url)) { } test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { - build_cores <- min(parallel::detectCores(), if (os_is_wsl()) 2 else 4) - dir <- local_build_tempdir() + build_cores <- min(parallel::detectCores(), 4) + dir <- withr::local_tempdir() withr::defer(set_cmdstan_path()) expect_message( expect_output( From 6b665c481b051d9278c3dd60a1fde7c43fb57655 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Sat, 24 Oct 2026 13:48:08 -0700 Subject: [PATCH 27/32] Run the WSL tests serially --- .github/workflows/R-CMD-check-wsl.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index d4a8f7410..44e66be88 100644 --- a/.github/workflows/R-CMD-check-wsl.yaml +++ b/.github/workflows/R-CMD-check-wsl.yaml @@ -29,7 +29,7 @@ jobs: R_REMOTES_NO_ERRORS_FROM_WARNINGS: true GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} NOT_CRAN: true - TESTTHAT_CPUS: 3 + TESTTHAT_PARALLEL: false CMDSTANR_OPENCL_TESTS: true steps: From a7a6a32b68466edfac6ba53b8da7032682914e33 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Sat, 24 Oct 2026 19:46:25 -0700 Subject: [PATCH 28/32] Clean up stale CmdStan copies in the test setup and tidy the test docs --- tests/testthat/README.md | 2 +- tests/testthat/helper-envvars-and-paths.R | 2 +- tests/testthat/setup.R | 16 +++++++++------- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/tests/testthat/README.md b/tests/testthat/README.md index 1a2203065..fa3330a0e 100644 --- a/tests/testthat/README.md +++ b/tests/testthat/README.md @@ -34,7 +34,7 @@ call, so a test can go through the build code without a compiler. record when the calling frame ends, so a later real compile of the same program does not find them. -The suite runs in parallel when `TESTTHAT_CPUS` is set, so files must not +The full suite runs in parallel unless `TESTTHAT_PARALLEL=false`, 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`. A test that changes the CmdStan installation (`make/local`, `bin/`, a rebuild) calls `local_private_cmdstan()`, diff --git a/tests/testthat/helper-envvars-and-paths.R b/tests/testthat/helper-envvars-and-paths.R index 01c851565..1570cede6 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -214,7 +214,7 @@ copy_cmdstan <- function(from, to) { local_build_tempdir <- function(envir = parent.frame()) { if (!os_is_wsl()) { - return(withr::local_tempdir(.local_envir = envir)) + return(withr::local_tempdir("cmdstan-private-", .local_envir = envir)) } wsl_dir <- wsl_tempdir() withr::defer( diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index 681639c54..fefbc3d1b 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -1,10 +1,5 @@ -# With NOT_CRAN=true, the first worker to get the lock prepares the CmdStan -# installation once, so parallel workers do not build in it at the same time: -# it adds -fPIC to make/local and rebuilds CmdStan if Linux needs it, then -# builds the precompiled headers and main objects, with and without threads. -# Tests that change the installation use a per-worker copy (see -# local_private_cmdstan()). Each worker runs two chains at a time, so four -# workers sample eight chains at once. +# Parallel workers building the shared precompiled headers and main objects at +# the same time corrupt them, so the first worker to get the lock builds them. options(mc.cores = 2) stan_dir <- stan_fixture() @@ -42,6 +37,12 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { 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) + make_variable <- function(make_args, name) { trimws( sub( @@ -68,6 +69,7 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { 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(missing, make_args), quiet = TRUE) From 55c527adf3f0877946b02b6a73c35cb2552db00c Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Mon, 26 Oct 2026 19:08:49 -0700 Subject: [PATCH 29/32] Batch test warm-up queries and cap CI job times --- .github/workflows/R-CMD-check-wsl.yaml | 2 +- .github/workflows/R-CMD-check.yaml | 1 + .github/workflows/Test-coverage.yaml | 1 + tests/testthat/setup.R | 23 ++++++++--------------- 4 files changed, 11 insertions(+), 16 deletions(-) diff --git a/.github/workflows/R-CMD-check-wsl.yaml b/.github/workflows/R-CMD-check-wsl.yaml index 44e66be88..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 diff --git a/.github/workflows/R-CMD-check.yaml b/.github/workflows/R-CMD-check.yaml index d50fb8800..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 }}) diff --git a/.github/workflows/Test-coverage.yaml b/.github/workflows/Test-coverage.yaml index a4c360fb3..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 }} diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index fefbc3d1b..acd5ebf85 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -43,25 +43,18 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { ) unlink(stale[file.mtime(stale) < Sys.time() - 86400], recursive = TRUE) - make_variable <- function(make_args, name) { - trimws( - sub( - ".*=", - "", - run_make( - c("-s", make_args, paste0("print-", name)), - quiet = TRUE - )$stdout - ) - ) - } 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")) { - header <- make_variable(make_args, "PRECOMPILED_MODEL_HEADER") - main_o <- make_variable(make_args, "CMDSTAN_MAIN_O") + 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), @@ -72,7 +65,7 @@ if (identical(Sys.getenv("NOT_CRAN"), "true")) { # 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(missing, make_args), quiet = TRUE) + run_make(c("-j2", missing, make_args), quiet = TRUE) } } }) From c193e4c65f62f2a7beb7ff61b261ef9288e8e156 Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Mon, 26 Oct 2026 19:36:50 -0700 Subject: [PATCH 30/32] Keep WSL test installations on the Linux filesystem --- tests/testthat/test-install.R | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/testthat/test-install.R b/tests/testthat/test-install.R index b5a756d49..13ed586ed 100644 --- a/tests/testthat/test-install.R +++ b/tests/testthat/test-install.R @@ -7,7 +7,7 @@ if (!nzchar(cmdstan_test_tarball_url)) { test_that("install_cmdstan() successfully installs cmdstan and rebuild_cmdstan() rebuilds it", { build_cores <- min(parallel::detectCores(), 4) - dir <- withr::local_tempdir() + dir <- local_build_tempdir() withr::defer(set_cmdstan_path()) expect_message( expect_output( @@ -139,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" @@ -388,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( From 91d77d150735abda8381a371b1991571939e315d Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Tue, 27 Oct 2026 01:27:15 -0700 Subject: [PATCH 31/32] Batch WSL file permission checks --- R/utils.R | 19 ++++++++++--------- tests/testthat/test-path.R | 18 ++++++++++++++++++ 2 files changed, 28 insertions(+), 9 deletions(-) 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/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) From aee17504cc8048a1e8024d3313b3cb1131f6912e Mon Sep 17 00:00:00 2001 From: VisruthSK Date: Tue, 27 Oct 2026 09:30:35 -0700 Subject: [PATCH 32/32] Some small docs changes --- tests/testthat/README.md | 14 +++++++++----- tests/testthat/helper-envvars-and-paths.R | 6 ++++++ tests/testthat/setup.R | 7 +++++-- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/tests/testthat/README.md b/tests/testthat/README.md index fa3330a0e..0f93db579 100644 --- a/tests/testthat/README.md +++ b/tests/testthat/README.md @@ -34,11 +34,15 @@ call, so a test can go through the build code without a compiler. record when the calling frame ends, so a later real compile of the same program does not find them. -The full suite runs in parallel unless `TESTTHAT_PARALLEL=false`, 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`. A test that changes the CmdStan -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. +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 1570cede6..c71c99a60 100644 --- a/tests/testthat/helper-envvars-and-paths.R +++ b/tests/testthat/helper-envvars-and-paths.R @@ -165,6 +165,10 @@ local_make_local_backup <- function(envir = parent.frame()) { invisible(NULL) } +# 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(), @@ -224,6 +228,8 @@ local_build_tempdir <- function(envir = parent.frame()) { 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)) { diff --git a/tests/testthat/setup.R b/tests/testthat/setup.R index acd5ebf85..46b0ca74b 100644 --- a/tests/testthat/setup.R +++ b/tests/testthat/setup.R @@ -1,5 +1,4 @@ -# Parallel workers building the shared precompiled headers and main objects at -# the same time corrupt them, so the first worker to get the lock builds them. +# Each worker runs two chains at a time; CI runs up to four workers. options(mc.cores = 2) stan_dir <- stan_fixture() @@ -29,6 +28,10 @@ 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")