# Content-Addressed Pipelines: Re-run Only the Stages That Changed

> How we key each pipeline stage by code, input and config so a changed setting re-runs only what depends on it, with atomic publishes and tested invalidation.

- URL: https://weaveward.com/blog/content-addressed-pipeline-caching
- Published: 2026-11-12
- Updated: 2026-11-12
- Category: Data & Dashboards
- Tags: data-pipelines, caching, reproducibility
- Author: Weaveward Team

Multi-stage AI pipelines are expensive in a lopsided way. Transcribing an hour of audio, running face detection over every frame or asking a model to read a whole transcript costs minutes and money; changing a subtitle colour should cost seconds. Most pipelines get this wrong one of two ways: they re-run everything on any change, or they cache by filename and timestamp and quietly serve stale results after a settings edit.

Our answer is to make every stage content-addressed. A stage's cache key is a hash of everything that can change its output: its name, its code version, the hash of the source data, the exact slice of configuration it reads, and the keys of the stages it depends on. If the key is unchanged, the output on disk is valid by construction. If it changed, the stage and everything downstream re-runs, and nothing else does.

Below is how we build it, grounded in our AI Video Clipper prototype: computing the fingerprint, publishing so a crash never leaves a half-written entry, finer caches inside stages, testing what re-runs, and the pitfalls that turn a cache into wrong answers.

## What goes into a stage fingerprint

The clipper runs a DAG of 16 stages, from `ingest` and `transcribe` to `framing` and `render`. Each stage class declares a `name`, a hand-maintained `version`, a `scope`, its `deps` and a `config_slice()` method. The pipeline hashes five ingredients into one SHA-256:

- **Stage name**, so two stages with identical config never collide
- **Code version**, bumped by hand when the stage's logic changes its output
- **Source content hash**, the SHA-256 of the video bytes, not its path
- **Config slice**, only the settings this stage actually reads
- **Upstream fingerprints**, so any change propagates down the graph

Outputs live at `<owner>/stages/<stage>/<fingerprint[:16]>/`. A self-contained version over a toy three-stage graph:

```python
import hashlib
import json
from collections.abc import Callable
from dataclasses import dataclass
from typing import Any


def canonical_json(data: Any) -> str:
    # Sorted keys, no whitespace, no default=: an unexpected type fails loudly.
    return json.dumps(data, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


@dataclass(frozen=True)
class Stage:
    name: str
    version: str  # bump by hand when the stage's code changes its output
    deps: tuple[str, ...] = ()
    config_slice: Callable[[dict[str, Any]], Any] = lambda cfg: None


STAGES = {
    "transcribe": Stage("transcribe", "1", (), lambda c: c["asr"]),
    "rank": Stage("rank", "3", ("transcribe",), lambda c: c["scoring"]),
    "render": Stage("render", "2", ("rank",), lambda c: c["render"]),
}


def plan(cfg: dict[str, Any], source_sha256: str) -> dict[str, str]:
    memo: dict[str, str] = {}

    def fp(name: str) -> str:
        if name not in memo:
            stage = STAGES[name]
            payload = {
                "stage": name,
                "version": stage.version,
                "source": source_sha256,
                "config": stage.config_slice(cfg),
                "deps": {d: fp(d) for d in stage.deps},
            }
            memo[name] = hashlib.sha256(canonical_json(payload).encode()).hexdigest()
        return memo[name]

    return {name: fp(name) for name in STAGES}
```

### Config slices and canonical JSON

The slice must contain everything the output depends on and nothing else. Too little gives stale hits; too much and a log-level change re-transcribes an hour of audio.

Two clipper details are worth copying. The `transcribe` slice resolves `auto` settings into the concrete model, device and compute type before hashing, and includes the installed `faster-whisper` version, because a library upgrade can change the transcript. The `render` slice includes renderer and QA version constants alongside its settings.

The serialisation must be canonical. `json.dumps` with `sort_keys=True` and compact separators makes key order irrelevant. Types matter too: `json.dumps` writes `1` and `1.0` differently, so the clipper dumps Pydantic models with `model_dump(mode="json")` first, and a `float` field normalises both to `1.0`. This is close to, but not, RFC 8785 (JCS), which also pins number formatting and sort order across languages. If another language must reproduce your keys, implement JCS; within one Python codebase this is enough.

### Chain fingerprints, not outputs

In the clipper a stage's key depends on upstream fingerprints, not upstream output bytes. Build systems such as Bazel instead hash each action's declared inputs. Both are valid trade-offs.

| Keying strategy | Plan known before running | Upstream re-run with identical output | Tolerates non-deterministic stages |
|---|---|---|---|
| Upstream fingerprints (clipper) | Yes, from config alone | Downstream re-runs anyway | Yes, keys stay stable |
| Upstream output hashes (Bazel style) | No, upstream must run first | Downstream is skipped | No, every re-run looks like a change |

Fingerprint chaining makes the whole plan computable from configuration, so `resume` prints which stages will run before any work starts, and invalidation is testable without media. Output hashing would skip downstream work on identical results, but ASR and LLM stages are not reliably byte-reproducible, so it would rarely fire where the cost is highest.

## Publish atomically: the manifest is the commit

If a stage crashes halfway through writing, the next run must not mistake the fragment for a result. The rule: a stage writes only into a private temporary directory, writes `manifest.json` last, and the directory is renamed into place in one step. "The final directory contains a manifest" is the only definition of a hit.

The clipper's `Pipeline.ensure` creates `.tmp-<fp16>-<random8>` beside the final directory, runs the stage inside a resource monitor, deletes the temporary directory on any exception (including `KeyboardInterrupt`), writes the manifest (fingerprint, config slice, input fingerprints, metrics, CPU, RAM and GPU statistics) and renames. Single JSON files use a helper that writes a temp file in the same directory and swaps it in with `Path.replace`. The sketch below adds an `fsync` on the manifest and handling for a concurrent writer that published the same key first.

```python
import json
import os
import shutil
import uuid
from collections.abc import Callable
from pathlib import Path
from typing import Any


def ensure(final_dir: Path, fingerprint: str, run: Callable[[Path], dict[str, Any]]) -> bool:
    """Return True on a cache hit. The manifest is the commit marker."""
    if (final_dir / "manifest.json").is_file():
        return True
    tmp = final_dir.parent / f".tmp-{final_dir.name}-{uuid.uuid4().hex[:8]}"
    tmp.mkdir(parents=True)
    try:
        metrics = run(tmp)  # the stage writes only inside tmp
        manifest = {"fingerprint": fingerprint, "metrics": metrics}
        with open(tmp / "manifest.json", "w", encoding="utf-8") as fh:
            json.dump(manifest, fh)
            fh.flush()
            os.fsync(fh.fileno())  # manifest last, and durable before the rename
        try:
            os.replace(tmp, final_dir)  # atomic; fails if final_dir already exists
        except OSError:
            if not (final_dir / "manifest.json").is_file():
                raise
            shutil.rmtree(tmp)  # a concurrent writer published the same key first
    except BaseException:
        shutil.rmtree(tmp, ignore_errors=True)
        raise
    return False
```

Python's documentation states that `os.replace` raises `OSError` when the destination is a non-empty directory, and that a successful rename is atomic on POSIX. Because the directory name is the fingerprint, the race loser was producing the same logical result, so discarding its copy is correct, not a lost update. We ran the snippet on Windows: a simulated crash left neither a final nor a temporary directory, the next call ran the stage once and the call after that was a hit, and a simulated race left one entry and no leftovers. Two caveats: the temp directory must be on the same filesystem as the target, and on POSIX, surviving power loss also needs an `fsync` of the parent directory. The clipper's helpers do not `fsync`, which covers process crashes but not power cuts.

When a user forces a stage, the clipper deletes the existing entry and then renames. In that brief window a reader sees no manifest: a miss, never a partial result.

## Finer caches inside stages

Stage keys are coarse: a render stage must re-run when any of its settings change, but that does not mean every encode must. The clipper adds two finer caches.

**LLM answers by prompt hash.** Each reasoning call is keyed by SHA-256 over canonical JSON of the engine version, backend, model, task, system prompt, user prompt and response JSON Schema. Answers live in a SQLite `llm_cache` table, and only validated answers are stored. A hit is validated again against the current Pydantic model and semantic checks; if it fails, the engine makes a fresh call instead. More on that in [structured LLM output with validation and repair](/blog/structured-llm-output-validation-repair).

**Renders by a hash of exactly the inputs that affect pixels and audio.** Each clip and aspect pair is keyed by the renderer version, source hash, colour matrix, clip start, end, words and speaker names, the full render spec including the framing plan, the music file's hash and the fit background, with the output path and QA result fields explicitly excluded. Items live in `render_cache/<hash[:24]>/` and count only when both `item.json` and `clip.mp4` exist; exports are hardlinked from there, with a copy as fallback. If a rank weight changes but the selected clips and framing plans come out the same, every item hash matches and nothing is re-encoded.

One memo sits in front of everything: the clipper stores each video's SHA-256 in a `file_hashes` table keyed by path, size and modification time in nanoseconds, trading a theoretical blind spot (content changed with size and mtime unchanged) for not re-reading gigabytes on every command.

## Share per-source stages across jobs

Fingerprints say whether work is valid; scope says who can reuse it. Each clipper stage is either `source` scoped or `job` scoped:

```text
workspace/
  clipper.db                         sources, jobs, stage_runs, llm_calls, llm_cache, file_hashes
  sources/<source_id>/stages/<stage>/<fp16>/   ingest .. semantic, shared by every job
  jobs/<job_id>/job.json                       config snapshot, source of truth for re-runs
  jobs/<job_id>/stages/<stage>/<fp16>/         candidates .. render
  jobs/<job_id>/render_cache/<item_hash>/      per clip x aspect render and QA
```

Evidence stages (transcription, diarisation, scenes, faces, audio events) and the two context layers are source scoped, so a second job with a different editorial profile on the same video starts at `candidates`. The pipeline enforces the direction: a source-scoped stage that declares a job-scoped dependency raises an error while fingerprints are computed. The semantic map of the whole video is deliberately profile-agnostic for the same reason; anything job-specific in it would fork the key per job.

The architecture notes record one measured run, a 21.4-minute interview on an RTX 2060 and Ryzen 9 4900H machine: a second job on the same video made zero LLM calls, because the global map is per source and the 13 discovery and verification answers came from the response cache. After a change to duplicate detection, `rank` and `edl` re-ran in 0.1 seconds with no LLM calls. One prototype run is not a benchmark, but the shape holds: expensive work is paid once per source.

## The invalidation matrix is a contract; test it

The most useful artefact in the design is a table that says what re-runs for which change. Here is the clipper's, from its architecture document:

| Change | Re-runs |
|---|---|
| Subtitle colours or fonts, title overlay, export quality | `render` only |
| Aspect ratio list | `framing`, `render` |
| Scoring weights or hard-rule thresholds | `rank`, `edl`, `framing`, `render` (no LLM calls) |
| Editorial profile (audience, tone, instructions, topics) | Editorial stages only, never extraction or the global map |
| Human review edits | `edl`, `framing`, `render` |
| Source video bytes | Everything |

A table in a document drifts; a test does not. Because fingerprints need only configuration, the clipper's `tests/core/test_caching.py` plans a fake source, applies one override and asserts which stages changed, for subtitle colour, aspect list, profile, scoring weights and a new source hash, with no media and no models. The same pattern against the toy graph:

```python
import pytest

from fingerprints import plan

BASE = {
    "asr": {"model": "large-v3-turbo", "language": None},
    "scoring": {"weights": {"hook": 0.4, "novelty": 0.6}},
    "render": {"aspects": ["9:16"], "subtitles": {"color": "#FFFFFF"}},
}


def merge(base: dict, patch: dict) -> dict:
    out = dict(base)
    for key, value in patch.items():
        both = isinstance(value, dict) and isinstance(out.get(key), dict)
        out[key] = merge(out[key], value) if both else value
    return out


@pytest.mark.parametrize(
    ("patch", "expected"),
    [
        ({"render": {"subtitles": {"color": "#00FF00"}}}, {"render"}),
        ({"scoring": {"weights": {"hook": 0.5, "novelty": 0.5}}}, {"rank", "render"}),
        ({"asr": {"model": "small"}}, {"transcribe", "rank", "render"}),
        ({"logging": {"level": "debug"}}, set()),  # unrelated keys change nothing
    ],
)
def test_change_reruns_only(patch: dict, expected: set[str]) -> None:
    before = plan(BASE, "a" * 64)
    after = plan(merge(BASE, patch), "a" * 64)
    assert {s for s in before if before[s] != after[s]} == expected


def test_key_order_is_irrelevant() -> None:
    reordered = {k: BASE[k] for k in reversed(BASE)}
    reordered["scoring"] = {"weights": {"novelty": 0.6, "hook": 0.4}}
    assert plan(reordered, "a" * 64) == plan(BASE, "a" * 64)
```

Assert equality, not just inclusion. "Render re-ran" catches a missing slice key; "only render re-ran" also catches an over-broad slice that would silently make every subtitle tweak re-transcribe.

## Resuming after a crash or a quota stop

With atomic publishes and deterministic keys, resume is just a normal run: completed stages are hits and execution starts at the first stage without a manifest. The clipper's `resume` command loads the job's saved config, applies overrides, prints the stages it will run and continues; `status` shows what is cached for the current config.

Quota stops are the interesting case. When the agent CLI behind the reasoning layer reports a usage limit, the engine raises `QuotaExceededError`, the run stops and the CLI says to resume after the limit resets. Answers already received inside the half-finished stage are in the LLM cache, so the re-run replays them for free and only the remaining calls reach the model; the unpublished stage directory needs no cleanup. Every stage execution, hit or miss, is recorded in a `stage_runs` table, which is how reports compute cache hit rates. The backend itself is covered in [our agent CLI batch reasoning article](/blog/agent-cli-batch-reasoning-backend).

## Pitfalls that turn a cache into wrong answers

**A config key the slice forgot.** The dangerous one, because it fails silently: the user changes a setting and gets the old output. Prefer slicing whole typed sub-models (the clipper's `structure` stage hashes its entire config section) over hand-picked fields, and test every setting users actually touch.

**Forgetting to bump a stage version.** An output-changing code change without a bump is a forgotten config key in disguise. The clipper's render stage comments when to bump its version, and slices carry library and renderer versions. Review rule: a diff that changes a stage's output must touch its `version`.

**Environment-dependent inputs.** Resolve anything decided at run time (an `auto` device, a model alias) before hashing, or two machines share a key for different work. For files, hash content, as the clipper does with `music_sha`, not location.

**Values whose serialisation is not stable.** The clipper's `canonical_json` passes `default=str` for convenience. That is fine for dates, but a Python `set` of strings stringifies in an order that varies between processes because string hashing is randomised; we ran the same `json.dumps` call in four fresh processes and got three different orders. A key that changes every run is a cache that never hits. Our snippet above omits `default=` so such values fail at hashing time instead.

**Timestamps inside outputs.** Keep wall-clock time in the manifest, not in artefacts, or byte comparisons and any output-hash scheme become useless.

**Truncated keys.** Directory names use the first 16 hex characters, or 64 bits. By the birthday bound, the chance of any collision among `n` entries is roughly `n**2 / 2**65`: about 2.7 in 100 million for a million entries in one stage directory, which only ever holds one entry per configuration tried for that source or job. The manifest keeps the full fingerprint if you want to verify on read.

## Garbage collection

Content-addressed stores only grow: every config experiment leaves a directory behind. The clipper prototype does not ship a collector yet, but it writes a `latest.json` pointer per stage and records every run in SQLite, which is what one needs. The design we would use is mark and sweep:

1. Mark: for every job you still care about, compute the plan from its saved config and keep those fingerprint directories, plus whatever `latest.json` points to
2. Sweep: delete unmarked stage directories older than a grace period, so a run in progress never loses its inputs
3. Delete `.tmp-*` directories older than the longest plausible stage run; they are leftovers from killed processes, since normal failures clean up after themselves
4. Expire LLM cache rows and render items by age, and remember that hardlinked exports survive deletion of the cache entry they came from

Bazel's documentation makes the underlying point plainly: a content-addressed cache cannot tell which build an output belongs to, so you either delete everything or delete old outputs. Roots from saved job configs are what let you do better than age alone.

## Checklist

- Key every stage by name, code version, input content hash, config slice and upstream keys
- Serialise slices canonically from typed models; reject types without a stable serialisation
- Write into a temp directory, write the manifest last, rename, and treat the manifest as the only proof of a hit
- Add finer caches where a stage fans out: per LLM prompt, per rendered item
- Scope expensive per-source work so every job on that source reuses it
- Encode the invalidation matrix as tests that assert exact sets, including "unrelated change re-runs nothing"
- Make resume the same code path as a normal run
- Plan garbage collection from live roots plus a grace period before the disk fills

## Primary references

- [Bazel: Remote Caching](https://bazel.build/remote/caching), on action caches, content-addressable storage and why deletion is by age or all at once
- [Pro Git: Git Objects](https://git-scm.com/book/en/v2/Git-Internals-Git-Objects), the canonical explanation of a content-addressable store
- [Python documentation: os.replace](https://docs.python.org/3/library/os.html#os.replace), including atomicity and the non-empty directory error
- [RFC 8785: JSON Canonicalization Scheme](https://www.rfc-editor.org/rfc/rfc8785), for hashing JSON reproducibly across languages

## Related reading

- [Data Quality Dashboards: Know When a Number Is Usable](/blog/data-quality-dashboards)
- [Data Warehouses: A Practical Guide for Growing Teams](/blog/data-warehouse-beginners-guide)

The full pipeline is described in our [AI Video Clipper case study](/work/ai-video-clipper), and our [AI solutions service](/services/ai-solutions) is where we build pipelines like it for clients.
