--- title: "Setup and Basics" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Setup and Basics} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup} # ---- setup, include=FALSE ---------------------------------------------------- # 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() ``` Let’s initialize a lightweight project and walk through the most common workflows: formats, saving/loading, sidecars, versions/lineage, primary-key helpers, and retention. The examples use temporary directories so you can run them locally without touching your real project. ## 1. Initialize a project `st_init()` prepares a small internal state directory (by default `.stamp/`) to hold the catalog, temporary files, and logs. **Artifacts and their version histories are stored directly in your project structure**, not inside `.stamp/`. ```{r init-example} # Use a private temp dir so the vignette is reproducible locally tdir <- tempfile("stamp-vignette-") fs::dir_create(tdir) st_init(tdir) # Inspect created structure - note .stamp/ contains only state fs::path(tdir, ".stamp") |> fs::dir_tree(recurse = TRUE, all = TRUE) ``` Notes - Default state dir: `.stamp/` (you can override via `st_init(state_dir = "_stamp")`). - **Storage model (v0.0.9+):** Artifacts are stored as `//` with version history in `//versions/`. The `.stamp/` directory contains only the catalog, locks, and temp files. ## 2. Options (`st_opts()`) Global behavior is controlled via `st_opts()`. Typical options you will use: - `meta_format`: how sidecars are written. Allowed: `"json"`, `"qs2"`, or `"both"`. - `default_format`: which format to use when none is inferred from a path. - `versioning`: controls whether saves create version snapshots (`"content"` vs `"timestamp"` vs `"off"). Example: ```{r opts-example} # show defaults st_opts(.get = TRUE) # write both JSON and QS2 sidecars st_opts(meta_format = "both") st_opts("meta_format", .get = TRUE) ``` Use `versioning` to control when a version snapshot is recorded. The default `"content"` mode records a new version only when content/code changed; `"timestamp"` forces a version on every save (useful for audit trails). ## 3. Paths and format registry Format inference maps known extensions through an internal registry, so a path ending in `.fst` is written with the `fst` handler. Pass `format =` to `st_save()` or `st_load()` whenever the extension does not imply the format you want. ```{r path-format} st_formats() # built-in handlers: csv, fst, json, parquet, qs2, rds ``` You can extend the registry with `st_register_format()` to add a new format (e.g. Parquet). The registry will also map file extensions if you provide them. ## 4. Save & load (atomic, with sidecar metadata) Use `st_save()` and `st_load()` for robust writes. `st_save()` performs an atomic write (temp file then move), writes sidecar metadata, and — depending on `versioning` — records a version snapshot. **Storage structure:** When you save to a path like `"outputs/example.qs2"`, stamp creates: - `outputs/example.qs2/example.qs2` - the actual file - `outputs/example.qs2/stmeta/` - sidecar metadata directory - `outputs/example.qs2/versions/` - version history (when versioning enabled) ```{r save-load} x <- data.frame(a = 1:3, b = letters[1:3]) res <- st_save(x, "stamp-output/example.qs2", metadata = list(description = "toy"), alias = NULL) res$path # Inspect the created structure artifact_dir <- fs::path_dir(res$path) fs::dir_tree(artifact_dir, recurse = 1) # load back (format auto-detected) y <- st_load("stamp-output/example.qs2", alias = NULL) identical(x, y) ``` `st_save()` accepts additional arguments useful for provenance: - `code`: a function/expression whose hash is recorded by `st_save()`. - `parents`: optional list of parent descriptors (list(list(path=..., version_id=...), ...)) to record provenance. - `code_label`: a short human label for the producing code. ### 4.1 Loading specific versions The `version` argument in `st_load()` allows you to load historical versions of artifacts. This is useful for comparing changes over time or recovering from mistakes. ```{r load-versions} # Ensure versioning is enabled for this example st_opts(versioning = "timestamp") # Force version on every save # Create multiple versions by modifying and saving v_path <- "versioned.qs2" # Version 1 v1 <- data.frame(x = 1:3, y = c("a", "b", "c")) st_save(v1, v_path, code_label = "initial", alias = NULL) Sys.sleep(1.1) # ensure distinct timestamps on all platforms # Version 2 v2 <- data.frame(x = 1:5, y = c("a", "b", "c", "d", "e")) st_save(v2, v_path, code_label = "added rows", alias = NULL) Sys.sleep(1.1) # Version 3 v3 <- data.frame(x = 1:5, y = c("a", "b", "c", "d", "e"), z = 10:14) st_save(v3, v_path, code_label = "added column z", alias = NULL) # Check available versions (explicit alias auto-detect) versions <- st_versions(v_path, alias = NULL) if (nrow(versions) == 0) { cat("Warning: No versions were created. Skipping version loading examples.\n") } else { print(versions[, .(version_id, created_at, size_bytes)]) # Load latest (default) current <- st_load(v_path, alias = NULL) cat(sprintf("Current: %d rows, %d columns\n", nrow(current), ncol(current))) # Load previous version (version = -1) when available; skip if snapshot missing if (nrow(versions) >= 2) { prev_ok <- TRUE previous <- tryCatch( st_load(v_path, version = -1, alias = NULL), error = function(e) { prev_ok <<- FALSE; NULL } ) if (isTRUE(prev_ok)) { cat(sprintf("Previous (v-1): %d rows, %d columns\n", nrow(previous), ncol(previous))) } else { cat("Previous (v-1): snapshot not available; skipping.\n") } } } # Load two versions back (version = -2) when available, else oldest by ID older_ok <- TRUE if (nrow(versions) >= 3) { older <- tryCatch( st_load(v_path, version = -2, alias = NULL), error = function(e) { older_ok <<- FALSE; NULL } ) } else if (nrow(versions) >= 1) { oldest_id <- versions$version_id[nrow(versions)] older <- tryCatch( st_load(v_path, version = oldest_id, alias = NULL), error = function(e) { older_ok <<- FALSE; NULL } ) } else { older_ok <- FALSE older <- NULL } if (isTRUE(older_ok)) { cat(sprintf("Older: %d rows, %d columns\n", nrow(older), ncol(older))) } else { cat("Older: snapshot not available; skipping.\n") } # Load specific version by ID (oldest) vid <- versions$version_id[nrow(versions)] spec_ok <- TRUE specific <- tryCatch( st_load(v_path, version = vid, alias = NULL), error = function(e) { spec_ok <<- FALSE; NULL } ) if (isTRUE(spec_ok) && isTRUE(older_ok)) { cat(sprintf("Specific version matches older: %s\n", identical(specific, older))) } # Reset to default versioning st_opts(versioning = "content") ``` The `version` argument supports several modes: - `NULL` (default): loads the current artifact file - `0`: same as NULL, loads latest version - Negative integers (`-1`, `-2`, etc.): load versions relative to latest - Character string: specific version ID (from `st_versions()`) - `"select"`, `"pick"`, or `"choose"`: interactive menu (in interactive sessions) ```{r load-interactive, eval=FALSE} # Interactive menu to choose a version (only works in interactive R sessions) # This will display a menu with formatted timestamps and file sizes selected <- st_load(v_path, version = "select") # The menu looks like: # ℹ Select a version to load from versioned.qs2: # Latest version is [1] # # Available versions: # # 1: [1] 2025-11-26 10:30:15 (0.12 MB) - 20251126T103015Z # 2: [2] 2025-11-26 10:30:10 (0.10 MB) - 20251126T103010Z # 3: [3] 2025-11-26 10:30:05 (0.08 MB) - 20251126T103005Z # # Selection: _ ``` ## 5. Sidecars (quick metadata) Sidecars live in an `stmeta/` directory next to the artifact (inside the artifact's parent directory) and contain metadata such as `path`, `format`, `created_at` (UTC), `size_bytes`, `content_hash`, `code_hash`, `code_label`, and `parents` (a quick view). **Example:** For artifact at `outputs/example.qs2/example.qs2`, the sidecar is at `outputs/example.qs2/stmeta/sidecar.json`. ```{r sidecar} sc <- st_read_sidecar(res$path) str(sc) ``` The sidecar is intended for quick inspection and for storing metadata even when a version snapshot may not be recorded (e.g., when `versioning = "content"` and nothing changed). For reproducible lineage and rebuilds, `st_save()` writes a snapshot in the artifact's `versions/` directory that includes committed copies of the artifact and its parents.json. ## 6. Versions, lineage, and inspection The package maintains a simple catalog of versions. Version snapshots are stored in a `versions/` directory next to each artifact (not centralized in `.stamp/`). Useful functions: - `st_versions(path)` — list recorded versions for an artifact. - `st_latest(path)` — get the latest version id. - `st_load_version(path, version_id)` — load a specific recorded version. - `st_info(path)` — quick inspection: returns current sidecar, catalog info, snapshot dir (if present), and parents (from snapshot or sidecar fallback). - `st_lineage(path, depth=1)` — walk immediate or recursive parents. Example that demonstrates parents and lineage (parents passed to `st_save`): ```{r lineage-example} # upstream artifact in_path <- "upstream.qs" st_save(data.frame(id=1:3), in_path, alias = NULL) in_vid <- st_latest(in_path, alias = NULL) # derived artifact recording parent info out_path <- "derived.qs" parents <- list(list(path = in_path, version_id = in_vid)) st_save(data.frame(id=1:3, v=10), out_path, parents = parents, code_label = "multiply", alias = NULL) st_info(out_path, alias = NULL)$sidecar st_lineage(out_path, depth = 1, alias = NULL) ``` Notes on behavior - The sidecar always contains `parents` for quick inspection. However, in the default `versioning = "content"` mode a new committed snapshot (and its `parents.json`) will only be created when content or code changed. The vignette code above deliberately saves upstream and derived artifacts so a snapshot is recorded. - Version snapshots are stored in `/versions//`, not in `.stamp/versions/` (the centralized storage was removed in v0.0.9). ## 7. Primary-key helpers (optional) You can record a primary-key (pk) for an artifact in its sidecar to make it easier to identify rows later. Helpers: - `st_pk()` — normalize/validate a pk spec. - `st_add_pk(path, keys)` — record a pk in the artifact sidecar (optionally validate against on-disk content). - `st_inspect_pk(path)` — read pk from sidecar. - `st_with_pk(df, keys)` and `st_get_pk()` — in-memory helpers. Example: ```{r pk-example} st_add_pk(out_path, keys = c("id")) st_inspect_pk(out_path) # load and filter by pk using st_filter df <- st_load(out_path, alias = NULL) st_filter(df, list(id = 1)) ``` ## 8. Retention / pruning To control disk usage, `st_prune_versions()` prunes older version snapshots according to a retention policy. The simplest call applies the default project policy; you can also pass `policy` or use `dry_run = TRUE` to preview. ```{r retention-example, eval=FALSE} # dry-run to preview deletions for this artifact st_prune_versions(path = out_path, policy = 5, dry_run = TRUE, alias = NULL) # apply retention (non-dry) st_prune_versions(path = out_path, policy = list(n = 5, days = 30), dry_run = FALSE, alias = NULL) ``` ## 9. Tips and conventions - Prefer `qs2` for artifact storage for speed/space, use JSON sidecars for readability during development. - Pass `format =` to `st_save()`/`st_load()` when the file extension does not imply the format you want. - Use `st_info()` and `st_lineage()` to inspect provenance; use `st_versions()` and `st_load_version()` to access historical snapshots. ```{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(tdir, recursive = TRUE) ```