@@ -149,6 +149,44 @@ test_that("Methods can be compiled with model", {
149149 expect_equal(unconstrained_variables , c(0.6 ))
150150})
151151
152+ test_that(" Reloaded models recompile model methods lazily after saveRDS/readRDS" , {
153+ # Also tests that fitted model objects are returned without error after
154+ # saveRDS/readRDS when model methods are compiled: https://github.com/stan-dev/cmdstanr/issues/1157
155+ mod <- cmdstan_model(
156+ testing_stan_file(" bernoulli_log_lik" ),
157+ force_recompile = TRUE ,
158+ compile_model_methods = TRUE
159+ )
160+ temp_rds_file <- tempfile(fileext = " .RDS" )
161+ saveRDS(mod , temp_rds_file )
162+ mod2 <- readRDS(temp_rds_file )
163+
164+ expect_no_error(
165+ utils :: capture.output(
166+ fit <- mod2 $ optimize(data = data_list )
167+ )
168+ )
169+ expect_equal(fit $ log_prob(unconstrained_variables = c(0.1 )),
170+ - 8.6327599208828509347 )
171+ })
172+
173+ test_that(" stale model-method bindings are detected and dropped" , {
174+ mod <- cmdstan_model(
175+ testing_stan_file(" bernoulli_log_lik" ),
176+ force_recompile = TRUE ,
177+ compile_model_methods = TRUE
178+ )
179+ temp_rds_file <- tempfile(fileext = " .RDS" )
180+ saveRDS(mod , temp_rds_file )
181+ mod2 <- readRDS(temp_rds_file )
182+ model_methods_env <- mod2 $ .__enclos_env__ $ private $ model_methods_env_
183+
184+ expect_true(source_cpp_native_symbol_is_null(model_methods_env $ model_ptr ))
185+ expect_true(drop_stale_model_methods(model_methods_env ))
186+ expect_equal(ls(model_methods_env , all.names = TRUE ), " hpp_code_" )
187+ expect_false(drop_stale_model_methods(model_methods_env ))
188+ })
189+
152190test_that(" unconstrain_variables correctly handles zero-length containers" , {
153191 model_code <- "
154192 data {
0 commit comments