From bafe2d9663ef3a33e0e2f61d48ac0373ea7f4c83 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 27 Nov 2026 12:19:22 -0700 Subject: [PATCH 1/3] Experimental Require.cloneMethod = "hardlinkReadOnly": clone by hard-linking read-only package files (default stays copy) A mode of copyPackageFilesInner(): the same lock, 00CLONE working folder and final rename; only the per-file step becomes chmod-source-read-only + file.link. Falls back to copy per package if chmod or link fails, and always on Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXeS4gUhjnvsZYVXumT --- NEWS.md | 2 + R/Require2.R | 59 +++++- R/RequireOptions.R | 20 ++ R/pak.R | 2 +- man/RequireOptions.Rd | 19 ++ tests/testthat/test-25cloneFrom_testthat.R | 205 ++++++++++++++++++++- 6 files changed, 292 insertions(+), 15 deletions(-) diff --git a/NEWS.md b/NEWS.md index 2ec8602f..1953fefb 100644 --- a/NEWS.md +++ b/NEWS.md @@ -2,6 +2,8 @@ ## New features +* Experimental: `options(Require.cloneMethod = "hardlinkReadOnly")` (or `R_REQUIRE_CLONE_METHOD`) makes `Require.cloneFrom` hard-link package files instead of copying them, after taking the write permission off the source files. The files are then read-only under every name, so an in-place write to one (`file.copy(overwrite = TRUE)`, `writeBin()`) fails instead of emptying it in every library that shares it; installs, `remove.packages()` and clones still work, as they replace files and folders by rename. The default stays `"copy"`. The mode makes the source library's files read-only too, is never used on Windows or across file systems, and copies any package it cannot chmod or link. See `?RequireOptions`. + * `install = "HEAD"`, or `options(Require.install = "HEAD")`, installs every requested package, GitHub or CRAN, if missing and updates it if not current: to the latest commit of its branch (GitHub) or the newest release (CRAN), as if each were written `"pkg (HEAD)"`. This replaces a minimum version (`>=`), as modules usually write, and other requests for the same package; a package with an exact or maximum version is kept as requested. Dependencies are updated only when they fail a version floor, like `pak::pak(upgrade = FALSE)`. Packages already loaded are installed too, with the usual "Please restart R" warning. New `UpdateOrInstall()` is `Install(packages, install = "HEAD", ...)`. Set the option before `setupProject()` to update all of a project's packages. `Install()` now also takes `"force"` and `"HEAD"` from `Require.install`. * `updatePackages()` has a new `packages` argument. `NULL`, the default, updates every installed package as before. Otherwise it installs or updates the named packages and all of their dependencies (recursively) to the latest GitHub commit or CRAN release, like `pak::pak(packages, upgrade = TRUE)`; `UpdateOrInstall()` is the `upgrade = FALSE` counterpart. `updatePackages()` now also passes `libPaths` on to `Install()`. diff --git a/R/Require2.R b/R/Require2.R index 67923bce..c6660595 100644 --- a/R/Require2.R +++ b/R/Require2.R @@ -3941,13 +3941,14 @@ clonePackages <- function(rcf, ipa, libPaths, skip = character(), ipa } -# Copy each of `Packages` from `fromLib` into `toLib`, never hard-linking: a link makes two -# libraries share one inode, so a later in-place write to either (a second clone, a reinstall) -# empties the file in both (26,525 files in every library sharing them, 2026-11-25). Each package -# is copied into a working folder inside `toLib` (same file system) and renamed into place, so a -# clone replaces the whole package folder, and `toLib` is locked meanwhile so two processes cannot -# clone into it at once. -copyPackageFilesInner <- function(Packages, fromLib, toLib) { +# Copy each of `Packages` from `fromLib` into `toLib`. By default (`Require.cloneMethod = "copy"`) every +# file is copied, never hard-linked: a link makes two libraries share one inode, so a later in-place +# write to either (a second clone, a reinstall) empties the file in both (26,525 files in every +# library sharing them, 2026-11-25). Each package is copied into a working folder inside `toLib` +# (same file system) and renamed into place, so a clone replaces the whole package folder, and `toLib` +# is locked meanwhile so two processes cannot clone into it at once. With `"hardlinkReadOnly"` +# (experimental) only the per-file step changes; see linkPackageReadOnly(). +copyPackageFilesInner <- function(Packages, fromLib, toLib, method = cloneMethod()) { checkPath(toLib, create = TRUE) withCloneLock(toLib, function(refreshLock) { lapply(Packages, function(packToClone) { @@ -3957,14 +3958,54 @@ copyPackageFilesInner <- function(Packages, fromLib, toLib) { work <- tempfile("00CLONE-", tmpdir = toLib) on.exit(unlink(work, recursive = TRUE), add = TRUE) dir.create(work) - ok <- all(file.copy(from, work, recursive = TRUE, copy.date = TRUE)) && - replaceDirByRename(file.path(work, packToClone), file.path(toLib, packToClone)) + ok <- (identical(method, "hardlinkReadOnly") && linkPackageReadOnly(from, work)) || + all(file.copy(from, work, recursive = TRUE, copy.date = TRUE)) + ok <- ok && replaceDirByRename(file.path(work, packToClone), file.path(toLib, packToClone)) refreshLock() # a long clone must not look abandoned invisible(ok) }) }) } +# `Require.cloneMethod`: "copy" (the default) or "hardlinkReadOnly". Never a link on Windows, and +# an unknown value is a warning and "copy". (A link that fails, e.g. across file systems, is +# handled per package by linkPackageReadOnly().) +cloneMethod <- function(method = getOption("Require.cloneMethod", "copy")) { + method <- as.character(method)[1] + if (is.na(method) || !method %in% c("copy", "hardlinkReadOnly")) { + warning("Require.cloneMethod must be 'copy' or 'hardlinkReadOnly', not '", method, "'; using 'copy'", + call. = FALSE) + return("copy") + } + if (isWindows()) "copy" else method +} + +# Experimental: make the folder `from` appear as `to`/ by hard-linking every file, +# after taking the write bits off the source file. Permissions belong to the inode, so the file is +# read-only under every name and a later write in place (`file.copy(overwrite = TRUE)`, `writeBin()`) +# fails with EACCES instead of truncating the file in every library that shares it. Replacing a +# file or folder by rename needs only a writable directory, and directories are made new, not linked, +# so installs, `remove.packages()` and `unlink()` still work. Returns FALSE, leaving nothing behind +# in `to`, if anything fails (a symlink in the package, chmod not permitted, a link across file +# systems); the caller then copies. Source files already made read-only stay read-only. +# (`link` and `chmod` are arguments so that tests can make them fail.) +linkPackageReadOnly <- function(from, to, link = file.link, chmod = Sys.chmod) { + top <- file.path(to, basename(from)) + ok <- tryCatch({ + files <- list.files(from, recursive = TRUE, all.files = TRUE, no.. = TRUE, include.dirs = FALSE) + dirs <- setdiff(list.dirs(from, full.names = FALSE, recursive = TRUE), "") + src <- file.path(from, files) + mode <- as.integer(file.mode(src)) + ro <- bitwAnd(mode, bitwNot(strtoi("222", 8L))) # no write bit for anyone + all(!is.na(mode)) && !any(nzchar(Sys.readlink(src))) && dir.create(top) && + all(vapply(file.path(top, dirs), dir.create, logical(1))) && + all(chmod(src[mode != ro], mode = as.octmode(ro[mode != ro]))) && + all(suppressWarnings(link(src, file.path(top, files)))) + }, error = function(e) FALSE) + if (!isTRUE(ok)) unlink(top, recursive = TRUE) + isTRUE(ok) +} + # Put the folder `new` at `to` with file.rename(), never writing into `to`. An existing `to` is # renamed aside first and removed only once `new` is in place; if that fails it is put back. replaceDirByRename <- function(new, to) { diff --git a/R/RequireOptions.R b/R/RequireOptions.R index 82d8416b..9d2bd623 100644 --- a/R/RequireOptions.R +++ b/R/RequireOptions.R @@ -107,6 +107,25 @@ #' copy must be exactly the version that would be installed, and neither #' GitHub packages nor the always-from-source packages ([sourcePkgs()]) are #' cloned.} +#' \item{`cloneMethod`}{ Default: `"copy"`. How `cloneFrom` puts a package into the +#' destination library: `"copy"` copies every file. `"hardlinkReadOnly"` is +#' experimental: each file is hard-linked, not copied, after the write +#' permission is taken off the *source* file. Permissions belong to the file, +#' not to a name for it, so the file is read-only in every library that shares it, +#' and writing into it in place (`file.copy(overwrite = TRUE)`, `writeBin()`, +#' `cat >`) is an error instead of silently emptying the file in all of them. +#' Replacing a file or folder by renaming one over it, as R's installer and +#' `Require` do, needs only a writable folder and still works, as do +#' `remove.packages()` and `unlink()`. **This mode changes the source library: +#' its package files become read-only, so any tool that edits an installed +#' package's files in place (a package that writes into its own folder at run +#' time, a manual edit) now fails there and in every clone.** Installing a +#' newer version into either library gives that library its own new files; the +#' other keeps the old ones. Space is saved and cloning is faster, but nothing +#' is shared across file systems or on Windows, where a package is copied; a +#' package that cannot be chmodded or linked (a symlink in it, a source you do +#' not own) is copied too, never left half-linked. Also set by the environment +#' variable `R_REQUIRE_CLONE_METHOD`.} #' \item{`downloadTimeout`}{Default: `300L` (seconds). Used as the floor for #' `options("timeout")` during GitHub source-archive downloads in the legacy #' (non-pak) install path. R's stock 60-second timeout is too short for @@ -173,6 +192,7 @@ RequireOptions <- function() { Require.cachePkgDir = "default", Require.checkInternet = TRUE, Require.cloneFrom = TRUE, + Require.cloneMethod = "copy", Require.downloadTimeout = 300L, Require.install = TRUE, Require.installPackagesSys = 2L, # if (isMacOS()) 2L else 2L, diff --git a/R/pak.R b/R/pak.R index 498d9ba6..50b87ec3 100644 --- a/R/pak.R +++ b/R/pak.R @@ -3667,7 +3667,7 @@ ensurePakInProjectLib <- function(projLib, repos = getOption("repos"), projLibNorm <- tryCatch(normalizePath(projLib, mustWork = FALSE), error = function(e) projLib) if (!is.null(src) && !identical(dirname(src), projLibNorm)) { - linked <- all(unlist(copyPackageFilesInner("pak", dirname(src), projLib))) + linked <- all(unlist(copyPackageFilesInner("pak", dirname(src), projLib, method = "copy"))) if (linked) messageVerbose(" Copied pak from ", src, " (no reinstall needed)", verbose = verbose, verboseLevel = 1) diff --git a/man/RequireOptions.Rd b/man/RequireOptions.Rd index ebfb5a87..7eb73fdd 100644 --- a/man/RequireOptions.Rd +++ b/man/RequireOptions.Rd @@ -117,6 +117,25 @@ resolved is preferred, then the highest. Under \code{Require.usePak = FALSE} the copy must be exactly the version that would be installed, and neither GitHub packages nor the always-from-source packages (\code{\link[=sourcePkgs]{sourcePkgs()}}) are cloned.} +\item{\code{cloneMethod}}{ Default: \code{"copy"}. How \code{cloneFrom} puts a package into the +destination library: \code{"copy"} copies every file. \code{"hardlinkReadOnly"} is +experimental: each file is hard-linked, not copied, after the write +permission is taken off the \emph{source} file. Permissions belong to the file, +not to a name for it, so the file is read-only in every library that shares it, +and writing into it in place (\code{file.copy(overwrite = TRUE)}, \code{writeBin()}, +\verb{cat >}) is an error instead of silently emptying the file in all of them. +Replacing a file or folder by renaming one over it, as R's installer and +\code{Require} do, needs only a writable folder and still works, as do +\code{remove.packages()} and \code{unlink()}. \strong{This mode changes the source library: +its package files become read-only, so any tool that edits an installed +package's files in place (a package that writes into its own folder at run +time, a manual edit) now fails there and in every clone.} Installing a +newer version into either library gives that library its own new files; the +other keeps the old ones. Space is saved and cloning is faster, but nothing +is shared across file systems or on Windows, where a package is copied; a +package that cannot be chmodded or linked (a symlink in it, a source you do +not own) is copied too, never left half-linked. Also set by the environment +variable \code{R_REQUIRE_CLONE_METHOD}.} \item{\code{downloadTimeout}}{Default: \code{300L} (seconds). Used as the floor for \code{options("timeout")} during GitHub source-archive downloads in the legacy (non-pak) install path. R's stock 60-second timeout is too short for diff --git a/tests/testthat/test-25cloneFrom_testthat.R b/tests/testthat/test-25cloneFrom_testthat.R index 631fbe58..3466c34c 100644 --- a/tests/testthat/test-25cloneFrom_testthat.R +++ b/tests/testthat/test-25cloneFrom_testthat.R @@ -562,7 +562,7 @@ test_that("cloning over an existing clone replaces it and leaves the source alon expect_setequal(dir(to, all.files = TRUE, no.. = TRUE), c("tinyCloneA", "tinyCloneB")) }) -test_that("two processes cloning the same packages into one library at once damage nothing", { +for (method in c("copy", "hardlinkReadOnly")) test_that(paste0("two processes cloning the same packages into one library at once damage nothing (", method, ")"), { skip_on_os("windows") skip_if_not_installed("callr") skip_if_not_installed("pkgload") @@ -579,8 +579,9 @@ test_that("two processes cloning the same packages into one library at once dama libs <- unique(c(.libPaths(), dirname(vapply(loadedNamespaces(), function(n) tryCatch(getNamespaceInfo(n, "path"), error = function(e) NA_character_), "")))) libs <- libs[!is.na(libs) & dir.exists(libs)] - worker <- function(reqPath, from, to, pkgs, sync, id) { + worker <- function(reqPath, from, to, pkgs, sync, id, method) { if (is.null(reqPath)) loadNamespace("Require") else pkgload::load_all(reqPath, quiet = TRUE) + options(Require.cloneMethod = method) file.create(file.path(sync, paste0("ready", id))) while (!file.exists(file.path(sync, "go"))) Sys.sleep(0.005) for (i in 1:8) { @@ -590,7 +591,7 @@ test_that("two processes cloning the same packages into one library at once dama "done" } procs <- lapply(1:2, function(id) - callr::r_bg(worker, args = list(reqPath, from, to, pkgs, sync, id), stderr = "2>&1", libpath = libs)) + callr::r_bg(worker, args = list(reqPath, from, to, pkgs, sync, id, method), stderr = "2>&1", libpath = libs)) while (length(dir(sync, pattern = "^ready")) < 2 && all(vapply(procs, function(p) p$is_alive(), logical(1)))) Sys.sleep(0.05) file.create(file.path(sync, "go")) @@ -598,13 +599,13 @@ test_that("two processes cloning the same packages into one library at once dama for (p in procs) expect_identical(p$get_result(), "done") ## the sources are untouched after <- statFiles(before$file) - expect_identical(after, before) + expect_identical(after[c("file", "inode", "size")], before[c("file", "inode", "size")]) expect_identical(tools::md5sum(before$file), md5Before) ## the clones are whole, loadable, and no file is empty unless its source is dst <- statFiles(pkgFiles(to, pkgs)) expect_identical(sort(sub(paste0("^", to), "", dst$file)), sort(sub(paste0("^", from), "", before$file))) expect_false(any(dst$size == 0 & !sub(paste0("^", to), "", dst$file) %in% sub(paste0("^", from), "", before$file[before$size == 0]))) - expect_true(all(dst$links == 1L)) + expect_true(all(dst$links == if (method == "copy") 1L else 2L)) # 2: this file and its source res <- system2(file.path(R.home("bin"), "Rscript"), c("-e", shQuote(paste0("cat(vapply(c(", paste0("'", pkgs, "'", collapse = ","), "), function(p) as.character(requireNamespace(p)), ''))"))), @@ -713,3 +714,197 @@ test_that("two processes taking over one abandoned lock never hold it together", expect_false(dir.exists(file.path(lib, "00LOCK-RequireClone"))) expect_identical(dir(lib, all.files = TRUE, no.. = TRUE), character()) }) + +## ---- Require.cloneMethod = "hardlinkReadOnly" (experimental) ---------------------------------- + +## Clone `pkgs` from `from` into a new library with the given method; return the library. +cloneWith <- function(from, pkgs, method, envir = parent.frame()) { + to <- withr::local_tempdir(.local_envir = envir) + withr::local_options(Require.cloneMethod = method) + Require:::cloneCopies(Require:::clonablePackages(from, pkgs), toLib = to) + to +} +## Version of `pkg` as a fresh R process loads it from `lib` ("FAIL" if it does not load). +versionIn <- function(lib, pkg) { + out <- system2(file.path(R.home("bin"), "Rscript"), + c("-e", shQuote(paste0("cat(if (suppressWarnings(requireNamespace('", pkg, "', quietly = TRUE))) as.character(packageVersion('", pkg, "')) else 'FAIL')"))), + env = paste0("R_LIBS=", lib), stdout = TRUE, stderr = FALSE) + if (length(out)) out else "FAIL" +} +pkgsAB <- c("tinyCloneA", "tinyCloneB") +## chmod does not stop root, so the in-place writes below would succeed +skipIfRoot <- function() testthat::skip_if(identical(Sys.info()[["effective_user"]], "root"), "root ignores file permissions") + +test_that("the default clone method is copy, also from the environment variable", { + expect_identical(RequireOptions()$Require.cloneMethod, "copy") + expect_identical(getOption("Require.cloneMethod"), "copy") + withr::local_envvar(R_REQUIRE_CLONE_METHOD = "hardlinkReadOnly") + expect_identical(RequireOptions()$Require.cloneMethod, "hardlinkReadOnly") + expect_identical(Require:::cloneMethod("copy"), "copy") + expect_warning(expect_identical(Require:::cloneMethod("symlink"), "copy"), "must be 'copy' or 'hardlinkReadOnly'") +}) + +test_that("hardlinkReadOnly: files are shared and read-only; an in-place write fails and truncates nothing", { + skip_on_os("windows") + skipIfRoot() + from <- cloneFromLib() + to <- cloneWith(from, pkgsAB, "hardlinkReadOnly") + src <- pkgFiles(from, pkgsAB) + rel <- sub(paste0("^", from, "/"), "", src) + st <- statFiles(c(src, file.path(to, rel))) + n <- length(src) + expect_identical(st$inode[1:n], st$inode[n + 1:n]) # one file, two names + expect_true(all(st$links == 2L)) + expect_false(any(file.access(c(src, file.path(to, rel)), 2) == 0)) # read-only under both names + expect_true(all(dir.exists(file.path(to, pkgsAB))) && all(file.access(file.path(to, pkgsAB), 2) == 0)) # folders are new and writable + expect_setequal(dir(to, all.files = TRUE, no.. = TRUE), pkgsAB) # nothing of the clone's own working left + + ## the 2026-11-25 incident: an in-place write onto a shared file. It fails; both names keep their bytes. + rdb <- "tinyCloneA/R/tinyCloneA.rdb" + empty <- withr::local_tempfile() + file.create(empty) + size <- file.size(file.path(from, rdb)) + expect_gt(size, 0) + for (f in file.path(c(from, to), rdb)) { + expect_warning(expect_false(file.copy(empty, f, overwrite = TRUE))) + expect_error(suppressWarnings(writeBin(raw(0), f))) + expect_error(suppressWarnings(cat("", file = f))) + } + expect_identical(file.size(file.path(c(from, to), rdb)), c(size, size)) + + ## contrast: the plain hard link the old code made, with no chmod, is emptied under both names + plainFrom <- withr::local_tempdir() + plainTo <- withr::local_tempdir() + tinyPkg(plainFrom, "tinyCloneA") + old <- file.path(plainFrom, rdb) + expect_true(file.link(old, file.path(plainTo, "x.rdb"))) + expect_true(file.copy(empty, file.path(plainTo, "x.rdb"), overwrite = TRUE)) + expect_identical(file.size(c(old, file.path(plainTo, "x.rdb"))), c(0, 0)) +}) + +test_that("hardlinkReadOnly through pakClonePackages: the clone loads and the source is still intact", { + skip_on_os("windows") + from <- cloneFromLib() + to <- withr::local_tempdir() + withr::local_options(Require.cloneFrom = from, Require.cloneMethod = "hardlinkReadOnly") + setSolve() + out <- Require:::pakClonePackages(planDT(), libPaths = to, verbose = 0) + expect_true(all(out$installResult == "OK")) + expect_true(all(statFiles(pkgFiles(to, pkgsAB))$links == 2L)) + expect_identical(versionIn(to, "tinyCloneB"), "0.0.1") + expect_identical(versionIn(from, "tinyCloneB"), "0.0.1") +}) + +test_that("hardlinkReadOnly: a newer version installed into the SOURCE library leaves the clone intact and loadable", { + skip_on_os("windows") + skipIfRoot() + from <- cloneFromLib() + to <- cloneWith(from, pkgsAB, "hardlinkReadOnly") + cloned <- pkgFiles(to, pkgsAB) + md5 <- tools::md5sum(cloned) + repo <- tinyRepo(list(list(name = "tinyCloneA", version = "0.0.2"))) + withr::local_options(repos = c(tiny = repo)) + utils::install.packages("tinyCloneA", lib = from, type = "source", quiet = TRUE) # R CMD INSTALL over read-only, linked files + expect_identical(versionIn(from, "tinyCloneA"), "0.0.2") + expect_identical(versionIn(to, "tinyCloneA"), "0.0.1") # the clone keeps the old one + expect_identical(versionIn(to, "tinyCloneB"), "0.0.1") # and still loads what imports it + expect_identical(tools::md5sum(cloned), md5) + clonedA <- pkgFiles(to, "tinyCloneA") + expect_true(all(statFiles(clonedA)$links == 1L)) # its files lost their other name, and are still read-only + expect_true(all(statFiles(pkgFiles(to, "tinyCloneB"))$links == 2L)) # B is still shared with the source + expect_false(any(file.access(cloned, 2) == 0)) + expect_length(dir(from, pattern = "^00LOCK|^00OLD", all.files = TRUE), 0) + ## and the other way: a newer version into the CLONE's library + utils::install.packages("tinyCloneA", lib = to, type = "source", quiet = TRUE) + expect_identical(versionIn(to, "tinyCloneA"), "0.0.2") + expect_identical(versionIn(from, "tinyCloneA"), "0.0.2") +}) + +test_that("hardlinkReadOnly: remove.packages() and unlink() in either library leave the other intact", { + skip_on_os("windows") + skipIfRoot() + from <- cloneFromLib() + to <- cloneWith(from, pkgsAB, "hardlinkReadOnly") + to2 <- cloneWith(from, pkgsAB, "hardlinkReadOnly") + md5 <- tools::md5sum(pkgFiles(from, pkgsAB)) + utils::remove.packages("tinyCloneB", lib = to) # R's own remover + expect_false(dir.exists(file.path(to, "tinyCloneB"))) + expect_identical(unlink(file.path(to2, "tinyCloneA"), recursive = TRUE), 0L) # a plain recursive unlink + expect_false(dir.exists(file.path(to2, "tinyCloneA"))) + expect_identical(tools::md5sum(names(md5)), md5) + expect_identical(versionIn(from, "tinyCloneB"), "0.0.1") + expect_identical(versionIn(to, "tinyCloneA"), "0.0.1") + expect_identical(versionIn(to2, "tinyCloneA"), "FAIL") # removed there only + ## removing from the source library: the clone is intact + utils::remove.packages(pkgsAB, lib = from) + expect_identical(versionIn(to, "tinyCloneA"), "0.0.1") + expect_true(all(file.exists(pkgFiles(to, "tinyCloneA")))) +}) + +test_that("hardlinkReadOnly gives up a package cleanly when a link or chmod fails, and the clone then copies", { + skip_on_os("windows") + from <- cloneFromLib() + pkg <- file.path(from, "tinyCloneA") + modes <- file.mode(pkgFiles(from, "tinyCloneA")) + noLink <- function(from, to) rep(FALSE, length(from)) + ## a link that fails part-way through (the first file is linked, as before a cross-file-system failure) + halfLink <- function(from, to) c(base::file.link(from[1], to[1]), rep(FALSE, length(from) - 1)) + noChmod <- function(paths, mode, ...) rep(FALSE, length(paths)) + ## (chmod first: a source file already made read-only is not chmodded again) + for (fns in list(list(chmod = noChmod), list(link = noLink), list(link = halfLink))) { + work <- withr::local_tempdir() + expect_false(do.call(Require:::linkPackageReadOnly, c(list(pkg, work), fns))) + expect_length(dir(work, all.files = TRUE, no.. = TRUE), 0) # nothing half-linked is left behind + if (!is.null(fns$chmod)) expect_identical(file.mode(pkgFiles(from, "tinyCloneA")), modes) # chmod never succeeded + } + ## a symlink in a package cannot be linked as a file: the whole package is copied instead + file.symlink("DESCRIPTION", file.path(pkg, "linkToDESCRIPTION")) + to <- cloneWith(from, pkgsAB, "hardlinkReadOnly") + st <- statFiles(pkgFiles(to, "tinyCloneA")) + expect_true(all(st$links == 1L)) # copied, so no link to the source + expect_true(all(statFiles(pkgFiles(to, "tinyCloneB"))$links == 2L)) # the other package was linked + expect_identical(versionIn(to, "tinyCloneA"), "0.0.1") + ## across file systems, where there is one to try: /dev/shm is not the disk of tempdir() + shm <- "/dev/shm" + if (dir.exists(shm) && file.access(shm, 2) == 0) { + fromShm <- withr::local_tempdir(tmpdir = shm) + file.copy(file.path(from, pkgsAB), fromShm, recursive = TRUE) + dev <- function(p) as.numeric(system2("stat", c(if (Sys.info()[["sysname"]] == "Darwin") c("-f", "%d") else c("-c", "%d"), shQuote(p)), stdout = TRUE)) + toDisk <- cloneWith(fromShm, pkgsAB, "hardlinkReadOnly") + if (dev(fromShm) != dev(toDisk)) expect_true(all(statFiles(pkgFiles(toDisk, pkgsAB))$links == 1L)) + expect_identical(versionIn(toDisk, "tinyCloneB"), "0.0.1") + } +}) + +test_that("hardlinkReadOnly is never used on Windows", { + testthat::local_mocked_bindings(isWindows = function() TRUE, .package = "Require") + expect_identical(Require:::cloneMethod("hardlinkReadOnly"), "copy") +}) + +test_that("hardlinkReadOnly: space and time against copy, on about 20 packages", { + skip_on_os("windows") + skip_if_not(nzchar(Sys.which("du"))) + ip <- utils::installed.packages(lib.loc = .libPaths()) + pkgs <- unique(ip[, "Package"][!ip[, "Package"] %in% Require:::.pakNoCopyPkgs()]) + pkgs <- head(pkgs[order(ip[match(pkgs, ip[, "Package"]), "Priority"] %in% "base")], 20) # not-base first + from <- withr::local_tempdir() + for (p in pkgs) file.copy(file.path(ip[match(p, ip[, "Package"]), "LibPath"], p), from, recursive = TRUE) # a temporary source library + pkgs <- intersect(pkgs, dir(from)) + res <- lapply(c("copy", "hardlinkReadOnly"), function(method) { + to <- withr::local_tempdir() + withr::local_options(Require.cloneMethod = method) + cp <- Require:::clonablePackages(from, pkgs) + secs <- system.time(Require:::cloneCopies(cp, toLib = to))[["elapsed"]] + ## `du` given both libraries counts a file once: the second line is what the clone added + kb <- as.numeric(sub("\\t.*", "", system2("du", c("-sk", shQuote(from), shQuote(to)), stdout = TRUE))) + data.frame(method = method, packages = length(cp$Package), files = length(pkgFiles(to, pkgs)), + sourceKB = kb[1], addedKB = kb[2], seconds = round(secs, 2)) + }) + res <- do.call(rbind, res) + cat("\n\nclone cost, ", res$packages[1], " packages from a temporary library:\n", sep = "") + print(res, row.names = FALSE) + cat("\n") + expect_identical(res$packages[1], res$packages[2]) + expect_identical(res$files[1], res$files[2]) + expect_gt(res$addedKB[1], 0) +}) From f64963af1642b3567b50c784ff240f8b4de8cada Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Fri, 27 Nov 2026 15:19:54 -0700 Subject: [PATCH 2/3] hardlinkReadOnly: link before chmod, restore exactly the modes changed on failure, so the fallback copy keeps the original modes; compare full frame in the copy race test Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXeS4gUhjnvsZYVXumT --- R/Require2.R | 19 +++++++++++++++---- tests/testthat/test-25cloneFrom_testthat.R | 15 ++++++++++----- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/R/Require2.R b/R/Require2.R index c6660595..c0ba4aea 100644 --- a/R/Require2.R +++ b/R/Require2.R @@ -3987,22 +3987,33 @@ cloneMethod <- function(method = getOption("Require.cloneMethod", "copy")) { # file or folder by rename needs only a writable directory, and directories are made new, not linked, # so installs, `remove.packages()` and `unlink()` still work. Returns FALSE, leaving nothing behind # in `to`, if anything fails (a symlink in the package, chmod not permitted, a link across file -# systems); the caller then copies. Source files already made read-only stay read-only. +# systems); the caller then copies. The cheap checks (symlinks, new folders) come first, then every +# file is linked, and only then are the sources chmodded (a link shares the inode, so the mode applies +# under both names). A failed link therefore changes no mode; a failed chmod puts back the modes of +# exactly the files it changed. Either way the fallback copy has the original modes. The shared files +# are writable for the moments between the links and the chmod, while the destination library is locked. # (`link` and `chmod` are arguments so that tests can make them fail.) linkPackageReadOnly <- function(from, to, link = file.link, chmod = Sys.chmod) { top <- file.path(to, basename(from)) + changed <- character() + orig <- integer() ok <- tryCatch({ files <- list.files(from, recursive = TRUE, all.files = TRUE, no.. = TRUE, include.dirs = FALSE) dirs <- setdiff(list.dirs(from, full.names = FALSE, recursive = TRUE), "") src <- file.path(from, files) mode <- as.integer(file.mode(src)) + orig <- setNames(mode, src) ro <- bitwAnd(mode, bitwNot(strtoi("222", 8L))) # no write bit for anyone + todo <- mode != ro all(!is.na(mode)) && !any(nzchar(Sys.readlink(src))) && dir.create(top) && all(vapply(file.path(top, dirs), dir.create, logical(1))) && - all(chmod(src[mode != ro], mode = as.octmode(ro[mode != ro]))) && - all(suppressWarnings(link(src, file.path(top, files)))) + all(suppressWarnings(link(src, file.path(top, files)))) && + { changed <- src[todo]; all(chmod(src[todo], mode = as.octmode(ro[todo]))) } }, error = function(e) FALSE) - if (!isTRUE(ok)) unlink(top, recursive = TRUE) + if (!isTRUE(ok)) { + unlink(top, recursive = TRUE) + if (length(changed)) Sys.chmod(changed, mode = as.octmode(orig[changed])) + } isTRUE(ok) } diff --git a/tests/testthat/test-25cloneFrom_testthat.R b/tests/testthat/test-25cloneFrom_testthat.R index 3466c34c..03c72c97 100644 --- a/tests/testthat/test-25cloneFrom_testthat.R +++ b/tests/testthat/test-25cloneFrom_testthat.R @@ -599,7 +599,8 @@ for (method in c("copy", "hardlinkReadOnly")) test_that(paste0("two processes cl for (p in procs) expect_identical(p$get_result(), "done") ## the sources are untouched after <- statFiles(before$file) - expect_identical(after[c("file", "inode", "size")], before[c("file", "inode", "size")]) + if (method == "copy") expect_identical(after, before) else # links and mode legitimately change + expect_identical(after[c("file", "inode", "size")], before[c("file", "inode", "size")]) expect_identical(tools::md5sum(before$file), md5Before) ## the clones are whole, loadable, and no file is empty unless its source is dst <- statFiles(pkgFiles(to, pkgs)) @@ -845,23 +846,27 @@ test_that("hardlinkReadOnly gives up a package cleanly when a link or chmod fail skip_on_os("windows") from <- cloneFromLib() pkg <- file.path(from, "tinyCloneA") - modes <- file.mode(pkgFiles(from, "tinyCloneA")) + modes <- file.mode(pkgFiles(from, "tinyCloneA")); names(modes) <- pkgFiles(from, "tinyCloneA") noLink <- function(from, to) rep(FALSE, length(from)) ## a link that fails part-way through (the first file is linked, as before a cross-file-system failure) halfLink <- function(from, to) c(base::file.link(from[1], to[1]), rep(FALSE, length(from) - 1)) noChmod <- function(paths, mode, ...) rep(FALSE, length(paths)) - ## (chmod first: a source file already made read-only is not chmodded again) - for (fns in list(list(chmod = noChmod), list(link = noLink), list(link = halfLink))) { + ## chmod succeeds for the first file only: that one is put back + partChmod <- function(paths, mode, ...) { Sys.chmod(paths[1], mode[1]); c(TRUE, rep(FALSE, length(paths) - 1)) } + for (fns in list(list(chmod = noChmod), list(chmod = partChmod), list(link = noLink), list(link = halfLink))) { work <- withr::local_tempdir() expect_false(do.call(Require:::linkPackageReadOnly, c(list(pkg, work), fns))) expect_length(dir(work, all.files = TRUE, no.. = TRUE), 0) # nothing half-linked is left behind - if (!is.null(fns$chmod)) expect_identical(file.mode(pkgFiles(from, "tinyCloneA")), modes) # chmod never succeeded + expect_identical(as.integer(file.mode(names(modes))), as.integer(modes)) # the source modes are exactly as before + expect_true(all(file.access(pkgFiles(from, "tinyCloneA"), 2) == 0)) # and still writable } ## a symlink in a package cannot be linked as a file: the whole package is copied instead file.symlink("DESCRIPTION", file.path(pkg, "linkToDESCRIPTION")) to <- cloneWith(from, pkgsAB, "hardlinkReadOnly") st <- statFiles(pkgFiles(to, "tinyCloneA")) expect_true(all(st$links == 1L)) # copied, so no link to the source + expect_true(all(file.access(pkgFiles(to, "tinyCloneA"), 2) == 0)) # and as writable as the source was + expect_identical(as.integer(file.mode(names(modes))), as.integer(modes)) expect_true(all(statFiles(pkgFiles(to, "tinyCloneB"))$links == 2L)) # the other package was linked expect_identical(versionIn(to, "tinyCloneA"), "0.0.1") ## across file systems, where there is one to try: /dev/shm is not the disk of tempdir() From 47141cbac91e64c2d672bfe1a193f3c0ea21d0e9 Mon Sep 17 00:00:00 2001 From: Eliot McIntire Date: Mon, 30 Nov 2026 15:10:26 -0700 Subject: [PATCH 3/3] hardlinkReadOnly: copy the files a package ships in inst/, link only what R installed Only R-made top-level entries (R, libs, help, html, Meta, data, doc, demo, po, exec, DESCRIPTION, NAMESPACE, INDEX) are linked and made read-only. Everything else came from inst/ (data files, databases), which a package may write into at run time -- climateData's WAL-mode SQLite index did -- so it is copied with its own mode and the source copy is never made read-only. About 16% of a typical library (0.18 of 1.13 GB here). New test; bump to 2.1.1.9042. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Lx3DXgG6hSA1CRAMhvKajR --- DESCRIPTION | 2 +- NEWS.md | 2 +- R/Require2.R | 15 ++++++++-- R/RequireOptions.R | 7 +++-- man/RequireOptions.Rd | 7 +++-- tests/testthat/test-25cloneFrom_testthat.R | 35 +++++++++++++++++++++- 6 files changed, 58 insertions(+), 10 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index dc68ff98..7c1973a6 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -16,7 +16,7 @@ URL: https://Require.predictiveecology.org, https://github.com/PredictiveEcology/Require Date: 2026-09-04 -Version: 2.1.1.9037 +Version: 2.1.1.9042 Authors@R: c( person(given = "Eliot J B", family = "McIntire", diff --git a/NEWS.md b/NEWS.md index e2867c21..1e0521b0 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,7 +12,7 @@ ## New features -* Experimental: `options(Require.cloneMethod = "hardlinkReadOnly")` (or `R_REQUIRE_CLONE_METHOD`) makes `Require.cloneFrom` hard-link package files instead of copying them, after taking the write permission off the source files. The files are then read-only under every name, so an in-place write to one (`file.copy(overwrite = TRUE)`, `writeBin()`) fails instead of emptying it in every library that shares it; installs, `remove.packages()` and clones still work, as they replace files and folders by rename. The default stays `"copy"`. The mode makes the source library's files read-only too, is never used on Windows or across file systems, and copies any package it cannot chmod or link. See `?RequireOptions`. +* Experimental: `options(Require.cloneMethod = "hardlinkReadOnly")` (or `R_REQUIRE_CLONE_METHOD`) makes `Require.cloneFrom` hard-link the files R itself installed (R code, compiled code, help) instead of copying them, after taking the write permission off the source files. Files a package ships in `inst/` (data files, databases) are still copied, so a package that writes into them is unaffected. The files are then read-only under every name, so an in-place write to one (`file.copy(overwrite = TRUE)`, `writeBin()`) fails instead of emptying it in every library that shares it; installs, `remove.packages()` and clones still work, as they replace files and folders by rename. The default stays `"copy"`. The mode makes the source library's files read-only too, is never used on Windows or across file systems, and copies any package it cannot chmod or link. See `?RequireOptions`. * `install = "HEAD"`, or `options(Require.install = "HEAD")`, installs every requested package, GitHub or CRAN, if missing and updates it if not current: to the latest commit of its branch (GitHub) or the newest release (CRAN), as if each were written `"pkg (HEAD)"`. This replaces a minimum version (`>=`), as modules usually write, and other requests for the same package; a package with an exact or maximum version is kept as requested. Dependencies are updated only when they fail a version floor, like `pak::pak(upgrade = FALSE)`. Packages already loaded are installed too, with the usual "Please restart R" warning. New `UpdateOrInstall()` is `Install(packages, install = "HEAD", ...)`. Set the option before `setupProject()` to update all of a project's packages. `Install()` now also takes `"force"` and `"HEAD"` from `Require.install`. diff --git a/R/Require2.R b/R/Require2.R index 6cf8498d..ef6857fb 100644 --- a/R/Require2.R +++ b/R/Require2.R @@ -2167,7 +2167,14 @@ cloneMethod <- function(method = getOption("Require.cloneMethod", "copy")) { if (isWindows()) "copy" else method } -# Experimental: make the folder `from` appear as `to`/ by hard-linking every file, +# Top-level entries of an installed package that R CMD INSTALL makes itself (code, help, metadata). +# Everything else in an installed package came from its inst/ folder (data files, databases, +# templates), which a package may write into at run time, so linkPackageReadOnly() copies it. +.cloneLinkableTop <- c("DESCRIPTION", "NAMESPACE", "INDEX", "Meta", "R", "data", "demo", "doc", + "exec", "help", "html", "libs", "po") + +# Experimental: make the folder `from` appear as `to`/ by hard-linking each file +# that R itself installed (see .cloneLinkableTop; files from inst/ are copied, keeping their mode), # after taking the write bits off the source file. Permissions belong to the inode, so the file is # read-only under every name and a later write in place (`file.copy(overwrite = TRUE)`, `writeBin()`) # fails with EACCES instead of truncating the file in every library that shares it. Replacing a @@ -2191,10 +2198,12 @@ linkPackageReadOnly <- function(from, to, link = file.link, chmod = Sys.chmod) { mode <- as.integer(file.mode(src)) orig <- setNames(mode, src) ro <- bitwAnd(mode, bitwNot(strtoi("222", 8L))) # no write bit for anyone - todo <- mode != ro + lnk <- sub("/.*", "", files) %in% .cloneLinkableTop # the rest came from inst/: copied + todo <- lnk & mode != ro all(!is.na(mode)) && !any(nzchar(Sys.readlink(src))) && dir.create(top) && all(vapply(file.path(top, dirs), dir.create, logical(1))) && - all(suppressWarnings(link(src, file.path(top, files)))) && + all(suppressWarnings(link(src[lnk], file.path(top, files[lnk])))) && + all(file.copy(src[!lnk], file.path(top, files[!lnk]), copy.mode = TRUE, copy.date = TRUE)) && { changed <- src[todo]; all(chmod(src[todo], mode = as.octmode(ro[todo]))) } }, error = function(e) FALSE) if (!isTRUE(ok)) { diff --git a/R/RequireOptions.R b/R/RequireOptions.R index bdaa28c3..c97e05f3 100644 --- a/R/RequireOptions.R +++ b/R/RequireOptions.R @@ -89,8 +89,11 @@ #' resolved is preferred, then the highest.} #' \item{`cloneMethod`}{ Default: `"copy"`. How `cloneFrom` puts a package into the #' destination library: `"copy"` copies every file. `"hardlinkReadOnly"` is -#' experimental: each file is hard-linked, not copied, after the write -#' permission is taken off the *source* file. Permissions belong to the file, +#' experimental: each file that R itself installed (R code, compiled code, +#' help, metadata) is hard-linked, not copied, after the write +#' permission is taken off the *source* file. Files the package ships in its +#' `inst/` folder (data files, databases) are copied as usual, because a +#' package may write into those. Permissions belong to the file, #' not to a name for it, so the file is read-only in every library that shares it, #' and writing into it in place (`file.copy(overwrite = TRUE)`, `writeBin()`, #' `cat >`) is an error instead of silently emptying the file in all of them. diff --git a/man/RequireOptions.Rd b/man/RequireOptions.Rd index 4b2e14f2..b44027b2 100644 --- a/man/RequireOptions.Rd +++ b/man/RequireOptions.Rd @@ -99,8 +99,11 @@ every package pak plans to install; of several copies, the version pak resolved is preferred, then the highest.} \item{\code{cloneMethod}}{ Default: \code{"copy"}. How \code{cloneFrom} puts a package into the destination library: \code{"copy"} copies every file. \code{"hardlinkReadOnly"} is -experimental: each file is hard-linked, not copied, after the write -permission is taken off the \emph{source} file. Permissions belong to the file, +experimental: each file that R itself installed (R code, compiled code, +help, metadata) is hard-linked, not copied, after the write +permission is taken off the \emph{source} file. Files the package ships in its +\verb{inst/} folder (data files, databases) are copied as usual, because a +package may write into those. Permissions belong to the file, not to a name for it, so the file is read-only in every library that shares it, and writing into it in place (\code{file.copy(overwrite = TRUE)}, \code{writeBin()}, \verb{cat >}) is an error instead of silently emptying the file in all of them. diff --git a/tests/testthat/test-25cloneFrom_testthat.R b/tests/testthat/test-25cloneFrom_testthat.R index 9fb61da3..5b34a806 100644 --- a/tests/testthat/test-25cloneFrom_testthat.R +++ b/tests/testthat/test-25cloneFrom_testthat.R @@ -2,10 +2,14 @@ ## them. Under pak (pakClonePackages()) a copy is used when it meets every version requirement; a ## GitHub ref needs the commit pak resolved, and a CRAN-style ref never takes a development build. -tinyPkg <- function(lib, name, version = "0.0.1", imports = NULL, extra = NULL) { +tinyPkg <- function(lib, name, version = "0.0.1", imports = NULL, extra = NULL, instFiles = NULL) { src <- withr::local_tempdir() p <- file.path(src, name) dir.create(file.path(p, "R"), recursive = TRUE) + for (f in names(instFiles)) { # e.g. list(`extdata/db.txt` = "x"): installed as /extdata/db.txt + dir.create(dirname(file.path(p, "inst", f)), recursive = TRUE, showWarnings = FALSE) + writeLines(instFiles[[f]], file.path(p, "inst", f)) + } writeLines(c(paste0("Package: ", name), paste0("Version: ", version), "Title: t", "Description: t.", "License: MIT", "Encoding: UTF-8", "NeedsCompilation: no", if (length(imports)) paste0("Imports: ", paste(imports, collapse = ", ")), extra), @@ -762,6 +766,35 @@ test_that("hardlinkReadOnly: files are shared and read-only; an in-place write f expect_identical(file.size(c(old, file.path(plainTo, "x.rdb"))), c(0, 0)) }) +test_that("hardlinkReadOnly copies the files a package ships in inst/; they stay writable in both libraries", { + skip_on_os("windows") + skipIfRoot() + from <- withr::local_tempdir() + tinyPkg(from, "tinyCloneInst", instFiles = list(`extdata/tiles.sqlite` = "db")) + srcDb <- file.path(from, "tinyCloneInst", "extdata", "tiles.sqlite") + modeBefore <- file.mode(srcDb) + to <- cloneWith(from, "tinyCloneInst", "hardlinkReadOnly") + toDb <- file.path(to, "tinyCloneInst", "extdata", "tiles.sqlite") + + st <- statFiles(c(srcDb, toDb)) + expect_false(identical(st$inode[1], st$inode[2])) # its own copy + expect_true(all(st$links == 1L)) + expect_identical(file.mode(srcDb), modeBefore) # the source is not made read-only + expect_true(all(file.access(c(srcDb, toDb), 2) == 0)) + ## a write (a database opening its -wal/-shm files, an update in place) touches one library only + writeLines("changed", toDb) + expect_identical(readLines(srcDb), "db") + writeLines("x", paste0(toDb, "-wal")) + expect_false(file.exists(paste0(srcDb, "-wal"))) + + ## the files R installed are still shared and read-only + rdb <- file.path(c(from, to), "tinyCloneInst", "R", "tinyCloneInst.rdb") + st <- statFiles(rdb) + expect_identical(st$inode[1], st$inode[2]) + expect_false(any(file.access(rdb, 2) == 0)) + expect_identical(versionIn(to, "tinyCloneInst"), "0.0.1") +}) + test_that("hardlinkReadOnly through pakClonePackages: the clone loads and the source is still intact", { skip_on_os("windows") from <- cloneFromLib()