Skip to the content.

Docs home · Overview · Architecture · Workflows

Deep Dive: Persistence and Sets

Overview

The stateful features are saved sessions, run history, sets, set templates and scheduled runs. They are built from four parts:

The plain crankfire [flags] command never touches the store.

User guides: Sets, Sessions & Scheduling and Terminal UI.

Responsibilities

Architecture

classDiagram
  class Store {
    <<interface>>
    +ListSessions() Sessions
    +GetSession(id) Session
    +SaveSession(s)
    +CreateRun(sessionID) Run
    +FinalizeRun(run, summary)
    +GetSet(id) Set
    +SaveSet(set)
    +CreateSetRun(setID) SetRun
    +FinalizeSetRun(run)
    +GetTemplate(id) bytes
  }
  class fsStore
  class SetRunner {
    +Run(ctx, setID, events) SetRun
    +RunSet(ctx, set, events) SetRun
  }
  class Builder {
    <<interface>>
    +Build(ctx, cfg, name) ItemRun
  }
  class Manager {
    +Reload(ctx, lister)
    +AddOrReplace(id, expr)
    +Remove(id)
    +Run(ctx)
  }
  Store <|.. fsStore
  SetRunner --> Store
  SetRunner --> Builder
  Manager ..> SetRunner : FireFunc

The Go type for SetRunner is setrunner.Runner. setrunner depends only on its Builder interface and never imports cli. The callers (the daemon, the TUI and set run) inject cli.NewSetBuilder(), which wraps cli.BuildRunner.

Key Files

Implementation Details

Data directory layout

The data directory is resolved in this order: an explicit --data-dir, which only tui and daemon accept; then $CRANKFIRE_DATA_DIR; then ~/.crankfire. NewFS creates the root, sessions/, runs/, sets/ and runs/sets/ with mode 0700. templates/ is created lazily:

<data>/
  daemon.lock
  sessions/<ULID>.yaml            (+ .lock sidecar)
  runs/<sessionID>/<RFC3339Nano>/run.json
                                 result.json, report.html   (TUI runs only)
  sets/<ULID>.yaml                (+ .lock sidecar)
  runs/sets/<setID>/<2006-01-02T15-04-05.000000000Z>/set-run.json
                                                     items/  (created, unused)
  templates/<id>.yaml             (+ .lock sidecar; must contain top-level `template: true`)

IDs. IDs are ULIDs from oklog/ulid/v2. validateID rejects:

Writes. writeAtomic writes <path>.tmp with mode 0600, then renames it into place. It does not call fsync. SaveSession, SaveSet and SaveTemplate also hold an exclusive flock on <file>.lock. Reads take no lock.

Session format. Sessions are YAML containing schema_version, id, name, description, tags, created_at, updated_at and config. config.Config has no yaml tags, so the keys of the nested config block are yaml.v3’s lowercased field names: targeturl, loadpatterns and so on. They are not the snake_case keys a config file uses.

Validation on save:

Import. ImportSessionFromConfigFile loads the file with config.LoadFromFile (no Validate) and saves it. It returns the session as it was before saving, with an empty ID and zero timestamps, because SaveSession takes the session by value (internal/store/fs.go:162-171).

FinalizeRun status. An empty or running status becomes completed. A completed run with a non-empty ErrorMessage becomes failed.

Set execution

Runner.Run loads the set from disk and forces set.ID to the requested ID. The TUI and the daemon use it. Runner.RunSet runs a set from memory; crankfire set run uses it, after loading the set itself and applying the --threshold and --override flags without saving them.

Set IDs come from the id: field inside the YAML, not from the file name. ListSets returns each set with whatever id: its file contains (internal/store/sets_fs.go:29-34).

Item configs come from the session store and go straight to BuildRunner, which does not call config.Validate. Session config.thresholds are not evaluated for set items; only set thresholds apply.

Execution then proceeds:

  1. CreateSetRun.
  2. For each stage, in order:
    1. Start a goroutine per item and wait for all of them.
    2. If the context was cancelled, set the run status to cancelled and stop.
    3. If any item did not complete, apply on_failure. An empty value or abort marks the run failed and stops it. continue moves on to the next stage.
  3. Aggregate the item results and evaluate thresholds. If any threshold fails, a completed run becomes failed.
  4. FinalizeSetRun writes set-run.json.

Per item (runItem):

  1. GetSession.
  2. ApplyOverrides.
  3. builder.Build(ctx, cfg, name).
  4. ItemRun.Run(ctx), which returns a RunSummary.

Set items do not create session Run records.

Events. Events (set, stage or item started and ended) are sent without blocking. If the caller’s buffer is full, the event is dropped.

Overrides.

Set thresholds

EvaluateThresholds reads values from a MetricSnapshot{P50, P95, P99, ErrorRate, RPS, TotalErrors} built from each item’s final RunSummary.

The scope field picks what each threshold is checked against:

Scope Checked against
aggregate (default) One result over all items: the max of the latency percentiles and error rate (worst case), and the sum of rps and total errors across all items, including items in different sequential stages
per_item One result per item
<item-name> A single item. The threshold fails only if that item’s stage never ran (for example after an earlier abort).

Every item that was attempted gets a snapshot, including items whose session lookup or build failed. Those items have an all-zero summary (internal/setrunner/runner.go:143), which passes lt and le thresholds and counts in per_item.

A set with no thresholds passes.

Compare and diff

Compare(items) compares the items of one set run. It reports p50, p95, p99, error_rate and total_errors, where lower is better, and rps, where higher is better. The winner for each metric is chosen only among completed items.

Diff(a, b) compares two runs of the same set:

Scheduler and daemon

cli.RunDaemon starts the scheduler:

  1. It takes a non-blocking flock on daemon.lock. If another daemon holds it, the command prints a message and exits 1.
  2. It builds setrunner.New(st, NewSetBuilder()).
  3. It calls Manager.Reload once.
  4. It runs cron in the local time zone.

Reload compares the current schedule fields with the cron entries and adds, replaces or removes entries as needed. It runs on SIGHUP; files are not watched.

Manager.fire makes runs single-flight within the process through sync.Map.LoadOrStore. If a set is still running when it fires again, that fire is skipped, not queued.

fire passes the manager’s run context, which is the daemon’s root context. So on SIGINT or SIGTERM in-flight set runs are cancelled first, then the daemon stops cron and waits, with no time limit, for them to finish writing. Logs are JSON lines on stdout with these events:

CLI subcommands

set run exits 0 if everything passed, 1 on a usage error, 2 if a threshold failed and 3 on a runner error or any status other than completed.

Dependencies

API/Interface

func ResolveDataDir(explicit string) (string, error)
func NewFS(dataDir string) (Store, error)
func New(s store.Store, b Builder) *Runner                       // setrunner
func (r *Runner) Run(ctx context.Context, setID string, ev chan<- Event) (store.SetRun, error)
func ApplyOverrides(base config.Config, o store.Override) config.Config
func EvaluateThresholds(ths []store.Threshold, agg MetricSnapshot, per map[string]MetricSnapshot) []store.ThresholdResult
func Compare(items []store.ItemResult) Comparison
func Diff(a, b store.SetRun) DiffResult
func scheduler.New(onFire FireFunc) *Manager

Testing

Known Issues & Improvement Opportunities