--- title: "Hashing, Change Detection and Versions" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Hashing, Change Detection and Versions} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup} # Use development build when interactive *and* explicitly enabled via env var. dev_mode <- (Sys.getenv("DEV_VIGNETTES", "false") == "true") if (dev_mode && requireNamespace("pkgload", quietly = TRUE)) { pkgload::load_all( export_all = FALSE, helpers = FALSE, attach_testthat = FALSE ) } else { # fall back to the installed package (the path CRAN, CI, and pkgdown take) library(stamp) } old_opts <- st_opts_get() old_alias <- st_alias_get() ``` This article explains how stamp detects changes and records versions. We'll cover: - Stable object hashing (`st_hash_obj()`), - Code hashes recorded by `st_save(code = ...)`, - Optional file hashes recorded by `st_save()` with `store_file_hash = TRUE`, - Change-detection helpers (`st_changed()`, `st_changed_reason()`, `st_should_save()`), and - The lightweight versions catalog (`st_versions()`, `st_latest()`, `st_load_version()`). The core idea: stamp compares object/code hashes and applicable restoration metadata with the saved state. For native RDS/QS2 data.tables, original keys are recorded separately from the content hash. Equal hashes alone do not imply a skipped save if the original key descriptor changed. ## Recommended options ```{r} st_opts_reset() st_opts( versioning = "content", # skip write when content unchanged code_hash = TRUE, # store code hash when 'code=' is provided to st_save() store_file_hash = TRUE, # compute & store file hash after write verify_on_load = TRUE, # verify content on load (warn on mismatch) meta_format = "both" # write JSON + QS2 sidecars ) ``` ## Save with hashes (and skip if content identical) ```{r} root <- tempfile("stamp-hashing-") st_init(root) p <- "demo.qs" x <- data.frame(a = 1:3) # First write: creates artifact + sidecars + catalog entry st_save(x, p, code = function(z) z, alias = NULL) # Second write, same content & same code: skipped (no new version) st_save(x, p, code = function(z) z, alias = NULL) nrow(st_versions(p, alias = NULL)) # should be 1 ``` In the snippet above the data.frame content, code and applicable restoration state are unchanged, so content policy skips the second save. For a data.table, a key-only change can instead create a metadata version without changing its content hash; unkeyed inputs never receive an inferred key. Note: the first write will always create the artifact and its sidecar(s). If you see the first write skipped, check that the path you passed to `st_save()` exactly matches subsequent calls. If you **change content** (or **change the code**), a new version is recorded: ```{r} x2 <- transform(x, a = a + 1L) st_save(x2, p, code = function(z) z, alias = NULL) nrow(st_versions(p, alias = NULL)) # now 2 st_latest(p, alias = NULL) # latest version id (string) ``` > **Policy:** By design, changing the `code=` you pass to `st_save()` creates a new version even if `x` is identical. This makes code provenance explicit. A short practical pattern: - Pass your transformation code to `st_save(..., code = )` so stamp can record the code hash. - Use `st_changed()` or `st_should_save()` to cheaply decide whether to run expensive computations before calling `st_save()`. ## Inspect sidecars & metadata ```{r} meta <- st_read_sidecar(p, alias = NULL) meta[c( "format", "created_at", "size_bytes", "content_hash", "code_hash", "file_hash" )] ``` Explanation: - `content_hash` is the stable hash of the R object written (via `st_hash_obj()`). - `code_hash` is recorded when you provide `code=` to `st_save()`. - `file_hash` is computed after the file write (if `store_file_hash = TRUE`) and can be used to detect external file tampering. * `content_hash` comes from `st_hash_obj(x)` * `code_hash` describes the function, expression, or text supplied as `code=` * `file_hash` is optional (post-write) and is used to verify on load ## Change detection (without writing) Use these **before** doing expensive work, to decide whether to recompute. ```{r} x_same <- x2 x_new <- transform(x2, a = a + 10L) st_changed(p, x = x_same, code = function(z) z, alias = NULL) st_changed_reason(p, x = x_same, code = function(z) z, alias = NULL) # "no_change" st_changed(p, x = x_new, code = function(z) z, alias = NULL) st_changed_reason(p, x = x_new, code = function(z) z, alias = NULL) # "content" st_should_save(p, x = x_same, code = function(z) z, alias = NULL) # recommends skip st_should_save(p, x = x_new, code = function(z) z, alias = NULL) # recommends save ``` When you call `st_changed()` or `st_changed_reason()` you avoid performing any file writes. These helpers are ideal as guards inside functions that compute expensive results only when necessary: Example pattern inside your pipeline function: ```r if (st_should_save(p, x = out, code = my_transform)$save) { st_save(out, p, code = my_transform) } else { message("Skipping write; content and code unchanged") } ``` ## Loading specific versions ```{r} vids <- st_versions(p, alias = NULL) head(vids) vid_latest <- st_latest(p, alias = NULL) obj_latest <- st_load_version(p, vid_latest, alias = NULL) # Load an older version by id if (nrow(vids) > 1L) { vid_old <- vids$version_id[[nrow(vids)]] obj_old <- st_load_version(p, vid_old, alias = NULL) } ``` `st_versions()` returns a table of version metadata. Each row includes the `version_id`, `created_at`, and a snapshot of sidecar fields available at commit time. Use `st_load_version()` to restore the artifact as it was at that version. ### Where are versions stored? Snapshots live in a `versions/` directory **next to each artifact**, not centralized in `.stamp/`. Each artifact manages its own version history. **Storage pattern:** `///versions//` ```{r} p <- "demo.qs" x <- data.frame(a = 1:5) # Write once to create a version snapshot st_save(x, p, code = function(z) z, alias = NULL) # Version history is stored next to the artifact info <- st_info(p, alias = NULL) artifact_dir <- fs::path_dir(info$sidecar$path) # e.g., root/demo.qs/ vroot <- fs::path(artifact_dir, "versions") if (fs::dir_exists(vroot)) { cat("Versions directory:", vroot, "\n\n") fs::dir_tree(vroot, recurse = TRUE, all = TRUE) } else { cat("No versions directory found (versioning may be disabled)\n") } ``` Each snapshot dir contains: * `artifact` — a copy of the saved file * `sidecar.json` and/or `sidecar.qs2` — depending on `meta_format` Additionally each snapshot may include a `parents.json` file capturing committed lineage between artifacts; this is created when stamp records explicit parents during a commit. Sidecar metadata (in `stmeta/` next to the artifact) is the primary local source used to decide whether to write, while snapshots are the long-term committed record. **Note:** Version directories are now distributed (one `versions/` folder per artifact), not centralized in `.stamp/versions/`. This makes it easy to locate all history for a specific artifact. ## Integrity checks on load (optional) If `verify_on_load = TRUE` and a `content_hash` exists in the sidecar, `st_load()` recomputes the object's hash and warns if it differs. A mismatch can indicate external changes, stale metadata, or a conversion by the file format. ```{r} invisible(st_load(p, alias = NULL)) # triggers optional verify; warns on mismatch ``` If `verify_on_load = TRUE`, `st_load()` recomputes `st_hash_obj()` and compares it to the `content_hash` recorded in the sidecar or snapshot. Compare the loaded data with the original source before updating metadata or saving again. Use RDS or QS2 when exact 'R' object round-trips are required. ## Troubleshooting **Q: The first `st_save()` was skipped and `st_versions(p)` is 0.** A: The first write should **never** be skipped. Ensure you’re using the current `st_should_save()` which returns `save = TRUE` when the artifact is missing or the sidecar is missing. **Q: `st_changed_reason()` says `"missing_meta"`.** A: The artifact exists but the sidecar was removed or is unreadable. Call `st_save(x, p, code = ...)` once; it will re-materialize metadata and record a version. **Q: Changing only `code=` didn’t create a new version.** A: By design, a code change **does** create a new version. Confirm `st_opts("code_hash", .get = TRUE)` is `TRUE` and you passed `code=` consistently (e.g., a function literal, not different object pointers to identical functions in rare cases). **Q: CSV round-trips aren’t byte-identical.** A: `data.table::fread/fwrite` may coerce types (e.g., integers vs doubles). Compare with relaxed checks or coerce types before comparison. **Q: I see a warning on load about hash mismatch.** A: With `verify_on_load = TRUE`, **stamp** recomputes the object hash and warns if it differs from the sidecar's `content_hash`. The cause can be an external change, stale metadata, or a format conversion such as the CSV type changes described above. Check the data before saving again. **Q: `qs2` isn’t installed.** A: `qs2` is a required dependency. The `"qs2"` handler does not fall back to `{qs}`. Restore the `{qs2}` installation before reading or writing QS2 artifacts. **Q: Sidecars not appearing.** A: Check `st_opts("meta_format", .get = TRUE)` — set to `"json"`, `"qs2"`, or `"both"`. Sidecars are written to `stmeta/` next to the artifact. **Q: Versions aren't where I expect.** A: Version snapshots now live **next to each artifact** in `/versions//`, not centralized in `.stamp/versions/`. Use `st_info(path)$snapshot_dir` to find the exact location, or explore `/versions/` directly. ## Tips & conventions * Keep `versioning = "content"` for reproducible artifacts; use `"timestamp"` if you want a new version on every save; `"off"` to skip versioning entirely. * Use `st_changed()` / `st_should_save()` to gate expensive computation inside your own functions. * Sidecars: prefer `meta_format = "json"` for readability, `"qs2"` for compactness, or `"both"` for redundancy. Further reading / next steps: - See the `lineage-rebuilds` vignette for how committed `parents` and sidecar parents interact during `st_rebuild()`. - Consider recording `code=` for critical data transformations so provenance is preserved even when object content is identical. ```{r cleanup, include=FALSE} suppressMessages(do.call(st_opts, old_opts)) if (!is.null(old_alias)) { st_init(old_alias$root, state_dir = old_alias$state_dir, verbose = FALSE) } unlink(root, recursive = TRUE) ```