Examples

---
title: Document a pipeline from scratch
---

Everything tardoc needs is a `_targets.R` and the R files it sources. This builds
a three-target pipeline in a temporary directory, runs it, and documents it.

```{r}
#| comment: "#>"
proj <- file.path(tempdir(), "demo-pipeline")
dir.create(file.path(proj, "R"), recursive = TRUE, showWarnings = FALSE)

writeLines(c(
  "#' Read the raw readings",
  "#'",
  "#' @param n Number of observations to simulate.",
  "#' @return A data frame of readings.",
  "read_readings <- function(n = 200) {",
  "  set.seed(1)",
  "  data.frame(station = rep(c('A', 'B'), length.out = n),",
  "             temp_c   = round(rnorm(n, 12, 30), 1))",
  "}",
  "",
  "#' Drop impossible readings",
  "#'",
  "#' @param readings Raw readings.",
  "#' @param min_c,max_c Rated range of the probe, in Celsius.",
  "#' @return The readings inside the probe's range.",
  "clean_readings <- function(readings, min_c = -40, max_c = 85) {",
  "  # Out-of-range values mean a probe was being serviced, not that the",
  "  # station was that cold. Dropping is deliberate: imputing would invent",
  "  # readings, and the counts downstream are reported as observed.",
  "  readings[readings$temp_c >= min_c & readings$temp_c <= max_c, ]",
  "}"
), file.path(proj, "R", "functions.R"))

writeLines(c(
  "library(targets)",
  "tar_source('R')",
  "",
  "list(",
  "  tar_target(raw, read_readings(400),",
  "             description = 'Simulated logger export'),",
  "  tar_target(clean, clean_readings(raw),",
  "             description = 'Readings inside the probe range'),",
  "  tar_target(by_station, aggregate(temp_c ~ station, clean, mean))",
  ")"
), file.path(proj, "_targets.R"))
```

Run it. `callr_function = NULL` reads `_targets.R` in this session rather than a
subprocess, which is what makes this work in a browser as well as on a desktop.

```{r}
#| comment: "#>"
withr::with_dir(proj, targets::tar_make(callr_function = NULL))
```

Now document it. One call writes the markdown, the viewer and the WASM analytics
page.

```{r}
#| comment: "#>"
tardoc::document_targets(project_path = proj, pkg_name = "Demo pipeline")

list.files(file.path(proj, "tardoc"), recursive = TRUE)
```

Each target gets a markdown page carrying its status, command, timings and the
functions it calls — this is what the viewer renders:

```{r}
#| comment: ""
cat(readLines(file.path(proj, "tardoc", "targets", "clean.md")), sep = "\n")
```

And each function gets one, with its roxygen rendered and its source kept
verbatim — comments included, because the source is read from the file rather
than reconstructed from the parsed function:

```{r}
#| comment: ""
cat(readLines(file.path(proj, "tardoc", "functions", "clean_readings.md")),
    sep = "\n")
```
---
title: Where a run spends its time
---

A pipeline's wall-clock floor is not its total runtime — it is the longest chain
of dependencies, because nothing on that chain can be run in parallel with the
rest of it. `pipeline_profile()` reports both, and `critical_path()` is the walk
underneath.

Two chains, one deliberately slow:

```{r}
#| comment: "#>"
proj <- file.path(tempdir(), "profile-demo")
dir.create(proj, recursive = TRUE, showWarnings = FALSE)

writeLines(c(
  "library(targets)",
  "",
  "list(",
  "  tar_target(seed,   { Sys.sleep(0.2); 1 }),",
  "  tar_target(slow_a, { Sys.sleep(0.6); seed + 1 }),",
  "  tar_target(slow_b, { Sys.sleep(0.6); slow_a + 1 }),",
  "  tar_target(slow_c, { Sys.sleep(0.6); slow_b + 1 }),",
  "  tar_target(quick,  { Sys.sleep(0.1); seed * 10 }),",
  "  tar_target(report, paste(slow_c, quick))",
  ")"
), file.path(proj, "_targets.R"))

withr::with_dir(proj, targets::tar_make(callr_function = NULL))
```

Read the pipeline, then profile it. `check_outdated = FALSE` skips the re-hashing
pass; freshness is not what this example is about.

```{r}
#| comment: "#>"
cfg <- tardoc::build_site_config(proj)
tardoc::setup_site_dirs(cfg)
td <- tardoc::load_targets_data(cfg, check_outdated = FALSE)

prof <- tardoc::pipeline_profile(td)

prof$slowest
```

```{r}
#| comment: "#>"
prof$critical_path

c(total_seconds    = round(prof$total_seconds, 2),
  critical_seconds = round(prof$critical_seconds, 2))
```

The critical path is `seed → slow_a → slow_b → slow_c → report`. Its total is the
floor on a full rebuild however many workers you give `tar_make()`: `quick` can
run alongside the slow chain, so its time is free, and shortening it would save
nothing. That is the number worth optimising, and the viewer draws it on the
graph.

`critical_path()` works on any `{name, seconds}` frame and edge list, so you can
run it against your own weights — estimated cost, memory, anything:

```{r}
#| comment: "#>"
nodes <- data.frame(name = c("a", "b", "c", "d"), seconds = c(1, 10, 1, 1))
edges <- data.frame(from = c("a", "a", "b", "c"), to = c("b", "c", "d", "d"))
tardoc::critical_path(nodes, edges)
```
---
title: Finding a pipeline's natural groups
---

Past a couple of hundred targets a flat graph is one unreadable line. The useful
clusters are usually already there — in how the author split their files, or how
they named things — so tardoc looks for them rather than asking you to configure
them.

A 20-target pipeline with four stages in its names, each stage feeding the next:

```{r}
#| comment: "#>"
proj <- file.path(tempdir(), "grouping-demo")
dir.create(proj, recursive = TRUE, showWarnings = FALSE)

nms <- c(paste0("ingest_", c("csv", "api", "excel", "fix", "join")),
         paste0("clean_",  c("names", "types", "ranges", "dupes", "units")),
         paste0("model_",  c("fit", "tune", "cv", "select", "explain")),
         paste0("report_", c("tables", "figures", "render", "publish", "archive")))

# Each target depends on the one before it, so the pipeline is a single chain:
# depth bands are available as a grouping signal as well as the name prefixes.
calls <- c(sprintf("  tar_target(%s, 1)", nms[1]),
           sprintf("  tar_target(%s, %s + 1)", nms[-1], nms[-length(nms)]))

writeLines(c("library(targets)", "", "list(",
             paste0(calls, c(rep(",", length(calls) - 1), "")), ")"),
           file.path(proj, "_targets.R"))

cfg <- tardoc::build_site_config(proj)
tardoc::setup_site_dirs(cfg)
td <- tardoc::load_targets_data(cfg, check_outdated = FALSE)
```

`target_groups()` tries four signals in descending order of authority —
declaration file, the functions a target calls, name prefix, dependency depth —
and takes the first that clears a quality bar:

```{r}
#| comment: "#>"
g <- tardoc::target_groups(td, cfg)

g$method
table(g$groups)
```

Prefix won, and that is the point of the ordering rather than an accident. Depth
bands score *better* on a chain this shape — six tidy bands against four groups:

```{r}
#| comment: "#>"
c(prefix = tardoc::target_groups(td, cfg, method = "prefix")$score,
  depth  = tardoc::target_groups(td, cfg, method = "depth")$score)
```

Taking the first signal past the bar instead of the highest-scoring one is what
keeps the precedence meaningful: a name prefix is the author's own vocabulary,
and dependency depth is arithmetic.

A grouping has to earn its place. `score_grouping()` rejects the degenerate ones
outright, so a bad grouping is never offered:

```{r}
#| comment: "#>"
c(sensible   = tardoc::score_grouping(rep(c("a", "b", "c"), each = 5)),
  one_group  = tardoc::score_grouping(rep("everything", 20)),
  singletons = tardoc::score_grouping(as.character(1:20)))
```

Below 15 targets `auto` does not group at all — seven targets read perfectly well
as a list — and a named method is honoured even when it falls short of the bar,
because the caller asked for it.