Watching your workflows

The Reader

From docs/architecture/reader.md at commit 548821a.

Spinto 0.1.0. These docs follow the main branch. Spinto isn't on crates.io yet, so you install it from a clone.

Introduction

spinto::workflows::Reader turns the workflow runtime’s records into spinto.v1 contracts (src/contracts/mod.rs). It only reads. Spinto never inserts, updates, or deletes a row in a workflow_* table.

Laravel for Rust has no public API to list runs, so the reader queries the database workflow store’s five tables directly, using the connection and table names in config.workflow. For one run, it also calls laravel::workflow::find and reports whether the two agree.

use spinto::workflows::Reader;
use spinto::contracts::RunFilters;

let reader = Reader::new();
let page = reader.runs(&RunFilters::default()).await?;
let detail = reader.run("01a234c7-65e3-7c96-8b40-f1ee6d1bd59e").await?;

Every method reads config.workflow and the SpintoConfig section when it runs, so a Reader is cheap to make per request. Reader::at(timestamp) measures elapsed times and “still in the future” from a fixed time instead of laravel::now().

The code is in four files:

File What it does
src/workflows/store.rs The select queries and the schema check.
src/workflows/derive.rs Pure functions from rows to contracts. No I/O.
src/workflows/redaction.rs The payload policy.
src/workflows/reader.rs Store resolution, filters, the overview, evidence checks.

Choosing the Store

The reader reads config.workflow.default and looks it up in config.workflow.stores:

  • StoreConfig::Database: the reader uses connection (None means the default connection) and the five table names.
  • StoreConfig::Memory or StoreConfig::Custom: listing isn’t possible. capabilities().listing is unsupported, and runs, failures, waiting, overview and definitions return ReaderError::ListingUnsupported. run(id) still works through laravel::workflow::find, with source: runtimeApi on every record. That API returns no input, context, step outputs or queue, so those fields are unsupported.

Errors

Methods return laravel::Result. When the reader can’t answer for a reason a page should explain, the error wraps a ReaderError:

match reader.runs(&filters).await {
    Err(error) => match error.downcast_ref::<ReaderError>() {
        Some(ReaderError::ListingUnsupported { store, driver }) => { /* explain */ }
        Some(ReaderError::Schema { missing }) => { /* list the missing columns */ }
        _ => return Err(error),
    },
    Ok(page) => { /* render */ }
}
Variant HTTP status When
ListingUnsupported 501 The default store isn’t a database store.
StoreMissing 503 config.workflow.default names a store that isn’t defined.
Schema 503 A query failed and the schema check found missing tables or columns.
InvalidFilter 422 A range other than 1h, 24h, 7d, 30d, all, or an attribute filter without =.

A missing table never panics. capabilities() always answers, with the missing columns in schema.missing.

Derived Fields

Everything here is in src/workflows/derive.rs and is tested against rows a real worker wrote (tests/fixtures/store-rows/).

Activity

The runtime’s waiting status covers three situations. The run’s pending entry tells them apart:

workflow_runs.status Pending entry activity
pending   queued
running   running
waiting a sleep sleeping
waiting a wait or inbox awaitingResume
waiting a step with tries > 0 and wake_at retryScheduled
waiting none of these unknown
completed, failed, cancelled   finished
anything else   unknown

The Current Entry

  • An unfinished run is at its pending entry whose wake_at equals the run’s wake_at, else its first pending wait, else its last pending entry.
  • A failed run is at the entry that failed, so failures shows where.
  • Otherwise the run is at the entry it reached last (latest started_at, then journal order).

A running run has no row for the step it’s running: the runtime writes a step’s row when a try ends. Its current entry is the last one recorded, and its frontier says a step may be running but isn’t recorded yet.

tries is the current entry’s try count when it’s a step. failure is the first line of the run’s error: a failed run’s error, or a cancelled run’s reason.

Attempts

The runtime keeps a try count and the last failed try’s error per step. A step with tries = n has attempts 1..n:

  • Attempts 1..n-1 failed, or there would be no attempt n. Their errors and times are unsupported, and their source is derived.
  • Attempt n takes its outcome from the entry: succeeded when completed, failedFinal when failed, failedWillRetry when pending with an error. Its retryAt is the entry’s wake_at.

The reader never invents an attempt time. A try that a killed worker never reported isn’t counted by the runtime, so it isn’t an attempt here either: the welcome-pack step in tests/fixtures/store-rows/06-finished.jsonl ran twice and has tries = 1.

Durations

  • An entry’s duration is finished_at - started_at. started_at is when the run first reached the entry, so a retried step’s duration includes the backoff between tries.
  • A run’s duration is finished_at - created_at once it has ended (durationIsFinal: true), and the time elapsed since created_at until then.

The Timeline

The timeline has one event per stored time, and each event’s field names the column it came from, such as workflow_steps.finished_at:

  • runCreated from workflow_runs.created_at.
  • entryReached from each entry’s started_at.
  • entryCompleted or entryFailed from each entry’s finished_at.
  • retryScheduled from a pending step’s wake_at.
  • sleepScheduled when a sleep is reached, and entryCompleted when it wakes, with how late it woke.
  • waitResumed or waitTimedOut when a wait or inbox entry ends.
  • runCompleted, runFailed or runCancelled from workflow_runs.finished_at.

Events are ordered by time, then by journal order. A time still in the future, such as a pending retry or a wait’s timeout, is a scheduled event and is never shown as having happened.

An event a later record changed carries earlier: the kind, label and detail it had until that record arrived. An abandoned entry’s event read as pending, with its timeout or wake time, until the run ended, and an interrupted try was a started try until an observation showed its job attempt had ended. Only the run page’s replay reads earlier, for frames before until; the live view shows the event itself.

Waits

There is one WaitCondition per wait or inbox entry, and one per token the run owns in workflow_waits without having reached its wait (claimed). A delivered value the run hasn’t read yet is resumed, with resumedAt from workflow_resumes.created_at. The store deletes resumes when a run ends, so a finished run’s resumedAt is unavailable, and the entry’s finished_at is when the run read the value.

A completed wait without an output timed out. A purged run lost its outputs, so then only the times can tell: a wait that ended before its timeout was resumed, and otherwise the state is unknown.

A run that ended (completed, failed or cancelled) waits for nothing, even when its last entry is still a pending wait, as a cancelled run’s is: its waitingFor is empty, and the wait is abandoned, with no timeout and no resume. Every entry the store still has as pending is abandoned too, in the journal, the graph and the current entry: it has no finish time and no wakeAt, its duration runs to the run’s end, and the timeline schedules nothing for it. The stored wake or timeout time it held moves to lapsedWakeAt, which nothing shows as upcoming; a replay of the run before its end shows it as the entry’s wakeAt.

The Execution Graph

The graph shows what was observed, never a guessed future:

  • run:start is first.
  • Entries go into columns in the order the run reached them. An entry that started before every entry of the current column had finished overlapped them, so it shares the column on its own lane. In the onboarding example, create billing profile and reserve subdomain run under try_join! and share a column.
  • Edges join every entry of a column to every entry of the next. They’re observedSequence edges: the second column started after the first ended, which doesn’t prove a data dependency.
  • The graph ends at run:end for an ended run, and at run:frontier for an unfinished one, whose label says what’s known: “Waiting for customers.3.approval, or its timeout at … What comes next is unknown.”

Payloads and Redaction

Every payload, error and attribute value passes through PayloadPolicy (src/workflows/redaction.rs):

  • SPINTO_PAYLOADS=hidden makes every payload redacted. Any value other than redacted hides payloads, so a typo never shows more.
  • A JSON key matching the denylist has its value replaced with "[redacted]". A key is secret when it contains one of password, passwd, secret, token, api_key, apikey, authorization, authkey, cookie, credential, private, creditcard, cardnumber, sessionid or sessid (case-insensitive), when one of its words is auth, oauth, session, card, cvv, cvc, iban or ssn, when its last word is key, or when it contains a SPINTO_REDACT_KEYS substring. Words split at anything that isn’t a letter and at camel-case boundaries, so cardNumber, userSSN and cvc2 are secret while author, discard and classname are not. The long fragments still over-match on purpose: tokenizer is redacted.
  • String values anywhere are checked for credentials: Bearer tokens, Basic credentials, passwords in URLs, name=value pairs whose name a JSON key would be secret by, provider-prefixed keys (sk_live_, sk_test_, tok_, whsec_, ghp_, AKIA, and others), JWTs, and long hex or mixed-case base64 strings. Email addresses and UUIDs are kept.
  • redactedPaths lists the JSON pointer of each replaced value, in document order.
  • Redacted JSON longer than SPINTO_PAYLOAD_LIMIT bytes is cut to a string and truncated is true. bytes is the stored size.
  • Error messages get the same value checks. firstLine is the first non-empty line, at most 300 characters.
  • Of the run’s context, only the names of the logged values are shown. Hidden context values aren’t named.
  • An attribute whose name is on the denylist is shown as "[redacted]". Other attribute values get the value checks.

Queries

Lists

runs, failures and waiting page by run ID, newest first: a page selects id < cursor ORDER BY id DESC LIMIT per_page + 1, and nextCursor is the last ID shown when there’s another page. Run IDs are UUIDv7, so ID order is creation order. per_page defaults to 25 and is at most 100.

Filter Query
status status = ? (runs only)
workflow workflow = ?
attribute (name=value) id IN (SELECT run_id FROM workflow_attributes WHERE name = ? AND value = ?)
search ID prefix, or workflow name substring, or attribute value substring
range created_at >= now - range

total counts at most 10,000 matching runs (SELECT COUNT(*) FROM (... LIMIT 10001)), and is unknown beyond that.

  • failures lists runs whose status is failed, and runs with an entry whose status is failed.
  • waiting lists runs whose status is pending or waiting. A waiting run whose pending entry doesn’t say why is listed with activity unknown.

A page then reads the entries of its runs (without outputs, at most 20,000) and their attributes, in batches of 200 IDs.

The Overview

overview(range) returns aggregation, one sentence per number saying exactly what it counts. In short:

  • createdByStatus and workflows count runs created in the range.
  • activeByActivity counts every unfinished run now, whatever the range. Waiting runs are classified by their pending entry, for the newest 5,000; any beyond that count as unknown, and the aggregation says how many.
  • retriedSteps counts entries with tries > 1 reached in the range.
  • durations measures runs that finished in the range: nearest-rank p50 and p95, and the maximum, over at most the 10,000 most recently finished.
  • recentFailures and recentRuns are the 5 and 10 newest runs created in the range.

Definitions

definitions() lists the distinct workflow names with their run counts by status, the first and last created_at, and the step and sleep names reached by the 20 most recent runs of each, merged in the order runs first reached them. Wait and inbox names are left out because they usually contain IDs.

registered is unsupported. Laravel for Rust registers workflows through inventory with private fields, so Spinto only knows names that appear in stored runs.

Indexes and Full Scans

The workflow tables have these indexes: workflow_runs (workflow, id), (status, wake_at), (finished_at), unique_key; workflow_steps (run_id, kind, name); workflow_waits (run_id); workflow_resumes (run_id, token, number); workflow_attributes (run_id, name), (name, value).

Every query has a LIMIT or is bounded by one page’s run IDs. These can still scan a whole table, because no index covers them:

Query Scans
range filter and the overview’s createdByStatus and workflows workflow_runs: there’s no index on created_at.
search workflow_runs (workflow LIKE '%...%') and workflow_attributes (value LIKE '%...%').
failures workflow_steps: there’s no index on status.
overview retriedSteps workflow_steps: there’s no index on tries or started_at.
definitions workflow_runs, for each workflow’s first and last created_at.

On a large store, an index on workflow_runs (created_at) and workflow_steps (status) covers most of these. Add them in the application’s own migration; Spinto doesn’t change the schema.

Evidence Checks

run(id) adds checks to RunDetail.evidence:

id Outcome
runtime-agreement pass when laravel::workflow::find returns the same status, entry count, and per-entry kind, name, status and tries as the rows; fail with each difference otherwise. An unfinished run that differs is read once more, since it may have advanced between the reads. notRun for stores read through the runtime API.
schema The same check as capabilities().schema.
purged For runs started with purge_when_finished: pass when the store deleted the input, context, output, error, and entries’ outputs and errors; fail naming what remains. notRun while the run is unfinished.
journal-limit blocked when the run has 2,000 or more entries and only the first 2,000 are shown.

Provenance

Every run, entry and wait carries provenance: source, store, connection, table, key (id=... for a run, run_id=..., kind=..., name=... for an entry) and readAt.

Tests and Fixtures

Test What it proves
tests/reader_derive.rs Derivations, against rows a real worker wrote while waiting, retrying, being killed mid-step, and finishing.
tests/reader_redaction.rs The payload policy.
tests/reader_sqlite.rs The reader on the framework’s database store on SQLite, with runs advanced by RunsWorkflows; a missing schema; a memory store.
tests/reader_postgres.rs The reader against runs the example’s real queue:work process ran on PostgreSQL, compared with workflow:show --json. Ignored by default.
tests/reader_fixtures.rs Each fixture still deserializes into the contracts and serializes back unchanged.

The fixtures in tests/fixtures/*.json are written by reader_postgres from real runs:

cargo build
SPINTO_READER_DATABASE_URL=postgres://127.0.0.1/spinto_reader SPINTO_WRITE_FIXTURES=1 \
    cargo test --test reader_postgres -- --ignored --nocapture

Fixtures prove the frontend’s presentation only. Runtime compatibility is proven by reader_sqlite and reader_postgres.