| Title: | Reproducible Artifact Store with Sidecars and Version History |
| Description: | Stores 'R' objects with sidecar metadata, including hashes, provenance, and primary keys. Keeps an immutable version history and removes older versions according to retention policies. Tracks changes and dependencies so that analytical outputs remain traceable and reproducible across sessions. |
| Version: | 0.1.1 |
| URL: | https://randrescastaneda.github.io/stamp/, https://github.com/randrescastaneda/stamp |
| BugReports: | https://github.com/randrescastaneda/stamp/issues |
| License: | MIT + file LICENSE |
| Encoding: | UTF-8 |
| Depends: | R (≥ 4.1) |
| Imports: | cli (≥ 3.4.1), fs (≥ 1.5.2), rlang (≥ 1.0.6), secretbase, jsonlite, data.table (≥ 1.14.6), utils, nanoparquet, qs2 |
| Suggests: | fst (≥ 0.9.8), testthat (≥ 3.1.5), knitr, rmarkdown, filelock, collapse, withr, pkgload, covr, callr |
| Config/testthat/edition: | 3 |
| VignetteBuilder: | knitr |
| Config/roxygen2/version: | 8.0.0 |
| NeedsCompilation: | no |
| Packaged: | 2026-11-12 16:27:35 UTC; acastanedaa |
| Author: | R.Andres Castaneda
|
| Maintainer: | R.Andres Castaneda <acastanedaa@worldbank.org> |
| Repository: | CRAN |
| Date/Publication: | 2026-12-04 18:00:02 UTC |
stamp: Reproducible Artifact Store with Sidecars and Version History
Description
Stores 'R' objects with sidecar metadata, including hashes, provenance, and primary keys. Keeps an immutable version history and removes older versions according to retention policies. Tracks changes and dependencies so that analytical outputs remain traceable and reproducible across sessions.
Author(s)
Maintainer: R.Andres Castaneda acastanedaa@worldbank.org (ORCID) [copyright holder]
Authors:
R.Andres Castaneda acastanedaa@worldbank.org (ORCID) [copyright holder]
Diana C. Garcia Rojas dgarciarojas@worldbank.org (ORCID) [copyright holder]
See Also
Useful links:
Report bugs at https://github.com/randrescastaneda/stamp/issues
Retrieve alias configuration (internal)
Description
Retrieve alias configuration (internal)
Usage
.st_alias_get(alias)
Register or update an alias configuration (internal)
Description
Register or update an alias configuration (internal)
Usage
.st_alias_register(alias, root, state_dir, stamp_path)
Compute artifact identifier (internal)
Description
Derive an artifact identifier from path using a stable SipHash
of the normalized path. This identifier is used to group versions
belonging to the same logical artifact.
Usage
.st_artifact_id(path)
Arguments
path |
Character path to the artifact. |
Value
Character scalar identifier.
Compute the actual artifact path (internal)
Description
Returns the path where the actual user file will be stored.
Usage
.st_artifact_path(rel_path, alias = NULL)
Arguments
rel_path |
Character relative path from alias root |
alias |
Optional alias |
Details
Structure: <root>/<rel_path>/<filename>
Examples:
rel_path: "data.qs2" → artifact:
<root>/data.qs2/data.qs2rel_path: "dirA/file.qs" → artifact:
<root>/dirA/file.qs/file.qs
Value
Character scalar absolute path to the artifact file
Empty catalog template (internal)
Description
Create an empty catalog structure used when no catalog file exists on
disk. The structure contains artifacts and versions tables and will
use data.table if available, otherwise base data.frame.
Usage
.st_catalog_empty()
Value
A list with elements artifacts and versions (data.frame or data.table).
Catalog file path (internal)
Description
Return the path to the on-disk catalog file under the package state
directory: <root>/<state_dir>/catalog.qs2
Usage
.st_catalog_path(alias = NULL)
Value
Character scalar path to the catalog file.
Read catalog from disk (internal)
Description
Read the persisted catalog from the on-disk catalog file. If the file does not exist, an empty catalog template is returned.
Usage
.st_catalog_read(alias = NULL)
Value
A list with elements artifacts and versions.
Write catalog to disk (internal)
Description
Persist the catalog list to disk using a QS2-backed format. The write is performed atomically by writing to a temporary file in the same directory and then moving it into place.
Usage
.st_catalog_write(cat, alias = NULL)
Arguments
cat |
Catalog list to persist (with |
Value
Invisible path to the catalog file.
List children (reverse lineage) of an artifact (internal helper)
Description
Internal helper that finds immediate children that list path as a parent
in their committed parents.json snapshots. Returned columns: child_path,
child_version, parent_path, parent_version.
Usage
.st_children_once(path, version_id = NULL, alias = NULL)
Arguments
path |
Character path to the parent artifact. |
version_id |
Optional version id to match; if provided, only children listing that exact parent version are returned. |
Value
A data.frame of matching children (may be empty).
Safely delete a version directory (internal)
Description
Safely delete a version directory (internal)
Usage
.st_delete_version_dir_safe(vdir)
Detect which alias a path belongs to (internal)
Description
Detect which alias a path belongs to (internal)
Usage
.st_detect_alias_from_path(path)
Ensure directory exists (idempotent)
Description
Create path if it does not already exist. Intermediate directories
are created as needed.
Usage
.st_dir_create(path)
Arguments
path |
Character scalar path to a directory. |
Value
Invisibly returns NULL.
Extract relative path from an absolute path (internal)
Description
Given an absolute path under alias root, extract the relative path component.
Usage
.st_extract_rel_path(abs_path, alias = NULL)
Arguments
abs_path |
Character absolute path |
alias |
Optional alias |
Details
Structure: <root>/<rel_path>/<filename> or <root>/<rel_path>/stmeta/... or <root>/<rel_path>/versions/...
Value
Character relative path from root, or NULL if path not under root
Compute file storage directory (internal)
Description
Given a relative path from alias root, compute the storage directory where the file, versions, and metadata will be stored.
Usage
.st_file_storage_dir(rel_path, alias = NULL)
Arguments
rel_path |
Character relative path from alias root (includes filename) |
alias |
Optional alias |
Details
Structure: <root>/<rel_path>/
Examples:
rel_path: "data.qs2" → storage:
<root>/data.qs2/rel_path: "dirA/file.qs" → storage:
<root>/dirA/file.qs/
Value
Character scalar absolute path to the file storage directory
Check if object has custom (non-default) row names (internal)
Description
R's default row.names are integer sequences stored efficiently via .set_row_names(). This helper checks if an object has custom row.names (e.g., character names) that differ from the default representation.
Usage
.st_has_custom_rownames(x)
Arguments
x |
A data.frame or similar object |
Value
Logical: TRUE if custom row.names exist, FALSE otherwise
Helper: produce an absolute path safely (internal)
Description
Helper: produce an absolute path safely (internal)
Usage
.st_make_abs(p)
Normalize a path for use as an identifier (internal)
Description
Convert a path to an absolute, canonical character representation suitable for deterministic hashing and use as an identifier.
Usage
.st_norm_path(p)
Arguments
p |
Character path. |
Value
Character scalar absolute path.
Normalize path for platform-aware comparison (internal)
Description
Normalize path for platform-aware comparison (internal)
Usage
.st_normalize_path(path)
Current time as UTC ISO-8601 (Z) string with microsecond precision
Description
Current time as UTC ISO-8601 (Z) string with microsecond precision
Usage
.st_now_utc()
Value
Character scalar like "2025-10-30T15:42:07.123456Z"
Normalize parents structure (internal)
Description
Ensure the parents object has the canonical shape: a list of lists
each containing path and version_id. Accepts data.frames, singleton
lists, or list-of-lists.
Usage
.st_parents_normalize(parents)
Arguments
parents |
Object representing parents (data.frame, list, etc.) |
Value
A list of parent descriptors (each a list with path and version_id).
Parse UTC timestamp strings (internal)
Description
Parse UTC timestamp strings (internal)
Usage
.st_parse_utc_times(chr)
Check if a path belongs to an alias's root (internal)
Description
Check if a path belongs to an alias's root (internal)
Usage
.st_path_matches_alias(path, alias)
Compute version IDs to keep under a retention policy (internal)
Description
Compute version IDs to keep under a retention policy (internal)
Usage
.st_policy_keep_ids(vtab, pol)
Arguments
vtab |
data.frame of versions sorted newest → oldest |
pol |
normalized policy from |
Resolve version specification to a concrete version_id (internal)
Description
Resolve version specification to a concrete version_id (internal)
Usage
.st_resolve_version(path, version = NULL, alias = NULL)
Arguments
path |
artifact path |
version |
NULL (latest), 0 (latest), negative integer (versions back), character (specific version ID), or "select"/"pick"/"choose" to show interactive menu |
Value
character version_id or NA_character_
Resolve a version identifier to a version_id (internal)
Description
Helper function for st_restore() that handles multiple version specification formats. Centralizes identifier resolution logic for clarity and testability.
Usage
.st_resolve_version_identifier(version, versions_df, file)
Arguments
version |
Version to restore. Can be specified as:
|
versions_df |
data.frame from st_versions() with version_id column |
file |
Original file path for error messages |
Value
Character scalar version_id
Note
Offsets count through retained snapshots, newest first. Positive
positions retain their old meaning with a deprecation warning; replace
position p with offset 1 - p. The public restore default is
unchanged. No stored version IDs or snapshots are modified by resolution.
Restore original object attributes after sanitization (internal)
Description
Reverse the transformations applied by st_sanitize_for_hash() to return the object to its original user-facing form. This includes:
Restoring data.table class if it was a data.table originally
Restoring original row.names if they were preserved
Removing internal stamp attributes
Usage
.st_restore_sanitized_object(res)
Arguments
res |
Object to restore (typically just read from disk) |
Value
The restored object with original attributes
Project root directory recorded by st_init() (internal)
Description
Return the absolute project root directory previously recorded by
st_init(). If not set, defaults to the current working directory.
Usage
.st_root_dir(alias = NULL)
Value
Character scalar absolute path to project root.
Sidecar metadata path helper (internal)
Description
Build the path to a sidecar metadata file for a given relative path.
New structure: <data_folder>/<rel_path>/stmeta/<filename>.stmeta.<ext>
Usage
.st_sidecar_path(rel_path, ext = c("json", "qs2"), alias = NULL)
Arguments
rel_path |
Character relative path from alias root (includes filename). |
ext |
Character scalar extension for the sidecar (e.g. "json" or "qs2"). |
alias |
Optional alias |
Value
Character scalar with the computed sidecar path.
Absolute state directory path (internal)
Description
Compute the absolute path to the package state directory. This is
constructed as <root>/<state_dir> where root is from
st_init() and state_dir is an option stored in the package state.
Usage
.st_state_dir_abs(alias = NULL)
Value
Character scalar absolute path to the state directory.
Commit artifact and sidecars into a version snapshot (internal)
Description
Copy the artifact file, any sidecars, and write the parents snapshot into
the version directory for the given version_id.
Usage
.st_version_commit_files(rel_path, version_id, parents = NULL, alias = NULL)
Arguments
rel_path |
Relative path from alias root (includes filename). |
version_id |
Version identifier for the snapshot. |
parents |
Optional list of parent descriptors to write into parents.json. |
alias |
Optional alias. |
Value
Invisibly returns the version directory path.
Version directory for an artifact (internal)
Description
Compute the version directory path for a file.
New structure: <data_folder>/<rel_path>/versions/<version_id>
Usage
.st_version_dir(rel_path, version_id, alias = NULL)
Arguments
rel_path |
Relative path from alias root (includes filename). |
version_id |
Version identifier (character). |
alias |
Optional alias |
Value
Character scalar path to the version directory, or NA if version_id is NA/empty.
Read parents metadata for a version (internal)
Description
Read and return the parents metadata stored in parents.json inside the
given version_dir. If no parents file exists an empty list is returned.
Usage
.st_version_read_parents(version_dir)
Arguments
version_dir |
Path to the version directory. |
Value
List of parent descriptors, or an empty list.
Write parents metadata for a version (internal)
Description
Persist the list of parent descriptors for a version as JSON inside the version directory. The function performs an atomic write to avoid partial files on disk.
Usage
.st_version_write_parents(version_dir, parents)
Arguments
version_dir |
Path to the version directory where parents.json will be written. |
parents |
List of parent descriptors (each a list with |
Value
Invisibly NULL.
Versions root directory (internal, deprecated)
Description
DEPRECATED: This function returns the old centralized versions directory.
In the current architecture, versions are stored per-artifact in
<artifact_folder>/versions/ rather than in a central location.
For compatibility with old vignettes and examples, this still returns
<root>/<state_dir>/versions, but this location is no longer used
for storing new versions.
Usage
.st_versions_root(alias = NULL)
Value
Character scalar path to the (legacy) versions root directory.
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 |
check_unique |
Logical; when |
Value
Invisibly returns the character vector of keys recorded.
Examples
local({
root <- tempfile("stamp-add-pk-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(data.frame(id = 1:3), "table.rds", verbose = FALSE)
st_opts(warn_missing_pk_on_load = FALSE)
st_add_pk("table.rds", "id", check_unique = TRUE)
st_inspect_pk("table.rds")
})
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
A list with root, state_dir and stamp_path, or NULL if the
alias is not registered.
Examples
st_alias_get()
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
Examples
st_alias_list()
List registered builders
Description
List registered builders
Usage
st_builders()
Value
data.frame with columns: path, name
Examples
st_builders()
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. |
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 |
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.
See Also
st_versions() to query all versions for a single artifact.
Examples
local({
root <- tempfile("stamp-catalog-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
st_save(4:6, "values.rds", verbose = FALSE)
st_save(list(total = 15L), "summary.rds", verbose = FALSE)
latest <- st_catalog_query()
latest[, c("path", "version_id", "size_bytes"), with = FALSE]
})
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. Omit this argument
to leave content unchecked. Explicitly supplying |
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 |
Details
Omitted x leaves details$content_changed unchecked (NA); file and code
comparisons still follow their existing options. Explicit x = NULL is a
content comparison against NULL. This distinction also applies to
st_changed_reason() and st_should_save(). To retain the old behavior of
explicitly passing x = NULL to skip content comparison, omit x instead.
For native RDS/QS2 artifacts and a supplied object, original data.table key
changes are reported separately as details$metadata_changed. The content
hash still excludes keys. mode = "any" includes metadata differences;
mode = "content" remains hash-only. Reasons report all detected components
and can include "metadata", even when a different mode selects the flag.
Value
A list: list(changed = <lgl>, reason = <chr>, details = <named list>).
metadata_changed is included when original data.table key state is relevant.
Examples
local({
root <- tempfile("stamp-changed-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
st_changed("values.rds", x = 1:3, mode = "content")
st_changed("values.rds", x = 4:6, mode = "content")
})
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. Omit this argument
to leave content unchecked. Explicitly supplying |
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", "metadata" for an original data.table key change, or a combined reason.
Examples
local({
root <- tempfile("stamp-reason-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
st_changed_reason("values.rds", x = 1:3)
st_changed_reason("values.rds", x = 4:6)
})
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 |
depth |
Integer depth >= 1. Use |
alias |
Optional stamp alias to target a specific stamp folder. |
Value
data.frame with columns:
level, child_path, child_version,
parent_path, parent_version.
Examples
local({
root <- tempfile("stamp-children-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
parent <- st_save(1:3, "input.rds", verbose = FALSE)
st_save(6L, "total.rds", verbose = FALSE,
parents = list(list(path = parent$path,
version_id = parent$version_id)))
st_children("input.rds", version_id = parent$version_id)
})
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. |
Value
Invisibly, TRUE after removing the selected registrations.
Examples
local({
path <- tempfile(fileext = ".rds")
on.exit(st_clear_builders(path), add = TRUE)
st_register_builder(path, function(path, parents) list(x = 1L))
st_clear_builders(path)
st_builders()
})
Inspect durable execution proof without loading artifact data
Description
Validates committed receipt bytes, retained snapshots and pinned metadata.
Byte checksum streaming does not invoke the artifact format reader.
In a valid store, an explicit unknown receipt ID errors; an explicit ID never
falls back to the latest record. This function inspects proof, not a new
requested calculation. Use st_plan_rebuild() for requested currentness.
Usage
st_execution_info(path, receipt_id = NULL, alias = NULL)
Arguments
path |
Artifact logical path. |
receipt_id |
Exact receipt or outcome ID; NULL selects the latest record. |
alias |
Optional stamp alias. |
Value
A list with state, reason, receipt, outcome, version_id,
receipt_id and outcome_id. States are absent (no committed record),
invalid (contradictory proof/current storage), recorded (an outcome or
historical success without a currently usable pin), and success.
receipt contains a decoded success envelope; outcome contains the
selected decoded envelope, including failures/blocks. Unavailable records
are NULL; unavailable IDs and unusable version pins are NA_character_.
An older success remains inspectable by ID, but its version is returned as
usable only when the current materialization also matches its retained pin.
See Also
st_read_sidecar(), st_record_outcome(), st_rebuild()
Examples
local({
root <- tempfile("stamp-info-")
old_opts <- st_opts_get()
on.exit({
suppressMessages(do.call(st_opts, old_opts))
unlink(root, recursive = TRUE)
}, add = TRUE)
st_opts_reset()
alias <- basename(root)
st_init(root, alias = alias, verbose = FALSE)
st_execution_info("result.rds", alias = alias)$state # "absent"
saved <- st_save(1:3, "result.rds", format = "rds",
alias = alias, verbose = FALSE)
st_read_sidecar("result.rds", alias, saved$version_id)$format
# Saving data alone does not certify that a requested builder executed.
st_execution_info("result.rds", alias = alias)$state # still "absent"
})
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;
when strict = FALSE they are skipped with a warning.
Usage
st_filter(df, filters = list(), strict = TRUE)
Arguments
df |
A data.frame to filter. |
filters |
Named list of filtering values, e.g. |
strict |
Logical scalar; when |
Value
A subsetted data.frame (same columns as df).
Examples
df <- data.frame(country = c("PER", "COL", "PER"), year = c(2020, 2020, 2021))
st_filter(df, list(country = "PER", year = 2021))
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 |
Value
Character vector of primary-key column names (may be length 0).
Examples
df <- st_with_pk(data.frame(id = 1:3), "id")
st_get_pk(df)
st_get_pk(list(pk = list(keys = c("country", "year"))))
st_get_pk(data.frame(id = 1:3))
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:
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.
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
x <- data.frame(id = 1:3, value = letters[1:3])
st_hash_obj(x)
identical(st_hash_obj(x), st_hash_obj(x))
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)
Examples
local({
root <- tempfile("stamp-info-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
info <- st_info("values.rds")
info$catalog
info$sidecar$content_hash
})
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 |
verbose |
logical; if |
Value
Invisibly, the absolute path to the state directory.
Examples
local({
root <- tempfile("stamp-init-")
old_alias <- st_alias_get()
on.exit({
if (!is.null(old_alias)) {
st_init(old_alias$root, state_dir = old_alias$state_dir, verbose = FALSE)
}
unlink(root, recursive = TRUE)
}, add = TRUE)
state_dir <- st_init(root, verbose = FALSE)
dir.exists(state_dir)
st_alias_get()
})
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).
Examples
local({
root <- tempfile("stamp-pk-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(data.frame(id = 1:3), "table.rds", pk = "id", verbose = FALSE)
st_inspect_pk("table.rds")
})
Inspect parent staleness or requested artifact currentness
Description
With no request, inspect committed parents.json for the latest snapshot and determine whether any parent advanced. With a complete request, validate durable proof, prerequisites and failure precedence without executing work.
Usage
st_is_stale(path, alias = NULL, request = NULL)
Arguments
path |
Character path to the artifact to inspect. |
alias |
Optional stamp alias to target a specific stamp folder. |
request |
Optional complete calculation request. NULL preserves legacy
parent-only inspection. A verified matching success returns FALSE; eligible
work returns TRUE; blocked proof raises |
Value
Logical scalar. With no request, TRUE if any parent advanced,
otherwise FALSE. Request-aware calls never report blocked work as current.
Examples
local({
root <- tempfile("stamp-stale-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
parent <- st_save(1:3, "input.rds", verbose = FALSE)
st_save(6L, "total.rds", verbose = FALSE,
parents = list(list(path = parent$path,
version_id = parent$version_id)))
st_is_stale("total.rds")
st_save(4:6, "input.rds", verbose = FALSE)
st_is_stale("total.rds")
})
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. |
Value
A character version ID, or NA_character_ if no version is recorded.
Examples
local({
root <- tempfile("stamp-latest-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_latest("values.rds")
st_save(1:3, "values.rds", verbose = FALSE)
st_latest("values.rds")
})
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
A data.frame with columns level, child_path, child_version,
parent_path and parent_version. It is empty if no parents are recorded.
Examples
local({
root <- tempfile("stamp-lineage-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
parent <- st_save(1:3, "input.rds", verbose = FALSE)
st_save(6L, "total.rds", verbose = FALSE,
parents = list(list(path = parent$path,
version_id = parent$version_id)))
st_lineage("total.rds")
})
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. 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 |
Details
Native RDS/QS2 loads restore only an original data.table key recorded in the selected sidecar. The descriptor must have valid columns and agree with the existing row order; invalid metadata aborts rather than sorting the result. An absent legacy descriptor does not imply or create a key. This does not promise key fidelity for projected/combined partitions or arbitrary classes.
The version argument allows you to load specific versions:
-
NULL(default): loads the current live artifact. Zero (
0): loads the latest committed snapshot, which can differ from an edited or uncommitted live file.Negative integer: loads that many retained snapshots before the latest;
-1is previous,-2is two retained versions back, 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
local({
root <- tempfile("stamp-load-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
first <- st_save(1:3, "values.rds", verbose = FALSE)
st_save(4:6, "values.rds", verbose = FALSE)
st_load("values.rds", verbose = FALSE)
st_load("values.rds", version = -1, verbose = FALSE)
st_load("values.rds", version = first$version_id, verbose = FALSE)
})
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 |
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. |
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. When available, snapshot sidecar metadata selects the reader
independently of the current default format. With
st_opts(verify_on_load = TRUE), recorded file and content hashes are
checked and mismatches warn when verbose = TRUE. This does not apply
the live loader's mutable PK/schema/domain annotations. If no readable
metadata identifies a modern snapshot, unavailable or unreadable metadata
permits data recovery using the path extension or default format. This does
not certify execution proof or repair historical metadata; exact pinned
metadata and execution-proof readers still fail closed on damaged proof.
Any readable modern marker requires strict exact snapshot metadata validation.
Live metadata updates from st_add_pk() do not modify previously committed
snapshots.
Native RDS/QS2 snapshots use only their own recorded original data.table key descriptor. No key is inferred from live metadata, PKs or sorted rows. Invalid or row-order-inconsistent descriptors abort without reordering the returned data; legacy snapshots without descriptors retain their previous behavior.
Value
The object produced by the format-specific read handler (typically an R object loaded from disk).
Examples
local({
root <- tempfile("stamp-load-version-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
first <- st_save(1:3, "values.rds", verbose = FALSE)
st_save(4:6, "values.rds", verbose = FALSE)
st_load_version("values.rds", first$version_id, verbose = FALSE)
})
Normalize attributes for consistent hashing
Description
Normalizes the order of object attributes to a canonical form by creating a new object with attributes in the correct order. This is necessary because R does not allow reordering attributes in-place.
Usage
st_normalize_attrs(x)
Arguments
x |
A data.frame, data.table, list, or other object. |
Value
A new object with the same data but attributes in canonical order. The class is preserved.
Problem
Operations like collapse::rowbind() + collapse::funique() can leave
attributes in different orders even when content is identical. Since
serialize() includes attribute order, this causes different byte streams
and thus different hashes for logically identical objects.
Solution
This function reorders attributes to a canonical order:
Priority attributes: names, row.names, class, .internal.selfref
Additional attributes: alphabetically sorted
Implementation Strategy
The function creates a new object with attributes in canonical order. This is a shallow copy - the actual data (columns, elements) is referenced, not copied, making it efficient even for large objects.
For data.table objects:
Warning on the need of sanitation of the object using
st_sanitize_for_hash
For regular data.frames:
Rebuilds from column list with canonical attribute order
Shallow copy (column data is referenced, not copied)
Preserves data.frame class
For lists and other objects:
Uses
unclass()+ attribute replacementShallow copy when possible
Performance
Shallow copy strategy: data is referenced, not duplicated
Fast path: returns unchanged if already in canonical order
Negligible overhead for most use cases (< 1% of hashing time)
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 |
Logical. If |
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,
reference_copy_on_save.
reference_copy_on_save is a scalar logical, defaulting to FALSE. When
TRUE, only st_save() of a supported ordinary root environment with the
native RDS writer uses a single owned copy. Unsupported environment graphs
error before save side effects. Non-environment roots and direct hashing or
change-detection calls keep legacy behavior. See st_save() for the pilot's
deliberately limited value graph and special-parent boundary.
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
Examples
local({
old <- st_opts(.get = TRUE)
on.exit(suppressMessages(do.call(st_opts, old)), add = TRUE)
st_opts(versioning = "content", retain_versions = 3)
st_opts("retain_versions", .get = TRUE)
})
Convenience getter (optional sugar)
Description
Convenience getter (optional sugar)
Usage
st_opts_get(key = NULL)
Arguments
key |
Option name or |
Value
The requested option value, or NULL for an unknown key. With
key = NULL, a named list of all package options.
Examples
st_opts_get("versioning")
names(st_opts_get())
Reset all options to package defaults
Description
Reset all options to package defaults
Usage
st_opts_reset()
Value
invisible(NULL)
Examples
local({
old <- st_opts_get()
on.exit(suppressMessages(do.call(st_opts, old)), add = TRUE)
st_opts(retain_versions = 2)
st_opts_reset()
st_opts_get("retain_versions")
})
Declare a path (with optional format)
Description
Not currently consumed by st_save() or st_load(); kept internal until it
is wired through every path-taking function.
Usage
st_path(path, format = NULL)
Arguments
path |
file or directory path |
format |
optional explicit format ("qs2","rds","csv","fst","json") |
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 |
keys |
Character vector of column names comprising the primary key. |
validate |
Logical; when |
check_unique |
Logical; when |
Value
A list with element keys containing the canonical character vector.
Examples
df <- data.frame(id = 1:3, value = c(10, 20, 30))
st_pk(df, keys = "id", check_unique = TRUE)
st_pk(keys = c("country", "year", "country"))
Plan a rebuild of descendants when parents changed
Description
With requests = NULL, returns the set of stale descendants of
targets. Two legacy modes:
-
"propagate"(default): treat eachtargetas "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).
With explicit requests, uses their current dependency graph and retains every selected run, skip and blocked candidate. The mode does not change this selection. Rebuild re-evaluates every selected candidate after actual upstream outcomes, including candidates that were current in the preview.
Usage
st_plan_rebuild(
targets,
depth = Inf,
include_targets = FALSE,
mode = c("propagate", "strict"),
requests = NULL
)
Arguments
targets |
Character vector of artifact paths. |
depth |
Integer depth >= 1, or Inf. |
include_targets |
Logical; on the legacy route, include a target at level 0 when stale (or assumed to change in propagate mode). With requests, include every target at level 0 and require an explicit normalized recipe for each. |
mode |
"propagate" (default) or "strict". Controls only legacy planning when requests is NULL; explicit requests determine their own currentness. |
requests |
Optional unnamed list of explicit calculation requests. NULL preserves legacy planning. Requests define current graph edges and include recipes for missing outputs. Selected deferred parents are resolved to validated output pins before execution. Planning never writes state. |
Details
Each request is a named list with exactly these required fields:
-
schema: integer1L;path: artifact logical path within its alias. -
root: logical scalar;parents: unnamed list of records containingpathand exactversion_id. Empty parents require root TRUE. In a preview only, NULL pins may name explicit selected recipes that will run. -
required_components: unique character IDs includingcalculation;components: named list with exactly those IDs. Each descriptor contains nonemptyhash,algorithmand caller canonicalizationschemastrings. Algorithms aresiphash13(16 lowercase hex characters) orsha256(64). -
semantic_schemaandsemantic: descriptors as inst_save()and a uniquely named list of their typed values, with no undeclared fields. With no semantic fields, use NULL schema andlist()values. -
format: exact case-sensitive registeredst_formats()identifier.
Optional audit is a named list of scalar source-identity strings. Optional
review is list(outcome_id = <governing failure ID>). Neither enters request
equality. Unknown/duplicated fields are invalid. Paths and parent/component
ordering are canonicalized; semantic types and declared shapes are retained.
Callers must cover all known result-affecting helpers, constants and rules, not just a source label. Stamp validates declared proof; it does not discover hidden closure dependencies. Valid complete requests can recover absent legacy proof, but legacy parent-only inspection is not complete currentness. Contradictory committed modern proof blocks rather than silently recovering. Serial isolated publication is supported, not SMB or multiwriter guarantees.
Value
data.frame with columns: level, path, reason, latest_version_before With requests, adds request (list-column), decision (run, skip, blocked), request_id and receipt_id; includes current skips and blocked candidates.
Examples
local({
root <- tempfile("stamp-plan-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
parent <- st_save(1:3, "input.rds", verbose = FALSE)
st_save(6L, "total.rds", verbose = FALSE,
parents = list(list(path = parent$path,
version_id = parent$version_id)))
st_plan_rebuild("input.rds", mode = "strict")
st_save(4:6, "input.rds", verbose = FALSE)
st_plan_rebuild("input.rds", mode = "strict")
})
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 logical 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. |
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 = 2keeps 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 whosecreated_atis 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 byn+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
each artifact's versions/ folder and updates the catalog accordingly:
removes rows from the
versionstable,adjusts each artifact’s
n_versionsandlatest_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 = TRUEfirst to verify what would be removed.Committed records protect output/parent pins and retained original ancestry. Before applying a path-filtered deletion, the relevant alias-wide proof is validated. Invalid proof or a protected selection causes refusal before any deletion. Automatic save-time retention uses the same protection.
Committed execution records themselves are retained; receipt garbage collection is not provided.
Value
Invisibly, a data.frame of pruned (or would-prune) versions with
columns artifact_id, artifact_path, version_id, created_at, size_bytes,
protected and reason. Protected candidates have reason
"execution_reference"; other candidates have "policy". Some no-op
cases return an empty data.frame without columns.
Examples
local({
root <- tempfile("stamp-prune-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
for (i in 1:3) st_save(i, "value.rds", verbose = FALSE)
preview <- st_prune_versions("value.rds", policy = 1, dry_run = TRUE)
preview$version_id
st_prune_versions("value.rds", policy = 1, dry_run = FALSE)
nrow(st_versions("value.rds"))
st_load("value.rds", verbose = FALSE)
})
Read current or exact historical sidecar metadata
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.
Modern metadata restores declared semantic fields to their original R types
and validates both sidecars when both were required. Legacy JSON-first reads
do not reinterpret arbitrary descriptive lists as semantic/execution proof.
Usage
st_read_sidecar(rel_path, alias = NULL, version_id = 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 |
version_id |
Optional exact version identifier. Reads only that retained snapshot and errors if its artifact or required sidecars are unavailable. There is no fallback to current metadata. NULL keeps the current reader. No artifact format reader is called; metadata parsing is data-free. |
Value
A metadata list, with typed declared semantic fields for modern sidecars. Legacy metadata remains in its original reader representation. A current read with no sidecar returns NULL; explicit unavailable versions or inconsistent modern envelopes error.
Examples
local({
root <- tempfile("stamp-sidecar-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
saved <- st_save(1:3, "values.rds", metadata = list(label = "Example"),
verbose = FALSE)
st_read_sidecar("values.rds")$label
st_read_sidecar("values.rds", version_id = saved$version_id)$content_hash
})
Rebuild planned artifacts in dependency order
Description
Rebuild planned artifacts in dependency order
Usage
st_rebuild(plan, rebuild_fun = NULL, dry_run = FALSE)
Arguments
plan |
A data.frame from |
rebuild_fun |
Optional function called as:
|
dry_run |
If TRUE, invoke no builders and write no outcomes/receipts. Reports a preview, not successful execution evidence. |
Details
On the legacy route, a selected parent that fails or is blocked prevents its
dependents from running or publishing versions. Such dependents report
blocked with msg = "failed_parent" and no usable version ID. Independent
branches can still rebuild.
Request-aware execution revalidates each candidate after actual upstream
results. A changed parent alone can require an actual builder call while
retaining equal output and publishing a new receipt; original snapshot
provenance is not rewritten. A satisfied repeat writes neither a receipt nor
a version. Missing builder configuration is recoverable blocked work, not an
actual unknown execution failure. Invoked builder errors inheriting
stamp_deterministic_failure or stamp_external_failure retain that class;
other actual failures are unknown and block further execution.
Deterministic recovery requires both changed input/component proof and
request$review$outcome_id naming the governing deterministic failure.
Intervening blocked observations do not replace that failure. External
failures permit one attempt on the next analyst-started rebuild with valid
prerequisites; no automatic retry is scheduled. There is no Force interface.
Value
Invisibly, a data.frame with level, path, reason, status, version_id and msg. Request-aware results also include request_id, receipt_id and outcome_id. Their statuses are built, unchanged, skipped, blocked, failed and dry_run. Only validated successful or reused outputs have a usable version_id.
Examples
local({
root <- tempfile("stamp-rebuild-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
parent <- st_save(1:3, "input.rds", verbose = FALSE)
st_save(6L, "total.rds", verbose = FALSE,
parents = list(list(path = parent$path,
version_id = parent$version_id)))
st_save(4:6, "input.rds", verbose = FALSE)
plan <- st_plan_rebuild("input.rds", mode = "strict")
result <- st_rebuild(plan, rebuild_fun = function(path, parents) {
input <- st_load_version(parents[[1]]$path, parents[[1]]$version_id,
verbose = FALSE)
list(x = sum(input), format = "rds")
})
result$status
st_load("total.rds", verbose = FALSE)
})
Record externally classified failed or blocked execution facts
Description
This interface cannot publish success. Failure messages are preserved and never used to guess classification. A blocked observation does not supersede the preceding actual execution for failure/review precedence.
Usage
st_record_outcome(path, outcome, request, failure = NULL, alias = NULL)
Arguments
path |
Artifact logical path. |
outcome |
Either "failed" or "blocked". |
request |
Complete effective request as documented in
|
failure |
Required list with exactly |
alias |
Optional stamp alias. |
Value
Invisibly, the decoded immutable outcome envelope, including its
id, canonical request, classified outcome and failure. Its output
is NULL; recording an outcome cannot manufacture a usable version pin.
See Also
st_execution_info(), st_rebuild()
Examples
local({
root <- tempfile("stamp-outcome-")
on.exit({
unlink(root, recursive = TRUE)
}, add = TRUE)
alias <- basename(root)
st_init(root, alias = alias, verbose = FALSE)
calculate <- function() 1L + 1L
# Caller contract: hash the actual formals/body, not a source-file label.
component <- list(
hash = st_hash_obj(list(formals = formals(calculate),
body = body(calculate))),
algorithm = "siphash13", schema = "r-formals-body-v1"
)
request <- list(
schema = 1L, path = "result.rds", root = TRUE, parents = list(),
required_components = "calculation",
components = list(calculation = component),
semantic_schema = NULL, semantic = list(), format = "rds"
)
fact <- st_record_outcome("result.rds", "failed", request,
failure = list(class = "external", message = "Example input unavailable"),
alias = alias)
st_execution_info("result.rds", fact$id, alias)$outcome$outcome
})
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 |
name |
Optional label so you can register multiple builders per path. |
Value
Invisibly TRUE.
Examples
local({
path <- tempfile(fileext = ".rds")
on.exit(st_clear_builders(path), add = TRUE)
st_register_builder(path, function(path, parents) list(x = 1:3),
name = "sequence")
st_builders()
})
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. |
read |
Function |
write |
Function |
extensions |
Optional character vector of file extensions (e.g. |
Value
Invisibly returns TRUE on success.
Examples
local({
# Register a session-local format under a unique name.
name <- basename(tempfile("stamp-text-"))
st_register_format(
name,
read = function(path, ...) readLines(path, ...),
write = function(x, path, ...) writeLines(x, path, ...),
extensions = name
)
name %in% st_formats()
})
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:
|
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. |
Details
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. A failed save is reported as a restore error rather than a successful restore.
Numeric offsets count through retained history in the order returned by
st_versions(). Zero selects the latest committed snapshot, which may
differ from an edited or uncommitted live file. Positive positions are
deprecated and will be removed in a future release. Replace a positive
position p with 1 - p to select the same snapshot. Deprecation
warnings are not suppressed by verbose = FALSE. The default remains
version = "oldest".
Value
Invisibly returns the restored object.
See Also
st_load_version, st_versions, st_save
Examples
local({
root <- tempfile("stamp-restore-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
st_save(4:6, "values.rds", verbose = FALSE)
restored <- st_restore("values.rds", version = -1, verbose = FALSE)
restored
st_load("values.rds", verbose = FALSE)
})
Sanitize object prior to hashing
Description
For tabular data we want hashing to depend only on the data/frame content,
not on volatile data.table internals (e.g. .internal.selfref) or differing
row name representations. Strategy:
If
xis a data.table: coerce to plain data.frame (drops DT internals).If
xis a data.frame (including coerced DT): enforce deterministic row.names via.set_row_names(NROW(x))and preserve original row.names inst_original_rownamesattribute for later restoration.Record original class in
st_original_formatso a loader can restore it.
Usage
st_sanitize_for_hash(x)
Details
Non-tabular objects are returned unchanged (attribute normalization handles them subsequently).
NOTE: The returned object is a shallow copy; column data is not duplicated.
Save an R object to disk with metadata & versioning (atomic move)
Description
Native RDS/QS2 saves record an original data.table's ordered key columns in
reserved sidecar metadata under attrs$stamp_data_table, not in the content
hash or sanitized payload. Unkeyed inputs stay unkeyed; keys are never inferred
from primary-key annotations, column names or sorted rows. Key-only changes
can create a metadata version even when the content hash is unchanged.
Legacy snapshots without a descriptor cannot recover a lost key.
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,
...,
request = NULL,
semantic_schema = NULL
)
Arguments
x |
Object to save, including |
file |
destination path. Can be:
|
format |
Optional registered format identifier. With a request, NULL uses its exact, case-sensitive identifier; a different explicit format errors. Without a request, legacy extension/default precedence applies. |
metadata |
Named list of extra metadata. Modern saves require unique, nonempty names and reject stamp-owned keys. Declared semantic fields must match the request exactly; other descriptive fields do not affect equality. |
code |
Optional function/expression/character whose hash is stored as |
parents |
Optional list of parent descriptors:
|
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 |
request |
Optional complete execution request. Exact-name-only after
|
semantic_schema |
Optional named semantic field descriptors. Changes to
declared types, shapes or values create a new immutable version even when
data are equal. Descriptive-only edits on unchanged saves are ignored.
Each descriptor has exactly |
Details
The limited pilot st_opts(reference_copy_on_save = TRUE) copies a root
environment once before metadata capture, sanitization, and the existing
save sequence. Its default is FALSE, which keeps legacy behavior. Only the
native RDS writer and ordinary unclassed environment graphs with NULL/atomic
binding values and recursively atomic attributes are supported. Classed/R6
environments, promises, active bindings, lists, closures, S4 objects, and
opaque resources are declined before save side effects. Graphs are bounded
to 10000 inspected values/bindings and 64 levels. Special environments are
declined as roots or binding values; recognized special parents stay shared,
uninspected serialization boundaries. List-valued attributes are unsupported.
Unrecognized environments with namespace/package markers are rejected before
copying, without evaluating marker bindings.
Non-environment roots (including lists, data.frames, data.tables, and NULL)
and direct calls to st_hash_obj() or change-detection APIs are unchanged.
This is not a generic reference-object copy or isolation guarantee.
Value
Invisibly, a new-save list with path, metadata and version_id.
An unchanged save returns path, skipped = TRUE, reason and a validated
retained version_id, with no receipt or descriptive metadata rewrite.
Request-aware and
semantic-schema-enabled save failures propagate; the legacy write-error
route may return NULL metadata/version_id rather than a successful save.
Examples
local({
root <- tempfile("stamp-save-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
df <- data.frame(id = 1:3, value = c(10, 20, 30))
saved <- st_save(df, "table.rds", pk = "id", verbose = FALSE)
saved$version_id
st_load("table.rds", verbose = FALSE)
st_save(df, "table.rds", pk = "id", verbose = FALSE)$skipped
})
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,
request = NULL,
semantic_schema = NULL,
metadata = list()
)
Arguments
path |
Artifact path on disk. |
x |
Current in-memory object for content comparison. Omit this argument
to leave content unchecked. Explicitly supplying |
code |
Optional function/expression/character (for code comparison). |
alias |
Optional stamp alias to target a specific stamp folder. |
request |
Optional complete requested proof for the supplied result.
Invalid or incomparable proof raises |
semantic_schema |
Optional named semantic field descriptors. |
metadata |
Named metadata list supplying declared semantic values. |
Value
A list with save and reason. Request-aware results additionally
contain latest_version_id (a validated character pin on skip, otherwise
a character pin or NA_character_) and decision ("run" or "skip").
Blocked requests raise stamp_blocked_request carrying decision = "blocked" and reason, never a successful result/output pin. NULL request
preserves the legacy return shape.
Examples
local({
root <- tempfile("stamp-should-save-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_should_save("values.rds", x = 1:3)
st_save(1:3, "values.rds", verbose = FALSE)
st_should_save("values.rds", x = 1:3)
st_should_save("values.rds", x = 4:6)
})
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.
Examples
local({
root <- tempfile("stamp-switch-")
old_alias <- st_alias_get()
on.exit({
if (!is.null(old_alias)) {
st_init(old_alias$root, state_dir = old_alias$state_dir, verbose = FALSE)
}
unlink(root, recursive = TRUE)
}, add = TRUE)
alias <- basename(root)
st_init(root, alias = alias, verbose = FALSE)
st_switch(alias)
st_alias_get()
})
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.
Examples
local({
root <- tempfile("stamp-versions-")
old_opts <- st_opts_get()
old_alias <- st_alias_get()
on.exit({
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)
}, add = TRUE)
st_opts_reset()
st_init(root, verbose = FALSE)
st_save(1:3, "values.rds", verbose = FALSE)
st_save(4:6, "values.rds", verbose = FALSE)
versions <- st_versions("values.rds")
versions[, c("version_id", "size_bytes", "created_at"), with = FALSE]
})
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.
Examples
df <- st_with_pk(data.frame(id = 1:3, value = letters[1:3]), "id")
st_get_pk(df)
Internal format handlers for stamp
Description
Internal format handlers for stamp
Arguments
x |
R object to save. |
path |
Destination file path. |
... |
Additional arguments passed to the underlying writer/reader. |