Skip to content

Support custom cache pack/unpack via S3 generics for non-serializable objects - #2340

Merged
yihui merged 7 commits into
yihui:masterfrom
atusy:cache-hook
Sep 17, 2026
Merged

yihui merged 7 commits into
yihui:masterfrom
atusy:cache-hook

Conversation

@atusy

@atusy atusy commented Apr 26, 2024 •

Copy link
Copy Markdown
Collaborator

This PR allows implementing knit_cache_hook methods which may preprocess objects (e.g., save to an external file) and define custom loaders.

I will add a NEWS item after we agree with the design.

  • refactor(cache): use saveRDS/readRDS instead of makeLazyLoadDB/lazyload
    • For migration, cache_save replaces rdb/rdx files with rds file
    • For backward compatibility, cache_load() attempts lazyload() if rdb/rdx files are available
  • feat(cache): allow pre/postprocessing cache objects)
    • knit_cache_preprocess preprocesses objects being saved
    • knit_cache_postprocess postprocesses objects being loaded
  • feat!(cache): implement knit_cache_hook instead of pre/post-processors
    • Call knit_cache_hook methods on saving cache
      • Methods may save extra files under ${cache_path(h)}__extra directory
      • Methods may return custom loader functions which is saved to ${cache_path(h).rds}

With this PR, we can add some hooks on objects to be cached.
For example, we can use writeLines to save character objects.

```{r}
library(knitr)
registerS3method(
  "knit_cache_hook",
  "character",
  function(x, nm, path) {
    # Cache x as is if it extends character class
    if (!identical(class(x), "character")) {
      return(x)
    }

    # Preprocess data (e.g., save data to an external file)
    # Create external files under the directory of `paste0(path, "__extra")`
    # if knitr should cleanup them on refreshing/cleaning cache
    d <- paste0(path, "__extra")
    dir.create(d, showWarnings = FALSE, recursive = TRUE)
    f <- file.path(d, paste0(nm, '.txt'))
    writeLines(x, f)

    # Return loader function
    # which receives ellipsis for future extentions and has knit_cache_loader class
    structure(function(...) readLines(f), class = 'knit_cache_loader')
  },
  envir = asNamespace("knitr")
)
```

```{r, cache=TRUE}
x <- 'foo bar'
print(x)
```

```{r}
print(x)
```

@atusy atusy linked an issue Apr 26, 2024 that may be closed by this pull request
3 tasks done
@atusy atusy mentioned this pull request Apr 26, 2024
3 tasks done
@atusy

atusy commented Apr 26, 2024 •

Copy link
Copy Markdown
Collaborator Author

maybe preprocess and postprocess are not good names... 🤔

@atusy

This comment was marked as resolved.

@atusy
atusy marked this pull request as draft April 26, 2024 15:28
@atusy
atusy force-pushed the cache-hook branch 3 times, most recently from 259fdd5 to ccc14d7 Compare April 27, 2024 15:20
@atusy atusy changed the title customizible cache (closes #2176) customizable cache (closes #2176) Apr 30, 2024
Comment thread R/cache.R
Comment on lines 13 to 15
cache_purge = function(hash) {
for (h in hash) unlink(paste(cache_path(h), c('rdb', 'rdx', 'RData'), sep = '.'))
for (h in hash) unlink(paste(cache_path(h), c('rds', 'rdb', 'rdx', 'RData'), sep = '.'))
}

@atusy atusy Apr 30, 2024 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cache_purge() and clean_cache() take into account of limited file types/names.
There may be some cases where knitr should remove more files.

The example in the description saved an extra file as a part of cache, which will not be removed by knitr.

registerS3method("knit_cache_preprocess", "data.frame", function(x) {
  write.csv(x, "cache.csv") # NOTE: this file is not removed by `cache$purge()` or `clean_cache()`
  structure("cache.csv", class = "knit_cache_csv")
}, envir = asNamespace("knitr"))

Comment thread R/cache.R Outdated
Comment on lines +148 to +149
knit_cache_postprocess = function(x, ...) UseMethod('knit_cache_postprocess')
knit_cache_postprocess.default = function(x, ...) x

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Postprocess is skipped if a package is not loaded.

@atusy

atusy commented Apr 30, 2024

Copy link
Copy Markdown
Collaborator Author

To solve the above problems, I implemented the knit_cache_hook generic function in place of knit_cache_preprocess and knit_cache_postprocess. See updated description for the details.

@atusy
atusy marked this pull request as ready for review April 30, 2024 03:22

@yihui yihui left a comment •

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I feel this implementation is too complicated, and I'd like to propose a different way: in the latest version of xfun, I added two functions lazy_save() and lazy_load() as a different and simple implementation of base R's lazyLoad() and tools:::makeLazyLoadDB(). By default, xfun::lazy_save()/lazy_load() use the rds format, which should solve the problems #2176 and #2339 (I've only briefly tested #2176).

For backward compatibility, we can first test if *.rdb/*.rdx exist. If they do, we use the old approach (base R), otherwise we switch to xfun's lazy loading.

What do you think?


Correction: I don't remember how I tested #2176 now. I was expecting that this would just work:

```{r}
library(terra)
```

```{r, cache=TRUE}
r = rast(matrix(1:12,3,4))
```

```{r}
r
```

but it doesn't (even if we save r to *.rds). The object r will fail to load in a new R session, and we still have to do wrap()/unwrap():

```{r}
library(terra)
```

```{r, cache=TRUE}
r = rast(matrix(1:12,3,4))
p = wrap(r)
```

```{r}
unwrap(p)
```

That said, I had this issue in mind when designing the new cache system for litedown. With litedown, it's possible to customize the read/write methods for cache via the chunk option cache.rw, e.g.,

---
title: "Caching terra objects with litedown"
knit: litedown:::knit
---

```{r}
library(terra)
rw_terra = list(
  name = 'terra',
  save = function(x, file) {
    if (inherits(x, 'SpatRaster')) x = wrap(x)
    saveRDS(x, file)
  },
  load = function(...) {
    x = readRDS(...)
    if (inherits(x, 'PackedSpatRaster')) x = unwrap(x)
    x
  }
)
```

```{r, cache=TRUE, cache.rw=rw_terra}
r = rast(matrix(1:12,3,4))
```

```{r}
r
```

@atusy

atusy commented Aug 27, 2024

Copy link
Copy Markdown
Collaborator Author

Thanks for the comment.
I do not have a strong opinion, but let me leave some comments below.

I accepted the complexity for following reasons:

  • the feature is mainly for package developers and not for end users
  • usage is limited (I guess)

With my implementation, user's do not have to care about what is going on under saving/loading caches.

For developers, I agree chunk option is a good idea.
The implementation becomes simple.
However, this imposes end-users to understand tricks for edge-cases.
Can we expect end-users read documents carefully before facing troubles on cache behavior?

@yihui

yihui commented Aug 27, 2024

Copy link
Copy Markdown
Owner

Good points, and I agree. Let me think more about it. Thanks!

… generics

Replace tools::makeLazyLoadDB()/lazyLoad() with xfun::lazy_save()/
lazy_load() (rds format). Caches from the former format (.rdb/.rdx) are
still detected and loaded, so the change is backward compatible.

Add two S3 generics, knit_cache_pack() and knit_cache_unpack(), to
customize how objects are written to and restored from the cache.
knit_cache_pack() is called on each object before caching (dispatching
on the live object) and should return a serializable value;
knit_cache_unpack() is called after reading an object back (dispatching
on the packed object) and should restore the original. Both default to
identity. This supersedes the earlier knit_cache_hook approach and lets
users cache objects the default method cannot handle, e.g. external
pointers such as terra rasters via wrap()/unwrap() (closes yihui#2176).

The pack/unpack happen at xfun's per-object read/write layer, so lazy
loading is preserved: an object is only unpacked when actually accessed.
Package authors can register methods for their classes in .onLoad(), so
users need no configuration.

Cache file enumeration (cache_rx, load_cache, cache_exists, cache_purge,
clean_cache) is updated for the numbered lazy-load files (<hash>.0.rds,
<hash>.1.rds, ...).

Co-Authored-By: atusy <30277794+atusy@users.noreply.github.com>
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@yihui

yihui commented Sep 17, 2026 •

Copy link
Copy Markdown
Owner

Reworked. The cache backend now uses xfun::lazy_save() / xfun::lazy_load() (rds) instead of tools::makeLazyLoadDB() / lazyLoad(); existing .rdb/.rdx caches still load, so it's backward-compatible.

Instead of the knit_cache_hook generic (which had to dispatch on the object when saving but fall back to a stored loader closure when loading), customization is now done with two S3 generics that both dispatch on a real object:

  • knit_cache_pack(x) — called on each object before caching, returns a serializable version;
  • knit_cache_unpack(x) — called after an object is read back, restores the original.

Both default to identity. The pack/unpack happen at xfun's per-object read/write layer, so lazy loading is preserved — an object is only unpacked when it's actually accessed. This closes #2176; packages register methods for their classes in .onLoad() and users configure nothing, e.g. terra:

registerS3method("knit_cache_pack", "SpatRaster", function(x, ...) terra::wrap(x), envir = asNamespace("knitr"))
registerS3method("knit_cache_unpack", "PackedSpatRaster", function(x, ...) terra::unwrap(x), envir = asNamespace("knitr"))

@atusy What do you think of this approach?

@yihui yihui linked an issue Sep 17, 2026 that may be closed by this pull request
@yihui

yihui commented Sep 17, 2026

Copy link
Copy Markdown
Owner

I'll merge this PR first. The next CRAN release won't take place anytime soon (typically it will be several months later), so you still have enough time to review and discuss. I'm open to alternative approaches. Thanks!

@yihui yihui changed the title customizable cache (closes #2176) Support custom cache pack/unpack via S3 generics for non-serializable objects (closes #2176, #2340) Sep 17, 2026
@yihui yihui changed the title Support custom cache pack/unpack via S3 generics for non-serializable objects (closes #2176, #2340) Support custom cache pack/unpack via S3 generics for non-serializable objects Sep 17, 2026
@yihui
yihui merged commit fad2d0d into yihui:master Sep 17, 2026
10 checks passed
yihui added a commit that referenced this pull request Sep 18, 2026
#2491)

Refactor of #2340: replace the two S3 generics knit_cache_pack()/knit_cache_unpack() with a single process_cache(x, pack = TRUE, ...).
@atusy

atusy commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

Sounds nice! thanks a lot!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Problem caching instances of torch modules and datasets Caching reference objects

2 participants