feat(statestore): step_executions, StartStep/FinishStep under the run credential
Plan item 3 of docs/prds/execution-tree-state-machine.md (archie-core-1220), on top of the transition tables and ErrIllegalTransition enforcement (1214/1215, archie-core-qdbo.5): - Migration 0017 adds step_executions -- id, org_id, workspace_id, execution_id, attempt, parent_id, depth, kind, name, called_execution_id, status, detail, tokens_used, started_at, finished_at, indexed on (execution_id, attempt, id). Ownership fields are stamped from the execution's row; depth is derived from the parent, never supplied by a caller. Existing rows gain no backfilled steps. - task.Store (the workflow engine's mid-run facade) gains StartStep/FinishStep (5 methods, within the 8 cap), with storecontract.StepRecorder fronting them on the server; deadlineStore wraps both with its per-call timeout. - The store enforces each write as one transaction: the guarded row write under the shared step transition table plus the transition's own stage_start/stage_finish event row. Staleness is decided before legality, the way guardTransition decides it, and the store returns the persisted event for the caller's post-commit publish -- the EmitDurable convention (the daemon's event sink skips already-persisted rows by assigned ID), which is why workflow.Run stops emitting stage events beside the store and no longer discards step-write errors: a failed start or finish parks the execution, and the stage does not run unrecorded. An interrupted stage records interrupted rather than failed; a recording failure on that shutdown path is logged and left to RecoverStale, which owns the interrupted-execution sweep in plan item 6. - The run credential of docs/prds/orgs-and-access.md authorises StartStep and FinishStep on its own execution only: both requests carry the execution ID the grant check verifies (FinishStep carries it because the interceptor never reads the database), and FinishStep verifies handler-side that the step really is that execution's. authorizesTaskScopedCall's sanctioned widenings are now held as a lookup table so the next one stops growing a switch. - The PRD's wire contract is StartStep(execution, attempt, parent, kind, name) -> step id; the responses also carry the persisted event (needed for the post-commit publish) and FinishStep's request carries execution_id (needed for the grant check) -- both noted here as deliberate additions to the PRD's shorthand. called_execution_id exists in the table but not yet on the wire: its named consumer is the workflow-call recording of plan item 4 (#1216). Conformance drives both adapters; grant tests pin the own-execution scoping; the wire sentinel set gains ErrInvalidStep (InvalidArgument, "step execution invalid") for a step kind no consumer names.
This commit is contained in:
1 parent
c07c04e45a
commit
3f0071e27b
29 files changed
+2637
-937
No files matched your search
@@ -0,0 +1,32 @@
|
||||
-- Step executions: one durable record per stage run and per agent or
|
||||
-- workflow.call step inside a WorkflowExecution
|
||||
-- (docs/prds/execution-tree-state-machine.md). Statuses are taskstate's
|
||||
-- StepStatus vocabulary and move only through the step transition table the
|
||||
-- store enforces; depth is derived from parent_id, never supplied by a
|
||||
-- caller. Existing rows gain no backfilled steps: their stage history stays
|
||||
-- in transitions and events.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE step_executions (
|
||||
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
|
||||
org_id text NOT NULL DEFAULT 'default',
|
||||
workspace_id text NOT NULL DEFAULT 'default',
|
||||
execution_id bigint NOT NULL,
|
||||
attempt bigint NOT NULL,
|
||||
parent_id bigint,
|
||||
depth int NOT NULL DEFAULT 0,
|
||||
kind text NOT NULL,
|
||||
name text NOT NULL,
|
||||
called_execution_id bigint NOT NULL DEFAULT 0,
|
||||
status text NOT NULL DEFAULT 'pending',
|
||||
detail text NOT NULL DEFAULT '',
|
||||
tokens_used bigint NOT NULL DEFAULT 0,
|
||||
started_at timestamptz,
|
||||
finished_at timestamptz
|
||||
);
|
||||
CREATE INDEX idx_step_executions_attempt ON step_executions (execution_id, attempt, id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE step_executions;
|
||||
@@ -306,6 +306,24 @@ type Source struct {
|
||||
WorkspaceID string
|
||||
}
|
||||
|
||||
type StepExecution struct {
|
||||
ID int64
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ExecutionID int64
|
||||
Attempt int64
|
||||
ParentID pgtype.Int8
|
||||
Depth int32
|
||||
Kind string
|
||||
Name string
|
||||
CalledExecutionID int64
|
||||
Status string
|
||||
Detail string
|
||||
TokensUsed int64
|
||||
StartedAt pgtype.Timestamptz
|
||||
FinishedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type SysAudit struct {
|
||||
ID int64
|
||||
At time.Time
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: steps.sql
|
||||
|
||||
package postgresdb
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const finishStepExecution = `-- name: FinishStepExecution :execrows
|
||||
UPDATE step_executions
|
||||
SET status = $1, detail = $2, tokens_used = $3, finished_at = now()
|
||||
WHERE id = $4 AND status = $5
|
||||
`
|
||||
|
||||
type FinishStepExecutionParams struct {
|
||||
Status string
|
||||
Detail string
|
||||
TokensUsed int64
|
||||
ID int64
|
||||
Status_2 string
|
||||
}
|
||||
|
||||
func (q *Queries) FinishStepExecution(ctx context.Context, arg FinishStepExecutionParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, finishStepExecution,
|
||||
arg.Status,
|
||||
arg.Detail,
|
||||
arg.TokensUsed,
|
||||
arg.ID,
|
||||
arg.Status_2,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const insertStepExecution = `-- name: InsertStepExecution :one
|
||||
INSERT INTO step_executions (org_id, workspace_id, execution_id, attempt, parent_id, depth, kind, name, called_execution_id, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'pending')
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
type InsertStepExecutionParams struct {
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
ExecutionID int64
|
||||
Attempt int64
|
||||
ParentID pgtype.Int8
|
||||
Depth int32
|
||||
Kind string
|
||||
Name string
|
||||
CalledExecutionID int64
|
||||
}
|
||||
|
||||
func (q *Queries) InsertStepExecution(ctx context.Context, arg InsertStepExecutionParams) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, insertStepExecution,
|
||||
arg.OrgID,
|
||||
arg.WorkspaceID,
|
||||
arg.ExecutionID,
|
||||
arg.Attempt,
|
||||
arg.ParentID,
|
||||
arg.Depth,
|
||||
arg.Kind,
|
||||
arg.Name,
|
||||
arg.CalledExecutionID,
|
||||
)
|
||||
var id int64
|
||||
err := row.Scan(&id)
|
||||
return id, err
|
||||
}
|
||||
|
||||
const lockExecutionForStep = `-- name: LockExecutionForStep :one
|
||||
|
||||
SELECT id, status, org_id, workspace_id, owner, repo, issue_number, workflow, attempt
|
||||
FROM tasks WHERE id = $1 FOR UPDATE
|
||||
`
|
||||
|
||||
type LockExecutionForStepRow struct {
|
||||
ID int64
|
||||
Status string
|
||||
OrgID string
|
||||
WorkspaceID string
|
||||
Owner string
|
||||
Repo string
|
||||
IssueNumber int64
|
||||
Workflow string
|
||||
Attempt int64
|
||||
}
|
||||
|
||||
// Step-execution queries (docs/prds/execution-tree-state-machine.md). The
|
||||
// store method owns the transaction that pairs each step transition with its
|
||||
// event row; these are only the guarded row writes and reads.
|
||||
// FOR UPDATE locks the execution's row, so the status check, the step insert
|
||||
// and the event append are one serialized operation per execution -- the way
|
||||
// guardTransition locks a task's row for its transition. The row also carries
|
||||
// every field the transition's event needs (org, workspace, the task
|
||||
// identity) and the attempt the step must belong to.
|
||||
func (q *Queries) LockExecutionForStep(ctx context.Context, id int64) (LockExecutionForStepRow, error) {
|
||||
row := q.db.QueryRow(ctx, lockExecutionForStep, id)
|
||||
var i LockExecutionForStepRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Status,
|
||||
&i.OrgID,
|
||||
&i.WorkspaceID,
|
||||
&i.Owner,
|
||||
&i.Repo,
|
||||
&i.IssueNumber,
|
||||
&i.Workflow,
|
||||
&i.Attempt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const lockStepExecution = `-- name: LockStepExecution :one
|
||||
SELECT id, org_id, workspace_id, execution_id, attempt, parent_id, depth, kind, name, called_execution_id, status, detail, tokens_used, started_at, finished_at
|
||||
FROM step_executions WHERE id = $1 FOR UPDATE
|
||||
`
|
||||
|
||||
// FOR UPDATE, shared by a start's parent check and a finish's guarded write:
|
||||
// the row is held for the caller's transaction, so the state a check reads is
|
||||
// the state the guarded write sees.
|
||||
func (q *Queries) LockStepExecution(ctx context.Context, id int64) (StepExecution, error) {
|
||||
row := q.db.QueryRow(ctx, lockStepExecution, id)
|
||||
var i StepExecution
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.OrgID,
|
||||
&i.WorkspaceID,
|
||||
&i.ExecutionID,
|
||||
&i.Attempt,
|
||||
&i.ParentID,
|
||||
&i.Depth,
|
||||
&i.Kind,
|
||||
&i.Name,
|
||||
&i.CalledExecutionID,
|
||||
&i.Status,
|
||||
&i.Detail,
|
||||
&i.TokensUsed,
|
||||
&i.StartedAt,
|
||||
&i.FinishedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const startStepExecution = `-- name: StartStepExecution :execrows
|
||||
UPDATE step_executions SET status = 'running', started_at = now()
|
||||
WHERE id = $1 AND status = 'pending'
|
||||
`
|
||||
|
||||
// The pending -> running half of StartStep, guarded by the row's own status:
|
||||
// the step transition table routes the pair, so a row that is not pending is
|
||||
// stale rather than silently restarted.
|
||||
func (q *Queries) StartStepExecution(ctx context.Context, id int64) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, startStepExecution, id)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
-- Step-execution queries (docs/prds/execution-tree-state-machine.md). The
|
||||
-- store method owns the transaction that pairs each step transition with its
|
||||
-- event row; these are only the guarded row writes and reads.
|
||||
|
||||
-- name: LockExecutionForStep :one
|
||||
-- FOR UPDATE locks the execution's row, so the status check, the step insert
|
||||
-- and the event append are one serialized operation per execution -- the way
|
||||
-- guardTransition locks a task's row for its transition. The row also carries
|
||||
-- every field the transition's event needs (org, workspace, the task
|
||||
-- identity) and the attempt the step must belong to.
|
||||
SELECT id, status, org_id, workspace_id, owner, repo, issue_number, workflow, attempt
|
||||
FROM tasks WHERE id = $1 FOR UPDATE;
|
||||
|
||||
-- name: InsertStepExecution :one
|
||||
INSERT INTO step_executions (org_id, workspace_id, execution_id, attempt, parent_id, depth, kind, name, called_execution_id, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'pending')
|
||||
RETURNING id;
|
||||
|
||||
-- name: StartStepExecution :execrows
|
||||
-- The pending -> running half of StartStep, guarded by the row's own status:
|
||||
-- the step transition table routes the pair, so a row that is not pending is
|
||||
-- stale rather than silently restarted.
|
||||
UPDATE step_executions SET status = 'running', started_at = now()
|
||||
WHERE id = $1 AND status = 'pending';
|
||||
|
||||
-- name: LockStepExecution :one
|
||||
-- FOR UPDATE, shared by a start's parent check and a finish's guarded write:
|
||||
-- the row is held for the caller's transaction, so the state a check reads is
|
||||
-- the state the guarded write sees.
|
||||
SELECT id, org_id, workspace_id, execution_id, attempt, parent_id, depth, kind, name, called_execution_id, status, detail, tokens_used, started_at, finished_at
|
||||
FROM step_executions WHERE id = $1 FOR UPDATE;
|
||||
|
||||
-- name: FinishStepExecution :execrows
|
||||
UPDATE step_executions
|
||||
SET status = $1, detail = $2, tokens_used = $3, finished_at = now()
|
||||
WHERE id = $4 AND status = $5;
|
||||
@@ -0,0 +1,232 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// The step-execution writes of docs/prds/execution-tree-state-machine.md.
|
||||
// Each is one transaction: the guarded row write, and the domain event row
|
||||
// the step transition produces, so the events table records exactly the
|
||||
// transitions the step row does. The events land in the table; the caller
|
||||
// publishes the returned event to its bus after the write commits, and the
|
||||
// daemon's event sink skips already-persisted rows by their assigned ID --
|
||||
// the EmitDurable convention.
|
||||
|
||||
// StartStep records a StepExecution entering running: the row is created
|
||||
// pending, guarded into running under the shared step transition table, and
|
||||
// the stage_start event is appended in the same transaction. The execution's
|
||||
// row is locked for the whole write, so its status check cannot race the
|
||||
// guarded updates, and org and workspace are stamped from it -- the request's
|
||||
// ownership fields are ignored, like every owned record.
|
||||
func (s *Store) StartStep(ctx context.Context, start task.StepStart) (int64, events.Event, error) {
|
||||
if !task.ValidStepKind(start.Kind) {
|
||||
return 0, events.Event{}, fmt.Errorf("%w: unknown step kind %q", storecontract.ErrInvalidStep, start.Kind)
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := postgresdb.New(tx)
|
||||
|
||||
execution, err := q.LockExecutionForStep(ctx, start.ExecutionID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
// The execution the caller names does not exist: its view of the run
|
||||
// is stale, matching what guardTransition returns for a missing row.
|
||||
return 0, events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
if execution.Attempt != int64(start.Attempt) {
|
||||
// A step belongs to exactly one attempt; a caller naming one the
|
||||
// execution no longer runs is describing a run that is over.
|
||||
return 0, events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
|
||||
depth, err := s.startParent(ctx, q, start)
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
// A step cannot reach running while its execution is not running, and
|
||||
// never under a terminal parent. Both are the state machine's rules, so
|
||||
// they refuse as illegal transitions.
|
||||
if err := taskstate.CheckStepStart(execution.Status, depth.underTerminal); err != nil {
|
||||
return 0, events.Event{}, fmt.Errorf("%w: %w", storecontract.ErrIllegalTransition, err)
|
||||
}
|
||||
|
||||
stepID, err := q.InsertStepExecution(ctx, postgresdb.InsertStepExecutionParams{
|
||||
OrgID: execution.OrgID, WorkspaceID: execution.WorkspaceID,
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stepParentID(start.ParentID), Depth: int32(depth.depth),
|
||||
Kind: start.Kind, Name: start.Name, CalledExecutionID: 0,
|
||||
})
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
n, err := q.StartStepExecution(ctx, stepID)
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
if n == 0 {
|
||||
return 0, events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
|
||||
event := stepEvent(events.KindStageStart, execution.ID,
|
||||
execution.Owner, execution.Repo, execution.IssueNumber, execution.Workflow,
|
||||
int(execution.Attempt), start.Name, nil)
|
||||
eventID, err := insertEventQ(ctx, q, event)
|
||||
if err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
event.ID = eventID
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return 0, events.Event{}, err
|
||||
}
|
||||
return stepID, event, nil
|
||||
}
|
||||
|
||||
// stepParent resolves the enclosing StepExecution a child step names: its
|
||||
// row is locked in the same transaction, the tree must stay inside one
|
||||
// execution and one attempt, and depth is derived from the parent, never
|
||||
// supplied by the caller.
|
||||
func (s *Store) startParent(ctx context.Context, q *postgresdb.Queries, start task.StepStart) (stepParentState, error) {
|
||||
if start.ParentID == 0 {
|
||||
return stepParentState{}, nil
|
||||
}
|
||||
parent, err := q.LockStepExecution(ctx, start.ParentID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return stepParentState{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err != nil {
|
||||
return stepParentState{}, err
|
||||
}
|
||||
if parent.ExecutionID != start.ExecutionID || parent.Attempt != int64(start.Attempt) {
|
||||
// Trees never nest across executions, and a parent from another
|
||||
// attempt is a tree the caller is not running.
|
||||
return stepParentState{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
return stepParentState{
|
||||
depth: int(parent.Depth) + 1,
|
||||
underTerminal: taskstate.StepTerminal(taskstate.StepStatus(parent.Status)),
|
||||
}, nil
|
||||
}
|
||||
|
||||
type stepParentState struct {
|
||||
depth int
|
||||
underTerminal bool
|
||||
}
|
||||
|
||||
// FinishStep moves one step to its outcome under the shared step transition
|
||||
// table, writing the stage_finish event in the same transaction and returning
|
||||
// it for the caller's post-commit publish. A step that is missing, that is
|
||||
// not the named execution's, or whose status does not match from is stale; an
|
||||
// off-table from->to pair is refused as an illegal transition.
|
||||
func (s *Store) FinishStep(ctx context.Context, finish task.StepFinish) (events.Event, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := postgresdb.New(tx)
|
||||
|
||||
step, err := q.LockStepExecution(ctx, finish.StepID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
// The step belongs to another run, or the caller believes a state the row
|
||||
// does not hold. Either way its view is stale, and writing would move
|
||||
// another execution's record.
|
||||
if step.ExecutionID != finish.ExecutionID || taskstate.StepStatus(step.Status) != finish.From {
|
||||
return events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
// Staleness is decided first, the way guardTransition decides it: a caller
|
||||
// that is wrong about the row's state gets the stale sentinel even when
|
||||
// its pair is also unroutable.
|
||||
if !taskstate.CanStepTransition(finish.From, finish.To) {
|
||||
return events.Event{}, fmt.Errorf("%w: %s -> %s is not a step transition",
|
||||
storecontract.ErrIllegalTransition, finish.From, finish.To)
|
||||
}
|
||||
execution, err := q.TaskByID(ctx, step.ExecutionID)
|
||||
if err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
|
||||
durationMS := int64(0)
|
||||
if step.StartedAt.Valid {
|
||||
durationMS = time.Since(step.StartedAt.Time).Milliseconds()
|
||||
}
|
||||
n, err := q.FinishStepExecution(ctx, postgresdb.FinishStepExecutionParams{
|
||||
Status: string(finish.To), Detail: clip(finish.Detail, 4000), TokensUsed: finish.TokensUsed,
|
||||
ID: finish.StepID, Status_2: string(finish.From),
|
||||
})
|
||||
if err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
if n == 0 {
|
||||
return events.Event{}, storecontract.ErrStaleTransition
|
||||
}
|
||||
|
||||
event := stepEvent(events.KindStageFinish, execution.ID,
|
||||
execution.Owner, execution.Repo, execution.IssueNumber, execution.Workflow,
|
||||
int(step.Attempt), step.Name,
|
||||
stepEventData(finish.To, durationMS, finish.Detail))
|
||||
eventID, err := insertEventQ(ctx, q, event)
|
||||
if err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
event.ID = eventID
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return events.Event{}, err
|
||||
}
|
||||
return event, nil
|
||||
}
|
||||
|
||||
// stepEvent builds the event row one step transition writes, stamped with the
|
||||
// execution's identity the way TaskContext.Emit stamped it -- the same fields
|
||||
// the timeline and the stage statistics read back.
|
||||
func stepEvent(kind string, executionID int64, owner, repo string, issue int64, wf string, attempt int, stage string, data map[string]any) events.Event {
|
||||
return events.Event{
|
||||
Kind: kind, TaskID: executionID,
|
||||
Repo: owner + "/" + repo, Issue: int(issue), Workflow: wf,
|
||||
Attempt: attempt, Stage: stage, Data: data,
|
||||
}
|
||||
}
|
||||
|
||||
// stepEventData reads a stage_finish event's data the way the dashboard
|
||||
// (stageOutcome) and the stage statistics (StageStats) do: duration always,
|
||||
// the error text only when the step reported failure, and the interruption
|
||||
// marker only for an interrupted step.
|
||||
func stepEventData(to taskstate.StepStatus, durationMS int64, detail string) map[string]any {
|
||||
data := map[string]any{"duration_ms": durationMS}
|
||||
switch to {
|
||||
case taskstate.StepFailed:
|
||||
data["error"] = detail
|
||||
case taskstate.StepInterrupted:
|
||||
data["interrupted"] = true
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// stepParentID encodes the nullable parent id an insert takes: 0 means "no
|
||||
// parent" -- a stage at the tree's root -- which the column stores as NULL
|
||||
// rather than as a reference to a row that does not exist.
|
||||
func stepParentID(parentID int64) pgtype.Int8 {
|
||||
return pgtype.Int8{Int64: parentID, Valid: parentID != 0}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
task "github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/taskstate"
|
||||
)
|
||||
|
||||
// The step-execution writes (docs/prds/execution-tree-state-machine.md): each
|
||||
// of StartStep and FinishStep is one transaction -- guarded row write plus the
|
||||
// domain event row -- under the step transition table, with the execution's
|
||||
// own status gating whether a step may run at all.
|
||||
|
||||
// runningExecution enqueues and claims one task, the state a step runs in.
|
||||
func runningExecution(t *testing.T, s *Store) *workflow.Task {
|
||||
t.Helper()
|
||||
seed, err := s.EnqueueChatTask(t.Context(), "acme", "widgets", "t", "b", "implement", "")
|
||||
if err != nil || seed == nil {
|
||||
t.Fatalf("EnqueueChatTask: %+v %v", seed, err)
|
||||
}
|
||||
claimed, err := s.ClaimNext(t.Context())
|
||||
if err != nil || claimed == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", claimed, err)
|
||||
}
|
||||
return claimed
|
||||
}
|
||||
|
||||
func TestStartStepRecordsAStageEnteringRunning(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, startEvent, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if startEvent.Kind != events.KindStageStart || startEvent.Stage != "implement" ||
|
||||
startEvent.TaskID != execution.ID || startEvent.Attempt != execution.Attempt ||
|
||||
startEvent.Repo != "acme/widgets" || startEvent.ID == 0 {
|
||||
t.Fatalf("stage_start event = %+v, want the transition's row", startEvent)
|
||||
}
|
||||
|
||||
eventsForTask, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
if n := len(eventsForTask); n != 1 {
|
||||
t.Fatalf("events after StartStep = %d, want exactly the one the transition wrote", n)
|
||||
}
|
||||
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "implemented",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Kind != events.KindStageFinish || step.Stage != "implement" || step.ID == 0 {
|
||||
t.Fatalf("stage_finish event = %+v, want the transition's row", step)
|
||||
}
|
||||
if _, ok := step.Data["duration_ms"]; !ok {
|
||||
t.Errorf("stage_finish data = %v, want duration_ms: the stage statistics read it", step.Data)
|
||||
}
|
||||
if _, has := step.Data["error"]; has {
|
||||
t.Errorf("stage_finish data = %v, want no error key for a succeeded step", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepFailedCarriesTheErrorTheDashboardRenders(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
step, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepFailed, Detail: "review found 3 findings",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
if step.Data["error"] != "review found 3 findings" {
|
||||
t.Errorf("stage_finish data = %v, want the error text stageOutcome renders", step.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepRefusesWhatTheStateMachineForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
seed func(s *Store, taskID int64) error
|
||||
start task.StepStart
|
||||
want error
|
||||
}{
|
||||
{
|
||||
name: "an execution that is not running",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrIllegalTransition,
|
||||
},
|
||||
{
|
||||
name: "an execution that does not exist",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an attempt the execution no longer runs",
|
||||
start: task.StepStart{Kind: task.StepKindStage, Name: "plan", Attempt: 99},
|
||||
want: storecontract.ErrStaleTransition,
|
||||
},
|
||||
{
|
||||
name: "an unknown step kind",
|
||||
start: task.StepStart{Kind: "quantum", Name: "plan", Attempt: 1},
|
||||
want: storecontract.ErrInvalidStep,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "an execution that is not running" {
|
||||
// Back on the queue: nothing may run under it. The seed rides
|
||||
// the legal running->queued edge, not a hand-written pair.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
}
|
||||
start := tt.start
|
||||
start.ExecutionID = execution.ID
|
||||
if tt.name == "an execution that does not exist" {
|
||||
start.ExecutionID = execution.ID + 999999
|
||||
}
|
||||
if _, _, err := s.StartStep(t.Context(), start); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("StartStep = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestStartStepUnderATerminalParentIsIllegal(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep parent: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: parentID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep parent: %v", err)
|
||||
}
|
||||
|
||||
_, _, err = s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "review:2",
|
||||
})
|
||||
if !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("StartStep under a terminal parent = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStepDepthIsDerivedFromTheParent(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
parentID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: parentID, Kind: task.StepKindAgent, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep agent child: %v", err)
|
||||
}
|
||||
var depths map[int64]int
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, depth) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&depths); err != nil {
|
||||
t.Fatalf("read depths: %v", err)
|
||||
}
|
||||
if depths[parentID] != 0 || depths[childID] != 1 {
|
||||
t.Fatalf("depths = %v, want the stage at 0 and its child at 1", depths)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFinishStepRefusesStaleAndForeign(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
other := runningExecution(t, s)
|
||||
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "plan",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: other.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep naming another execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepSucceeded, To: taskstate.StepFailed,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep with an untruthful from = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepPending,
|
||||
}); !errors.Is(err, storecontract.ErrIllegalTransition) {
|
||||
t.Fatalf("FinishStep off-table pair = %v, want ErrIllegalTransition", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID + 999999, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("FinishStep on a missing step = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
|
||||
// A late FinishStep for a step another path already finished is stale, the
|
||||
// PRD's named wire behaviour: errors.Is matches on the client too.
|
||||
func TestFinishStepOffTablePairIsIllegalOverTheTable(t *testing.T) {
|
||||
if !taskstate.CanStepTransition(taskstate.StepPending, taskstate.StepRunning) {
|
||||
t.Fatal("pending -> running must be in the step transition table")
|
||||
}
|
||||
if taskstate.CanStepTransition(taskstate.StepSucceeded, taskstate.StepRunning) {
|
||||
t.Fatal("succeeded -> running must not be in the step transition table: terminal is terminal")
|
||||
}
|
||||
}
|
||||
@@ -124,6 +124,7 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
|
||||
// Compile-time checks: *Store satisfies every surface the SQLite store did.
|
||||
var (
|
||||
_ storecontract.TaskStore = (*Store)(nil)
|
||||
_ storecontract.StepRecorder = (*Store)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Store)(nil)
|
||||
_ storecontract.ConfigSnapshotStore = (*Store)(nil)
|
||||
_ storecontract.ChannelStatusStore = (*Store)(nil)
|
||||
|
||||
Reference in new issue
Block a user