From d4f8386a9be04e5d7c54cd231a9425e508a4276d Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Sat, 7 Nov 2026 14:18:22 -0700 Subject: [PATCH] Write hostSpeed.rds and fitMemory.rds at rebalance and fit end, not every generation Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_014G18Mik3fH4z5M5CyMSUS6 --- NEWS.md | 2 ++ R/DEoptim.R | 16 ++++++---- R/fitMemory.R | 7 +++-- R/hostSpeed.R | 32 ++++++++++++++++---- tests/testthat/test-hostSpeed.R | 52 +++++++++++++++++++++++++++++++++ 5 files changed, 96 insertions(+), 13 deletions(-) diff --git a/NEWS.md b/NEWS.md index 414462c..a9bbcbb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # clusters (development version) +* A fit no longer reads and rewrites the shared `hostSpeed.rds` and `fitMemory.rds` after every generation, which took 2.9 s with all workers idle at 367k rows (8 s at a full 30-day window; 0.03 s on an empty file). `DEoptimIterative()` keeps its records in memory and writes them at each rebalance (`options(clusters.rebalanceEvery)`, default 100 generations), which reads them, and when the fit ends, under the same lock; the files, columns and record semantics are unchanged, so other versions keep sharing them. A fit that is killed loses the records since its last write. + * `plan_psock_min()` mirrors every library of `libPath` (or `.libPaths()`) to the other hosts, in order, not only the first; R's own library is skipped. A single `libPath` behaves as before. A worker's `.libPaths()` now starts with those libraries, in order; the per-user library (`R_LIBS_USER`) comes after them, not first, so what is installed there no longer shadows the run's libraries. * Fixed: a cluster rebuilt after a worker died mid-fit kept every worker of its first host but only one of each other host (`.addNode()` added only the first node of the piece `.startReachable()` gave it). Sending the fit's objects to the rebuilt cluster then reached a NULL node ("no applicable method for 'sendData'"), the `clusterExport()` fallback left replies unread on the other workers, and DEoptim failed with "objective function result has different length than parameter matrix" (FireSense, 2026-11-02: 11 of 13 fits failed after the workers of two hosts were killed). The rebuilt cluster now has every worker it started. diff --git a/R/DEoptim.R b/R/DEoptim.R index b0bf3e1..0d16025 100644 --- a/R/DEoptim.R +++ b/R/DEoptim.R @@ -282,6 +282,10 @@ DEoptimIterative <- function(fn, lower, upper, control, ..., convergence <- deoptimConvergence(convergence) progressFile <- .progressStart(progressFile, figurePath, runName) ranEvaluations <- list() # evaluations computed in this call, not replayed from the cache + ## The host-speed and memory records stay here and are written to the shared ledgers when the workers are + ## rebalanced (which reads them) and when the fit ends, not after every generation (see .replaceRecords()). + pendingRecords <- new.env() + on.exit(.flushRecords(pendingRecords), add = TRUE) ## Progress figures are drawn by the master while every worker waits: 8.3 s of each 53 s generation ## (16% of the wall time) in a FireSense fit (ELF 4.2.2, 2026-09-28). They are drawn only for a chunk ## whose generations include a multiple of `plotEvery`, and always for the final chunk. @@ -418,8 +422,9 @@ DEoptimIterative <- function(fn, lower, upper, control, ..., if (computedNow && !is.null(DE[[iter]]$member$evaluations)) { ranEvaluations[[length(ranEvaluations) + 1L]] <- DE[[iter]]$member$evaluations .recordHostSpeed(list(DE[[iter]]$member$evaluations), id = .chunkId(runName, iter), - booked = .bookedByNodename(control$cluster)) - .recordFitMemory(list(DE[[iter]]$member$evaluations), runName = runName, id = .chunkId(runName, iter)) + booked = .bookedByNodename(control$cluster), pending = pendingRecords) + .recordFitMemory(list(DE[[iter]]$member$evaluations), runName = runName, id = .chunkId(runName, iter), + pending = pendingRecords) message(.evaluationTimes(DE[[iter]]$member$evaluations, chunkLengths[iter], proc.time()[["elapsed"]] - chunkStarted)) } @@ -442,9 +447,10 @@ DEoptimIterative <- function(fn, lower, upper, control, ..., } rebalance <- attr(control$cluster, "rebalance", exact = TRUE) - if (computedNow && rebalanceEvery > 0L && is.function(rebalance) && - chunkEnds[iter] %/% rebalanceEvery > (chunkEnds[iter] - chunkLengths[iter]) %/% rebalanceEvery && - iter < length(itersToDo)) + rebalanceDue <- computedNow && rebalanceEvery > 0L && + chunkEnds[iter] %/% rebalanceEvery > (chunkEnds[iter] - chunkLengths[iter]) %/% rebalanceEvery + if (rebalanceDue) .flushRecords(pendingRecords) # placement reads the ledgers + if (rebalanceDue && is.function(rebalance) && iter < length(itersToDo)) control$cluster <- rebalance(control$cluster) control$initialpop <- DE[[iter]]$member$pop diff --git a/R/fitMemory.R b/R/fitMemory.R index 32f397e..2ac4c68 100644 --- a/R/fitMemory.R +++ b/R/fitMemory.R @@ -26,8 +26,9 @@ ## Append the memory of one chunk of evaluations (a list of `member$evaluations` data frames with `host`, ## `pid` and `peakGB`) to fitMemory.rds: one row per chunk, summarising its workers' peaks (each worker's ## largest reading). `id` names the chunk and replaces its earlier row (see .recordHostSpeed()). Never -## fails the fit. -.recordFitMemory <- function(evaluations, runName, id, path = getOption("clusters.reservationsPath")) { +## fails the fit. `pending`: see .replaceRecords(). +.recordFitMemory <- function(evaluations, runName, id, path = getOption("clusters.reservationsPath"), + pending = NULL) { tryCatch({ evaluations <- Filter(function(x) is.data.frame(x) && all(c("host", "pid", "peakGB") %in% names(x)), evaluations) @@ -42,7 +43,7 @@ runName <- if (length(runName) && nzchar(as.character(runName)[1])) as.character(runName)[1] else NA_character_ new <- data.frame(runName = runName, id = id, time = Sys.time(), workers = length(peak), memMedianGB = stats::median(peak), memMaxGB = max(peak), stringsAsFactors = FALSE) - .replaceRecords(.fitMemoryFile(path), new, .fitMemoryColumns) + .replaceRecords(.fitMemoryFile(path), new, .fitMemoryColumns, pending) invisible(new) }, error = function(e) { warning("Could not record fit memory: ", conditionMessage(e), call. = FALSE) diff --git a/R/hostSpeed.R b/R/hostSpeed.R index 254a84f..85649cf 100644 --- a/R/hostSpeed.R +++ b/R/hostSpeed.R @@ -16,8 +16,16 @@ Filter(function(x) is.data.frame(x) && "host" %in% names(x), evaluations) ## Add `new` rows to the records in `file` (hostSpeed.rds, fitMemory.rds), dropping the rows of the same -## `id` and those older than the window. One lock for the read and the write. -.replaceRecords <- function(file, new, columns) { +## `id` and those older than the window. One lock for the read and the write. Reading and rewriting the whole +## shared file takes 2.9 s with 367k rows (8 s at a full window) while every worker waits, so a fit passes +## `pending` (an environment, see .flushRecords()) to keep its rows in memory instead; the file is then +## written when the fit flushes. The file's format is the same either way. +.replaceRecords <- function(file, new, columns, pending = NULL) { + if (is.environment(pending)) { + kept <- pending[[file]]$new + pending[[file]] <- list(new = rbind(kept[!kept$id %in% new$id, , drop = FALSE], new), columns = columns) + return(invisible(NULL)) + } .withReservationLock(file, { old <- if (file.exists(file)) tryCatch(readRDS(file), error = function(e) NULL) ## rows from before a column existed (e.g. `workers`, added in 0.0.65) get NA there @@ -27,6 +35,19 @@ }) } +## Write the rows a fit kept in `pending` (see .replaceRecords()) into the shared files, one write per file, +## under the lock, and empty `pending`. The result is what a write per record would have left. A fit that +## dies loses the rows since its last flush. Never fails the fit. +.flushRecords <- function(pending) { + for (file in ls(pending, all.names = TRUE)) { + entry <- pending[[file]] + rm(list = file, envir = pending) + tryCatch(.replaceRecords(file, entry$new, entry$columns), + error = function(e) warning("Could not record host speeds: ", conditionMessage(e), call. = FALSE)) + } + invisible(NULL) +} + ## The workers every live cluster has booked on each host, named as the evaluation records name the hosts ## (`nodename`), for `cl` built by plan_psock_min() (its "hostNodenames" attribute maps its ssh aliases); ## NULL for any other cluster, or when the ledger cannot be read. This is the load .workerSpeed() was @@ -50,8 +71,9 @@ ## number): a chunk computed again, e.g. after a restart, replaces its earlier rows instead of adding a ## duplicate. `evaluations` is a list of `member$evaluations` data frames. `workers` is the workers this fit ## had on each host, `booked` the workers every cluster had booked there (see .bookedByNodename(); NA when -## not known). Never fails the fit. -.recordHostSpeed <- function(evaluations, id, booked = NULL, path = getOption("clusters.reservationsPath")) { +## not known). `pending`: see .replaceRecords(). Never fails the fit. +.recordHostSpeed <- function(evaluations, id, booked = NULL, path = getOption("clusters.reservationsPath"), + pending = NULL) { tryCatch({ evaluations <- .withHost(evaluations) if (!length(evaluations)) return(invisible(NULL)) @@ -62,7 +84,7 @@ file <- .hostSpeedFile(path) new <- cbind(tab[setdiff(.hostSpeedColumns, c("time", "id"))], time = Sys.time(), id = id, stringsAsFactors = FALSE) - .replaceRecords(file, new, .hostSpeedColumns) + .replaceRecords(file, new, .hostSpeedColumns, pending) invisible(new) }, error = function(e) { warning("Could not record host speeds: ", conditionMessage(e), call. = FALSE) diff --git a/tests/testthat/test-hostSpeed.R b/tests/testthat/test-hostSpeed.R index fe28395..f39eee6 100644 --- a/tests/testthat/test-hostSpeed.R +++ b/tests/testthat/test-hostSpeed.R @@ -121,3 +121,55 @@ test_that("each row records the workers every cluster had booked on the host, by withr::local_options(clusters.useReservations = FALSE) expect_null(.bookedByNodename(cl)) }) + +## The shared ledgers were read and rewritten after every generation: 2.9 s with all workers idle at 367k rows. + +test_that("records kept in memory and flushed leave the ledger a write per record would", { + recs <- list(list(mkEv(c("a", "a", "b"), c(1, 1, 3)), "r1"), list(mkEv("a", 2), "r2"), + list(mkEv(c("a", "b"), c(1, 2)), "r1")) + run <- function(pending) { + d <- withr::local_tempdir() + withr::local_options(clusters.reservationsPath = d, clusters.hostSpeedDays = 30) + saveRDS(data.frame(host = "old", n = 3L, median = 1, p90 = 2, ratio = 1, time = Sys.time(), id = "r0", + workers = 1L, booked = NA_integer_, stringsAsFactors = FALSE), .hostSpeedFile()) + for (r in recs) { + .recordHostSpeed(r[[1]], id = r[[2]], pending = pending) + .recordFitMemory(list(transform(r[[1]], peakGB = 1)), runName = "x", id = r[[2]], pending = pending) + } + if (is.environment(pending)) { + expect_equal(nrow(readRDS(.hostSpeedFile())), 1L) # nothing written yet + .flushRecords(pending) + } + lapply(list(.hostSpeedFile(), .fitMemoryFile()), function(f) { x <- readRDS(f); x$time <- NULL; x }) + } + expect_equal(run(new.env()), run(NULL)) +}) + +test_that("a fit writes the ledgers at each rebalance and at its end, not after each generation", { + skip_on_cran() + skip_if_not_installed("DEoptim") + d <- withr::local_tempdir() + withr::local_options(clusters.reservationsPath = d, reproducible.cachePath = withr::local_tempdir(), + clusters.rebalanceEvery = 3L) + cl <- localTestCluster(2) + seen <- integer(0) + attr(cl, "rebalance") <- function(cl) { seen <<- c(seen, nrow(.readHostSpeeds())); cl } + writes <- character(0) + replaceRecords <- .replaceRecords + testthat::local_mocked_bindings(.replaceRecords = function(file, new, columns, pending = NULL) { + if (is.null(pending)) writes <<- c(writes, basename(file)) # a write to the shared file + replaceRecords(file, new, columns, pending) + }) + N <- 8L + fn <- function(par) sum((par - 0.3)^2) + suppressWarnings(suppressMessages( + clusters:::DEoptimIterative(fn, lower = c(a = 0, b = 0), upper = c(a = 1, b = 1), + control = list(NP = 8L, itermax = N, trace = FALSE, cluster = cl), + figurePath = FALSE, progressFile = FALSE, .plots = NULL, + cachePath = withr::local_tempdir(), runName = "hs", .verbose = -1))) + expect_lte(sum(writes == "hostSpeed.rds"), ceiling(N / 3) + 1L) + expect_lte(sum(writes == "fitMemory.rds"), ceiling(N / 3) + 1L) + expect_true(all(seen > 0L)) # a rebalance sees the generations before it + expect_equal(length(seen), 2L) + expect_equal(sort(unique(readRDS(file.path(d, "hostSpeed.rds"))$id)), paste0("hs_", 1:N)) +})