Skip to content

Caching and Checkpointing

Accrue provides two complementary persistence features: caching (skip redundant API calls) and checkpointing (crash recovery). They serve different purposes and can be used independently or together.

Caching

Enable caching

from accrue import Pipeline, LLMStep, EnrichmentConfig

pipeline = Pipeline([
    LLMStep("analyze", fields={"summary": "Summarize the company"}, model="gpt-6-luna"),
])

# Caching is on by default — no config flag needed.
result = pipeline.run(data)

Re-running the same pipeline with the same data skips cached rows entirely. No API calls are made for rows that already have results.

How it works

  • Results are stored in a SQLite database at ~/.cache/accrue/cache.db ($XDG_CACHE_HOME/accrue/cache.db when that is set) (WAL mode for concurrent access).
  • Each cached entry is keyed by a SHA-256 hash of the step's inputs and settings: step name, row data, prior results from dependency steps, field specs, model, prompts and provider_kwargs, among others (full list under What is in the cache key).
  • Change a prompt, add a field, switch models, or adjust temperature or provider_kwargs and the cache auto-invalidates (different hash).
  • TTL: default 3600 seconds (1 hour). Expired entries are lazily deleted on next read.

Configuration

config = EnrichmentConfig(
    enable_caching=True,
    cache_ttl=7200,          # 2 hours (default: 3600). 0 = no expiry.
    cache_dir="./.accrue",   # Directory for cache.db (default: ~/.cache/accrue)
)

What is in the cache key

For LLMStep: - Step name - Row data (the full input dict for that row) - Prior results (merged outputs from dependency steps) - Field specs (prompts, types, formats, enums, examples, bad_examples, defaults) - Model name - Temperature and max_tokens - Custom system_prompt (hashed) - system_prompt_header (hashed) - For steps without a custom system_prompt: the version of the generated prompt, outside_knowledge and whether structured outputs are on - Grounding config (domains, location, max_searches, its provider_kwargs) - Output schema - provider_kwargs (so changing thinking mode or effort level re-runs the step) - Attachments (hashed by content, not path)

For FunctionStep: - Step name - Row data - Prior results - cache_version (if set)

What is NOT in the cache key

These can be changed without invalidating cached results:

  • sources_field -- change the citation output field name freely.
  • Hook configuration.
  • max_workers, max_retries, and other runtime config.

Upgrading accrue

When an accrue release changes the generated prompt, steps that use it have a new key and re-run once, at cost, so answers to the old and new prompts are not mixed. Steps with a custom system_prompt and FunctionSteps keep their cached results, unless a step they depend on re-ran and returned something different.

Per-step control

# Default: caching follows the global config setting
LLMStep("analyze", fields={...}, cache=True)

# Disable caching for this step (useful for non-deterministic functions)
FunctionStep("stock_price", fn=get_price, fields=["price"], cache=False)

# Bump version to invalidate cache when function logic changes
FunctionStep("score", fn=score_v2, fields=["score"], cache_version="v2")

A step with cache=False always makes the API call (or runs the function), even when caching is enabled at the config level. A step with cache=True only caches when the global config has enable_caching=True (the default).

Clear cache

# Clear all cached results in the default cache directory
pipeline.clear_cache()

# Clear cache for a specific step
pipeline.clear_cache(step="analyze")

# A custom cache directory: pass the same cache_dir as the config
pipeline.clear_cache(cache_dir="./.accrue")

Checkpointing

Enable checkpointing

config = EnrichmentConfig(
    enable_checkpointing=True,
    auto_resume=True,            # Resume from last checkpoint on re-run (default: True)
)
result = pipeline.run(data, config=config)

How it works

  • After each step completes (across all rows), the full pipeline state is written to a JSON file -- per-row results and the row indices that errored.
  • If the pipeline crashes mid-execution and is re-run, completed steps are skipped. Their results are loaded from the checkpoint and fed to downstream steps.
  • Rows that errored inside a completed step are the exception: they re-run. Checkpointed means done only for cells that actually succeeded.
  • Checkpoint files are cleaned up automatically once nothing is left to heal. A run that ends with row errors keeps its checkpoint, because that record is what a retry reads.

pipeline.run() and pipeline.runner(config).run() both checkpoint; they share the same file for the same dataset, so you can start with one and resume with the other.

Retrying failed cells

A run that left errors can be healed without paying for the rows that worked:

config = EnrichmentConfig(enable_checkpointing=True)

result = pipeline.run(data, config=config, run_log="logs/tonight.jsonl")
if result.has_errors:
    # Re-runs ONLY the (step, row) cells that errored. Everything that
    # succeeded is served from the checkpoint -- not one extra API call.
    result = pipeline.retry_failed(data, config=config, run_log="logs/tonight.jsonl")

retry_failed_async() is the await form. Both take the same arguments as run(), plus:

Argument Effect
rows Restrict the retry to these row indices. Failures left out stay recorded in the checkpoint for a later retry.
steps Restrict the retry to these step names.
run_log Path of the failed run's log to append to. The retry keeps that run's run_id and display_key and appends a retry_start ... retry_end segment, so recovered cells arrive as ordinary row_complete records a dashboard can apply directly.
data_identifier Explicit checkpoint identifier, if the original run passed one.

This is the API behind a dashboard's "retry failed rows" button, and the groundwork for CLI resume.

Points worth knowing:

  • Pass the config the run used. retry_failed() needs enable_checkpointing=True and the same checkpoint_dir to find the file. It raises PipelineError rather than silently re-running the whole dataset.
  • A clean run has nothing to retry. Its checkpoint was removed on success, so retry_failed() raises.
  • Steps the run never finished still run in full. A killed run has no results for them at all.
  • A cell that fails again surfaces normally. It comes back in result.errors and stays recorded for the next attempt.
  • result.row_status covers the whole dataset; result.errors covers only this pass. A failure you left out with rows= / steps= is not in errors, but reads "error" in row_status. Checkpointed cells keep their recorded outcome, including "skipped". See Error Handling.
  • Downstream cells of a healed row re-run too. Healing score for row 7 re-runs flag for row 7, and anything downstream of flag, walked transitively through the DAG -- but only for row 7. By default flag was skipped on row 7 because of the failure, so the retry is what gives it a value. A step with run_on_upstream_error=True had instead computed its answer from the None placeholder the failure left behind; leaving that in place would hand you wrong data with no errors attached to it. If the upstream fails again, its default dependents stay skipped. A retry therefore costs the failed cells plus their dependents for those rows, still nothing for the rows that worked. Steps on a sibling branch, which consumed nothing broken, are untouched.
  • Row indices are positional, matching the row field in the run log.
  • A cell that gets skipped on the retry stays failed. If a run_if / skip_if predicate now excludes a cell you asked to heal, nothing ran, so its recorded failure is kept and the checkpoint stays for a later attempt.
  • steps= names are validated. A step name the pipeline does not have raises PipelineError instead of silently selecting nothing and reporting success.

Configuration

config = EnrichmentConfig(
    enable_checkpointing=True,
    checkpoint_dir="/tmp/my_checkpoints",  # Default: ~/.local/state/accrue
    checkpoint_interval=100,                # Save partial progress every 100 rows (default: 0 = disabled)
    auto_resume=True,                       # Default: True
)

checkpoint_interval controls intra-step progress saving. When set to 100, the pipeline saves partial results every 100 rows within a single step. This is useful for long-running steps processing thousands of rows.

Cache vs. checkpoint

Caching Checkpointing
Purpose Skip redundant API calls Crash recovery and failed-cell retry
Granularity Per row, per step Per step, plus the failed rows within it
Persistence Permanent (until TTL or manual clear) Temporary (cleaned up once nothing is left to heal)
Storage SQLite (~/.cache/accrue/cache.db) JSON files
When it helps Re-running with same/similar data Pipeline crashes mid-execution
Cost savings Yes (avoids duplicate API calls) Yes (avoids re-running completed steps)

Using both together

For production workloads, enable both:

config = EnrichmentConfig(
    enable_caching=True,       # Skip individual row/step combos already computed
    enable_checkpointing=True, # Resume from last completed step on crash
    checkpoint_interval=100,   # Save partial progress within steps
)

Or use the production preset:

config = EnrichmentConfig.for_production()
# Sets: max_workers=30, enable_checkpointing=True, enable_caching=True,
#        checkpoint_interval=100, max_retries=5

Other presets:

EnrichmentConfig.for_development()  # Low concurrency, caching on, debug logging
EnrichmentConfig.for_server()       # No progress bars, high concurrency
EnrichmentConfig.for_batch()        # Batch API settings with caching and checkpointing

Gotchas

  • Caching is on by default (enable_caching=True). To run without caching — typically for one-off runs or when you need a guaranteed-fresh result — pass EnrichmentConfig(enable_caching=False). The cache=True default on individual steps only means "this step is cacheable"; it does not by itself enable or disable the cache system.
  • cache_version is a FunctionStep feature. LLMStep cache keys are derived from prompts, model, temperature, field specs, provider_kwargs and the rest of the step's settings, so they auto-invalidate when those change. There is no cache_version on LLMStep.
  • Cache TTL is checked lazily on read. Expired entries are not proactively deleted. Call CacheManager.cleanup_expired() if you need to reclaim disk space.
  • The default cache directory is outside the project. If you point cache_dir inside it (e.g. .accrue/), add that directory to your .gitignore.
  • A checkpoint is not checked against the prompt, model or settings. Resuming, or calling retry_failed(), after editing a step's prompt, model or settings, or upgrading accrue, keeps the finished cells and runs the rest with the new prompt, so one column can hold both. To redo everything, run with auto_resume=False and either enable_caching=False or a cleared cache.
  • Checkpoint files are identified by a combination of data identifier and category. The default data identifier covers the input's columns, row count, and a digest of the first and last five rows' values -- so changing the data invalidates the checkpoint and the next run starts fresh. That is deliberate: checkpoint_dir defaults to one global state directory, and a shape-only identifier meant two unrelated datasets with the same columns and row count resolved to the same file, silently serving one dataset's enrichments to the other. Pass an explicit data_identifier= to run() / retry_failed() if you need a checkpoint to survive edits to the data.
  • Editing a row in the middle of a large dataset does not invalidate the checkpoint -- only the first and last five rows are sampled. Row count and column names still have to match, and every other mismatch is caught by the strict validation on load (with a warning).
  • A checkpoint write that fails -- most often a step value JSON cannot encode, such as a UUID, Path, or Enum -- logs an error and the run continues without checkpointing rather than throwing away work you have already paid for. The run is then not resumable; convert such values to a JSON-friendly type (str(uuid)) if you need checkpointing.
  • checkpoint_interval=0 (default) means no intra-step saves. Progress is only saved after each step completes in full. Set it to a positive number for long-running steps.