An input-invalidated make pipeline for R
README.md

cibles #

cibles is a targets-like pipeline tool for R, redesigned from scratch. You declare steps as named expressions, run() computes what is missing, read() gives you results back. Every result is keyed by its inputs only, never by the step's name, so renaming, reorganising or duplicating steps across pipelines never triggers a recomputation.

How it differs from targets:

  • Inputs-only content addressing. A step is cached under the hash of its expression and of the values of its inputs. Two pipelines (or two steps of one pipeline) that compute the same thing share one stored object and one computation; one store serves many pipelines.
  • Pipelines are values. p <- pipeline(...), then run(p), read(x, from = p), and vary(p, ...) to derive a new pipeline from an existing one.
  • Implicit branching with named branches. lambda = branch(c(0.1, 1)) branches every step downstream automatically; each branch has an id and is displayed as fit[lambda = 0.1]. gather() and reduce() gather them.
  • Parallelized steps. step(f(df), parallelize_by = "region") caches each region on its own: a change in a few regions only recomputes those. Grouped tibbles and keyed data.tables are stored group by group.
  • Element access without a step. coefs = summarise(model$coef): named lists are stored element by element, so coefs only depends on model$coef.
  • Pins and accumulators. Pins protect current values; accumulate() folds distinct contributions across runs and pipelines.
  • keep garbage collection. Each step carries a retention weight; prune() evicts the least valuable objects first.
  • Interactive view(). A standalone HTML page of the graph.
  • No _targets.R file, no tar_* prefix. Pipelines live in ordinary R code; the API is a handful of short verbs.

Install #

From a local checkout:

pak::pak("local::.")
# or
devtools::install()

Benchmark #

For a reproducible engine benchmark and an optional comparison with targets, see the benchmark report. Run Rscript bench/scenarios.R --quick from the repository root to produce its CSV. The report includes a dated three-repetition baseline for both engines.

Quick start #

library(cibles)

clean <- function(df) df[!is.na(df$x), ]
fit   <- function(df) lm(y ~ x, data = df)

p <- pipeline(
  raw   = data.frame(x = c(1, 2, NA, 4, 5), y = c(2.1, 3.9, 6, 8.2, 9.8)),
  data  = clean(raw),
  model = fit(data),
  coefs = coef(model)
)
p
#> <cibles_pipeline> 4 steps, store: <default>
#>   * raw   = data.frame(x = c(1, 2, NA, 4, 5), y = c(2.1, 3.9, 6, 8.2, 9…
#>   * data  = clean(raw)
#>   * model = fit(data)
#>   * coefs = coef(model)

run(p)                     # computes the four steps, stores them in _cibles/
read(coefs, from = p)
#> (Intercept)           x
#>        0.09        1.97
run(p)                     # nothing to do

The key promise: a step is identified by what it computes, not by what it is called. Rename every step and the second pipeline is already up to date:

p2 <- pipeline(
  input   = data.frame(x = c(1, 2, NA, 4, 5), y = c(2.1, 3.9, 6, 8.2, 9.8)),
  cleaned = clean(input),
  lm_fit  = fit(cleaned),
  betas   = coef(lm_fit)
)
status(p2)$status
#> [1] "uptodate" "uptodate" "uptodate" "uptodate"

Other verbs: make(model, with = p) runs only what model needs; status(p) is a data frame with one row per step; read() never runs anything and errors if the step is pending. fingerprint(c(model, betas), from = p) is a hash of the values read() would return, computed from the store index without loading them: it changes only when one of these values changes, e.g. to decide whether to render a report that reads them again. read(lst$key, from = p) reads one element of a list, loading only that element when the list is stored element by element; locate() and fingerprint() accept the same lst$key.

Bare names in make(), read(), fingerprint(), pin(), freeze() and unfreeze() are literal step names. To supply a name held in a variable, inject it with !!: nm <- "model"; make(!!nm, with = p).

For a branch-level diagnosis, use explain(p). It reports why each known instance is pending or available and how many instances need work. It also works before the first run, without creating a store. If an axis still needs to run before its branches can be expanded, the final count is NA. compare(p, p2) aligns matching branches and reports changed recipe keys, definitions, and inputs. explain(p2, against = p) adds those input changes to the diagnosis. Unknown downstream values remain marked as unknown until the upstream steps run. When the store exists, explain() also shows each stored recipe's date, duration, value size, and format. If an earlier run was recorded with run(p, record = "baseline"), use explain(p2, against = run_ref("baseline")) to compare its saved input hashes even when the original pipeline object is gone. The store's recipe index alone does not associate old input hashes with step names, so an unrecorded earlier pipeline cannot be reconstructed from it.

Branching #

branch() declares an axis. Every step that depends on it, directly or not, is branched too, without any annotation. gather() gathers the branches into a named list, reduce() folds them.

p <- pipeline(
  lambda = branch(c(0.1, 1, 10)),
  x      = 1:5,
  b      = x * lambda,          # branched: b[lambda = 0.1], b[lambda = 1], ...
  all_b  = gather(b),          # a named list of three vectors
  total  = reduce(b, `+`, 0)    # folded over the branches
)
run(p)
read(b, from = p, branch = c(lambda = "1"))
#> [1] 1 2 3 4 5
make(b, with = p, branch = c(lambda = "1")) # compute just this branch when possible
names(read(all_b, from = p))
#> [1] "0.1" "1"   "10"

Branch ids come from branch(..., id = ), else from the names of the values, else from the values themselves ("0.1", "1", "10"), else from 1..n. They label branches everywhere: in read(), in status(), and in error messages (Step b[lambda = 10] failed). With strict = FALSE, read() and fingerprint() ignore the coordinates on axes a step does not carry, so that one branch = c(scenario = "central", lambda = "1") serves steps upstream of lambda as well as branched ones.

Two different axes cross (x = a + f has branches x[a = 1, f = u], ...); an axis reached through two paths is zipped; gather(x, over = "a") consumes only a. Axes can be sized at run time (branch(seq_len(n))). only(x, .id == "estimation", over = "mode") keeps the mode axis; take(x, mode = "estimation") selects that branch and removes mode, while preserving any other axes. This lets one fitted model be shared across modes.

Pipelines can be defined separately and composed later. Dependencies are rescanned across the combined steps, so calculations below is not runnable alone but the composed pipeline is:

sources <- pipeline(a = 3)
calculations <- pipeline(b = a + 1)
p <- compose(sources, calculations)
run(p)

Each step keeps the environment in which it was defined. Pipelines created in different functions can therefore be composed without moving their helpers into one common environment. New or replaced steps in vary() use the environment of its call; compose(..., env = e) explicitly rebinds all steps to e.

vary() returns a new pipeline with replaced or added steps. An ordinary expression gives one value; branch() explicitly creates an axis:

p1 <- pipeline(lambda = 1, x = 1:5, b = x * lambda)
run(p1)
p2 <- vary(p1, lambda = branch(c(1, 2, 3)), all = gather(b))
run(p2)                        # computes b for lambda = 2 and 3 only
vary(p1, lambda = c(1, 2, 3)) # lambda becomes one vector value
vary(p1, b = x / lambda)       # replaces a computation

Filtering branches #

only(x, cond) keeps the branches of x for which cond is TRUE; the axes are preserved, so everything downstream (joins, gather(over = )) keeps working, and nothing is stored: a kept branch is the branch of x. Inside cond, .id holds the branch ids, .u a deterministic uniform number per id, .value the values (loaded only if mentioned); another branched step arrives as a list. thin(x, rate) is only(x, .u < rate).

p <- pipeline(
  shard   = branch(seq_len(1000)),
  rate    = branch(c(0.01, 0.1, 1)),
  sample  = thin(shard, rate),           # the sample for each rate
  fit     = fit_one(sample),             # once per shard in the union
  summary = reduce(fit, combine, over = "shard")
)

Sampling depends on the ids only, so the 1 % sample is a subset of the 10 % sample, which is a subset of the full data: fit_one runs once per shard of the largest sample, and the three summaries share the work through content addressing. Widen the rate later with vary() and only the new shards are fitted.

Parallelized steps #

parallelize_by caches a table computation sub-population by sub-population, for computations that work row by row or group by group:

p <- pipeline(
  raw   = read_survey(),
  clean = step(recode(raw), parallelize_by = "region"),
  score = step(model_score(clean, params), parallelize_by = "region"),
  report = summarise_scores(score)   # sees one data frame
)

When raw changes for two regions, recode() and model_score() run for those two regions only. clean and score are still tables (the parts bound back in key order); score reads the parts of clean directly, without binding or splitting again. Behind the scenes parallelize_by is branch(partitions(raw, by = "region")), the computation per part, and gather(..., bind = TRUE), which binds branches into one table stored as a manifest of the parts (no copy). The computation must not use statistics over all rows (mean(x) inside transform(), scale(), lags across groups): parallelize_by would silently change its result.

Grouped tables are partitioned automatically: a grouped tibble (dplyr), a keyed data.table or a grouped lazy table is stored group by group, and read back exactly as it was (class, groups or key, row order). A change in some groups only writes those groups, and a parallelize_by step on the same key takes the parts as they are, without loading or splitting the table:

p <- pipeline(
  raw = read_survey(),
  dt  = raw |> group_by(sexe) |> mutate(m = mean(income), adjusted = income - m),
  dt2 = step(post_treatment(dt), parallelize_by = sexe)
)

When raw changes for women only, dt is recomputed (it is one grouped computation), its part for men is unchanged, and post_treatment() only runs for women. storage(partition = c("region", "year")) partitions any table that way, storage(partition = FALSE) stores a grouped table whole.

Parallel execution #

The pending branches of a step are independent: executor_mirai() computes them in parallel on mirai daemons, while steps still run one after the other.

mirai::daemons(4)
run(p, executor = executor_mirai())
options(cibles.executor = executor_mirai())   # default for run() and make()

Before each step, the daemons are set up to compute what the session would: the user functions and global objects the step uses, S3 methods defined in the global environment, the attached packages (packages loaded with pkgload::load_all() are loaded the same way), the options and the working directory. The input values are sent with the tasks, in chunks for small branches (chunk_size); the session keeps writing the store. Steps whose inputs are lazy tables run in the session. Warnings raised on workers are re-raised in the session, labeled with the branch.

Instances of a step that share a recipe key are computed once.

Random numbers #

Every instance runs under a seed derived from its recipe key (expression and input values), with R's default generators. A random step gives the same values on every run, with any executor and any number of workers; branches with different inputs draw different numbers; set.seed() in the session has no effect on steps and the session's random stream is left untouched. The seed has the 128 bits of the recipe key (set.seed() alone takes 32 bits, which would make two branches out of about 1e5 draw identical numbers).

Rerunning an instance (invalidation = "always", a time-out) draws the same numbers. For new draws, change the key: invalidation(salt = "draw 2"), or pipeline(..., .invalidation = invalidation(salt = "draw 2")) for every step. set_seed(x, from = p, branch = c(i = "2")) sets the session's random state to the one of an instance, to rerun its code by hand.

Lazy tables (parquet) #

A step that returns a lazy table (a dbplyr query, e.g. on duckdb, or an arrow query or dataset) is streamed to a parquet file in the store, without being materialised in R. Consumers receive a lazy table over that file (a duckdb table; an arrow dataset with options(cibles.lazy_engine = "arrow")) and call dplyr::collect() when they need the rows:

library(dplyr)
p <- pipeline(
  events = track("data/events/", format = "parquet"),   # a lazy table over the files
  clean  = events |> filter(!is.na(x)) |> mutate(y = 2 * x),
  agg    = clean |> group_by(g) |> summarise(m = mean(y)) |> collect(),
  byg    = step(clean |> mutate(z = y - mean(y)), parallelize_by = "g")
)
read(clean, from = p)                      # a lazy table
read(clean, from = p, materialize = TRUE)  # a data frame

The value is the file: its hash is derived from the bytes of the parquet file, so a query that produces the same file cuts off downstream work. storage = "parquet" stores a data frame the same way. track(path, format = "parquet") reads an external file, or every file of a (hive-partitioned) directory. partitions() and parallelize_by work on lazy tables: each part is a parquet file, and the bound result is one lazy table over the files. Byte hashes depend on the writer: the same rows written by another engine or version give another hash.

A sink publishes a parquet value at a stable location, for other tools or pipelines: step(q, storage = storage(path = "lake/clean.parquet")). A partitioned value (a grouped table, or partition = "year") is published as a hive-partitioned directory. The value stays in the store and is keyed as usual; the location receives the same bytes (a hard link when possible) and is only rewritten when the value changes. Another pipeline reading it with track("lake/clean.parquet", format = "parquet") and sharing the store finds its downstream results up to date. The duckdb, DBI, dbplyr and dplyr packages (arrow for the arrow engine) are needed only when lazy tables are used.

A sink needs an unbranched step. To read the value of any instance with another tool, locate(clean, from = p, branch = c(scenario = "central")) gives the paths of its files in the store (copied first from an upstream store): read-only, and valid until the value is pruned.

Lists and element access #

Steps that return an unclassed named list are stored element by element (a manifest plus one object per element). Downstream steps can use one element with $ or [["..."]], and then depend on that element only:

fit <- function(df) {
  m <- lm(y ~ x, data = df)
  list(coef = coef(m), resid = resid(m))
}
p <- pipeline(
  data  = data.frame(x = 1:4, y = c(2.1, 3.9, 6.2, 7.8)),
  model = fit(data),
  slope = model$coef[["x"]],   # depends on model$coef only
  rmse  = sqrt(mean(model$resid^2))
)

If a change in data leaves model$coef identical, slope is not recomputed. storage(split = FALSE) opts out for a given step.

Options #

Options are grouped by concern. A shorthand string covers the common cases; a constructor gives the details:

step(f(a), invalidation = "always")                       # rerun every time
step(f(a), invalidation = invalidation(time_out = "1 day", packages = TRUE))
step(big(a), storage = "compact")                         # qs2, compressed
step(big(a), storage = storage(format = "rds", split = FALSE))
  • invalidation: "auto" (keyed by inputs, the default), "always" (a clock or the environment: step(Sys.Date(), invalidation = "always"); downstream steps rerun only if the value actually changed; random draws are seeded, see below), "never" (reuse the pinned value whatever the inputs), or invalidation(time_out =, packages =, files =, salt =, steps =, globals =, imports =). pipeline(..., .invalidation = invalidation(imports = "monpkg")) shares an invalidation between all steps; it is combined with each step's own invalidation, whose explicit arguments win (a step with invalidation(time_out = "1 day") keeps the imports).
  • storage: "auto", "rds", "qs2", "compact", or storage(format =, split =, inline =); format may be a custom list(read =, write =, ext =).
  • keep: retention weight for garbage collection. 0 means evict first, Inf never, the default 1 in between (see ?prune).
  • pin: TRUE or a pin id (below).

External files and directories are declared with track(): src = track("data/raw.csv"), then raw = read.csv(src). The path is passed to consumers for reading. By default, dependent recipes are keyed by content, independently of location. Use invalidation(files = "content_path") if a computation observes the path. Directory content includes relative names and file bytes.

Pins and incremental experiments #

A pin protects a current value across runs. accumulate() instead records distinct branch contributions across runs and folds them into a persistent value named after its pipeline step.

fit <- function(x, lambda) list(beta = sum(x) / lambda, date = Sys.Date())

p <- pipeline(
  x       = 1:5,
  lambda  = branch(1),
  model   = fit(x, lambda),
  beta_   = model$beta,
  date_   = model$date,
  summary = accumulate(data.frame(beta = beta_, date = date_), rbind)
)
run(p)
read("summary", from = "_cibles")   # one row

run(vary(p, lambda = branch(1:10))) # fits lambda = 2..10, appends 9 rows
run(p)                               # nothing new: still 10 rows, no double count
pins("_cibles")

reduce(<expression>, f), accumulate(<expression>, f) and gather(<expression>) accept an expression rather than a step name: it becomes an implicit step named .summary.

By default, a contribution is distinct when its source, branch coordinates or value changes (unique = "by_version"). Use "by_id" to reject a changed value at an existing branch id, or "by_value" to count equal values once even when they come from different branches. Changing the reducer, init or unique on an existing accumulator is refused explicitly. Use stable branch() ids or named branch values with "by_id"; otherwise an atomic branch's default id changes with its value.

Older step(reduce(...), pin = TRUE) accumulator records remain readable, but cannot be extended without a signature. Give the new accumulate() step a new name to keep the old history, or call unpin() to start that name afresh.

An ordinary step, including reduce(), with pin = TRUE is protected from garbage collection and readable by name with read("id", from = store). pin(x, from = p) pins after the fact, unpin("id", store) removes, pins(store) lists.

Freezing an estimate #

freeze() captures the current value of an up-to-date, single-instance value step in a new pipeline. Unlike pin(), it also makes that value the input of downstream steps and cuts dependencies used only to compute it. The original pipeline remains unchanged. For a pipeline defining model_y, model_w, z and data, the workflow is:

run(p)
p_fixed <- freeze(model_y, model_w, with = p)
p_changed <- vary(p_fixed, z = new_z(data))
make(summary, with = p_changed, branch = c(mode = "simulation")) # old models
p_refit <- unfreeze(model_w, with = p_changed)
make(summary, with = p_refit, branch = c(mode = "simulation")) # refits W

The snapshot is protected by an internal pin, but unfreeze() does not delete it: p_changed remains readable. When no pipeline needs the snapshot, call release_freeze(model_y, with = p_fixed) to remove its pin and return an unfrozen pipeline. Other copies using that snapshot then become unreadable. pins("_cibles") marks these pins with kind freeze and reports their referenced value bytes in size (record_size is the pin file size), along with the primary value's vhash, hits and last_access. Sizes can overlap across pins. Compose fragments before freezing. Pruning is branch-specific when using make(..., branch = ...). If branch coordinates are not yet known, make() builds the necessary axes automatically before selecting instances. Value-dependent filters may still need their whole input group. run() continues to request every output branch. exemple-freeze-estimations.R runs a self-contained comparison. exemple-taux-echantillonnage.R varies estimation and simulation sample rates without an explicit loop over pipelines.

Store, prune(), view() #

By default a pipeline uses _cibles/ in the working directory; pass store = "path" or store = store("path") to pipeline() to use another. It holds content-addressed objects, an append-only recipe index and pins.

store_info()                          # bytes by directory (from the index), counts
store_info(measure = "disk")          # every file measured, compared with the index
prune("_cibles", limit = "5 GB")      # target the complete store size
prune("_cibles", dry_run = TRUE)      # estimate what would go
vacuum("_cibles")                     # forget old evicted metadata
view(p)                               # open the graph; Refresh follows a run
view(pRef, pVar)                     # switch between pipelines sharing a store
view(pRef, variantes = pVar)         # optional label for the selector
view(p, file = "pipeline.html", open = FALSE, live = FALSE)

In an interactive R session, view(p) writes a companion status file beside the HTML. The page's Refresh button checks it every second and stops checking 10 seconds after the run finishes. Statuses are published between steps of run() and make(). The HTML remains readable as a snapshot after R exits; use live = FALSE for a single standalone file. With multiple pipelines, the page shows a selector. Each pipeline has its own graph and status; a run using the shared store refreshes all of them.

run() and make() check the complete store size after execution against its size_limit (see store_config()), else getOption("cibles.gc_limit", "10 GB"); make() checks it once, after all its passes, so that a pass never evicts what the next one reads. The values of that run (every value it resolved, computed or up to date) are evicted last, after the leftovers of other branches and older versions; with verbose = TRUE, the run reports what it evicted and warns when the limit forced it to evict its own values. File and inline values can be evicted. An evicted value is recomputed only when something reads it: while the steps that use it are up to date, it costs nothing. The targets of make(), and the leaves of the pipeline for run(), are always recomputed, so that they can be read. Values with keep = Inf, pins and everything they reference remain protected, so the target can be impossible to reach. Metadata for evicted values is forgotten after the metadata_grace of the store (see store_config()), else getOption("cibles.metadata_grace", 30 * 86400) seconds, when the index is vacuumed. Recorded runs retain their hashes and provenance; statistics about forgotten objects may become unavailable.

Shared cache: an upstream store #

Several machines can share a cache, for instance a store on a slow network drive, without writing to it. Each machine works in a fast local store that consults the shared one read-only, without taking its lock:

store("_cibles", upstream = "/mnt/shared/_cibles")  # or options(cibles.upstream = )
run(p)          # a recipe known upstream is up to date: nothing is recomputed
status(p)       # n_upstream: instances whose value is only upstream
read(model, from = p)   # copies that value (and only that one) here

The recipe keys of downstream steps are computed from the upstream value hashes, so a whole chain resolves without loading anything. An upstream object is copied here only when its value is actually loaded: as the input of a step that runs here, by read(), or by only() on .value. A run also keeps the upstream recipes it used (not their objects), so downstream keys still resolve once the upstream is detached. A local recipe always wins over an upstream one. During a run, the upstream index is refreshed before each step (at most every cibles.upstream_refresh seconds, 10), reading only what was appended since: a run sees what other machines publish meanwhile. The recorded runs of the upstream store are visible (see Recorded runs and historical reuse below), and its pins are shared by versions (below).

When a step running here needs an upstream value, copying it is compared with recomputing it: copy = latency + bytes / bandwidth, recompute = the duration measured upstream + the cost of obtaining its inputs (recursively, each the cheaper of the two). A large value produced quickly is thus recomputed rather than copied over a slow drive, and the elements of an axis are extracted from the axis value rather than copied one by one. Latency and bandwidth are measured on the copies already made (small ones for the latency, large ones for the bandwidth); options(cibles.upstream_latency =, cibles.upstream_bandwidth =, cibles.upstream_speed = 1) fix the model, and cibles.upstream_fetch = "always" disables it. A recomputed value must have the upstream hash; a step that gives another value is reported as not deterministic (cibles_warning_nondeterministic) and copied from then on.

Publishing is a separate, explicit step. store_export() writes to the shared store only the delta: the recipes it does not resolve, the values they reach and the recorded runs it does not have. It takes the shared store's lock for the duration of the export only, waiting for it when several machines publish at the same time. store_import() copies the other way, to seed the local store:

store_export("/mnt/shared/_cibles", dry_run = TRUE)  # what would be written
store_export("/mnt/shared/_cibles")                  # from the local store "_cibles"
store_import("/mnt/shared/_cibles")                  # into the local store "_cibles"

Publishing can also happen while a run goes on, so that a CI job restarted on another machine after a crash, or the pipeline of a merge request based on this one, finds what was already computed:

options(cibles.upstream_publish = TRUE)
run(p)   # a background process copies to the shared store as values are computed

The copy runs in a separate R process (package callr) at the lowest CPU and I/O priority; cibles.upstream_publish_bandwidth (bytes per second) also caps it. Recipes go first, with the small values inlined in the index, then the other values, the latest first: a later value spares everything upstream of it. A recipe whose value has not arrived yet is announced: another run counts it as up to date and, if it needs the value itself, recomputes it. The run waits for the publication to finish at its end, even after an error.

A publication that fails (the share gone, its lock held too long) is not an error: the run goes on in the local store, which keeps everything it computes. A run recorded with record is then kept pending there (runs() lists it with location = "pending"), and recorded in the shared store by store_export(), or by the next run whose publication succeeds, with its original record order, creation time and git commit.

bench/network.R compares these strategies on a simulated slow share.

Pins are shared by versions, so that people working on one project find each other's pins. A pin changed here is written to the shared store as its next version once its values are there (by the publication of a run, or at once by pin()); a pin that someone else replaced there is read from there, and you are told once:

read("model")
#> i Pin "model" was replaced by bob (branch main): you get version 3.
#> i To get the value you pinned before, use `read("model@2")`.
pins(history = TRUE)   # every version, who pinned it, from which git branch

Older versions stay protected for pin_history (store_config(), 30 days). Replacing someone else's pin with a value of another shape warns: a name used for two things. A frozen step (step(pin = , invalidation = "never")) adopts the latest version when it has none. unpin() removes a shared pin for everyone.

Recorded runs and historical reuse #

run() can write a lightweight manifest mapping the names and branch coordinates used in that run to their recipe and value hashes. The manifest does not copy or permanently retain the values. Recording a name again adds a revision: the name follows the latest one, name@revision stays fixed:

run(p, record = "baseline")
run(p, record = "baseline")    # after a change: baseline@2
make(fit, with = p, record = "baseline")  # updates fit only: baseline@3
runs("_cibles")

# In CI, order revisions by pipeline number rather than by start time:
run(p, record = "mr-312", record_order = as.numeric(Sys.getenv("CI_PIPELINE_IID")))

historical <- pipeline(
  versions = branch(c(before = "baseline", after = "candidate")),
  old_fit = reuse(fit, run = versions),
  scores = score(old_fit),
  comparison = gather(scores)
)

The historical name is resolved inside each run manifest, so the current step may have a different name. reuse(fit, run = branch(c("baseline", "candidate"))) is equivalent sugar with a private implicit run axis. The historical result must currently be a complete single value; record a selected or gathered result when the original step is branched.

Outside a pipeline, read() and locate() take the values of any step of a revision, branched or not, from the manifest alone: the pipeline that computed them is not needed, and values recorded in the upstream store are copied here:

old <- run_ref("master@3")
read(fit, from = old)
locate(tab, from = old, branch = c(scenario = "central", echantillon = "simulation"))

fingerprint(c(tab1, tab2), from = old) takes the value hashes from the manifest alone, copying nothing: comparing the fingerprints of successive revisions of master tells which ones changed these values. As with a pipeline, an evicted value is an error unless readable = FALSE, which hashes the values known whether they are still in the store or not.

A revision recorded by make() carries over the other steps of the previous one; those whose code or inputs have changed since are stale, and reusing them fails unless reuse(x, run = "baseline", permissive = TRUE), which warns about the revision the value comes from.

A name refers to its revision of highest record_order (the start time of the call by default), so that a pipeline that started earlier but finishes later does not move it back. A store sees the runs of its upstream store and, with publishing enabled, records them there.

Reused values remain ordinary content-addressed inputs: equal historical values share every downstream computation. A warning recommends pin() when a reused object is not protected. Pins can be added afterwards, including for a branched selection, or directly from a manifest:

pin(old_fit, from = historical, id = "comparison-inputs")
pin(fit, from = run_ref("baseline"), id = "baseline-fit")

Run manifests remember hashes and provenance; pins express durable retention. If an unpinned value has already been pruned, reuse() reports it as evicted rather than silently recomputing different code.

Design notes #

Every value has a hash of its serialisation. Every computation has a recipe key: the hash of the step's expression (with dependency symbols replaced by placeholders, so names do not matter), of the hashes of its inputs and of the user functions it calls. The store maps recipe keys to value hashes; running a pipeline is walking the steps in order, looking recipe keys up, and executing only the misses.

The signed-zero hash correction distinguishes -0.0 from +0.0, including inside lists and data frames. Its versioned recipe keys cause existing pipelines to recompute once after upgrading; new zero-containing values also use fresh hashes so older ambiguous objects cannot answer new computations. Existing pins and recorded runs remain references to their original objects.

A data.table hashes without its secondary indices (dt[x == 1] adds one by reference) or its over-allocation, but with its key. This changed the hash of every data.table, so steps downstream of one recompute once after upgrading.

What is hashed: the expression, the input values, user-defined functions found in the pipeline environment (recursively, through the user functions they call), the non-function data captured in their closures, and globals referenced directly or read statically by user functions. Package versions are opt in with invalidation(packages = TRUE). For a package developed alongside the pipeline, invalidation(imports = "monpkg") (the equivalent of targets::tar_option_set(imports = )) hashes its functions by code instead: calls are followed inside its namespace, so editing a function the step reaches reruns it, while editing an unrelated function or bumping the version does not. Dynamic lookups such as get("k") and mutable globals such as environments are diagnosed; declare them with invalidation(globals = "k") or pass them as step inputs. Use invalidation(steps = "name") to add a pipeline step to a recipe key even when the expression does not mention it.

Limits of this version: one writer per store (a lock is taken by the session that opens it; any number of sessions can read it as an upstream store); parallel execution within a step only (executor_mirai(): steps run one after the other, inputs are sent by the session); about 1 GB of memory for an index of 1e6 objects; 1 and 1L hash differently, as do 1:3 and c(1L, 2L, 3L) before materialisation.

Status #

Experimental. The API is not stable and the store format may change.