1.9 Errors, Cancellation, and Cleanup
1.9.1 Error propagation and system design
A simulation runs successfully on three workers. You start it on four workers and one crashes with a memory error. Whether the other workers keep running, whether the partial results survive, and whether the crashed task can be retried safely all depend on design choices in the parallel system.
1.9.2 Error propagation: when a worker fails
When one worker fails, the outcome depends on the parallel backend and on whether the failure is an R error or a crash of the whole process.
PSOCK clusters (spawned processes). An R error inside a task does not kill the worker. parallel catches it on the worker and sends it back, and parLapply() then stops in the main session with “one node produced an error”, discarding the results of the other tasks. The worker stays alive and the cluster stays usable. A crash is different. If the worker process dies (a segfault, or the operating system killing it for memory), the main session’s read fails with “error reading from connection”, the whole call fails, and every later call on that cluster fails with “error writing to connection”. You have to stop the cluster and make a new one.
A backend can respond to a failure in several ways: cancel the entire job, ignore the failure and continue with the other tasks, or mark the task as failed and retry it later. For its socket clusters parallel stops the whole call, which at least avoids a silent failure. mclapply() instead returns and leaves NULL or try-error elements with a warning.
Forked workers from mclapply(). A forked worker that crashes with a segfault exits immediately, and the parent sees its end of the pipe close. mclapply() returns NULL for every element that child was handling, with a warning, and an R error in a child comes back as a "try-error" object for each element of that child’s job, even those that did not fail.
Threaded backends. If workers are threads in the same process, one thread’s crash (segfault, assertion failure) crashes the entire process. All workers die together. This is the cost of shared memory and lack of process-level isolation.
1.9.3 Partial results and checkpointing
When a parallel job starts, the main process divides work among workers. Each worker processes its tasks. Results accumulate.
A worker can crash at task 800 of 1000, after tasks 1 to 799 have finished. Most R parallel backends do not save results incrementally. Results live in memory until the entire job finishes. If the main process crashes, all results are lost, even the completed ones.
The parallel package with parLapply() does not checkpoint. Results are collected into a list in the main process when the whole call returns. If the main process crashes, results vanish.
The future package, under plan(cluster) or plan(multisession), keeps results only in memory, on the worker until it sends them and in the main session afterwards. If a worker crashes before returning a result, that result is lost.
furrr’s future_map() takes .options = furrr_options(seed = 1234) for reproducible random numbers, but it does not checkpoint either.
Pipeline tools do checkpoint: targets stores each finished target on disk and skips it on the next run. parallel, future and mirai do not.
If checkpointing is important, you must implement it explicitly: write results to a file after each worker reports. On restart, skip tasks already finished.
1.9.4 Cancellation: stopping a running job
When you press Ctrl+C at the R console, the main process receives a signal (SIGINT). The standard behavior is to stop evaluation and return to the prompt.
The workers are separate processes, and whether the interrupt reaches them depends on the backend and on where R runs.
cl <- parallel::makePSOCKcluster(4)
result <- parallel::parLapply(cl, 1:400, function(x) {
Sys.sleep(0.1) # stands in for a long computation
sqrt(x)
})
# Press Ctrl+C while this runs in a terminal: the main session returns to
# the prompt, and each local worker drops its chunk and waits for the next callIn R 4.6.1, makePSOCKcluster() starts local workers so that they receive the console’s Ctrl+C too, and each worker’s command loop catches the interrupt, drops the task it was running, and goes back to waiting. mclapply() kills its children with SIGTERM when it is interrupted (mc.cleanup = TRUE, the default). A worker that never sees the interrupt, under a front end or backend that signals only the main session, keeps consuming CPU until it finishes its task. With parallel, its late result then sits unread in the socket, and the next call on the same cluster can pick up that stale answer. If you are not sure the workers stopped, stop the cluster and start a new one.
Clean shutdown requires explicit cleanup: parallel::stopCluster(cl), or future::plan(sequential), which shuts down the workers of the previous plan, before exiting.
1.9.5 Resource cleanup: files, connections, and memory
When a task ends, it must clean up resources: close file handles, disconnect from databases, free allocated memory.
In a sequential program, the runtime handles part of the cleanup. You allocate memory, and the garbage collector frees it. You open a file and register on.exit(close(con)), and R runs that when the function exits, error or not.
In parallel, each worker is its own process or thread. Resources allocated on a worker must be released by that worker. When a worker process dies, the operating system closes its files and sockets. The leaks that last are the ones in workers that survive an error and keep running.
worker_task <- function(file_path) {
fh <- file(file_path, "r")
tryCatch({
result <- readLines(fh)
process(result)
}, finally = {
close(fh) # cleanup must run even if process() fails
})
}The finally clause runs whether or not process() fails. Without it, every failed task leaves a connection open in a worker that is still alive. R allows 128 connections by default, three of them taken by the terminal (the --max-connections startup option changes that), so a long-running worker that leaks one per failure eventually stops with “all 128 connections are in use”.
1.9.6 Retry semantics: safety and determinism
Retrying a failed task requires care. If you retry without changing anything, the task fails the same way. If you retry with a different RNG state, results change, and reproducibility breaks.
Unsafe retries. A task fails partway through. You retry it on a different worker. The worker starts the task from the beginning. If the task uses random numbers, it draws from a different RNG stream (because it is a new worker or a later slot in the sequence). Results are different, and reproducibility is broken.
Safe retries with independent RNG streams. Each task receives a unique stream index. Task 47 always draws from stream 47, regardless of which worker runs it or how many times it retries. The task is deterministic from the stream’s perspective. Retries produce identical results.
The stream index must be part of the task definition, not dependent on scheduling.
# unsafe: the worker seeds once at startup, then every task draws from
# wherever that worker's stream has reached. Task 47's values depend on how
# many tasks this worker already ran, so a retry somewhere else differs.
worker_init <- function() set.seed(Sys.getpid())
map_fn <- function(i) {
rnorm(100)
}
# reproducible: the seed comes from the task id, so task 47 draws the same
# values on any worker, at any position in the queue, on any retry
map_fn <- function(i) {
set.seed(i)
rnorm(100)
}set.seed(i) makes each task reproducible, but R does not promise that the sequences started from neighboring integer seeds are independent of each other. The L’Ecuyer-CMRG streams in Reproducible Random Numbers in Parallel do come with that guarantee.
sunlight derives one L’Ecuyer-CMRG stream per task from the pool’s seed in the main process and ships it with the task. Task 47 draws from stream 47 whichever worker or chunk runs it, and again when the same call is run on a pool with the same seed.
clusterSetRNGStream() in the parallel package gives each worker its own stream, not each task. A task retried on a different worker therefore draws different numbers. For streams per task, compute them in the main process with nextRNGStream() and send one with each task, or use future.apply’s future.seed = TRUE, which does exactly that.
1.9.7 Deadlocks and resource ordering
When multiple workers compete for resources, deadlock can occur. Worker A holds resource X and waits for resource Y. Worker B holds resource Y and waits for resource X. Both wait forever.
In R parallelism, deadlocks are rare because workers are isolated. Each worker usually holds only resources it allocated. Deadlocks happen when workers take more than one shared resource:
- Two workers each lock one file and then wait for a lock on the other’s file.
- Workers hold connections from a database pool with limited slots while they wait for something that needs another connection.
Preventing deadlock requires discipline: acquire resources in the same order on all workers, use timeouts, or use a central resource manager that serializes access.
1.9.8 A practical error-handling pattern
Here is a pattern that handles errors, tracks results, and allows retries:
run_with_errors <- function(tasks, worker_fn, max_retries = 2) {
results <- list()
errors <- list()
for (task_id in seq_along(tasks)) {
retries <- 0
while (retries <= max_retries) {
tryCatch({
result <- worker_fn(task_id, tasks[[task_id]])
results[[task_id]] <- result
break # success
}, error = function(e) {
retries <<- retries + 1
if (retries > max_retries) {
errors[[task_id]] <<- e
}
})
}
}
list(results = results, errors = errors)
}This pattern:
- Attempts each task.
- Records errors without stopping.
- Retries failed tasks up to
max_retriestimes. - Returns both results and errors.
In production, write errors and completed results to a file. On restart, skip tasks already finished.
Further reading
- R Language Definition, Exception handling <https://cran.r-project.org/doc/manuals/r-release/R-lang.html#Exception-handling>:
stop(),warning()andon.exit(). - Condition Handling and Recovery <https://stat.ethz.ch/R-manual/R-devel/library/base/html/conditions.html>, R’s help page for
tryCatch(),withCallingHandlers()andfinally. - Processes vs Threads. Isolation and process safety.