From e8366683a90393c14c7ba7efc1f19c5736f7c67a Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 15 Nov 2026 17:14:05 +1100 Subject: [PATCH] feat(runs): durable run engine with step checkpoints and lease-fenced writes (#1977) --- internal/app/archie/run.go | 30 +- .../pg/migrations/00001_runs_engine.sql | 50 ++++ internal/platform/pg/pg.go | 35 ++- modules/runs/context.go | 219 ++++++++++++++ modules/runs/internal/store/store.go | 278 ++++++++++++++++++ modules/runs/runs.go | 221 ++++++++++++++ modules/runs/runs_test.go | 157 ++++++++++ 7 files changed, 979 insertions(+), 11 deletions(-) create mode 100644 internal/platform/pg/migrations/00001_runs_engine.sql create mode 100644 modules/runs/context.go create mode 100644 modules/runs/internal/store/store.go create mode 100644 modules/runs/runs.go create mode 100644 modules/runs/runs_test.go diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index a35333ec1..537beced8 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -11,11 +11,13 @@ import ( "net" "net/http" "os" + "strconv" "time" "github.com/samcharles93/archie-core/internal/buildinfo" "github.com/samcharles93/archie-core/internal/platform/health" "github.com/samcharles93/archie-core/internal/platform/pg" + "github.com/samcharles93/archie-core/modules/runs" ) const shutdownGrace = 10 * time.Second @@ -29,7 +31,7 @@ func Run(ctx context.Context, configPath string) error { if err != nil { return err } - if err := pg.Migrate(ctx, log, cfg.Database.OwnerURL); err != nil { + if err := pg.Migrate(ctx, log, cfg.Database.OwnerURL, cfg.Database.URL, schemas); err != nil { return err } db, err := pg.Open(ctx, cfg.Database.URL) @@ -41,9 +43,33 @@ func Run(ctx context.Context, configPath string) error { checks := health.NewRegistry() checks.Register("database", db.PingContext) + engine := runs.New(db, log.With("module", "runs"), runs.Options{Owner: owner()}) + ctx, stop := context.WithCancel(ctx) + defer stop() + working := make(chan struct{}) + go func() { + defer close(working) + engine.Work(ctx) + }() + mux := http.NewServeMux() checks.Routes(mux) - return serve(ctx, log, cfg.Listen, mux) + err = serve(ctx, log, cfg.Listen, mux) + stop() + <-working + return err +} + +// schemas are the module schemas the runtime role is granted DML on. +var schemas = []string{"runs"} + +// owner names this process in run leases. +func owner() string { + host, err := os.Hostname() + if err != nil { + host = "archie" + } + return host + ":" + strconv.Itoa(os.Getpid()) } func serve(ctx context.Context, log *slog.Logger, addr string, handler http.Handler) error { diff --git a/internal/platform/pg/migrations/00001_runs_engine.sql b/internal/platform/pg/migrations/00001_runs_engine.sql new file mode 100644 index 000000000..4bce78960 --- /dev/null +++ b/internal/platform/pg/migrations/00001_runs_engine.sql @@ -0,0 +1,50 @@ +-- +goose Up +CREATE SCHEMA runs; + +CREATE TABLE runs.runs ( + id uuid PRIMARY KEY, + org_id text NOT NULL, + workflow text NOT NULL, + start_key text, + input jsonb NOT NULL, + state text NOT NULL CHECK (state IN ('queued', 'running', 'waiting', 'succeeded', 'failed', 'cancelled')), + lease_token uuid, + lease_owner text, + lease_expires_at timestamptz, + wake_at timestamptz, + waiting_for text, + cancel_requested boolean NOT NULL DEFAULT false, + attempts integer NOT NULL DEFAULT 0, + result jsonb, + error text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + finished_at timestamptz, + UNIQUE (org_id, start_key) +); + +-- Claiming scans only runs that could be claimed. +CREATE INDEX runs_claimable ON runs.runs (created_at) + WHERE state IN ('queued', 'waiting', 'running'); + +CREATE TABLE runs.steps ( + run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE, + seq integer NOT NULL, + name text NOT NULL, + outcome text NOT NULL CHECK (outcome IN ('done', 'failed', 'unknown')), + output jsonb, + error text, + recorded_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (run_id, seq) +); + +CREATE TABLE runs.signals ( + run_id uuid NOT NULL REFERENCES runs.runs (id) ON DELETE CASCADE, + key text NOT NULL, + payload jsonb NOT NULL, + received_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (run_id, key) +); + +-- +goose Down +DROP SCHEMA runs CASCADE; diff --git a/internal/platform/pg/pg.go b/internal/platform/pg/pg.go index 3d82cb547..d42af38bc 100644 --- a/internal/platform/pg/pg.go +++ b/internal/platform/pg/pg.go @@ -5,11 +5,11 @@ package pg import ( "context" "embed" - "errors" "fmt" "io/fs" "log/slog" + "github.com/jackc/pgx/v5" // Registers the "pgx" database/sql driver that sqlx and goose use. _ "github.com/jackc/pgx/v5/stdlib" "github.com/jmoiron/sqlx" @@ -34,9 +34,10 @@ func Open(ctx context.Context, url string) (*sqlx.DB, error) { } // Migrate applies every pending migration as the owner, under a session -// advisory lock, so two instances starting together never race. A failed -// migration returns an error and the boot stops. -func Migrate(ctx context.Context, log *slog.Logger, ownerURL string) error { +// advisory lock, so two instances starting together never race, then grants +// the runtime role DML on each module schema. A failed migration returns an +// error and the boot stops. +func Migrate(ctx context.Context, log *slog.Logger, ownerURL, runtimeURL string, schemas []string) error { db, err := Open(ctx, ownerURL) if err != nil { return fmt.Errorf("owner connection: %w", err) @@ -52,11 +53,6 @@ func Migrate(ctx context.Context, log *slog.Logger, ownerURL string) error { return fmt.Errorf("migration lock: %w", err) } provider, err := goose.NewProvider(goose.DialectPostgres, db.DB, files, goose.WithSessionLocker(locker)) - if errors.Is(err, goose.ErrNoMigrations) { - // The series is empty until the first module adds its schema. - log.InfoContext(ctx, "no migrations to apply") - return nil - } if err != nil { return fmt.Errorf("migration provider: %w", err) } @@ -67,5 +63,26 @@ func Migrate(ctx context.Context, log *slog.Logger, ownerURL string) error { for _, r := range results { log.InfoContext(ctx, "migration applied", "version", r.Source.Version, "file", r.Source.Path, "took", r.Duration) } + return grantRuntime(ctx, db, runtimeURL, schemas) +} + +// grantRuntime gives the runtime role USAGE and DML on each schema, never DDL. +func grantRuntime(ctx context.Context, db *sqlx.DB, runtimeURL string, schemas []string) error { + cfg, err := pgx.ParseConfig(runtimeURL) + if err != nil { + return fmt.Errorf("parse runtime URL: %w", err) + } + role := pgx.Identifier{cfg.User}.Sanitize() + for _, schema := range schemas { + name := pgx.Identifier{schema}.Sanitize() + for _, stmt := range []string{ + "GRANT USAGE ON SCHEMA " + name + " TO " + role, + "GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA " + name + " TO " + role, + } { + if _, err := db.ExecContext(ctx, stmt); err != nil { + return fmt.Errorf("grant runtime role on %s: %w", schema, err) + } + } + } return nil } diff --git a/modules/runs/context.go b/modules/runs/context.go new file mode 100644 index 000000000..24b046fd7 --- /dev/null +++ b/modules/runs/context.go @@ -0,0 +1,219 @@ +package runs + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "strconv" + "time" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +var ( + // ErrCancelled ends a run whose cancellation was requested. + ErrCancelled = errors.New("run cancelled") + // ErrOutcomeUnknown is returned by a step that can't confirm what its + // effect did. The step is recorded as unknown and is never repeated (R15). + ErrOutcomeUnknown = errors.New("outcome unknown") + // ErrWaitTimedOut is returned by Wait when its deadline passes. + ErrWaitTimedOut = errors.New("wait timed out") + // ErrNondeterministic means replay met a step the saved history doesn't + // have at that position: the workflow's code took a different path. + ErrNondeterministic = errors.New("workflow replay diverged from its saved steps") + + errSuspended = errors.New("run suspended") +) + +// Context is a run's handle on the engine while its workflow executes. +type Context struct { + // The run owns its context, as an http.Request does: every step takes its + // cancellation from it, and a second context passed beside it could disagree. + ctx context.Context //nolint:containedctx // see above + work workerStore + run store.Run + token uuid.UUID + saved map[int]store.Step + next int +} + +func newContext(ctx context.Context, work workerStore, run store.Run, token uuid.UUID, steps []store.Step) *Context { + saved := make(map[int]store.Step, len(steps)) + for _, s := range steps { + saved[s.Seq] = s + } + return &Context{ctx: ctx, work: work, run: run, token: token, saved: saved} +} + +// RunID is the run's id. +func (rc *Context) RunID() uuid.UUID { return rc.run.ID } + +// OrgID is the organisation the run belongs to. +func (rc *Context) OrgID() string { return rc.run.OrgID } + +// Step runs fn once for this position in the workflow and saves its result. +// On replay it returns the saved result without calling fn. fn receives an +// idempotency key unique to this run and step, for connectors to honour. +func Step[T any](rc *Context, name string, fn func(ctx context.Context, key string) (T, error)) (T, error) { + var zero T + seq := rc.advance() + if saved, ok := rc.saved[seq]; ok { + return replay[T](saved, name) + } + if err := rc.checkCancel(); err != nil { + return zero, err + } + out, err := fn(rc.ctx, rc.run.ID.String()+":"+strconv.Itoa(seq)) + step, recErr := rc.record(seq, name, out, err) + if errors.Is(recErr, store.ErrStepExists) { + // Another holder recorded this step first; its result is the one that + // counts. + return reload[T](rc, seq, name) + } + if recErr != nil { + return zero, recErr + } + if step.Outcome != store.OutcomeDone { + return zero, err + } + return out, nil +} + +// Sleep suspends the run durably until d has passed since the first time this +// step ran. +func Sleep(rc *Context, d time.Duration) error { + wake, err := Step(rc, "sleep", func(context.Context, string) (time.Time, error) { + return time.Now().Add(d).UTC(), nil + }) + if err != nil { + return err + } + if time.Now().Before(wake) { + return rc.suspend(&wake, "") + } + return nil +} + +// Wait returns the payload signalled to this run under key, suspending the run +// durably until it arrives or timeout passes from the first time it waited. +func Wait(rc *Context, key string, timeout time.Duration) (json.RawMessage, error) { + deadline, err := Step(rc, "wait-start:"+key, func(context.Context, string) (time.Time, error) { + return time.Now().Add(timeout).UTC(), nil + }) + if err != nil { + return nil, err + } + return Step(rc, "wait:"+key, func(ctx context.Context, _ string) (json.RawMessage, error) { + payload, ok, err := rc.work.Signalled(ctx, rc.run.ID, key) + switch { + case err != nil: + return nil, err + case ok: + return payload, nil + case !time.Now().Before(deadline): + return nil, ErrWaitTimedOut + } + return nil, rc.suspend(&deadline, key) + }) +} + +func (rc *Context) advance() int { + seq := rc.next + rc.next++ + return seq +} + +func (rc *Context) checkCancel() error { + cancelled, err := rc.work.CancelRequested(rc.ctx, rc.run.ID) + if err != nil { + return err + } + if cancelled { + return ErrCancelled + } + return nil +} + +// record saves a step's outcome. A suspension, a lost lease or a cancelled +// context is not an outcome: nothing is recorded and the error passes through. +func (rc *Context) record(seq int, name string, out any, stepErr error) (store.Step, error) { + if errors.Is(stepErr, errSuspended) || errors.Is(stepErr, store.ErrLeaseLost) || errors.Is(stepErr, context.Canceled) { + return store.Step{}, stepErr + } + step := store.Step{RunID: rc.run.ID, Seq: seq, Name: name, Outcome: store.OutcomeDone} + switch { + case errors.Is(stepErr, ErrOutcomeUnknown): + step.Outcome = store.OutcomeUnknown + step.Error = sql.NullString{String: stepErr.Error(), Valid: true} + case stepErr != nil: + step.Outcome = store.OutcomeFailed + step.Error = sql.NullString{String: stepErr.Error(), Valid: true} + default: + raw, err := json.Marshal(out) + if err != nil { + return store.Step{}, fmt.Errorf("encode step %q: %w", name, err) + } + step.Output = raw + } + if err := rc.work.RecordStep(rc.ctx, rc.token, step); err != nil { + return store.Step{}, err + } + return step, nil +} + +// reload reads the step another holder recorded at seq and returns its result. +func reload[T any](rc *Context, seq int, name string) (T, error) { + var zero T + steps, err := rc.work.Steps(rc.ctx, rc.run.ID) + if err != nil { + return zero, err + } + for _, s := range steps { + if s.Seq == seq { + rc.saved[seq] = s + return replay[T](s, name) + } + } + return zero, fmt.Errorf("step %d reported as recorded but not found", seq) +} + +func (rc *Context) suspend(wakeAt *time.Time, waitingFor string) error { + if err := rc.work.Suspend(rc.ctx, rc.run.ID, rc.token, wakeAt, waitingFor); err != nil { + return err + } + return errSuspended +} + +// replay returns a saved step's result as T. +func replay[T any](saved store.Step, name string) (T, error) { + var zero T + if saved.Name != name { + return zero, fmt.Errorf("%w: step %d is %q, replay asked for %q", ErrNondeterministic, saved.Seq, saved.Name, name) + } + switch saved.Outcome { + case store.OutcomeUnknown: + return zero, fmt.Errorf("%w: %s", ErrOutcomeUnknown, saved.Error.String) + case store.OutcomeFailed: + return zero, savedError(saved.Error.String) + } + var out T + if err := json.Unmarshal(saved.Output, &out); err != nil { + return zero, fmt.Errorf("decode step %q: %w", name, err) + } + return out, nil +} + +// savedError rebuilds a recorded step error, keeping the engine's own +// sentinels comparable with errors.Is after a replay. +func savedError(text string) error { + for _, sentinel := range []error{ErrWaitTimedOut, ErrCancelled} { + if text == sentinel.Error() { + return sentinel + } + } + return errors.New(text) +} diff --git a/modules/runs/internal/store/store.go b/modules/runs/internal/store/store.go new file mode 100644 index 000000000..8f4192234 --- /dev/null +++ b/modules/runs/internal/store/store.go @@ -0,0 +1,278 @@ +// Package store holds the runs module's SQL. Every write a worker makes is +// fenced by its lease token, so a worker that lost its lease writes nothing. +package store + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" +) + +// Run states. +const ( + StateQueued = "queued" + StateRunning = "running" + StateWaiting = "waiting" + StateSucceeded = "succeeded" + StateFailed = "failed" + StateCancelled = "cancelled" +) + +// Step outcomes. +const ( + OutcomeDone = "done" + OutcomeFailed = "failed" + OutcomeUnknown = "unknown" +) + +var ( + // ErrLeaseLost means the writer no longer holds the run's lease. + ErrLeaseLost = errors.New("lease lost") + // ErrStepExists means the step was already recorded, by this run's replay + // or by a previous lease holder. + ErrStepExists = errors.New("step already recorded") +) + +// Run is a claimed run. +type Run struct { + ID uuid.UUID `db:"id"` + OrgID string `db:"org_id"` + Workflow string `db:"workflow"` + Input json.RawMessage `db:"input"` + Attempts int `db:"attempts"` +} + +// Step is one recorded step of a run. +type Step struct { + RunID uuid.UUID `db:"run_id"` + Seq int `db:"seq"` + Name string `db:"name"` + Outcome string `db:"outcome"` + Output json.RawMessage `db:"output"` + Error sql.NullString `db:"error"` +} + +// Store is the runs module's Postgres store. +type Store struct { + db *sqlx.DB +} + +// New returns a store on db. +func New(db *sqlx.DB) *Store { + return &Store{db: db} +} + +// Start inserts a queued run. A run with the same organisation and start key +// is not inserted again; its id is returned instead. +func (s *Store) Start(ctx context.Context, orgID, workflow, startKey string, input json.RawMessage) (uuid.UUID, error) { + key := sql.NullString{String: startKey, Valid: startKey != ""} + var id uuid.UUID + err := s.db.GetContext(ctx, &id, ` + INSERT INTO runs.runs (id, org_id, workflow, start_key, input, state) + VALUES ($1, $2, $3, $4, $5, 'queued') + ON CONFLICT (org_id, start_key) DO NOTHING + RETURNING id`, uuid.New(), orgID, workflow, key, input) + if errors.Is(err, sql.ErrNoRows) && key.Valid { + err = s.db.GetContext(ctx, &id, `SELECT id FROM runs.runs WHERE org_id = $1 AND start_key = $2`, orgID, startKey) + } + if err != nil { + return uuid.Nil, fmt.Errorf("start run: %w", err) + } + return id, nil +} + +// Claim takes the oldest run that is queued, due to wake, or whose lease has +// expired. SKIP LOCKED only keeps claimers from waiting on each other; +// correctness rests on the lease token every later write is fenced by. +func (s *Store) Claim(ctx context.Context, owner string, token uuid.UUID, ttl time.Duration) (Run, bool, error) { + var run Run + err := s.db.GetContext(ctx, &run, ` + UPDATE runs.runs r + SET state = 'running', lease_token = $1, lease_owner = $2, + lease_expires_at = now() + make_interval(secs => $3), + attempts = attempts + 1, updated_at = now() + WHERE r.id = ( + SELECT id FROM runs.runs + WHERE state = 'queued' + OR (state = 'waiting' AND wake_at <= now()) + OR (state = 'running' AND lease_expires_at < now()) + ORDER BY created_at + FOR UPDATE SKIP LOCKED + LIMIT 1) + RETURNING r.id, r.org_id, r.workflow, r.input, r.attempts`, token, owner, ttl.Seconds()) + if errors.Is(err, sql.ErrNoRows) { + return Run{}, false, nil + } + if err != nil { + return Run{}, false, fmt.Errorf("claim run: %w", err) + } + return run, true, nil +} + +// RenewLease extends the lease while the token still holds it. +func (s *Store) RenewLease(ctx context.Context, id, token uuid.UUID, ttl time.Duration) (bool, error) { + res, err := s.db.ExecContext(ctx, ` + UPDATE runs.runs SET lease_expires_at = now() + make_interval(secs => $3), updated_at = now() + WHERE id = $1 AND lease_token = $2`, id, token, ttl.Seconds()) + if err != nil { + return false, fmt.Errorf("renew lease: %w", err) + } + return affected(res) == 1, nil +} + +// Steps returns a run's recorded steps in order. +func (s *Store) Steps(ctx context.Context, id uuid.UUID) ([]Step, error) { + var steps []Step + if err := s.db.SelectContext(ctx, &steps, ` + SELECT run_id, seq, name, outcome, output, error FROM runs.steps + WHERE run_id = $1 ORDER BY seq`, id); err != nil { + return nil, fmt.Errorf("load steps: %w", err) + } + return steps, nil +} + +// RecordStep writes a step if the token holds the lease and the step is new. +func (s *Store) RecordStep(ctx context.Context, token uuid.UUID, step Step) error { + res, err := s.db.ExecContext(ctx, ` + INSERT INTO runs.steps (run_id, seq, name, outcome, output, error) + SELECT $1, $2, $3, $4, $5, $6 + WHERE EXISTS (SELECT 1 FROM runs.runs WHERE id = $1 AND lease_token = $7) + ON CONFLICT (run_id, seq) DO NOTHING`, + step.RunID, step.Seq, step.Name, step.Outcome, nullJSON(step.Output), step.Error, token) + if err != nil { + return fmt.Errorf("record step: %w", err) + } + if affected(res) == 1 { + return nil + } + return s.whyNotWritten(ctx, step.RunID, token) +} + +// Suspend releases the lease and parks the run until wakeAt or a signal for +// waitingFor. A signal that arrived before the park queues the run at once. +func (s *Store) Suspend(ctx context.Context, id, token uuid.UUID, wakeAt *time.Time, waitingFor string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE runs.runs r + SET state = CASE WHEN $4 <> '' AND EXISTS ( + SELECT 1 FROM runs.signals s WHERE s.run_id = r.id AND s.key = $4) + THEN 'queued' ELSE 'waiting' END, + wake_at = $3, waiting_for = NULLIF($4, ''), + lease_token = NULL, lease_owner = NULL, lease_expires_at = NULL, updated_at = now() + WHERE id = $1 AND lease_token = $2`, id, token, wakeAt, waitingFor) + if err != nil { + return fmt.Errorf("suspend run: %w", err) + } + if affected(res) == 0 { + return ErrLeaseLost + } + return nil +} + +// Finish records a terminal state while the token holds the lease. +func (s *Store) Finish(ctx context.Context, id, token uuid.UUID, state string, result json.RawMessage, errText string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE runs.runs + SET state = $3, result = $4, error = NULLIF($5, ''), finished_at = now(), updated_at = now(), + lease_token = NULL, lease_owner = NULL, lease_expires_at = NULL + WHERE id = $1 AND lease_token = $2`, id, token, state, nullJSON(result), errText) + if err != nil { + return fmt.Errorf("finish run: %w", err) + } + if affected(res) == 0 { + return ErrLeaseLost + } + return nil +} + +// Signal stores a signal for a run and queues the run if it is waiting for it. +func (s *Store) Signal(ctx context.Context, id uuid.UUID, key string, payload json.RawMessage) error { + tx, err := s.db.BeginTxx(ctx, nil) + if err != nil { + return fmt.Errorf("signal run: %w", err) + } + defer func() { _ = tx.Rollback() }() + if _, err := tx.ExecContext(ctx, ` + INSERT INTO runs.signals (run_id, key, payload) VALUES ($1, $2, $3) + ON CONFLICT (run_id, key) DO NOTHING`, id, key, payload); err != nil { + return fmt.Errorf("store signal: %w", err) + } + if _, err := tx.ExecContext(ctx, ` + UPDATE runs.runs SET state = 'queued', wake_at = NULL, updated_at = now() + WHERE id = $1 AND state = 'waiting' AND waiting_for = $2`, id, key); err != nil { + return fmt.Errorf("wake run: %w", err) + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("signal run: %w", err) + } + return nil +} + +// Signalled returns the payload of a run's signal, if one arrived. +func (s *Store) Signalled(ctx context.Context, id uuid.UUID, key string) (json.RawMessage, bool, error) { + var payload json.RawMessage + err := s.db.GetContext(ctx, &payload, `SELECT payload FROM runs.signals WHERE run_id = $1 AND key = $2`, id, key) + if errors.Is(err, sql.ErrNoRows) { + return nil, false, nil + } + if err != nil { + return nil, false, fmt.Errorf("read signal: %w", err) + } + return payload, true, nil +} + +// Cancel asks a run to stop. A run not currently held ends at once; a running +// one sees the request at its next step. +func (s *Store) Cancel(ctx context.Context, id uuid.UUID) error { + if _, err := s.db.ExecContext(ctx, ` + UPDATE runs.runs + SET cancel_requested = true, updated_at = now(), + state = CASE WHEN state IN ('queued', 'waiting') THEN 'cancelled' ELSE state END, + finished_at = CASE WHEN state IN ('queued', 'waiting') THEN now() ELSE finished_at END + WHERE id = $1 AND state NOT IN ('succeeded', 'failed', 'cancelled')`, id); err != nil { + return fmt.Errorf("cancel run: %w", err) + } + return nil +} + +// CancelRequested reports whether a run has been asked to stop. +func (s *Store) CancelRequested(ctx context.Context, id uuid.UUID) (bool, error) { + var requested bool + if err := s.db.GetContext(ctx, &requested, `SELECT cancel_requested FROM runs.runs WHERE id = $1`, id); err != nil { + return false, fmt.Errorf("read cancel request: %w", err) + } + return requested, nil +} + +// whyNotWritten tells a lost lease from a step that already exists. +func (s *Store) whyNotWritten(ctx context.Context, id, token uuid.UUID) error { + var holds bool + if err := s.db.GetContext(ctx, &holds, ` + SELECT COALESCE(lease_token = $2, false) FROM runs.runs WHERE id = $1`, id, token); err != nil { + return fmt.Errorf("check lease: %w", err) + } + if !holds { + return ErrLeaseLost + } + return ErrStepExists +} + +func affected(res sql.Result) int64 { + n, err := res.RowsAffected() + if err != nil { + return 0 + } + return n +} + +func nullJSON(v json.RawMessage) any { + if len(v) == 0 { + return nil + } + return []byte(v) +} diff --git a/modules/runs/runs.go b/modules/runs/runs.go new file mode 100644 index 000000000..8340b8f43 --- /dev/null +++ b/modules/runs/runs.go @@ -0,0 +1,221 @@ +// Package runs is Archie's durable run engine. A run executes a registered +// workflow 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" + "errors" + "fmt" + "log/slog" + "sync" + "time" + + "github.com/google/uuid" + "github.com/jmoiron/sqlx" + + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +// Workflow is the code a run executes. It must choose its next step only from +// its input and the results of earlier steps; clock reads, randomness and +// lookups belong inside steps. +type Workflow func(rc *Context, input json.RawMessage) (json.RawMessage, error) + +// StartRequest names the workflow to run and the organisation it runs for. +// A non-empty Key makes the start idempotent within the organisation. +type StartRequest struct { + OrgID string + Workflow string + Key string + Input json.RawMessage +} + +// 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, state string, result json.RawMessage, errText string) error + Signalled(ctx context.Context, id uuid.UUID, key string) (json.RawMessage, bool, error) + CancelRequested(ctx context.Context, id uuid.UUID) (bool, error) +} + +// Engine starts, executes and resumes runs. +type Engine struct { + db *store.Store + work workerStore + log *slog.Logger + opts Options + mu sync.RWMutex + workflows map[string]Workflow +} + +// 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 workerStore, 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" + } + return &Engine{db: db, work: work, log: log, opts: opts, workflows: map[string]Workflow{}} +} + +// Register makes a workflow available to runs by name. +func (e *Engine) Register(name string, wf Workflow) { + e.mu.Lock() + defer e.mu.Unlock() + e.workflows[name] = wf +} + +// Start queues a run and returns its id. +func (e *Engine) Start(ctx context.Context, req StartRequest) (uuid.UUID, error) { + input := req.Input + if len(input) == 0 { + input = json.RawMessage("null") + } + return e.db.Start(ctx, req.OrgID, req.Workflow, req.Key, input) +} + +// 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 json.RawMessage) error { + return e.db.Signal(ctx, id, key, payload) +} + +// Cancel asks a run to stop. +func (e *Engine) Cancel(ctx context.Context, id uuid.UUID) error { + return e.db.Cancel(ctx, id) +} + +// 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 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 + } + e.execute(ctx, run, token) + 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, 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 + } + state, errText := store.StateSucceeded, "" + if errors.Is(err, ErrCancelled) { + state, errText = store.StateCancelled, err.Error() + } else if err != nil { + state, errText = store.StateFailed, err.Error() + } + if ferr := e.work.Finish(ctx, run.ID, token, state, result, errText); ferr != nil { + log.WarnContext(ctx, "finish run", "error", ferr) + return + } + log.InfoContext(ctx, "run finished", "state", 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 json.RawMessage, err error) { + defer func() { + if p := recover(); p != nil { + err = fmt.Errorf("panic: %v", p) + } + }() + wf, ok := e.workflow(run.Workflow) + if !ok { + return nil, fmt.Errorf("no workflow named %q", run.Workflow) + } + steps, err := e.work.Steps(ctx, run.ID) + if err != nil { + return nil, err + } + return wf(newContext(ctx, e.work, run, token, steps), run.Input) +} + +func (e *Engine) workflow(name string) (Workflow, bool) { + e.mu.RLock() + defer e.mu.RUnlock() + wf, ok := e.workflows[name] + return wf, ok +} + +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 + } + } + } +} diff --git a/modules/runs/runs_test.go b/modules/runs/runs_test.go new file mode 100644 index 000000000..846c0f76d --- /dev/null +++ b/modules/runs/runs_test.go @@ -0,0 +1,157 @@ +package runs + +import ( + "context" + "encoding/json" + "log/slog" + "sync" + "testing" + "time" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/modules/runs/internal/store" +) + +// fakeWork is an in-memory worker store with lease-fenced writes, used to +// drive the engine through a lost lease and a conflicting step write. +type fakeWork struct { + mu sync.Mutex + // leaseLost makes every fenced write fail as if another worker held the run. + leaseLost bool + // recordedElsewhere is a step another lease holder already recorded; it + // becomes visible once this worker tries to write the same position. + recordedElsewhere *store.Step + steps []store.Step + finished []string + results []json.RawMessage +} + +func (f *fakeWork) Claim(context.Context, string, uuid.UUID, time.Duration) (store.Run, bool, error) { + return store.Run{}, false, nil +} + +func (f *fakeWork) RenewLease(context.Context, uuid.UUID, uuid.UUID, time.Duration) (bool, error) { + return true, nil +} + +func (f *fakeWork) Steps(context.Context, uuid.UUID) ([]store.Step, error) { + f.mu.Lock() + defer f.mu.Unlock() + return append([]store.Step(nil), f.steps...), nil +} + +func (f *fakeWork) RecordStep(_ context.Context, _ uuid.UUID, step store.Step) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.leaseLost { + return store.ErrLeaseLost + } + if f.recordedElsewhere != nil && f.recordedElsewhere.Seq == step.Seq { + f.steps = append(f.steps, *f.recordedElsewhere) + return store.ErrStepExists + } + f.steps = append(f.steps, step) + return nil +} + +func (f *fakeWork) Suspend(context.Context, uuid.UUID, uuid.UUID, *time.Time, string) error { + return nil +} + +func (f *fakeWork) Finish(_ context.Context, _, _ uuid.UUID, state string, result json.RawMessage, _ string) error { + f.mu.Lock() + defer f.mu.Unlock() + if f.leaseLost { + return store.ErrLeaseLost + } + f.finished = append(f.finished, state) + f.results = append(f.results, result) + return nil +} + +func (f *fakeWork) Signalled(context.Context, uuid.UUID, string) (json.RawMessage, bool, error) { + return nil, false, nil +} + +func (f *fakeWork) CancelRequested(context.Context, uuid.UUID) (bool, error) { + return false, nil +} + +// TestLeaseFencesStepWrites guards 2.2's guarantee that correctness rests on +// fenced writes: a worker that lost its lease stops before running another +// step (which could repeat an effect), and a step another holder already +// recorded wins over this worker's own result. +func TestLeaseFencesStepWrites(t *testing.T) { + theirs := json.RawMessage(`"theirs"`) + tests := []struct { + name string + work *fakeWork + wantSteps int + wantEffects int + wantFinished []string + wantResult string + }{ + { + name: "lost lease stops the run before its next step", + work: &fakeWork{leaseLost: true}, + wantSteps: 0, + wantEffects: 0, + wantFinished: nil, + }, + { + name: "a step recorded by another holder replaces this worker's result", + work: &fakeWork{recordedElsewhere: &store.Step{ + Seq: 0, Name: "probe", Outcome: store.OutcomeDone, Output: theirs, + }}, + wantSteps: 2, + wantEffects: 1, + wantFinished: []string{store.StateSucceeded}, + wantResult: `"theirs"`, + }, + { + name: "a held lease records the steps and finishes the run", + work: &fakeWork{}, + wantSteps: 2, + wantEffects: 1, + wantFinished: []string{store.StateSucceeded}, + wantResult: `"mine"`, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + engine := newEngine(nil, tt.work, slog.New(slog.DiscardHandler), Options{}) + effects := 0 + engine.Register("probe", func(rc *Context, _ json.RawMessage) (json.RawMessage, error) { + out, err := Step(rc, "probe", func(context.Context, string) (string, error) { + return "mine", nil + }) + if err != nil { + return nil, err + } + if _, err := Step(rc, "effect", func(context.Context, string) (bool, error) { + effects++ + return true, nil + }); err != nil { + return nil, err + } + return json.Marshal(out) + }) + run := store.Run{ID: uuid.New(), OrgID: "org", Workflow: "probe", Input: json.RawMessage(`null`)} + engine.execute(t.Context(), run, uuid.New()) + + if got := len(tt.work.steps); got != tt.wantSteps { + t.Fatalf("steps recorded = %d, want %d", got, tt.wantSteps) + } + if effects != tt.wantEffects { + t.Fatalf("effect step ran %d times, want %d", effects, tt.wantEffects) + } + if len(tt.work.finished) != len(tt.wantFinished) { + t.Fatalf("finished = %v, want %v", tt.work.finished, tt.wantFinished) + } + if len(tt.wantFinished) > 0 && string(tt.work.results[0]) != tt.wantResult { + t.Fatalf("result = %s, want %s", tt.work.results[0], tt.wantResult) + } + }) + } +}