Files
archie/modules/runs/runs.go
T
sam a101b64703 fix(runs): a cancelled run's trail records who stopped it (#2100)
Cancelling a run moved it and the runs it called to cancelled and wrote nothing
to either trail, so a stopped run could not say when it stopped or who asked.

The stop now returns the runs it stopped and records one cancel entry on each,
in the same transaction, naming the principal that asked. The entry is a step
named cancel with the caller's identity, so the run detail shows it with the
rest of the trail.
2026-11-27 19:24:19 +11:00

550 lines
18 KiB
Go

// Package runs is Archie's durable run engine. A run executes a stored
// workflow document step by step; each step's result is saved before the next starts,
// so after a crash the run replays from saved results without repeating a
// finished step. Every write is fenced by the worker's lease.
package runs
import (
"context"
"encoding/json/jsontext"
"errors"
"fmt"
"log/slog"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/samcharles93/archie-core/modules/governance"
"github.com/samcharles93/archie-core/modules/runs/internal/store"
)
// StartRequest specifies the workflow and organisation for a new run.
// A non-empty Key makes the start idempotent within the organisation.
type StartRequest struct {
OrgID string
WorkflowID uuid.UUID
Key string
Input jsontext.Value
}
// Options tune the engine. Zero values take the defaults.
type Options struct {
Owner string
Workers int
LeaseTTL time.Duration
PollInterval time.Duration
}
// workerStore is what a worker needs from storage; every write is fenced.
type workerStore interface {
Claim(ctx context.Context, owner string, token uuid.UUID, ttl time.Duration) (store.Run, bool, error)
RenewLease(ctx context.Context, id, token uuid.UUID, ttl time.Duration) (bool, error)
Steps(ctx context.Context, id uuid.UUID) ([]store.Step, error)
RecordStep(ctx context.Context, token uuid.UUID, step store.Step) error
Suspend(ctx context.Context, id, token uuid.UUID, wakeAt *time.Time, waitingFor string) error
Finish(ctx context.Context, id, token uuid.UUID, ended store.Ended) error
Signalled(ctx context.Context, id uuid.UUID, key string) (jsontext.Value, bool, error)
CancelRequested(ctx context.Context, id uuid.UUID) (bool, error)
}
// runWork is everything a running workflow needs from storage.
type runWork interface {
workerStore
runStarter
}
// canceller is what Cancel needs from storage: it stops a run and the runs it
// called, and records who asked. It is db except in tests.
type canceller interface {
Cancel(ctx context.Context, orgID string, id uuid.UUID, by string) error
}
// runStarter is what a step that starts another run needs from storage.
type runStarter interface {
workflowFinder
StartFor(ctx context.Context, token, parent uuid.UUID, n store.NewRun) (uuid.UUID, error)
}
// Engine starts, executes and resumes runs.
type Engine struct {
db *store.Store
// defs is the stored workflows; it is db except in tests.
defs definitions
// queue starts runs; it is db except in tests.
queue runQueue
// cancel stops a run and writes its trail entry; it is db except in tests.
cancel canceller
work runWork
log *slog.Logger
opts Options
mu sync.RWMutex
deps *Deps
// referrers finds the triggers that name a workflow.
referrers Referrers
// claimFailure is the last failed attempt to claim a run, cleared by the
// next attempt that succeeds.
claimFailure atomic.Pointer[claimFailure]
// load turns a claimed run into the code that executes it.
load func(ctx context.Context, run store.Run) (Workflow, error)
}
// New returns an engine on db.
func New(db *sqlx.DB, log *slog.Logger, opts Options) *Engine {
s := store.New(db)
return newEngine(s, s, log, opts)
}
func newEngine(db *store.Store, work runWork, log *slog.Logger, opts Options) *Engine {
if opts.Workers <= 0 {
opts.Workers = 4
}
if opts.LeaseTTL <= 0 {
opts.LeaseTTL = 30 * time.Second
}
if opts.PollInterval <= 0 {
opts.PollInterval = time.Second
}
if opts.Owner == "" {
opts.Owner = "archie"
}
e := &Engine{db: db, defs: db, queue: db, cancel: db, work: work, log: log, opts: opts}
e.load = e.loadDocument
return e
}
// Use gives the engine what a document's steps need. It must be called before
// Work, and is separate from New because the modules those steps use are built
// with the engine.
func (e *Engine) Use(d Deps) {
e.mu.Lock()
defer e.mu.Unlock()
e.deps = &d
}
func (e *Engine) steps() (Deps, error) {
e.mu.RLock()
defer e.mu.RUnlock()
if e.deps == nil {
return Deps{}, errNoDeps
}
return *e.deps, nil
}
// Install stores body as the next version of the workflow called name,
// creating the workflow when none has the name, unless body is what the latest
// version already is. It returns the workflow's id and the version in force. A
// body that doesn't validate is stored as nothing.
func (e *Engine) Install(ctx context.Context, orgID, name, body, by string) (uuid.UUID, int, error) {
id, err := e.WorkflowNamed(ctx, orgID, name)
if errors.Is(err, ErrNoWorkflow) {
id, err = e.Create(ctx, orgID, name)
}
if err != nil {
return uuid.Nil, 0, err
}
version, err := e.Publish(ctx, orgID, id, body, by, nil)
return id, version, err
}
func (e *Engine) validateDocument(ctx context.Context, body string) (Document, error) {
doc, err := ParseDocument(body)
if err != nil {
return Document{}, err
}
var problems []Problem
for i, step := range doc.Steps {
found, err := e.checkStepCapabilities(ctx, i, step)
if err != nil {
return Document{}, err
}
problems = append(problems, found...)
if step.Type != typeAgent {
continue
}
var s agentSettings
if err := decodeSettings(step.Settings, &s); err != nil {
return Document{}, err
}
deps, err := e.steps()
if err != nil {
return Document{}, err
}
// Ask what the run start asks, with the alias it would use. A step
// that names no model runs on the default, so it is checked the same
// way as "model: default".
if _, err := deps.Settings.WorkflowModelForAlias(ctx, modelAlias(s.Model)); err != nil {
switch message, ok := modelProblem(err, s.Model); {
case ok:
problems = append(problems, Problem{Path: fmt.Sprintf("steps[%d].settings.model", i), Message: message})
case errors.Is(err, governance.ErrNoAgentModel):
// The default isn't configured yet. The operator can set it
// later and the run start checks it again, so it doesn't block
// saving. A fresh install saves its starter workflow
// before any model exists.
default:
return Document{}, err
}
}
}
if len(problems) > 0 {
return Document{}, &InvalidError{Problems: problems}
}
return doc, nil
}
// modelProblem describes a model the organisation can't provide as a problem
// with the step. It reports false for an unconfigured default and for any
// other error.
func modelProblem(err error, alias string) (string, bool) {
switch {
case errors.Is(err, governance.ErrModelNotAllowed):
return err.Error(), true
case errors.Is(err, governance.ErrNoAgentModel) && modelAlias(alias) != "":
return fmt.Sprintf("unknown agent model alias %q", alias), true
}
return "", false
}
// WorkflowNamed returns the id of the workflow called name. It returns
// ErrNoWorkflow when no workflow that isn't deleted has the name.
func (e *Engine) WorkflowNamed(ctx context.Context, orgID, name string) (uuid.UUID, error) {
w, err := e.db.Named(ctx, orgID, name)
if err != nil {
return uuid.Nil, err
}
return w.ID, nil
}
// WorkflowName returns the name of a workflow, deleted or not.
func (e *Engine) WorkflowName(ctx context.Context, orgID string, id uuid.UUID) (string, error) {
w, err := e.db.Identity(ctx, orgID, id)
if err != nil {
return "", err
}
return w.Name, nil
}
// runQueue reads the workflow a run starts under and queues the run.
type runQueue interface {
workflowFinder
Start(ctx context.Context, n store.NewRun) (uuid.UUID, error)
}
// Start queues a run under the latest stored version of its workflow and
// returns its id. The principal in ctx must be allowed to run the workflow;
// work that starts runs on its own, such as a trigger, passes the workload
// principal. A start the policy chain can't decide queues nothing, and the
// error wraps governance.ErrChainUnavailable so the caller tries again.
func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error) {
if err := e.mayStart(ctx, req.WorkflowID); err != nil {
return uuid.Nil, err
}
n, err := newRun(ctx, e.queue, req)
if err != nil {
return uuid.Nil, err
}
return e.queue.Start(ctx, n)
}
// mayStart refuses a start by a caller who may not run the workflow, or whose
// right can't be checked.
func (e *Engine) mayStart(ctx context.Context, workflow uuid.UUID) error {
p, ok := governance.PrincipalFromContext(ctx)
if !ok {
return fmt.Errorf("%w: no principal starts the run", governance.ErrDenied)
}
deps, err := e.steps()
if err != nil {
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
}
return governance.Require(ctx, deps.Access, p, governance.ActionRun, governance.Resource{
Kind: governance.KindWorkflow, ID: resourceID(workflow), Org: p.Org,
})
}
// resourceID is a workflow's id as an access resource. A test run of a
// document that isn't a workflow yet has none, and is checked against
// workflows in general.
func resourceID(workflow uuid.UUID) string {
if workflow == uuid.Nil {
return ""
}
return workflow.String()
}
// workflowFinder reads stored workflow versions.
type workflowFinder interface {
Workflow(ctx context.Context, orgID string, id uuid.UUID, version int) (store.Workflow, error)
}
// newRun checks that the latest version of the workflow can start with the
// request's input, and returns the run to queue.
func newRun(ctx context.Context, finder workflowFinder, req StartRequest) (store.NewRun, error) {
w, err := finder.Workflow(ctx, req.OrgID, req.WorkflowID, 0)
if errors.Is(err, store.ErrNoWorkflow) || (err == nil && w.Deleted) {
return store.NewRun{}, fmt.Errorf("no workflow %s: %w", req.WorkflowID, ErrNoWorkflow)
}
if err != nil {
return store.NewRun{}, err
}
if w.Disabled {
return store.NewRun{}, fmt.Errorf("workflow %q: %w", w.Name, ErrDisabled)
}
doc, err := ParseDocument(w.Body)
if err != nil {
return store.NewRun{}, fmt.Errorf("workflow %q version %d: %w", w.Name, w.Version, err)
}
if err := doc.unsupported(); err != nil {
return store.NewRun{}, refusal{err}
}
input := req.Input
if len(input) == 0 {
input = jsontext.Value("null")
}
if err := doc.checkInputs(decodeInputs(input)); err != nil {
return store.NewRun{}, refusal{fmt.Errorf("workflow %q: %w", w.Name, err)}
}
return store.NewRun{
OrgID: req.OrgID, WorkflowID: w.ID, Version: w.Version, StartKey: req.Key, Input: input,
}, nil
}
// CheckTrigger refuses a trigger for a workflow it couldn't start: one that
// doesn't exist, or one that requires an input a trigger doesn't supply. A
// trigger supplies only the event that fired it.
func (e *Engine) CheckTrigger(ctx context.Context, orgID string, id uuid.UUID) error {
w, err := e.db.Workflow(ctx, orgID, id, 0)
refuse := func(format string, args ...any) error {
return &InvalidError{Problems: []Problem{{Path: "workflow_id", Message: fmt.Sprintf(format, args...)}}}
}
if errors.Is(err, store.ErrNoWorkflow) || (err == nil && w.Deleted) {
return refuse("no published workflow %s", id)
}
if err != nil {
return err
}
workflow := w.Name
doc, err := ParseDocument(w.Body)
if err != nil {
return refuse("workflow %q is not valid: %v", workflow, err)
}
if err := doc.unsupported(); err != nil {
return refuse("workflow %q can't start: %v", workflow, err)
}
if missing := doc.requires("event"); len(missing) > 0 {
return refuse("workflow %q requires %s, and a trigger supplies only event", workflow, strings.Join(missing, ", "))
}
return nil
}
// Signal delivers a payload to a run waiting on key, now or later.
func (e *Engine) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) error {
return e.db.Signal(ctx, id, key, payload)
}
// ErrEnded is returned by Cancel for a run that has already ended.
var ErrEnded = errors.New("run has already ended")
// Cancel asks a run to stop, along with every run it started through
// workflow.call. A run that has already ended is refused.
func (e *Engine) Cancel(ctx context.Context, orgID string, id uuid.UUID) error {
// The trail names who stopped the run, which is the caller asking for it.
by := ""
if p, ok := governance.PrincipalFromContext(ctx); ok {
by = string(p.IdentityID)
}
err := e.cancel.Cancel(ctx, orgID, id, by)
if errors.Is(err, store.ErrEnded) {
return fmt.Errorf("%w: %w", ErrEnded, err)
}
return err
}
// ErrNotRetryable is returned by Retry for a run that is not parked, or that
// never reached the step to retry from.
var ErrNotRetryable = errors.New("run can't be retried from there")
// Retry queues a parked run to run again from a top-level step, named by its id
// or, without one, its type and position as the trail shows it. An empty from
// is the step that parked the run. The steps before it keep their results.
func (e *Engine) Retry(ctx context.Context, orgID string, id uuid.UUID, from string) error {
err := e.db.Retry(ctx, orgID, id, from)
if errors.Is(err, store.ErrNotEnded) || errors.Is(err, store.ErrNoStep) {
return fmt.Errorf("%w: %w", ErrNotRetryable, err)
}
return err
}
// Work runs the engine's workers until ctx ends.
func (e *Engine) Work(ctx context.Context) {
var wg sync.WaitGroup
for range e.opts.Workers {
wg.Go(func() { e.workerLoop(ctx) })
}
wg.Wait()
}
func (e *Engine) workerLoop(ctx context.Context) {
for ctx.Err() == nil {
claimed, err := e.claimAndExecute(ctx)
if ctx.Err() == nil {
e.noteClaim(err)
}
if err != nil {
e.log.ErrorContext(ctx, "run worker", "error", err)
}
if claimed && err == nil {
continue
}
select {
case <-ctx.Done():
case <-time.After(e.opts.PollInterval):
}
}
}
func (e *Engine) claimAndExecute(ctx context.Context) (bool, error) {
token := uuid.New()
run, ok, err := e.work.Claim(ctx, e.opts.Owner, token, e.opts.LeaseTTL)
if err != nil || !ok {
return false, err
}
if err := e.mayExecute(ctx, run); err != nil {
return e.refuseClaim(ctx, run, token, err)
}
e.execute(ctx, run, token)
return true, nil
}
// mayExecute rechecks, each time a worker claims a run, that the workload
// principal may still run its workflow. A new run, a retry and a resume after
// a crash or a wake-up all pass through here.
func (e *Engine) mayExecute(ctx context.Context, run store.Run) error {
deps, err := e.steps()
if err != nil {
return fmt.Errorf("%w: %w", governance.ErrChainUnavailable, err)
}
return governance.RequireWorkload(ctx, deps.Access, governance.ActionRun, governance.Resource{
Kind: governance.KindWorkflow, ID: resourceID(run.WorkflowID),
})
}
// refuseClaim handles a claimed run that may not execute. A policy chain that
// can't decide leaves the run unfinished, so its lease lapses and a worker
// claims it again. A refusal ends the run as failed, and its trail says why.
func (e *Engine) refuseClaim(ctx context.Context, run store.Run, token uuid.UUID, cause error) (bool, error) {
if !errors.Is(cause, governance.ErrDenied) {
return false, fmt.Errorf("run %s waits for access policies: %w", run.ID, cause)
}
ended := store.Ended{State: store.StateFailed, Error: cause.Error()}
if err := e.work.Finish(ctx, run.ID, token, ended); err != nil {
return false, fmt.Errorf("finish refused run %s: %w", run.ID, err)
}
e.log.WarnContext(ctx, "run refused", "run", run.ID, "workflow", run.Workflow, "error", cause)
return true, nil
}
// execute runs one claimed run to its next suspension or end. The run's
// context ends if the lease can't be renewed, so a stale worker stops.
func (e *Engine) execute(ctx context.Context, run store.Run, token uuid.UUID) {
runCtx, cancel := context.WithCancel(ctx)
defer cancel()
go e.keepLease(runCtx, cancel, run.ID, token)
log := e.log.With("run", run.ID, "workflow", run.Workflow, "attempt", run.Attempts)
result, ending, err := e.invoke(runCtx, run, token)
switch {
case errors.Is(err, errSuspended):
log.InfoContext(ctx, "run suspended")
return
case errors.Is(err, store.ErrLeaseLost), errors.Is(err, context.Canceled):
log.WarnContext(ctx, "run stopped: lease lost or shutting down")
return
}
ended := store.Ended{State: store.StateSucceeded, Result: result}
switch {
case errors.Is(err, ErrCancelled):
ended.State, ended.Error = store.StateCancelled, err.Error()
case err != nil:
ended.State, ended.Error = store.StateFailed, err.Error()
case ending != nil:
ended.State, ended.Detail = ending.State, ending.Detail
}
if ferr := e.work.Finish(ctx, run.ID, token, ended); ferr != nil {
log.WarnContext(ctx, "finish run", "error", ferr)
return
}
log.InfoContext(ctx, "run finished", "state", ended.State)
}
// invoke runs the workflow, turning a panic in workflow or step code into a
// failure of this run rather than of the process.
func (e *Engine) invoke(ctx context.Context, run store.Run, token uuid.UUID) (result jsontext.Value, ending *Ending, err error) {
defer func() {
if p := recover(); p != nil {
err = fmt.Errorf("panic: %v", p)
}
}()
wf, err := e.load(ctx, run)
if err != nil {
return nil, nil, err
}
steps, err := e.work.Steps(ctx, run.ID)
if err != nil {
return nil, nil, err
}
rc := newContext(ctx, e.work, run, token, steps)
result, err = wf(rc, run.Input)
return result, rc.ending, err
}
// loadDocument reads the document a run executes: the version it started
// under, or for a dry run the document it carries.
func (e *Engine) loadDocument(ctx context.Context, run store.Run) (Workflow, error) {
deps, err := e.steps()
if err != nil {
return nil, err
}
var body string
if run.Dry {
o, err := readOverlay(run.Overlay)
if err != nil {
return nil, err
}
body = o.Document
} else {
w, err := e.db.Workflow(ctx, run.OrgID, run.WorkflowID, run.Version)
if err != nil {
return nil, fmt.Errorf("workflow %q version %d: %w", run.Workflow, run.Version, err)
}
body = w.Body
}
doc, err := ParseDocument(body)
if err != nil {
return nil, err
}
return deps.Compile(doc), nil //nolint:contextcheck // a workflow takes its context from the run handle, as a handler takes it from the request
}
func (e *Engine) keepLease(ctx context.Context, lost context.CancelFunc, id, token uuid.UUID) {
tick := time.NewTicker(e.opts.LeaseTTL / 3)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
held, err := e.work.RenewLease(ctx, id, token, e.opts.LeaseTTL)
if err != nil || !held {
e.log.WarnContext(ctx, "lease not renewed", "run", id, "error", err)
lost()
return
}
}
}
}