Debian Codegraph @

R/future_promise.R

raw
1 debug_msg_can_print <- FALSE
2 debug_msg <- function(...) {
3 if (debug_msg_can_print) {
4 message(...)
5 }
6 }
7
8 assert_work_queue_pkgs <- local({
9 val <- NULL
10 function() {
11 if (!is.null(val)) {
12 return()
13 }
14 for (pkg in list(
15 list(name = "future", version = "1.21.0"),
16 list(name = "fastmap", version = "1.1.0")
17 )) {
18 if (!is_installed(pkg$name, pkg$version)) {
19 stop(
20 "Package `",
21 pkg$name,
22 "` (",
23 pkg$version,
24 ") needs to be installed"
25 )
26 }
27 }
28 val <<- TRUE
29 return()
30 }
31 })
32 future_worker_is_free <- function() {
33 future::nbrOfFreeWorkers() > 0
34 }
35
36 Delay <- R6Class(
37 "Delay",
38 private = list(
39 delay_count = 0
40 ),
41 public = list(
42 is_reset = function() {
43 private$delay_count == 0
44 },
45 reset = function() {
46 private$delay_count <- 0
47 },
48
49 increase = function() {
50 private$delay_count <- private$delay_count + 1
51 },
52
53 delay = function() {
54 stop("$delay() not implemented")
55 }
56 ),
57 active = list(
58 count = function() {
59 private$delay_count
60 }
61 )
62 )
63
64 ExpoDelay <- R6Class(
65 "ExpoDelay",
66 inherit = Delay,
67 private = list(
68 base = 1 / 100,
69 min_seconds = 0.01,
70 max_seconds = 2
71 ),
72 public = list(
73 initialize = function(
74 base = 1 / 100,
75 min_seconds = 0.01,
76 max_seconds = 2
77 ) {
78 stopifnot(length(base) == 1 && is.numeric(base) && base >= 0)
79 stopifnot(
80 length(min_seconds) == 1 && is.numeric(min_seconds) && min_seconds >= 0
81 )
82 stopifnot(
83 length(max_seconds) == 1 && is.numeric(max_seconds) && max_seconds >= 0
84 )
85
86 private$base <- base
87 private$max_seconds <- max_seconds
88 private$min_seconds <- min_seconds
89
90 self
91 },
92
93 # return number of milliseconds until next attempt
94 # will randomly backoff to avoid extra work on long poll times
95 delay = function() {
96 # calculate expo backoff value
97 expo_val <- private$base * ((2^private$delay_count) - 1)
98 # find random value
99 random_val <- runif(n = 1, max = min(private$max_seconds, expo_val))
100 # perform `min()` on second step to avoid `runif(1, min = 5, max = 4)` which produces `NaN`
101 max(private$min_seconds, random_val)
102 }
103 )
104 )
105
106
107 # Situations
108 # √ No future workers are busy. All future calls are `future_promises()`
109 # * Can be accomplished using future job followup promise which calls `$attempt_work()`
110 # √ All future workers are busy with other tasks (but will become available).
111 # * Require using delay
112 # √ While processing the first batch, existing future workers are taken over
113 # * Require delay
114
115 # FIFO queue of workers
116 #' Future promise work queue
117 #'
118 #'
119 #' An \pkg{R6} class to help with scheduling work to be completed. `WorkQueue` will only execute work if the `can_proceed()` returns `TRUE`. For the use case of `future`, `can_proceed()` defaults to `future::nbrOfFreeWorkers() > 0` which will not allow for work to be executed if a \pkg{future} worker is not available.
120 #'
121 #' `WorkQueue` will constantly try to start new work once prior work item finishes. However, if `can_proceed()` returns `FALSE` (no future workers are available) and there is more work to be done, then work is attempted later a random amount of time later using exponential backoff. The exponential backoff will cap out at 10 seconds to prevent unnecessarily large wait times.
122 #'
123 #' Each time `WorkQueue` tries to start more work, it will repeat until `can_proceed()` returns `FALSE` or there is no more work in the `queue`.
124 #'
125 #' @section Global event loop:
126 #'
127 #' The global loop is used by default as the internal `WorkQueue` "delayed check" uses a single delay check for the whole queue, rather than having each item in the queue attempt to process.
128 #' This behavior might change in the future, but we are not exactly sure how at this point.
129 #'
130 #' If a private `later` loop wants to become synchronous by running until all jobs are completed but is waiting on a `future_promise()`, the private loop will not complete unless the global loop is allowed to move forward.
131 #'
132 #' However, it is possible to use a private loop inside a user-defined `WorkQueue` may work which can be provided directly to `future_promise(queue=custom_queue)`. Having a concrete example (or need) will help us understand the problem better. If you have an example, please reach out .
133 #'
134 #' @seealso [`promises::future_promise_queue()`] which returns a `WorkQueue` which is cached per R session.
135 #' @keywords internal
136 WorkQueue <- R6Class(
137 "WorkQueue",
138
139 # TODO - private loop proposal:
140 # The queued data would actually be a list of queues whose _key_ matches
141 # the loop ID. This would require that `schedule_work()` take in `loop` and have each loop have its own queue.
142 # The scheduled work in each queue would contain the `work` function and `submission_time`.
143 # Once `can_proceed_fn()` returns TRUE, the queue with the earliest `submission_time` should be processed.
144 # This concept is similar to a merge sort when trying to merge two pre-sorted lists.
145 # Check time: O(k), k = number of later loops ever registered. (This could become big!)
146 # Maybe, if `ID != 0`, the queue is removed if the number of elements goes to 0.
147 # Check time: O(kk), kk <= k, kk = number of _active_ later loops.
148 #
149 # Thought process, let's say chromote used the global WorkQueue
150 # and wanted to have its local loop synchronize (.. while(later::loop_empty(local_loop)) later::run_now(local_loop)) ..).
151 # [ ] In `do_work()`, Get loop from `later::current_loop()`
152 # * If is global loop, get item with earliest submission time
153 # * If is private loop (ID != 0), get first item in private queue
154 # [ ] Validate that an work item finishing in loop X, has a promise created using loop X
155 # [ ] Would each private queue need its own delay check?
156 #
157 #
158 # Implementation question:
159 # * Would it be better if we have a larger WorkQueue class that managed many WorkQueues for each loop?
160 # * This would allow for each loop to have its own delay check, delay counter, and loop
161 private = list(
162 queue = "fastmap::fastqueue()",
163 can_proceed_fn = "future_worker_is_free()",
164 can_proceed_cache_val = NULL,
165 # only _really_ used for delay checking
166 loop = "later::global_loop()",
167 delay = "ExpoDelay$new()",
168
169 # Used as a semaphore to make sure only 1 call of `attempt_work()` is delayed
170 cancel_delayed_attempt_work = NULL,
171
172 # Increment delay. Used with ExpoDelay
173 increase_delay = function() {
174 debug_msg("increase_delay()...", private$delay$count)
175 # Increment delay and try again later
176 private$delay$increase()
177 },
178
179 # Reset delay and cancel any delayed `attempt_work()` calls
180 reset_delay = function() {
181 debug_msg("reset_delay()")
182 private$delay$reset()
183
184 # disable any delayed executions of `attempt_work`
185 if (is.function(private$cancel_delayed_attempt_work)) {
186 private$cancel_delayed_attempt_work()
187 }
188 private$cancel_delayed_attempt_work <- NULL
189 },
190
191 # Returns a logical which let's work begin
192 can_proceed = function() {
193 can_proceed_cache_val <- private$can_proceed_cache_val
194 # Return early if no work can be submitted.
195 if (!is.null(can_proceed_cache_val)) {
196 return(can_proceed_cache_val)
197 }
198
199 ret <- isTRUE(private$can_proceed_fn())
200
201 # If we can no longer proceed, then we should avoid asking if the status has changed within the current {later} loop execution
202 # The value will be reset after have giving {future} the possibility to update the number of available workers
203 # While there is a possibility that a fast {future} job could finish in the middle of submitting many `future_promise()` job requests,
204 # the time saved by not asking the {future} cluster many many status questions is faster overall
205 # https://github.com/rstudio/promises/pull/78
206 if (is_false(ret)) {
207 private$can_proceed_cache_val <- FALSE
208 # Reset `$can_proceed()` functionality in the next event loop execution
209 later(
210 loop = private$loop,
211 delay = 0,
212 function() {
213 private$can_proceed_cache_val <- NULL
214 }
215 )
216 }
217 ret
218 },
219
220 # Function to attempt as much work as possible
221 # If no workers are available and a queue has elements,
222 # If a delayed check has already been registered, Return
223 # Else, check again after some delay
224 attempt_work = function(can_delay = FALSE) {
225 debug_msg('attempt_work()')
226 # If nothing to start, return early
227 if (private$queue$size() == 0) {
228 return()
229 }
230
231 # If we are not waiting on someone else, we can do work now
232 while ((private$queue$size() > 0) && private$can_proceed()) {
233 # Do work right away
234 private$reset_delay()
235 private$do_work()
236 }
237
238 # If there are still items to be processed, but we can not proceed...
239 if (private$queue$size() > 0 && !private$can_proceed()) {
240 # If we are allowed to delay (default FALSE), or nothing is currently delaying
241 if (can_delay || is.null(private$cancel_delayed_attempt_work)) {
242 # Try again later
243 private$increase_delay()
244 private$cancel_delayed_attempt_work <-
245 later(
246 loop = private$loop,
247 delay = private$delay$delay(),
248 function() {
249 private$attempt_work(can_delay = TRUE)
250 }
251 )
252 }
253 }
254 },
255
256 # Actually process an item in the queue
257 do_work = function() {
258 debug_msg("do_work()")
259
260 # Get first item in queue
261 work_fn <- private$queue$remove()
262
263 # Safety check...
264 # If nothing is returned, no work to be done. Return early
265 if (!is.function(work_fn)) {
266 return()
267 }
268
269 # Do scheduled work
270 debug_msg("execute work")
271 future_job <- work_fn()
272
273 # Try to attempt work immediately after the future job has finished
274 # (whether it succeeds or fails doesn't matter)
275 continue_work <- function() {
276 debug_msg("finished work. queue size: ", private$queue$size())
277 private$attempt_work()
278 }
279
280 # We're not using finally() here because we don't want rejections to be
281 # propagated (which would result in a warning). Any warnings will be
282 # handled by the user using a different promise object.
283 # https://github.com/rstudio/promises/issues/86
284 then(future_job, onFulfilled = continue_work, onRejected = continue_work)
285
286 return()
287 }
288 ),
289 public = list(
290 #' @description Create a new `WorkQueue`
291 #' @param can_proceed Function that should return a logical value. If `TRUE` is returned, then the next scheduled work will be executed. By default, this function checks if \code{\link[future:nbrOfWorkers]{future::nbrOfFreeWorkers()} > 0}
292 #' @param queue Queue object to use to store the scheduled work. By default, this is a "First In, First Out" queue using [fastmap::fastqueue()]. If using your own queue, it should have the methods `$add(x)`, `$remove()`, `$size()`.
293 #' @param loop \pkg{later} loop to use for calculating the next delayed check. Defaults to [later::global_loop()].
294 initialize = function(
295 # defaults to a future::plan agnostic function
296 can_proceed = future_worker_is_free,
297 queue = fastmap::fastqueue(), # FIFO
298 loop = later::global_loop()
299 ) {
300 stopifnot(is.function(can_proceed))
301 stopifnot(
302 is.function(queue$add) &&
303 is.function(queue$remove) &&
304 is.function(queue$size)
305 )
306 stopifnot(inherits(loop, "event_loop"))
307 delay <- ExpoDelay$new()
308 stopifnot(inherits(delay, "Delay"))
309
310 private$can_proceed_fn <- can_proceed
311 private$queue <- queue
312 private$loop <- loop
313 private$delay <- delay
314
315 # make sure delay is reset
316 private$reset_delay()
317
318 self
319 },
320
321 # add to schedule only
322 #' Schedule work
323 #' @param fn function to execute when `can_proceed()` returns `TRUE`.
324 schedule_work = function(fn) {
325 debug_msg("schedule_work()")
326 stopifnot(is.function(fn))
327 private$queue$add(fn)
328
329 private$attempt_work()
330
331 invisible(self)
332 }
333 )
334 )
335
336
337 #' @describeIn future_promise Default `future_promise()` work queue to use. This function returns a [`promises::WorkQueue`] that is cached per R session.
338 #' @seealso [`promises::WorkQueue`]
339 #' @export
340 future_promise_queue <- local({
341 future_promise_queue_ <- NULL
342 function() {
343 if (is.null(future_promise_queue_)) {
344 assert_work_queue_pkgs()
345 future_promise_queue_ <<- WorkQueue$new()
346 }
347 future_promise_queue_
348 }
349 })
350
351
352 #' \pkg{future} promise
353 #'
354 #'
355 #' When submitting \pkg{future} work, \pkg{future} (by design) will block the main R session until a worker becomes available.
356 #' This occurs when there is more submitted \pkg{future} work than there are available \pkg{future} workers.
357 #' To counter this situation, we can create a promise to execute work using future (using `future_promise()`) and only begin the work if a \pkg{future} worker is available.
358 #'
359 #' Using `future_promise()` is recommended whenever a continuous runtime is used, such as with \pkg{plumber} or \pkg{shiny}.
360 #'
361 #' For more details and examples, please see the [`vignette("future_promise", "promises")`](https://rstudio.github.io/promises/articles/promises_05b_future_promise.html) vignette.
362 #' @describeIn future_promise Creates a [promise()] that will execute the `expr` using [future::future()].
363 #' @inheritParams future::future
364 #' @param expr An R expression. While the `expr` is eventually sent to [`future::future()`], please use the same precautions that you would use with regular `promises::promise()` expressions. `future_promise()` may have to hold the `expr` in a [promise()] while waiting for a \pkg{future} worker to become available.
365 #' @param ... extra parameters provided to [`future::future()`]
366 #' @param queue A queue that is used to schedule work to be done using [future::future()]. This queue defaults to [`promises::future_promise_queue()`] and requires that method `queue$schedule_work(fn)` exist. This method should take in a function that will execute the promised \pkg{future} work.
367 #' @return Unlike [`future::future()`], `future_promise()` returns a [promise()] object that will eventually resolve the \pkg{future} `expr`.
368 #' @examples
369 #' \dontrun{# Relative start time
370 #' start <- Sys.time()
371 #' # Helper to force two `future` workers
372 #' with_two_workers <- function(expr) {
373 #' if (!require("future")) {
374 #' message("`future` not installed")
375 #' return()
376 #' }
377 #' old_plan <- future::plan(future::multisession, workers = 2)
378 #' on.exit({future::plan(old_plan)}, add = TRUE)
379 #' start <<- Sys.time()
380 #' force(expr)
381 #' while(!later::loop_empty()) {Sys.sleep(0.1); later::run_now()}
382 #' invisible()
383 #' }
384 #' # Print a status message. Ex: `"PID: XXX; 2.5s promise done"`
385 #' print_msg <- function(pid, msg) {
386 #' message(
387 #' "PID: ", pid, "; ",
388 #' round(difftime(Sys.time(), start, units = "secs"), digits = 1), "s " ,
389 #' msg
390 #' )
391 #' }
392 #'
393 #' # `"promise done"` will appear after four workers are done and the main R session is not blocked
394 #' # The important thing to note is the first four times will be roughly the same
395 #' with_two_workers({
396 #' promise_resolve(Sys.getpid()) |>
397 #' then(\(x) {print_msg("promise done")})
398 #' for (i in 1:6) {
399 #' future::future({Sys.sleep(1); Sys.getpid()}) |>
400 #' then(\(x) {print_msg("future done")})
401 #' }
402 #' })
403 #' {
404 #' #> PID: XXX; 2.5s promise done
405 #' #> PID: YYY; 2.6s future done
406 #' #> PID: ZZZ; 2.6s future done
407 #' #> PID: YYY; 2.6s future done
408 #' #> PID: ZZZ; 2.6s future done
409 #' #> PID: YYY; 3.4s future done
410 #' #> PID: ZZZ; 3.6s future done
411 #' }
412 #'
413 #' # `"promise done"` will almost immediately, before any workers have completed
414 #' # The first two `"future done"` comments appear earlier the example above
415 #' with_two_workers({
416 #' promise_resolve(Sys.getpid()) |>
417 #' then(\(x) {print_msg("promise")})
418 #' for (i in 1:6) {
419 #' future_promise({Sys.sleep(1); Sys.getpid()}) |>
420 #' then(\(x) {print_msg("future done")})
421 #' }
422 #' })
423 #' {
424 #' #> PID: XXX; 0.2s promise done
425 #' #> PID: YYY; 1.3s future done
426 #' #> PID: ZZZ; 1.4s future done
427 #' #> PID: YYY; 2.5s future done
428 #' #> PID: ZZZ; 2.6s future done
429 #' #> PID: YYY; 3.4s future done
430 #' #> PID: ZZZ; 3.6s future done
431 #' }}
432 #' @export
433 future_promise <- function(
434 expr = NULL,
435 envir = parent.frame(),
436 ...,
437 substitute = TRUE,
438 queue = future_promise_queue()
439 ) {
440 # make sure queue is the right structure
441 stopifnot(
442 is.function(queue$schedule_work) &&
443 length(formals(queue$schedule_work)) >= 1
444 )
445
446 if (substitute) {
447 expr <- substitute(expr)
448 }
449
450 # Force all variables to curb values changing before execution
451 # Does NOT fix R environment values changing
452 force(envir)
453 force(substitute)
454 force(list(...))
455
456 ## Record future object (but do not start it yet; lazy = TRUE)
457 future_job <- future::future(
458 expr,
459 envir = envir,
460 substitute = FALSE,
461 ...,
462 lazy = TRUE
463 )
464
465 promise(function(resolve, reject) {
466 # add to queue
467 queue$schedule_work(function() {
468 # Resolve the outer promising job value
469 # Kick off the future job
470 resolve(future_job)
471 # Return a promising object that can be chained by the `queue` after executing this _work_
472 future_job
473 })
474 })
475 }