<%---------------------------------------------------------------------
  This *.md.rsp.rsp file is used to generate the *.md.rsp that
  is the copied to vignettes/.  The latter contains no dynamic
  code.   The reason for this is that this RSP file uses
  multisession futures and for some unknown reason those give
  errors during R CMD build on Windows.  Everywhere else they
  work including when building this RSP manually.  /HB 2016-04-12
 ---------------------------------------------------------------------%>
<%%@meta language="R-vignette" content="--------------------------------
%\VignetteIndexEntry{A Future for R: A Comprehensive Overview}
%\VignetteAuthor{Henrik Bengtsson}
%\VignetteKeyword{R}
%\VignetteKeyword{package}
%\VignetteKeyword{vignette}
%\VignetteKeyword{future}
%\VignetteKeyword{promise}
%\VignetteKeyword{lazy evaluation}
%\VignetteKeyword{synchronous}
%\VignetteKeyword{asynchronous}
%\VignetteKeyword{parallel}
%\VignetteKeyword{cluster}
%\VignetteEngine{R.rsp::rsp}
%\VignetteTangle{FALSE}

Do not edit the *.md.rsp file.  Instead edit the *.md.rsp.rsp (sic!)
file found under inst/vignettes-static/ of the source package.
--------------------------------------------------------------------"%%>
<%@meta language="R-vignette" content="--------------------------------
%\VignetteIndexEntry{A Future for R: A Comprehensive Overview}
%\VignetteAuthor{Henrik Bengtsson}
%\VignetteKeyword{R}
%\VignetteKeyword{package}
%\VignetteKeyword{vignette}
%\VignetteKeyword{future}
%\VignetteKeyword{promise}
%\VignetteKeyword{lazy evaluation}
%\VignetteKeyword{synchronous}
%\VignetteKeyword{asynchronous}
%\VignetteKeyword{parallel}
%\VignetteKeyword{cluster}
%\VignetteEngine{R.rsp::rsp}
%\VignetteTangle{FALSE}
--------------------------------------------------------------------"%>
<%
R.utils::use("R.utils")
withCapture <- function(expr, ..., envir = parent.frame()) {
  expr <- substitute(expr)
  res <- withCallingHandlers({
    do.call(R.utils::withCapture, args = list(expr, ..., envir = envir))
  }, warning = function(w) {
    cat(sprintf("Warning in %s: %s\n", deparse(conditionCall(w)), conditionMessage(w)))
    invokeRestart("muffleWarning")
  }, message = function(m) {
    cat(conditionMessage(m))
    invokeRestart("muffleMessage")
  })
  res
}

## Avoid warnings on 'Careful, you are setting up 2 localhost parallel workers ...'
Sys.setenv("R_PARALLELLY_MAXWORKERS_LOCALHOST" = "+Inf")
Sys.setenv("R_FUTURE_CONNECTIONS_ONMISUSE" = "ignore")
use("future")

`%<-%` <- future::`%<-%`
options("withCapture/newline" = FALSE)
options(mc.cores = 2L)
%>
# <%@meta name="title"%>

## Introduction

The purpose of the **[future]** package is to provide a very simple and uniform way of evaluating R expressions asynchronously using various resources available to the user.

In programming, a _future_ is an abstraction for a _value_ that may be available at some point in the future.  The state of a future can either be _unresolved_ or _resolved_.  As soon as it is resolved, the value is available instantaneously.  If the value is queried while the future is still unresolved, the current process is _blocked_ until the future is resolved.  It is possible to check whether a future is resolved or not without blocking.  Exactly where and when futures are resolved depends on what future backend is set to evaluate them.  For instance, a future can be resolved using the sequential backend, which means it is resolved in the current R session.  Other backends may be used for resolving futures asynchronously, for instance, in parallel on the current machine or on a compute cluster.

Here is an example illustrating how the basics of futures work.  First, consider the following code snippet that uses plain R code:

```r
> v <- {
+   cat("Hello world!\n")
+   3.14
+ }
Hello world!
> v
[1] 3.14
```

It works by assigning the value of an expression to variable `v` and we then print the value of `v`.  Moreover, when the expression for `v` is evaluated we also print a message.

Here is the same code snippet modified to use futures instead:

```r
> library(future)
> v %<-% {
+   cat("Hello world!\n")
+   3.14
+ }
> v
Hello world!
[1] 3.14
```

The difference is in how `v` is constructed; with plain R we use `<-` whereas with futures we use `%<-%`.  The other difference is that output is relayed _after_ the future is resolved (not during) and when the value is queried (see Vignette 'Outputting Text').

So why are futures useful?  Because we can choose to evaluate the future expression in a separate R process asynchronously by simply switching settings as:

```r
> library(future)
> plan(multisession)
> v %<-% {
+   cat("Hello world!\n")
+   3.14
+ }
> v
Hello world!
[1] 3.14
```

With asynchronous futures, the current/main R process does _not_ block, which means it is available for further processing while the futures are being resolved
in separate processes that run in the background.  In other words, futures provide a simple but yet powerful construct for parallel and distributed processing in R.


Now, if you cannot be bothered to read all the nitty-gritty details about futures, but just want to try them out, then skip to the end to play with the Mandelbrot demo using both parallel and non-parallel evaluation.



## Implicit or Explicit Futures

Futures can be created either _implicitly_ or _explicitly_.  In the introductory example above we used _implicit futures_ created via the `v %<-% { expr }` construct.  An alternative is _explicit futures_ using the `f <- future({ expr })` and `v <- value(f)` constructs.  With these, our example could alternatively be written as:

```r
> library(future)
> f <- future({
+   cat("Hello world!\n")
+   3.14
+ })
> v <- value(f)
Hello world!
> v
[1] 3.14
```

Either style of future construct works equally(*) well.  The implicit style is most similar to how regular R code is written.  In principle, all you have to do is to replace `<-` with a `%<-%` to turn the assignment into a future assignment.  On the other hand, this simplicity can also be deceiving, particularly when asynchronous futures are being used.  In contrast, the explicit style makes it much clearer that futures are being used, which lowers the risk for mistakes and better communicates the design to others reading your code.

(*) There are cases where `%<-%` cannot be used without some (small) modifications.  We will return to this in Section 'Constraints when using Implicit Futures' near the end of this document.



To summarize, for explicit futures, we use:

* `f <- future({ expr })` - creates a future
* `v <- value(f)` - gets the value of the future (blocks if not yet resolved)

For implicit futures, we use:

* `v %<-% { expr }` - creates a future and a promise to its value

To keep it simple, we will use the implicit style in the rest of this document, but everything discussed will also apply to explicit futures.



## Controlling How Futures are Resolved

The **future** package comes with built-in future backends that leverage the **parallel** package part of R itself. In addition to these backends, others exist in package extensions, e.g. **[future.callr]**, **[future.mirai]**, and **[future.batchtools]**. Below is an overview of the most common backends that you as an end-user can choose from.

| Package / Backend             | Features    | How futures are evaluated
|:----------------|:------------|:-----------------------------------------------------
| **future**<br> `sequential`    | 📶<br>♻️<br>         | sequentially and in the current R process; default 
| **future**<br> `multisession`  | 📶<br>♻️<br>        | parallelly via background R sessions on current machine
| **future**<br> `cluster`       | 📶<br>♻️*<br>       | parallelly in external R sessions on current, local, and/or remote machines
| **future**<br> `multicore`     | 📶<br>♻️<br> | (not recommended) parallelly via forked R processes on current machine; not with GUIs like RStudio; not on Windows
| **[future.callr]**<br> `callr`                    | 📶<br>♻️<br> | parallelly via transient **[callr]** background R sessions on current machine; all memory is returned as each future is resolved
| **[future.mirai]**<br> `mirai_multisession`       | 📶<br>♻️<br> | parallelly via **[mirai]** background R sessions on current machine; low latency
| **[future.mirai]**<br> `mirai_cluster`            |♻️<br> | parallelly via **[mirai]** daemons running locally or remotely
| **[future.batchtools]**<br> `batchtools_lsf`<br>`batchtools_openlava`<br>`batchtools_sge`<br>`batchtools_slurm`<br>`batchtools_torque` | 📶(soon)<br> ♻️<br> | parallelly on HPC job schedulers (Load Sharing Facility [LSF], OpenLava, TORQUE/PBS, Son/Sun/Oracle/Univa Grid Engine [SGE], Slurm) via **[batchtools]**; for long-running tasks; high latency |

📶: futures relay progress updates in real-time, e.g. **[progressr]**<br>
♻️: futures are interruptible and restartable; * disabled by default<br>
(next): next release; (soon): in a near-future release

By default, future expressions are evaluated synchronously in the current R session via the "sequential" backend.  In this section, we will go through the other backend and discuss what they have in common and how they differ.


### Consistent Behavior Across Futures

Before going through each of the different future backends, it is probably helpful to clarify the objectives of the Future API (as defined by the **future** package).  When programming with futures, it should not matter what future backend is used for executing code.  This is because we cannot really know what computational resources the user has access to, so the choice of parallel backend should be in the hands of the user and not the developer. In other words, the code should not make any assumptions on where and when futures are resolved.

One of the designs of the Future API was to encapsulate any differences such that all types of futures will appear to work the same.  This is despite the fact that expressions may be evaluated locally in the current R session or across the world in remote R sessions.  Another obvious advantage of having a consistent API and behavior among different types of futures is that it helps while prototyping.  Typically one would use sequential evaluation while building up a script and, later, when the script is fully developed, one may turn on asynchronous processing.

Because of this, the defaults of the different backends are such that the results and side effects of evaluating a future expression are as similar as possible.  More specifically, the following is true for all futures:

* All _evaluation is done in a local environment_ (i.e. `local({ expr })`) so that assignments do not affect the calling environment.  This is natural when evaluating in an external R process, but is also enforced when evaluating in the current R session.

* When a future is constructed, _global variables are identified_.  For asynchronous evaluation, globals are exported to the R process/session that will be evaluating the future expression.  For sequential futures with lazy evaluation (`lazy = TRUE`), globals are "frozen" (cloned to a local environment of the future).  Also, in order to protect against exporting too large objects by mistake, there is a built-in assertion that the total size of all globals is less than a given threshold (controllable via an option, cf. `help("future.options")`).  If the threshold is exceeded, an informative error is thrown.

* Future _expressions are only evaluated once_.  As soon as the value (or an error) has been collected it will be available for all succeeding requests.

Here is an example illustrating that all assignments are done to a local environment:

```r
<%=withCapture({
plan(sequential)
a <- 1
x %<-% {
  a <- 2
  2 * a
}
x
a
})%>
```

<%---
And here is an example illustrating that globals are validated already when the future is created:

```r
> rm(b)
> x %<-% { 2 * b }
Error in globalsOf(expr, envir = envir, substitute = FALSE, tweak = tweak,  :
  Identified a global object via static code inspection ({; 2 * b; }), but
failed to locate the corresponding object in the relevant environments: 'b'
```

We will return to global variables and global functions in Section 'Globals' near the end of this document.
---%>

Now we are ready to explore the different future backends.


### Synchronous Futures

Synchronous futures are resolved one after another and most commonly by the R process that creates them.  When a synchronous future is being resolved it blocks the main process until resolved.


#### Sequential Futures

Sequential futures are the default unless otherwise specified.  They were designed to behave as similar as possible to regular R evaluation while still fulfilling the Future API and its behaviors.  Here is an example illustrating their properties:

```r
<%=withCapture({
plan(sequential)
<%@include file="incl/future-1-overview-example2.R"%>
})%>
```

Since eager sequential evaluation is taking place, each of the three futures is resolved instantaneously in the moment it is created.  Note also how `pid` in the calling environment, which was assigned the process ID of the current process, is neither overwritten nor removed.  This is because futures are evaluated in a local environment.  Since synchronous (uni-)processing is used, future `b` is resolved by the main R process (still in a local environment), which is why the value of `b` and `pid` are the same.
<%
## Sanity checks
stopifnot(b == pid)
%>


### Asynchronous Futures

Next, we will turn to asynchronous futures, which are futures that are resolved in the background.  By design, these futures are non-blocking, that is, after being created the calling process is available for other tasks including creating additional futures.  It is only when the calling process tries to access the value of a future that is not yet resolved, or tries to create another asynchronous future when all available R processes are busy serving other futures, that it blocks.


#### Multisession Futures

We start with multisession futures because they are supported by all operating systems.  A multisession future is evaluated in a background R session running on the same machine as the calling R process.  Here is our example with multisession evaluation:

```r
<%=bfr <- withCapture({
plan(multisession, workers = 2)
<%@include file="incl/future-1-overview-example2.R"%>
})%>
```

The first thing we observe is that the values of `a`, `c` and `pid` are the same as previously.  However, we notice that `b` is different from before.  This is because future `b` is evaluated in a different R process and therefore it returns a different process ID.

<%
## Sanity checks
if (availableCores() == 1L) {
  stopifnot(b == pid)
} else {
  stopifnot(b != pid)
}
%>

When multisession evaluation is used, the package launches a set of R sessions in the background that will serve multisession futures by evaluating their expressions as they are created.  If all background sessions are busy serving other futures, the creation of the next multisession future is _blocked_ until a background session becomes available again.  The total number of background processes launched is decided by the value of `availableCores()`, e.g.

```r
<%=withCapture({
availableCores()
})%>
```

This particular result tells us that the `mc.cores` option was set such that we are allowed to use in total two (2) processes including the main process.  In other words, with these settings, there will be two (2) background processes serving the multisession futures.  The `availableCores()` is also agile to different options and system environment variables.  For instance, if compute cluster schedulers are used (e.g. TORQUE/PBS and Slurm), they set specific environment variables specifying the number of cores that was allotted to any given job; `availableCores()` acknowledges these as well.  If nothing else is specified, all available cores on the machine will be utilized, cf. `parallel::detectCores()`.  For more details, please see `help("availableCores", package = "parallelly")`.


#### Multicore Futures

On operating systems where R supports _forking_ of processes, which is basically all operating systems except Windows, an alternative to spawning R sessions in the background is to fork the existing R process.  To use multicore futures, when supported, specify:

```r
plan(multicore)
```
<%---
```r
<%=if (supportsMulticore()) {
withCapture({
plan(multicore, workers = 2)
<%@include file="incl/future-1-overview-example2.R"%>
})
} else {
## If this vignette is compiled on a system not supporting
## multicore processing, let's fake the future based on
## the output of the multisession example
bfr <- gsub("multisession", "multicore", bfr)
bfr <- gsub(b, b + 5L, bfr)
bfr
}%>
```
---%>

Just like for multisession futures, the maximum number of parallel processes running will be decided by `availableCores()`, since in both cases the evaluation is done on the local machine.

Forking an R process can be faster than working with a separate R session running in the background.  One reason is that the overhead of exporting large globals to the background session can be greater than when forking, and therefore shared memory, is used.  On the other hand, the shared memory is _read only_, meaning any modifications to shared objects by one of the forked processes ("workers") will cause a copy by the operating system.  This can also happen when the R garbage collector runs in one of the forked processes.

On the other hand, process forking is also considered unstable in some R environments.  For instance, when running R from within RStudio process forking may result in crashed R sessions.  Because of this, the **future** package disables multicore futures by default when running from RStudio.  See `help("supportsMulticore")` for more details.


#### Cluster Futures

Cluster futures evaluate expressions on an ad-hoc cluster (as implemented by the **parallel** package).  For instance, assume you have access to three nodes `n1`, `n2` and `n3`, you can then use these for asynchronous evaluation as:

```r
<%=
## For the vignette we cannot assume nodes n1, n2 and n3 exist.
## The second best we can do is to use the local machine.
hosts <- c("localhost", "localhost", "localhost")
bfr <- withCapture({
plan(cluster, workers = hosts)
<%@include file="incl/future-1-overview-example2.R"%>
})
bfr <- gsub('hosts', 'c("n1", "n2", "n3")', bfr)
bfr
%>
```
<%
## Sanity checks
stopifnot(b != pid)
%>

Any types of clusters that `parallel::makeCluster()` creates can be used for cluster futures.  For instance, the above cluster can be explicitly set up as:

```r
cl <- parallel::makeCluster(c("n1", "n2", "n3"))
plan(cluster, workers = cl)
```

Also, it is considered good style to shut down cluster `cl` when it is no longer needed, that is, calling `parallel::stopCluster(cl)`.  However, it will shut itself down if the main process is terminated.  For more information on how to set up and manage such clusters, see `help("makeCluster", package = "parallel")`.
Clusters created implicitly using `plan(cluster, workers = hosts)` where `hosts` is a character vector will also be shut down when the main R session terminates, or when the future backend is changed, e.g. by calling `plan(sequential)`.

Note that with automatic authentication setup (e.g. SSH key pairs), there is nothing preventing us from using the same approach for using a cluster of remote machines.

If you want to run multiple workers on each node, replicate the node name as many times as the number of workers to run on that node.  For example,

```
> plan(cluster, workers = c(rep("n1", times = 3), "n2", rep("n3", times = 5)))
```

will run three workers on `n1`, one on `n2`, and five on `n3`, in total nine parallel workers.


<%---
### Different Backends for Different Futures

Sometimes one may want to use an alternative backend for a specific future.  Although one can use `old <- plan(new)` and afterward `plan(old)` to temporarily switch backend, a simpler approach is to use the `%plan%` operator, e.g.

```r
<%=withCapture({
plan(sequential)
pid <- Sys.getpid()
pid
a %<-% { Sys.getpid() }
b %<-% { Sys.getpid() } %plan% multisession
c %<-% { Sys.getpid() } %plan% multisession
a
b
c
})%>
```

As seen by the different process IDs, future `a` is evaluated sequentially using the same process as the calling environment whereas the other two are evaluated using multisession futures.

<%
## Sanity checks
stopifnot(a == pid)
if (availableCores() == 1L) {
  stopifnot(b == pid, c == pid, c == b)
} else if (availableCores() == 2L && !supportsMulticore()) {
  stopifnot(b != pid, c != pid, c == b)
} else {
  stopifnot(b != pid, c != pid, c != b)
}
%>



However, using different backends for individual futures has the drawback of hardwiring the backend in the code, leaving the end user with no control.  Doing so may prevent some users from using your script or your package, because they do not have the sufficient resources.  It may also prevent users with a lot of resources from utilizing those because you assumed a less-powerful set of hardware.  Because of this, we recommend against the use of `%plan%` other than for interactive prototyping.
---%>

### Nested Futures and Evaluation Topologies

Thus far we have discussed what can be referred to as "flat topology" of futures, that is, all futures are created in and assigned to the same environment.  However, there is nothing stopping us from using a "nested topology" of futures, where one set of futures may, in turn, create another set of futures internally and so on.

For instance, here is an example of two "top" futures (`a` and `b`) that uses multisession evaluation and where the second future (`b`) in turn uses two internal futures:

```r
<%=withCapture({
plan(multisession, workers = 2)
<%@include file="incl/future-1-overview-example3.R"%>
pid
a
b
})%>
```

By inspecting the process IDs, we see that there are in total three different processes involved for resolving the futures.  There is the main R process
(pid <%= pid %>),
and there are the two processes used by `a`
(pid <%= a %>)
and `b`
(pid <%= b[1] %>).
However, the two futures (`b1` and `b2`) that are nested by `b` are evaluated by the same R process as `b`.  This is because nested futures use sequential evaluation unless otherwise specified.  There are a few reasons for this, but the main reason is that it protects us from spawning off a large number of background processes by mistake, e.g. via recursive calls.

<%
## Sanity checks
if (availableCores() == 1L) {
  stopifnot(a == pid, all(b == pid))
} else if (availableCores() == 2L && !supportsMulticore()) {
  stopifnot(a != pid, all(b != pid), !all(b != a), all(b == b[1]))
} else {
  stopifnot(a != pid, all(b != pid),  all(b != a), all(b == b[1]))
}
%>


To specify a different type of _evaluation topology_, other than the first level of futures being resolved by multisession evaluation and the second level by sequential evaluation, we can provide a sequence of nested backends by specifying a list to `plan()`.  To clarify, first, the same sequence of backends as used above can be explicitly specified as:

```r
plan(list(multisession, sequential))
```

We would actually get the same behavior if we try with multiple levels of multisession evaluations;

```r
<%=withCapture({
plan(list(multisession, multisession))
})%>
[...]
<%
<%@include file="incl/future-1-overview-example3.R"%>
%>
<%=withCapture({
pid
a
b
})%>
```

The second multisession backend will default to single, sequential
processing.  The reason for this is, also here, to protect us from
launching more processes than what the machine can support.  This is
the case for both multisession and multicore evaluation.

<%
## Sanity checks
if (availableCores() == 1L) {
  stopifnot(a == pid, all(b == pid))
} else if (availableCores() == 2L && !supportsMulticore()) {
  stopifnot(a != pid, all(b != pid), !all(b != a), all(b == b[1]))
} else {
  stopifnot(a != pid, all(b != pid),  all(b != a), all(b == b[1]))
}
%>

Continuing, if we start off with the sequential backend and then use the multisession backend for any nested futures, we get:

```r
<%=withCapture({
plan(list(sequential, multisession))
})%>
[...]
<%
<%@include file="incl/future-1-overview-example3.R"%>
%>
<%=withCapture({
pid
a
b
})%>
```

which clearly show that `a` and `b` are resolved in the calling
process (pid <%= pid %>) whereas the two nested futures (`b1` and
`b2`) are resolved in two separate R processes (pids <%= b[2] %> and
<%= b[3] %>).

<%
## Sanity checks
stopifnot(a == pid, b[1] == pid)
if (availableCores() == 1L) {
  stopifnot(all(b == b[1]))
} else if (availableCores() == 2L && !supportsMulticore()) {
  stopifnot(all(b[-1] != b[1]), b[2] == b[3])
} else {
  stopifnot(all(b[-1] != b[1]), b[2] != b[3])
}
%>


Having said this, it is indeed possible to use nested multisession backend that are not forced to sequential processing by explicitly specifying (read _forcing_) the number of workers available at each level.  In order to do this we need to "tweak" the default settings, which can be done as follows:

```r
<%=withCapture({
plan(list(
  tweak(multisession, workers = 2),
  tweak(multisession, workers = 2)
))})%>
[...]
<%
<%@include file="incl/future-1-overview-example3.R"%>
%>
<%=withCapture({
pid
a
b
})%>
```

First, we see that both `a` and `b` are resolved in different processes
(pids <%= a %> and <%= b[1] %>)
than the calling process
(pid <%= pid %>).
Second, the two nested futures (`b1` and `b2`) are resolved in yet two other R processes
(pids <%= b[2] %> and <%= b[3] %>).

<%
## Sanity checks
stopifnot(a != pid, b[1] != pid)
if (supportsMulticore()) {
} else {
  stopifnot(b[2] != b[1], b[3] != b[1])
}
%>

For more details on working with nested futures and different future backends at each level, see Vignette '[A Future for R: Future Topologies]'.


### Checking A Future without Blocking

It is possible to check whether a future has been resolved or not without blocking.  This can be done using the `resolved(f)` function, which takes an explicit future `f` as input.  If we work with implicit futures (as in all the examples above), we can use the `f <- futureOf(a)` function to retrieve the explicit future from an implicit one.  For example,

```r
<%=withCapture({
plan(multisession, workers = 2)
a %<-% {
  cat("Future 'a' ...")
  Sys.sleep(2)
  cat("done\n")
  Sys.getpid()
}

cat("Waiting for 'a' to be resolved ...\n")
f <- futureOf(a)
count <- 1
while (!resolved(f)) {
  cat(count, "\n")
  Sys.sleep(0.2)
  count <- count + 1
}
cat("Waiting for 'a' to be resolved ... DONE\n")

a
})%>
```


## Failed Futures

Sometimes the future is not what you expected.  If an error occurs while evaluating a future, the error is propagated and thrown as an error in the calling environment _when the future value is requested_.  For example, if we use lazy evaluation on a future that generates an error, we might see something like

```r
<%=withCapture({
plan(sequential)
b <- "hello"
a %<-% {
  cat("Future 'a' ...\n")
  log(b)
} %lazy% TRUE
cat("Everything is still ok although we have created a future that will fail.\n")
})%>
<% captureOutput(try(resolve(a), silent = TRUE)) %>
> a
Future 'a' ...
Error in log(b) : non-numeric argument to mathematical function
```

The error is thrown each time the value is requested, that is, if we try to get the value again, it will generate the same error (and output):

```r
> a
Future 'a' ...
Error in log(b) : non-numeric argument to mathematical function
In addition: Warning message:
restarting interrupted promise evaluation
```

To see the _last_ call in the call stack that gave the error, we can use the `backtrace()` function(\*) on the future, i.e.

```r
> backtrace(a)
[[1]]
log(a)
```

(\*\) The commonly used `traceback()` does not provide relevant information in the context of futures.  Furthermore, it is unfortunately not possible to see the list of calls (evaluated expressions) that led up to the error; only the call that gave the error (this is due to a limitation in `tryCatch()` used internally).


## Globals

Whenever an R expression is to be evaluated asynchronously (in parallel) or sequentially via lazy evaluation, global (aka "free") objects have to be identified and passed to the evaluator.  They need to be passed exactly as they were at the time the future was created, because, for lazy evaluation, globals may otherwise change between when it is created and when it is resolved.  For asynchronous processing, the reason globals need to be identified is so that they can be exported to the process that evaluates the future.

The **future** package tries to automate these tasks as far as possible.  It does this with help of the **[globals]** package, which uses static-code inspection to identify global variables.  If a global variable is identified, it is captured and made available to the evaluating process.
<%---
If it identifies a symbol that it believes is a global object, but it fails to locate it in the calling environment (or any the environment accessible from that one), an error is thrown immediately.  This minimizing the risk for run-time errors occurring later (sometimes much later) and in a different process (possible in a remote R session), which otherwise may be hard to troubleshoot.  For instance,

```r
> rm(a)
> x <- 5.0
> y %<-% { a * x }
Error in globalsOf(expr, envir = envir, substitute = FALSE, tweak = tweak,  :
  Identified a global object via static code inspection ({; a * x; }), but
failed to locate the corresponding object in the relevant environments: 'a'

> a <- 1.8
> y %<-% { a * x }
> y
[1] 9
```

---%>
Moreover, if a global is defined in a package, then that global is not exported.  Instead, it ensures that the corresponding package is attached when the future is evaluated.  This not only better reflects the setup of the main R session, but it also minimizes the need for exporting globals, which saves not only memory but also time and bandwidth, especially when using remote compute nodes.
<%---
As mentioned previously, for consistency across future backends, all types of futures collect and validate globals when created. This takes place before the future is sent to the future backend, meaning this validation takes place also for sequential and multicore (forks the calling process "as-is") futures where it would technically not be needed. This done in order for a future be send to any type of backend at any time. It also helps to assure that futures are resolved identically regardless of future backend.
---%>

Finally, it should be clarified that identifying globals from static code inspection alone is a challenging problem.  There will always be corner cases where automatic identification of globals fails so that either false globals are identified (less of a concern) or some of the true globals are missing (which will result in a run-time error or possibly the wrong results).  Vignette '[A Future for R: Common Issues with Solutions]' provides examples of common cases and explains how to avoid them as well as how to help the package to identify globals or to ignore falsely identified globals.  If that does not suffice, it is always possible to manually specify the global variables by their names (e.g. `globals = c("a", "slow_sum")`) or as name-value pairs (e.g. `globals = list(a = 42, slow_sum = my_sum)`).


## Constraints when using Implicit Futures

There is one limitation with implicit futures that does not exist for explicit ones.  Because an explicit future is just like any other object in R it can be assigned anywhere/to anything.  For instance, we can create several of them in a loop and assign them to a list, e.g.

```r
<%=withCapture({
plan(multisession, workers = 2)
fs <- list()
for (ii in 1:3) {
  fs[[ii]] <- future({ Sys.getpid() })
}
v <- value(fs)
str(v)
})%>
```

This is _not_ possible to do when using implicit futures.  This is because the `%<-%` assignment operator _cannot_ be used in all cases where the regular `<-` assignment operator can be used.  It can only be used to assign future values to _environments_ (including the calling environment) much like how `assign(name, value, envir)` works.  However, we can assign implicit futures to environments using _named indices_, e.g.

```r
<%=withCapture({
plan(multisession, workers = 2)
v <- new.env()
for (name in c("a", "b", "c")) {
  v[[name]] %<-% { Sys.getpid() }
}
v <- as.list(v)
str(v)
})%>
```

Here `as.list(v)` blocks until all futures in the environment `v` have been resolved.  Then their values are collected and returned as a regular list.

If _numeric indices_ are required, then _list environments_ can be used.  List environments, which are implemented by the **[listenv]** package, are regular environments with customized subsetting operators making it possible to index them much like how lists can be indexed.  By using list environments where we otherwise would use lists, we can also assign implicit futures to list-like objects using numeric indices.  For example,

```r
<%=withCapture({
library(listenv)
plan(multisession, workers = 2)
v <- listenv()
for (ii in 1:3) {
  v[[ii]] %<-% { Sys.getpid() }
}
v <- as.list(v)
str(v)
})%>
```

As previously, `as.list(v)` blocks until all futures are resolved.



## Demos

To see a live illustration of how different types of futures are evaluated, run the Mandelbrot demo of this package.  First, try with the sequential evaluation,

```r
library(future)
plan(sequential)
demo("mandelbrot", package = "future", ask = FALSE)
```

which resembles how the script would run if futures were not used.  Then, try multisession evaluation, which calculates the different Mandelbrot planes using parallel R processes running in the background.  Try,

```r
plan(multisession)
demo("mandelbrot", package = "future", ask = FALSE)
```

Finally, if you have access to multiple machines you can try to set up a cluster of workers and use them, e.g.

```r
plan(cluster, workers = c("n2", "n5", "n6", "n6", "n9"))
demo("mandelbrot", package = "future", ask = FALSE)
```

<%
## Make sure to shut down any parallel workers
plan(sequential)
%>

[batchtools]: https://cran.r-project.org/package=batchtools
[callr]: https://cran.r-project.org/package=callr
[mirai]: https://cran.r-project.org/package=mirai
[future]: https://future.futureverse.org
[future.batchtools]: https://future.batchtools.futureverse.org
[future.callr]: https://future.callr.futureverse.org
[future.mirai]: https://future.mirai.futureverse.org
[globals]: https://globals.futureverse.org
[listenv]: https://listenv.futureverse.org
[progressr]: https://progressr.futureverse.org
[A Future for R: Common Issues with Solutions]: future-4-issues.html
[A Future for R: Future Topologies]: future-3-topologies.html
