| Title: | Reproducible Artifact Store with Sidecars, Versions, and Partitions |
|---|---|
| Description: | Stamp saves R objects with sidecar metadata (hashes, provenance, PKs), keeps version history, prunes old versions, and supports Hive-style partitions. |
| Authors: | R.Andres Castaneda [aut, cre] (ORCID: <https://orcid.org/0000-0003-1154-1374>), Diana C. Garcia Rojas [aut] (ORCID: <https://orcid.org/0000-0001-9423-3865>) |
| Maintainer: | R.Andres Castaneda <[email protected]> |
| License: | MIT + file LICENSE |
| Version: | 0.0.11 |
| Built: | 2026-12-05 15:46:50 UTC |
| Source: | https://github.com/randrescastaneda/stamp |
Update the artifact sidecar for path to include primary-key metadata
(pk element). The artifact file itself is not rewritten. By default the
function validates the provided keys against the current on-disk artifact
(and optionally checks uniqueness). Use validate = FALSE to skip
validation and perform a pure metadata update.
st_add_pk(path, keys, validate = TRUE, check_unique = FALSE)st_add_pk(path, keys, validate = TRUE, check_unique = FALSE)
path |
Path to the artifact file whose sidecar will be updated. Can be an absolute path or relative path. |
keys |
Character vector of column names to set as the primary key. |
validate |
Logical; when |
check_unique |
Logical; when |
Invisibly returns the character vector of keys recorded.
Get a registered alias configuration
st_alias_get(alias = NULL)st_alias_get(alias = NULL)
alias |
Optional alias; if NULL, uses "default" |
list(root, state_dir, stamp_path) or NULL if not found
List registered stamp aliases in the current session
st_alias_list()st_alias_list()
data.frame with columns: alias, root, state_dir, stamp_path
List registered builders
st_builders()st_builders()
data.frame with columns: path, name
Return a data.table with one row per artifact in the catalog,
containing the metadata for that artifact's most recent version only.
This provides a snapshot of the current state of all tracked artifacts
without having to iterate over individual artifact paths.
st_catalog_query(alias = NULL)st_catalog_query(alias = NULL)
alias |
Character scalar. Stamp alias to query. |
Unlike st_versions(), which returns all historical versions for a
single artifact, st_catalog_query() returns exactly one row per
artifact — the latest version — across the entire alias catalog.
A data.table with one row per artifact and columns:
path |
Absolute path to the artifact file. |
version_id |
Latest version identifier for this artifact. |
content_hash |
Content hash of the latest version (may be |
code_hash |
Code hash of the latest version (may be |
size_bytes |
Size in bytes of the latest version artifact. |
created_at |
ISO8601 timestamp when the latest version was recorded. |
An empty data.table with the same schema is returned when the catalog
has no artifacts.
st_versions() to query all versions for a single artifact.
## Not run: # Query all latest versions in a named alias latest <- st_catalog_query(alias = "my_project") nrow(latest) # one row per artifact # Use default alias latest <- st_catalog_query() ## End(Not run)## Not run: # Query all latest versions in a named alias latest <- st_catalog_query(alias = "my_project") nrow(latest) # one row per artifact # Use default alias latest <- st_catalog_query() ## End(Not run)
Compares the current object/code/file to the latest saved metadata (from the sidecar) and reports if a change is detected.
st_changed( path, x = NULL, code = NULL, mode = c("any", "content", "code", "file"), alias = NULL )st_changed( path, x = NULL, code = NULL, mode = c("any", "content", "code", "file"), alias = NULL )
path |
Artifact path on disk. |
x |
Current in-memory object (for content comparison). |
code |
Optional function/expression/character (for code comparison). |
mode |
Which changes to check: "content", "code", "file", or "any". |
alias |
Optional character alias to identify this stamp folder.
If |
A list: list(changed =
Explain why an artifact would change
st_changed_reason( path, x = NULL, code = NULL, mode = c("any", "content", "code", "file"), alias = NULL )st_changed_reason( path, x = NULL, code = NULL, mode = c("any", "content", "code", "file"), alias = NULL )
path |
Artifact path on disk. |
x |
Current in-memory object (for content comparison). |
code |
Optional function/expression/character (for code comparison). |
mode |
Which changes to check: "content", "code", "file", or "any". |
alias |
Optional stamp alias to target a specific stamp folder. |
Character scalar: "no_change", "missing_artifact", "missing_meta", or e.g. "content+code"
Finds artifacts that depend on path (i.e., that record it in their
parents.json snapshots). If version_id is given, matches only
that specific parent version; otherwise, any parent version of path.
st_children(path, version_id = NULL, depth = 1L, alias = NULL)st_children(path, version_id = NULL, depth = 1L, alias = NULL)
path |
Character path to the parent artifact. |
version_id |
Optional version id of |
depth |
Integer depth >= 1. Use |
alias |
Optional stamp alias to target a specific stamp folder. |
data.frame with columns:
level, child_path, child_version,
parent_path, parent_version.
Clear all builders (or only those for a given path)
st_clear_builders(path = NULL)st_clear_builders(path = NULL)
path |
Optional character path; if provided, only builders for that path are removed. |
Convenience helper to subset a data.frame by a set of named values. The
filters argument is a named list mapping column names to allowed values
(vector). When strict = TRUE, unknown filter columns raise an error.
st_filter(df, filters = list(), strict = TRUE)st_filter(df, filters = list(), strict = TRUE)
df |
A data.frame to filter. |
filters |
Named list of filtering values, e.g. |
strict |
Logical; when |
A subsetted data.frame (same columns as df).
Return a sorted character vector with the names of formats currently registered in the internal registry.
st_formats()st_formats()
Character vector of format names.
st_formats()st_formats()
Extract the primary-key column names from either an in-memory data.frame
(via the stamp_pk attribute) or from a sidecar/meta list (a previously
recorded pk element). Returns an empty character vector when none is found.
st_get_pk(x_or_meta)st_get_pk(x_or_meta)
x_or_meta |
Either a data.frame (with attribute |
Character vector of primary-key column names (may be length 0).
Computes a stable hash of an R object by serializing it with
base::serialize(version = 3) and hashing the resulting bytes via
secretbase::siphash13(). The hash is stable across R sessions (given the
same R version and object structure) and suitable for change detection.
st_hash_obj(x)st_hash_obj(x)
x |
Any R object (data.frame, data.table, list, vector, etc.) |
Lowercase hex string (16 hex characters) from siphash13().
Before hashing, this function normalizes the order of object attributes to
ensure consistent hashes even when operations (like collapse::rowbind() +
collapse::funique()) leave attributes in different orders.
The normalization reorders attributes to a canonical form:
Priority attributes: names, row.names, class, .internal.selfref
Other attributes: alphabetically sorted
This ensures that logically identical objects produce identical hashes regardless of their attribute creation history.
Without normalization, two data.frames that are identical() can produce
different hashes if their internal attributes are in different orders. This
breaks change detection in stamp, causing false positives where objects are
incorrectly flagged as changed.
For small to medium objects: negligible overhead
For large objects: creates a shallow copy (data is referenced, not duplicated)
The normalization cost is typically < 1% of total hashing time
## Not run: # Two ways to create the "same" data dt_a <- data.table(x = 1:5) dt_b <- data.table(x = 1:5) |> collapse::rowbind(data.table(x = 1:5)) |> collapse::funique() # They're identical in content identical(dt_a, dt_b) # TRUE # And now they hash the same too! st_hash_obj(dt_a) == st_hash_obj(dt_b) # TRUE ## End(Not run)## Not run: # Two ways to create the "same" data dt_a <- data.table(x = 1:5) dt_b <- data.table(x = 1:5) |> collapse::rowbind(data.table(x = 1:5)) |> collapse::funique() # They're identical in content identical(dt_a, dt_b) # TRUE # And now they hash the same too! st_hash_obj(dt_a) == st_hash_obj(dt_b) # TRUE ## End(Not run)
Inspect an artifact's current status (sidecar + catalog + snapshot location)
st_info(path, alias = NULL)st_info(path, alias = NULL)
path |
Artifact path |
alias |
Optional stamp alias to target a specific stamp folder. |
A named list with fields:
sidecar: sidecar list (or NULL)
catalog: list(latest_version_id, n_versions)
snapshot_dir: absolute path to latest version dir (or NA)
parents: list(...) parsed from latest version's parents.json (if any)
Initialize a stamp folder under root using state_dir and optionally
register it under an alias. Aliases allow multiple independent stamp
folders to be managed in a single R session without changing any
on-disk path structures.
st_init(root = ".", state_dir = ".stamp", alias = NULL, verbose = TRUE)st_init(root = ".", state_dir = ".stamp", alias = NULL, verbose = TRUE)
root |
project root (default ".") |
state_dir |
directory name for internal state (default ".stamp") |
alias |
Optional character alias to identify this stamp folder.
If |
verbose |
logical; if |
(invisibly) the absolute state dir
Read the sidecar for path and return the recorded primary-key column
names. If no sidecar or pk information is present, returns character(0).
st_inspect_pk(path)st_inspect_pk(path)
path |
Path to the artifact file. |
Character vector of primary-key column names (may be length 0).
Inspect the committed parents.json for the latest snapshot of path and
determine whether any parent now has a different latest version id.
st_is_stale(path, alias = NULL)st_is_stale(path, alias = NULL)
path |
Character path to the artifact to inspect. |
alias |
Optional stamp alias to target a specific stamp folder. |
Logical scalar. TRUE if any parent advanced, otherwise FALSE.
Get the latest version_id for an artifact path
st_latest(path, alias = NULL)st_latest(path, alias = NULL)
path |
file or directory path |
alias |
Optional stamp alias to target a specific stamp folder. |
Show immediate or recursive parents for an artifact
st_lineage(path, depth = 1L, alias = NULL)st_lineage(path, depth = 1L, alias = NULL)
path |
Artifact path (child) |
depth |
Integer depth >= 1. Use Inf to walk recursively. |
alias |
Optional stamp alias to target a specific stamp folder. |
data.frame with columns: level, child_path, child_version, parent_path, parent_version
List available partitions under a base directory
st_list_parts(base, filter = NULL, recursive = TRUE)st_list_parts(base, filter = NULL, recursive = TRUE)
base |
Base dir |
filter |
Partition filter. Supports three formats:
|
recursive |
Logical; search subdirs (default TRUE) |
A data.frame with columns: path plus one column per partition key
## Not run: # List all partitions st_list_parts("data/parts") # Exact match (backward compatible) st_list_parts("data/parts", filter = list(country = "USA")) # Expression-based (flexible) st_list_parts("data/parts", filter = ~ year > 2010) st_list_parts("data/parts", filter = ~ country == "COL" & year >= 2012) ## End(Not run)## Not run: # List all partitions st_list_parts("data/parts") # Exact match (backward compatible) st_list_parts("data/parts", filter = list(country = "USA")) # Expression-based (flexible) st_list_parts("data/parts", filter = ~ year > 2010) st_list_parts("data/parts", filter = ~ country == "COL" & year >= 2012) ## End(Not run)
Load an object from disk (format auto-detected; optional integrity checks)
st_load(file, format = NULL, version = NULL, verbose = TRUE, alias = NULL, ...)st_load(file, format = NULL, version = NULL, verbose = TRUE, alias = NULL, ...)
file |
path or st_path. Can be:
|
format |
optional format override |
version |
An integer or a quoted directive. Retrieve a specific version of an artifact. See details. |
verbose |
logical; if FALSE, suppress informational messages and package-generated
warnings (default TRUE). When |
alias |
Optional stamp alias to target a specific stamp folder.
If |
... |
forwarded to format reader |
The version argument allows you to load specific versions:
NULL (default): loads the most recent version available.
Negative integer (e.g., -1) or zero (0): loads that number of versions
before the most recent version. So, if 0, it loads the current
version, which is equivalent to NULL. If -1, it will load the version
right before the current one, -2 loads two versions before, and so on.
Positive numbers: Error.
Character: treated as a specific version ID (e.g., "20250801T162739Z-d86e8").
Interactive selection (e.g., "select", "pick", "choose") is supported
and only non-interactive sessions must pass a concrete version id or negative
integer for relative selection.
the loaded object
## Not run: # Basic usage: load latest version data <- st_load("data/mydata.rds") # Load previous version old_data <- st_load("data/mydata.rds", version = -1) # Load specific version by ID vid <- st_versions("data/mydata.rds")$version_id[3] specific <- st_load("data/mydata.rds", version = vid) # Interactive menu (in interactive sessions only) # Interactive selection is not supported in non-interactive contexts. # Pass explicit version id or a negative integer. ## End(Not run)## Not run: # Basic usage: load latest version data <- st_load("data/mydata.rds") # Load previous version old_data <- st_load("data/mydata.rds", version = -1) # Load specific version by ID vid <- st_versions("data/mydata.rds")$version_id[3] specific <- st_load("data/mydata.rds", version = vid) # Interactive menu (in interactive sessions only) # Interactive selection is not supported in non-interactive contexts. # Pass explicit version id or a negative integer. ## End(Not run)
Load and row-bind partitioned data
st_load_parts(base, filter = NULL, columns = NULL, as = c("rbind", "dt"))st_load_parts(base, filter = NULL, columns = NULL, as = c("rbind", "dt"))
base |
Base dir |
filter |
Partition filter. Supports three formats:
|
columns |
Character vector of column names to load (optional). For parquet/fst formats, uses native column selection (fast, low memory). For other formats (qs/rds/csv), loads full object then subsets (with warning). |
as |
Data frame binding mode: "rbind" (base) or "dt" (data.table) |
Data frame with unioned columns and extra columns for the key fields
## Not run: # Load all partitions st_load_parts("data/parts") # Filter with exact match st_load_parts("data/parts", filter = list(country = "USA")) # Filter with expression st_load_parts("data/parts", filter = ~ year > 2010) # Combine filter + column selection st_load_parts("data/parts", filter = ~ year > 2010, columns = c("value", "metric")) ## End(Not run)## Not run: # Load all partitions st_load_parts("data/parts") # Filter with exact match st_load_parts("data/parts", filter = list(country = "USA")) # Filter with expression st_load_parts("data/parts", filter = ~ year > 2010) # Combine filter + column selection st_load_parts("data/parts", filter = ~ year > 2010, columns = c("value", "metric")) ## End(Not run)
Load a previously committed snapshot for an artifact identified by
path and version_id. The artifact file for the requested version is
read from the version snapshot directory using the format-specific
read handler registered in the package. This is useful for inspecting or
restoring historical versions of artifacts.
st_load_version(path, version_id, verbose = TRUE, ..., alias = NULL)st_load_version(path, version_id, verbose = TRUE, ..., alias = NULL)
path |
Character path to the artifact (same value used with |
version_id |
Character version identifier (as returned by |
verbose |
Logical; if TRUE (default), print informational messages. |
... |
Additional arguments forwarded to the format's read function (e.g. |
alias |
Optional stamp alias to target a specific stamp folder. |
The function will abort if the requested version snapshot does not exist or if there is no registered format handler for the artifact's format.
The object produced by the format-specific read handler (typically an R object loaded from disk).
## Not run: # load a historical version of a dataset old <- st_load_version("data/cleaned.rds", "20250101T000000Z-abcdef01") ## End(Not run)## Not run: # load a historical version of a dataset old <- st_load_version("data/cleaned.rds", "20250101T000000Z-abcdef01") ## End(Not run)
Setter: st_opts(meta_format = "both", versioning = "timestamp")
Getter: st_opts(.get = TRUE) returns a named list of all options
Single getter: st_opts("meta_format", .get = TRUE) returns one value
st_opts(..., .get = FALSE)st_opts(..., .get = FALSE)
... |
Named pairs for setting options; or a single character key when |
.get |
Logical. If |
Valid keys (defined in .stamp_default_opts in R/aaa.R):
meta_format, versioning, force_on_code_change,
retain_versions, code_hash, store_file_hash,
verify_on_load, default_format, verbose,
timezone, timeformat, usetz,
require_pk_on_load, warn_missing_pk_on_load.
For a single authoritative source of truth, see .stamp_default_opts in
R/aaa.R; changes to that object determine the set of supported keys.
For setters, invisible(NULL). For getters, the requested value(s).
st_opts_reset(), .stamp_default_opts
Convenience getter (optional sugar)
st_opts_get(key = NULL)st_opts_get(key = NULL)
key |
Option name or |
Value or list of all values
Reset all options to package defaults
st_opts_reset()st_opts_reset()
invisible(NULL)
Build a concrete partition path under a base directory
st_part_path(base, key, file = NULL, format = NULL)st_part_path(base, key, file = NULL, format = NULL)
base |
Character base directory (e.g., "data/users") |
key |
Named list of scalar values, e.g. list(country="US", year=2025) |
file |
Optional filename (default "part. |
format |
Optional format (qs2|rds|csv|fst|json); default = stamp option |
Character file path to the partition artifact
Declare a path (with optional format & partition hint)
st_path(path, format = NULL, partition_key = NULL)st_path(path, format = NULL, partition_key = NULL)
path |
file or directory path |
format |
optional explicit format ("qs2","rds","csv","fst","json") |
partition_key |
optional partition key (not used in M2) |
list with class 'st_path'
Normalize and validate a primary-key (pk) specification. The canonical
representation is a list with element keys containing a character vector
of column names. When x (a data.frame) is provided and validate = TRUE
the function will check that the columns exist (and optionally that they
uniquely identify rows).
st_pk(x = NULL, keys, validate = TRUE, check_unique = FALSE)st_pk(x = NULL, keys, validate = TRUE, check_unique = FALSE)
x |
Optional data.frame to validate the keys against. If |
keys |
Character vector of column names comprising the primary key. |
validate |
Logical; when |
check_unique |
Logical; when |
A list with element keys containing the canonical character vector.
Returns the set of stale descendants of targets.
Two modes:
"propagate" (default): treat each target as "will change",
then breadth-first schedule children whose parents intersect the set of nodes
marked "will change". Newly scheduled nodes are also marked "will change"
so their children are considered at the next level.
"strict": only include nodes already stale against their parents'
current latest versions (no propagation).
st_plan_rebuild( targets, depth = Inf, include_targets = FALSE, mode = c("propagate", "strict") )st_plan_rebuild( targets, depth = Inf, include_targets = FALSE, mode = c("propagate", "strict") )
targets |
Character vector of artifact paths. |
depth |
Integer depth >= 1, or Inf. |
include_targets |
Logical; if TRUE and a target is stale, include it at level 0. |
mode |
"propagate" (default) or "strict". |
data.frame with columns: level, path, reason, latest_version_before
Prune stored versions according to a retention policy
st_prune_versions(path = NULL, policy = Inf, dry_run = TRUE, alias = NULL)st_prune_versions(path = NULL, policy = Inf, dry_run = TRUE, alias = NULL)
path |
Optional character vector of artifact paths to restrict pruning. If NULL (default), applies the policy to all artifacts in the catalog. |
policy |
One of:
|
dry_run |
logical; if TRUE, only report what would be pruned. |
alias |
Optional stamp alias to target a specific stamp folder. |
Retention policy semantics
policy = Inf — keep all versions (no pruning).
policy = <numeric> — interpreted as “keep the n most recent versions
per artifact.” For example, policy = 2 keeps the latest two and prunes older ones.
policy = list(...) — a combined policy where multiple conditions are
UNIONed (kept if any condition keeps it):
n: keep the latest n per artifact.
days: keep versions whose created_at is within the last days days.
keep_latest / min_keep (internal fields in some flows) ensure at least
a floor of versions are preserved; typical use is covered by n + days.
Grouping & order. Pruning decisions are made per artifact, after sorting
each artifact’s versions by created_at (newest → oldest). The “latest n”
condition is applied on this order.
Dry runs vs destructive mode. With dry_run = TRUE, the function only
reports what would be pruned (and estimates reclaimed space). With
dry_run = FALSE, it deletes the snapshot directories under
<state_dir>/versions/... and updates the catalog accordingly:
removes rows from the versions table,
adjusts each artifact’s n_versions and latest_version_id
(to the newest remaining version), or drops the artifact row if none remain.
Scope. You can restrict pruning to specific artifacts by supplying their paths via the path argument. By default (path = NULL), pruning considers all artifacts recorded in the catalog. If you provide one or more artifact paths, only versions associated with those artifacts are considered for pruning.
Integration with writes. If you set a default policy via
st_opts(retain_versions = <policy>), internal helpers may apply pruning
right after st_save() for the just-written artifact (keep-all is the default).
Safety notes.
Pruning never touches the live artifact files (A.qs, etc.) — only the
stored version snapshots and catalog entries.
Use dry_run = TRUE first to verify what would be removed.
Invisibly, a data.frame of pruned (or would-prune) versions with columns: artifact_path, version_id, created_at, size_bytes.
# Minimal setup: temp project with three artifacts and multiple versions st_opts_reset() st_opts(versioning = "content", meta_format = "json") root <- tempdir() st_init(root) # A, B, C pA <- fs::path(root, "A.qs"); xA <- data.frame(a = 1:3) pB <- fs::path(root, "B.qs"); pC <- fs::path(root, "C.qs") # First versions st_save(xA, pA, code = function(z) z) st_save(transform(xA, b = a * 2), pB, code = function(z) z, parents = list(list(path = pA, version_id = st_latest(pA)))) st_save(transform(st_load(pB), c = b + 1L), pC, code = function(z) z, parents = list(list(path = pB, version_id = st_latest(pB)))) # Create a couple of extra versions for A to have data to prune st_save(transform(xA, a = a + 10L), pA, code = function(z) z) st_save(transform(xA, a = a + 20L), pA, code = function(z) z) # Inspect versions for A st_versions(pA) # 1) Keep everything (no-op) st_prune_versions(policy = Inf, dry_run = TRUE) # 2) Keep only the latest 1 per artifact (dry run) st_prune_versions(policy = 1, dry_run = TRUE) # 3) Combined policy: # - keep the latest 2 per artifact # - and also keep any versions newer than 7 days (union of both) st_prune_versions(policy = list(n = 2, days = 7), dry_run = TRUE) # 4) Restrict pruning to a single artifact path st_prune_versions(path = pA, policy = 1, dry_run = TRUE) # 5) Apply pruning (destructive): keep latest 1 everywhere # (Uncomment to run for real) # st_prune_versions(policy = 1, dry_run = FALSE) # Optional: set a default retention policy and have st_save() apply it # after each write via .st_apply_retention() (internal helper). # For example, keep last 2 versions going forward: st_opts(retain_versions = 2) # Next saves will write a new version and then prune older ones for that artifact.# Minimal setup: temp project with three artifacts and multiple versions st_opts_reset() st_opts(versioning = "content", meta_format = "json") root <- tempdir() st_init(root) # A, B, C pA <- fs::path(root, "A.qs"); xA <- data.frame(a = 1:3) pB <- fs::path(root, "B.qs"); pC <- fs::path(root, "C.qs") # First versions st_save(xA, pA, code = function(z) z) st_save(transform(xA, b = a * 2), pB, code = function(z) z, parents = list(list(path = pA, version_id = st_latest(pA)))) st_save(transform(st_load(pB), c = b + 1L), pC, code = function(z) z, parents = list(list(path = pB, version_id = st_latest(pB)))) # Create a couple of extra versions for A to have data to prune st_save(transform(xA, a = a + 10L), pA, code = function(z) z) st_save(transform(xA, a = a + 20L), pA, code = function(z) z) # Inspect versions for A st_versions(pA) # 1) Keep everything (no-op) st_prune_versions(policy = Inf, dry_run = TRUE) # 2) Keep only the latest 1 per artifact (dry run) st_prune_versions(policy = 1, dry_run = TRUE) # 3) Combined policy: # - keep the latest 2 per artifact # - and also keep any versions newer than 7 days (union of both) st_prune_versions(policy = list(n = 2, days = 7), dry_run = TRUE) # 4) Restrict pruning to a single artifact path st_prune_versions(path = pA, policy = 1, dry_run = TRUE) # 5) Apply pruning (destructive): keep latest 1 everywhere # (Uncomment to run for real) # st_prune_versions(policy = 1, dry_run = FALSE) # Optional: set a default retention policy and have st_save() apply it # after each write via .st_apply_retention() (internal helper). # For example, keep last 2 versions going forward: st_opts(retain_versions = 2) # Next saves will write a new version and then prune older ones for that artifact.
Read the sidecar metadata for a file if it exists, returning NULL
when no sidecar file is present. Preference order is JSON first,
then QS2.
st_read_sidecar(rel_path, alias = NULL)st_read_sidecar(rel_path, alias = NULL)
rel_path |
Character relative path from alias root, or an absolute path. If an absolute path is provided, it will be normalized to a relative path. |
alias |
Optional alias. If |
A list (parsed JSON / qs object) or NULL if not found.
Rebuild artifacts from a plan (level order)
st_rebuild(plan, rebuild_fun = NULL, dry_run = FALSE)st_rebuild(plan, rebuild_fun = NULL, dry_run = FALSE)
plan |
A data.frame from |
rebuild_fun |
Optional function called as:
|
dry_run |
If TRUE, do not write anything; just report what would happen. |
Invisibly, a data.frame with the build results (status, version_id, msg).
A "builder" knows how to (re)create an artifact. It will be called by
st_rebuild() as fun(path, parents) and must return a list:
list(
x = <object to save>, # required
format = NULL, # optional ("qs2", "rds", ...)
metadata = list(), # optional, merged into sidecar
code = NULL, # optional (function/expr/character)
code_label = NULL # optional (short description)
)
st_register_builder(path, fun, name = NULL)st_register_builder(path, fun, name = NULL)
path |
Character path this builder produces (exact match). |
fun |
Function with signature |
name |
Optional label so you can register multiple builders per path. |
Invisibly TRUE.
Public function that allows users to register a new format handler or override an existing one. Handlers must be functions with the expected signatures documented below.
st_register_format(name, read, write, extensions = NULL)st_register_format(name, read, write, extensions = NULL)
name |
Character scalar: format name (e.g. |
read |
Function |
write |
Function |
extensions |
Optional character vector of file extensions (e.g. |
Invisibly returns TRUE on success.
st_register_format( "txt", read = function(p, ...) readLines(p, ...), write = function(x, p, ...) writeLines(x, p, ...), extensions = "txt" )st_register_format( "txt", read = function(p, ...) readLines(p, ...), write = function(x, p, ...) writeLines(x, p, ...), extensions = "txt" )
Replaces the current artifact file with a specified historical version.
This is a convenience wrapper around st_load_version and
st_save that restores an artifact in-place.
st_restore(file, version = "oldest", verbose = TRUE, alias = NULL, ...)st_restore(file, version = "oldest", verbose = TRUE, alias = NULL, ...)
file |
Character path to the artifact to restore. Can be:
|
version |
Version identifier to restore to. Can be:
|
verbose |
Logical; if TRUE, prints informative messages. |
alias |
Optional stamp alias to target a specific stamp folder. |
... |
Additional arguments passed to format reader/writer. |
The function:
Loads the specified version from version history
Overwrites the current artifact file with that version
Creates a new version entry for the restoration
This allows you to revert changes by restoring to any previous version. The restoration itself becomes a new version in the history, so you can always go forward again if needed.
Invisibly returns the restored object.
st_load_version, st_versions, st_save
## Not run: # Initialize and create some versions st_init() df1 <- data.frame(x = 1:5) st_save(df1, "data.qs2") df2 <- data.frame(x = 6:10) st_save(df2, "data.qs2") # Restore to previous version st_restore("data.qs2", version = "oldest") # Or restore to a specific version ID versions <- st_versions("data.qs2") st_restore("data.qs2", version = versions$version_id[1]) ## End(Not run)## Not run: # Initialize and create some versions st_init() df1 <- data.frame(x = 1:5) st_save(df1, "data.qs2") df2 <- data.frame(x = 6:10) st_save(df2, "data.qs2") # Restore to previous version st_restore("data.qs2", version = "oldest") # Or restore to a specific version ID versions <- st_versions("data.qs2") st_restore("data.qs2", version = versions$version_id[1]) ## End(Not run)
Save an R object to disk with metadata & versioning (atomic move)
st_save( x, file, format = NULL, metadata = list(), code = NULL, parents = NULL, code_label = NULL, pk = NULL, domain = NULL, unique = TRUE, verbose = TRUE, alias = NULL, ... )st_save( x, file, format = NULL, metadata = list(), code = NULL, parents = NULL, code_label = NULL, pk = NULL, domain = NULL, unique = TRUE, verbose = TRUE, alias = NULL, ... )
x |
object to save |
file |
destination path (character or st_path). Can be:
|
format |
optional format override ("qs2" | "rds" | "csv" | "fst" | "json") |
metadata |
named list of extra metadata (merged into sidecar) |
code |
Optional function/expression/character whose hash is stored as |
parents |
Optional list of parent descriptors:
list(list(path = " |
code_label |
Optional short label/description of the producing code (for humans). |
pk |
optional character vector of primary-key columns (for tables) |
domain |
optional character scalar or vector label(s) for the dataset |
unique |
logical; enforce uniqueness of pk at save time (default TRUE) |
verbose |
logical; if |
alias |
Optional stamp alias to target a specific stamp folder.
If |
... |
forwarded to format writer |
invisibly, a list with path, metadata, and version_id (or skipped=TRUE)
Save a single partition (uses st_save under the hood)
st_save_part( x, base, key, code = NULL, parents = NULL, code_label = NULL, format = NULL, ... )st_save_part( x, base, key, code = NULL, parents = NULL, code_label = NULL, format = NULL, ... )
x |
Object to save |
base |
Base dir for partitions |
key |
Named list of scalar values (e.g., list(country="US", year=2025)) |
code, parents, code_label, format, ...
|
Passed to st_save() |
invisibly, list(path=..., version_id=...)
Decide if a save should proceed given current st_opts() Uses versioning policy and code-change rule.
st_should_save(path, x = NULL, code = NULL, alias = NULL)st_should_save(path, x = NULL, code = NULL, alias = NULL)
path |
Artifact path on disk. |
x |
Current in-memory object (for content comparison). |
code |
Optional function/expression/character (for code comparison). |
alias |
Optional stamp alias to target a specific stamp folder. |
list(save =
Rebase the session "default" alias to the configuration stored under
alias. This does not modify any on-disk paths; it only affects which
stamp folder is used when functions are called without an explicit
alias argument.
st_switch(alias)st_switch(alias)
alias |
Character alias to make the session default. |
Invisibly returns the alias.
Return a table of recorded versions for the artifact identified by
path from the catalog. When data.table is available the result is a
data.table; otherwise a base data.frame is returned. The table contains
one row per recorded version with the columns described below. Rows are
ordered by created_at descending.
st_versions(path, alias = NULL)st_versions(path, alias = NULL)
path |
file or directory path |
alias |
Optional stamp alias to target a specific stamp folder. |
A data.frame or data.table with columns:
version_id |
Character version identifier. |
artifact_id |
Character artifact identifier (hashed). |
content_hash |
Character content hash for the version (may be NA). |
code_hash |
Character code hash for the version (may be NA). |
size_bytes |
Numeric size of the stored artifact in bytes. |
created_at |
Character ISO8601 timestamp when the version was recorded. |
sidecar_format |
Character sidecar format present: "json", "qs2", "both", or "none". |
An empty table is returned when no versions exist for the given path.
Attach primary-key metadata to a data.frame by setting an attribute
stamp_pk with the normalized pk list returned by st_pk(). This does
not modify on-disk sidecars; it is an in-memory convenience.
st_with_pk(x, keys)st_with_pk(x, keys)
x |
Data.frame to annotate. |
keys |
Character vector of column names making the primary key. |
The input data.frame with attribute stamp_pk set.
Splits a data.frame/data.table by partition columns and saves each partition to a separate file using Hive-style directory structure. Eliminates manual looping and splitting logic.
st_write_parts( x, base, partitioning, code = NULL, parents = NULL, code_label = NULL, format = NULL, pk = NULL, domain = NULL, unique = TRUE, .progress = NULL, ... )st_write_parts( x, base, partitioning, code = NULL, parents = NULL, code_label = NULL, format = NULL, pk = NULL, domain = NULL, unique = TRUE, .progress = NULL, ... )
x |
Data.frame or data.table to partition and save |
base |
Base directory for partitions (e.g., "data/welfare_parts") |
partitioning |
Character vector of column names to partition by (e.g., c("country", "year", "reporting_level")) |
code, parents, code_label, format, ...
|
Passed to st_save() for each partition |
pk |
Optional primary key columns (passed to st_save()) |
domain |
Optional domain label(s) (passed to st_save()) |
unique |
Logical; enforce PK uniqueness at save time (default TRUE) |
.progress |
Logical; show progress bar for partitions (default TRUE for >10 parts) |
Invisibly, a data.frame with columns:
partition_key: list-column of key values
path: file path
version_id: version identifier
n_rows: number of rows in partition
For large datasets with many partitions, this function uses data.table's
split for efficiency when available. Progress reporting can be disabled
with .progress = FALSE.
## Not run: # Create sample data welfare <- data.frame( country = rep(c("USA", "CAN"), each = 100), year = rep(2020:2021, each = 50), reporting_level = sample(c("national", "urban"), 200, replace = TRUE), value = rnorm(200) ) # Auto-partition and save st_write_parts( welfare, base = "data/welfare_parts", partitioning = c("country", "year", "reporting_level"), code_label = "welfare_partition" ) # Result: files saved to: # data/welfare_parts/country=USA/year=2020/reporting_level=national/part.qs2 # data/welfare_parts/country=USA/year=2020/reporting_level=urban/part.qs2 # ... etc ## End(Not run)## Not run: # Create sample data welfare <- data.frame( country = rep(c("USA", "CAN"), each = 100), year = rep(2020:2021, each = 50), reporting_level = sample(c("national", "urban"), 200, replace = TRUE), value = rnorm(200) ) # Auto-partition and save st_write_parts( welfare, base = "data/welfare_parts", partitioning = c("country", "year", "reporting_level"), code_label = "welfare_partition" ) # Result: files saved to: # data/welfare_parts/country=USA/year=2020/reporting_level=national/part.qs2 # data/welfare_parts/country=USA/year=2020/reporting_level=urban/part.qs2 # ... etc ## End(Not run)