Package 'stamp'

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

Help Index


Add or repair primary-key metadata in an artifact sidecar

Description

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.

Usage

st_add_pk(path, keys, validate = TRUE, check_unique = FALSE)

Arguments

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 TRUE validate keys against the on-disk data.

check_unique

Logical; when TRUE assert that the keys uniquely identify rows in the on-disk data (if validate = TRUE).

Value

Invisibly returns the character vector of keys recorded.


Get a registered alias configuration

Description

Get a registered alias configuration

Usage

st_alias_get(alias = NULL)

Arguments

alias

Optional alias; if NULL, uses "default"

Value

list(root, state_dir, stamp_path) or NULL if not found


List registered stamp aliases in the current session

Description

List registered stamp aliases in the current session

Usage

st_alias_list()

Value

data.frame with columns: alias, root, state_dir, stamp_path


List registered builders

Description

List registered builders

Usage

st_builders()

Value

data.frame with columns: path, name


Query latest version metadata for all artifacts in an alias

Description

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.

Usage

st_catalog_query(alias = NULL)

Arguments

alias

Character scalar. Stamp alias to query. NULL (default) uses the default alias.

Details

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.

Value

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 NA).

code_hash

Code hash of the latest version (may be NA).

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.

See Also

st_versions() to query all versions for a single artifact.

Examples

## 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)

Check whether an artifact would change if saved now

Description

Compares the current object/code/file to the latest saved metadata (from the sidecar) and reports if a change is detected.

Usage

st_changed(
  path,
  x = NULL,
  code = NULL,
  mode = c("any", "content", "code", "file"),
  alias = NULL
)

Arguments

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 NULL, uses "default" for backwards compatibility.

Value

A list: list(changed = , reason = , detail = )


Explain why an artifact would change

Description

Explain why an artifact would change

Usage

st_changed_reason(
  path,
  x = NULL,
  code = NULL,
  mode = c("any", "content", "code", "file"),
  alias = NULL
)

Arguments

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.

Value

Character scalar: "no_change", "missing_artifact", "missing_meta", or e.g. "content+code"


List children (reverse lineage) of an artifact

Description

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.

Usage

st_children(path, version_id = NULL, depth = 1L, alias = NULL)

Arguments

path

Character path to the parent artifact.

version_id

Optional version id of path to match. Default: any.

depth

Integer depth >= 1. Use Inf to recurse fully.

alias

Optional stamp alias to target a specific stamp folder.

Value

data.frame with columns: level, child_path, child_version, parent_path, parent_version.


Clear all builders (or only those for a given path)

Description

Clear all builders (or only those for a given path)

Usage

st_clear_builders(path = NULL)

Arguments

path

Optional character path; if provided, only builders for that path are removed.


Filter a data.frame by primary-key values (or arbitrary columns)

Description

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.

Usage

st_filter(df, filters = list(), strict = TRUE)

Arguments

df

A data.frame to filter.

filters

Named list of filtering values, e.g. list(country = "PER").

strict

Logical; when TRUE unknown filter columns cause an error.

Value

A subsetted data.frame (same columns as df).


Inspect available formats

Description

Return a sorted character vector with the names of formats currently registered in the internal registry.

Usage

st_formats()

Value

Character vector of format names.

Examples

st_formats()

Read primary-key keys from a data.frame or sidecar/meta list

Description

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.

Usage

st_get_pk(x_or_meta)

Arguments

x_or_meta

Either a data.frame (with attribute stamp_pk) or a sidecar/meta list as returned by st_read_sidecar().

Value

Character vector of primary-key column names (may be length 0).


Stable SipHash-1-3 of an R object

Description

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.

Usage

st_hash_obj(x)

Arguments

x

Any R object (data.frame, data.table, list, vector, etc.)

Value

Lowercase hex string (16 hex characters) from siphash13().

Attribute Normalization

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:

  1. Priority attributes: names, row.names, class, .internal.selfref

  2. Other attributes: alphabetically sorted

This ensures that logically identical objects produce identical hashes regardless of their attribute creation history.

Why This Matters

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.

Performance

  • 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

Examples

## 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)

Description

Inspect an artifact's current status (sidecar + catalog + snapshot location)

Usage

st_info(path, alias = NULL)

Arguments

path

Artifact path

alias

Optional stamp alias to target a specific stamp folder.

Value

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 stamp project structure

Description

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.

Usage

st_init(root = ".", state_dir = ".stamp", alias = NULL, verbose = TRUE)

Arguments

root

project root (default ".")

state_dir

directory name for internal state (default ".stamp")

alias

Optional character alias to identify this stamp folder. If NULL, uses "default" for backwards compatibility.

verbose

logical; if FALSE, suppress informational messages and warnings (default TRUE). Errors are never suppressed.

Value

(invisibly) the absolute state dir


Inspect primary-key of an artifact from its sidecar

Description

Read the sidecar for path and return the recorded primary-key column names. If no sidecar or pk information is present, returns character(0).

Usage

st_inspect_pk(path)

Arguments

path

Path to the artifact file.

Value

Character vector of primary-key column names (may be length 0).


Is a child artifact stale because its parents advanced?

Description

Inspect the committed parents.json for the latest snapshot of path and determine whether any parent now has a different latest version id.

Usage

st_is_stale(path, alias = NULL)

Arguments

path

Character path to the artifact to inspect.

alias

Optional stamp alias to target a specific stamp folder.

Value

Logical scalar. TRUE if any parent advanced, otherwise FALSE.


Get the latest version_id for an artifact path

Description

Get the latest version_id for an artifact path

Usage

st_latest(path, alias = NULL)

Arguments

path

file or directory path

alias

Optional stamp alias to target a specific stamp folder.


Show immediate or recursive parents for an artifact

Description

Show immediate or recursive parents for an artifact

Usage

st_lineage(path, depth = 1L, alias = NULL)

Arguments

path

Artifact path (child)

depth

Integer depth >= 1. Use Inf to walk recursively.

alias

Optional stamp alias to target a specific stamp folder.

Value

data.frame with columns: level, child_path, child_version, parent_path, parent_version


List available partitions under a base directory

Description

List available partitions under a base directory

Usage

st_list_parts(base, filter = NULL, recursive = TRUE)

Arguments

base

Base dir

filter

Partition filter. Supports three formats:

  • Named list for exact matching: list(country = "USA", year = 2020)

  • Formula with expression: ~ year > 2010 or ~ country == "COL" & year >= 2012

  • NULL for no filtering (default)

recursive

Logical; search subdirs (default TRUE)

Value

A data.frame with columns: path plus one column per partition key

Examples

## 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)

Description

Load an object from disk (format auto-detected; optional integrity checks)

Usage

st_load(file, format = NULL, version = NULL, verbose = TRUE, alias = NULL, ...)

Arguments

file

path or st_path. Can be:

  • A bare filename (e.g., "data.qs2") → loaded from ⁠<alias_root>/data.qs2/data.qs2⁠

  • A path with directory (e.g., "results/model.rds") → loaded from ⁠<alias_root>/results/model.rds/model.rds⁠ When using a path with directory and an explicit alias, the alias root must be a parent of the path, otherwise an error is raised.

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 FALSE, warnings about file/content hash mismatches and a missing primary key recorded by st_load() will not be shown.

alias

Optional stamp alias to target a specific stamp folder. If NULL (default), uses the default alias. If the default alias does not exist, an error is raised. Use aliases to operate across multiple stamp folders.

...

forwarded to format reader

Details

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.

Value

the loaded object

Examples

## 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

Description

Load and row-bind partitioned data

Usage

st_load_parts(base, filter = NULL, columns = NULL, as = c("rbind", "dt"))

Arguments

base

Base dir

filter

Partition filter. Supports three formats:

  • Named list for exact matching: list(country = "USA", year = 2020)

  • Formula with expression: ~ year > 2010 or ~ country == "COL" & year >= 2012

  • NULL for no filtering (default)

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)

Value

Data frame with unioned columns and extra columns for the key fields

Examples

## 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 specific version of an artifact

Description

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.

Usage

st_load_version(path, version_id, verbose = TRUE, ..., alias = NULL)

Arguments

path

Character path to the artifact (same value used with st_save/st_load).

version_id

Character version identifier (as returned by st_save or present in the catalog).

verbose

Logical; if TRUE (default), print informational messages.

...

Additional arguments forwarded to the format's read function (e.g. read options).

alias

Optional stamp alias to target a specific stamp folder.

Details

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.

Value

The object produced by the format-specific read handler (typically an R object loaded from disk).

Examples

## Not run: 
# load a historical version of a dataset
old <- st_load_version("data/cleaned.rds", "20250101T000000Z-abcdef01")

## End(Not run)

Get or set package options

Description

  • 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

Usage

st_opts(..., .get = FALSE)

Arguments

...

Named pairs for setting options; or a single character key when .get = TRUE.

.get

Logical. If TRUE, performs a read instead of a write.

Details

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.

Value

For setters, invisible(NULL). For getters, the requested value(s).

See Also

st_opts_reset(), .stamp_default_opts


Convenience getter (optional sugar)

Description

Convenience getter (optional sugar)

Usage

st_opts_get(key = NULL)

Arguments

key

Option name or NULL for all

Value

Value or list of all values


Reset all options to package defaults

Description

Reset all options to package defaults

Usage

st_opts_reset()

Value

invisible(NULL)


Build a concrete partition path under a base directory

Description

Build a concrete partition path under a base directory

Usage

st_part_path(base, key, file = NULL, format = NULL)

Arguments

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

Value

Character file path to the partition artifact


Declare a path (with optional format & partition hint)

Description

Declare a path (with optional format & partition hint)

Usage

st_path(path, format = NULL, partition_key = NULL)

Arguments

path

file or directory path

format

optional explicit format ("qs2","rds","csv","fst","json")

partition_key

optional partition key (not used in M2)

Value

list with class 'st_path'


Normalize a primary-key specification

Description

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).

Usage

st_pk(x = NULL, keys, validate = TRUE, check_unique = FALSE)

Arguments

x

Optional data.frame to validate the keys against. If NULL, only the keys vector is normalized.

keys

Character vector of column names comprising the primary key.

validate

Logical; when TRUE validate that columns exist (and uniqueness if check_unique is TRUE).

check_unique

Logical; when TRUE assert that keys uniquely identify rows in x (only checked when x is provided).

Value

A list with element keys containing the canonical character vector.


Plan a rebuild of descendants when parents changed

Description

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).

Usage

st_plan_rebuild(
  targets,
  depth = Inf,
  include_targets = FALSE,
  mode = c("propagate", "strict")
)

Arguments

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".

Value

data.frame with columns: level, path, reason, latest_version_before


Prune stored versions according to a retention policy

Description

Prune stored versions according to a retention policy

Usage

st_prune_versions(path = NULL, policy = Inf, dry_run = TRUE, alias = NULL)

Arguments

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:

  • Inf (keep everything)

  • numeric scalar n (keep the n most recent per artifact)

  • ⁠list(n = <int>, days = <num>)⁠ (keep most recent n and/or those newer than days; union of the two conditions)

dry_run

logical; if TRUE, only report what would be pruned.

alias

Optional stamp alias to target a specific stamp folder.

Details

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.

Value

Invisibly, a data.frame of pruned (or would-prune) versions with columns: artifact_path, version_id, created_at, size_bytes.

Examples

# 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 sidecar metadata (internal)

Description

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.

Usage

st_read_sidecar(rel_path, alias = NULL)

Arguments

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 NULL and an absolute path is provided, the alias will be auto-detected from the path.

Value

A list (parsed JSON / qs object) or NULL if not found.


Rebuild artifacts from a plan (level order)

Description

Rebuild artifacts from a plan (level order)

Usage

st_rebuild(plan, rebuild_fun = NULL, dry_run = FALSE)

Arguments

plan

A data.frame from st_plan_rebuild(...) with columns: level, path, reason, latest_version_before.

rebuild_fun

Optional function called as: rebuild_fun(path, parents) -> list(x=..., format=?, metadata=?, code=?, code_label=?). If omitted (NULL), st_rebuild() will look up a registered builder for path (by st_register_builder()).

dry_run

If TRUE, do not write anything; just report what would happen.

Value

Invisibly, a data.frame with the build results (status, version_id, msg).


Register a builder for an artifact path

Description

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)
  )

Usage

st_register_builder(path, fun, name = NULL)

Arguments

path

Character path this builder produces (exact match).

fun

Function with signature function(path, parents).

name

Optional label so you can register multiple builders per path.

Value

Invisibly TRUE.


Register or override a format handler

Description

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.

Usage

st_register_format(name, read, write, extensions = NULL)

Arguments

name

Character scalar: format name (e.g. "qs2", "rds").

read

Function ⁠function(path, ...)⁠ returning an R object.

write

Function ⁠function(object, path, ...)⁠ that writes object to path.

extensions

Optional character vector of file extensions (e.g. c("qs","qs2")) to map to this format; case-insensitive; without dots.

Value

Invisibly returns TRUE on success.

Examples

st_register_format(
  "txt",
  read  = function(p, ...) readLines(p, ...),
  write = function(x, p, ...) writeLines(x, p, ...),
  extensions = "txt"
)

Restore artifact to a previous version

Description

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.

Usage

st_restore(file, version = "oldest", verbose = TRUE, alias = NULL, ...)

Arguments

file

Character path to the artifact to restore. Can be:

  • Bare filename (e.g., "data.qs2") - stored in /data.qs2/

  • Relative path with subdirs (e.g., "results/model.rds") - stored in /results/model.rds/

  • Absolute path under project root - converted to relative for versioning

version

Version identifier to restore to. Can be:

  • A specific version_id string

  • "latest" - most recent version

  • "oldest" - first saved version

  • Integer offset from latest (1 = previous, 2 = two versions back, etc.)

verbose

Logical; if TRUE, prints informative messages.

alias

Optional stamp alias to target a specific stamp folder.

...

Additional arguments passed to format reader/writer.

Details

The function:

  1. Loads the specified version from version history

  2. Overwrites the current artifact file with that version

  3. 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.

Value

Invisibly returns the restored object.

See Also

st_load_version, st_versions, st_save

Examples

## 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)

Description

Save an R object to disk with metadata & versioning (atomic move)

Usage

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,
  ...
)

Arguments

x

object to save

file

destination path (character or st_path). Can be:

  • A bare filename (e.g., "data.qs2") → saved to ⁠<alias_root>/data.qs2/data.qs2⁠

  • A path with directory (e.g., "results/model.rds") → saved to ⁠<alias_root>/results/model.rds/model.rds⁠ When using a path with directory and an explicit alias, the alias root must be a parent of the path, otherwise an error is raised.

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 code_hash.

parents

Optional list of parent descriptors: list(list(path = "", version_id = ""), ...).

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 FALSE, suppress informational messages and package-generated warnings (default TRUE). When FALSE, messages about skipped saves or save failures emitted by st_save() will not be shown.

alias

Optional stamp alias to target a specific stamp folder. If NULL (default), uses the default alias. If the default alias does not exist, an error is raised. Use aliases to operate across multiple stamp folders.

...

forwarded to format writer

Value

invisibly, a list with path, metadata, and version_id (or skipped=TRUE)


Save a single partition (uses st_save under the hood)

Description

Save a single partition (uses st_save under the hood)

Usage

st_save_part(
  x,
  base,
  key,
  code = NULL,
  parents = NULL,
  code_label = NULL,
  format = NULL,
  ...
)

Arguments

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()

Value

invisibly, list(path=..., version_id=...)


Decide if a save should proceed given current st_opts() Uses versioning policy and code-change rule.

Description

Decide if a save should proceed given current st_opts() Uses versioning policy and code-change rule.

Usage

st_should_save(path, x = NULL, code = NULL, alias = NULL)

Arguments

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.

Value

list(save = , reason = , latest_version_id = )


Switch the session's default alias

Description

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.

Usage

st_switch(alias)

Arguments

alias

Character alias to make the session default.

Value

Invisibly returns the alias.


List versions for an artifact path

Description

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.

Usage

st_versions(path, alias = NULL)

Arguments

path

file or directory path

alias

Optional stamp alias to target a specific stamp folder.

Value

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 (in-memory)

Description

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.

Usage

st_with_pk(x, keys)

Arguments

x

Data.frame to annotate.

keys

Character vector of column names making the primary key.

Value

The input data.frame with attribute stamp_pk set.


Auto-partition and save a dataset (Hive-style)

Description

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.

Usage

st_write_parts(
  x,
  base,
  partitioning,
  code = NULL,
  parents = NULL,
  code_label = NULL,
  format = NULL,
  pk = NULL,
  domain = NULL,
  unique = TRUE,
  .progress = NULL,
  ...
)

Arguments

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)

Value

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

Performance

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.

Examples

## 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)