feat(statestore): CancelExecution, and one cancel path for daemon stop and operator actions
Plan item 5 of docs/prds/execution-tree-state-machine.md (archie-core-1217).
Until now a stop was a context cancel plus a caller-side transition, and the
step rows a worker still held running could never be told: the execution moved
while the work carried on, and the old interrupt-first ordering existed only
because the record could not defend itself. The step table can: the PRD's
ordering -- the store is the record, the context cancel is the delivery --
became safe the moment a worker's next step write fails ErrStaleTransition
against a cancelled step.
- storecontract.ExecutionCanceller and the CancelExecution RPC: one
transaction moves every non-terminal StepExecution of the execution's
current attempt to cancelled (one event row each, in the same
transaction), and the execution itself to the status the operator action
names, under the shared transition table with its audit row. Staleness is
decided before legality, the way guardTransition decides it. Earlier
attempts are never rewritten. Deliberately administrative: the
deny-by-default grant rule covers it, pinned by a test.
- taskactions.Service routes stop, cancel, abandon and reject through it and
the old Transition/CancelTask combinations are deleted; the daemon's
in-memory cancel is demoted to the delivery hook the PRD names, called
after the store record.
- The gateway's chat controller records first and delivers second, the same
order, and records even when no runtime is wired here (a standalone
gateway cannot reach the daemon's goroutines): the record is what unsticks
a lost-cancel task, and the delivery is best effort. StopRunning and
TaskRuntime.CancelRunningTasks are deleted outright -- no production
caller remained once the task_action tool owned stopping, and the daemon's
CancelRunningTasks/runningTasks.stopAll go with them.
- The gateway's chat adapter writes through CancelExecution instead of a
bare Transition, so chat /cancel and the dashboard's action service land
on the same path.
PRD decisions recorded here:
- Each cancelled step's event row is stage_finish with {cancelled: true} and
the reason as its detail -- the exact-one-event-per-step-transition rule
covers the pending -> cancelled transition too, even for a step that never
ran.
- A parked cancel carries the needs_human class, matching the Transition
path this replaces; the transient class stays with parkRunningTask's
unwind parks, which now meet ErrStaleTransition for cancelled runs and are
ignored there.
- Cancelling a wait:true callee is deferred to #1216's agent-call children:
the callee's own tree and the wait flag are what make
"cancelling a caller cancels each callee it waits on" decidable, and the
callee writes it cannot fake are this issue's half of the contract.
- RecoverStale's interrupted sweep is plan item 6, untouched here.
This commit is contained in:
29 files changed
+1646
-1028
No files matched your search
@@ -0,0 +1,194 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"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/taskstate"
|
||||
)
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md,
|
||||
// "Cancellation"): one transaction cancels every non-terminal StepExecution of
|
||||
// the execution's current attempt and moves the execution to the status the
|
||||
// operator action names, with one event row per step transition and the
|
||||
// execution's own audit row in the same write.
|
||||
|
||||
func TestCancelExecutionCancelsTheAttemptsStepsAndTheExecution(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt, Kind: task.StepKindStage, Name: "review",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep stage: %v", err)
|
||||
}
|
||||
childID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "review:1",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stageID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded, Detail: "done",
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
|
||||
steps, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked)
|
||||
if err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
if len(steps) != 1 || steps[0] != childID {
|
||||
t.Fatalf("cancelled steps = %v, want only the non-terminal %d", steps, childID)
|
||||
}
|
||||
|
||||
// Every non-terminal step of the current attempt is cancelled; the one
|
||||
// that already finished is never rewritten.
|
||||
var statuses map[int64]string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_object_agg(id, status) FROM step_executions WHERE execution_id = $1`,
|
||||
execution.ID).Scan(&statuses); err != nil {
|
||||
t.Fatalf("read steps: %v", err)
|
||||
}
|
||||
if statuses[stageID] != string(taskstate.StepSucceeded) || statuses[childID] != string(taskstate.StepCancelled) {
|
||||
t.Fatalf("statuses = %v, want the finished step kept and the child cancelled", statuses)
|
||||
}
|
||||
|
||||
got, err := s.TaskByID(t.Context(), execution.ID)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("TaskByID: %+v %v", got, err)
|
||||
}
|
||||
if got.Status != taskstate.Parked || got.ParkReason != "stopped by operator" {
|
||||
t.Fatalf("execution after cancel = %s (%q), want parked with the reason", got.Status, got.ParkReason)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionWritesOneEventPerCancelledStep(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
stageID, _, 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 _, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: execution.Attempt,
|
||||
ParentID: stageID, Kind: task.StepKindAgent, Name: "implement",
|
||||
}); err != nil {
|
||||
t.Fatalf("StartStep child: %v", err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), execution.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
var cancelled []events.Event
|
||||
for _, e := range evs {
|
||||
if e.Data["cancelled"] == true {
|
||||
cancelled = append(cancelled, e)
|
||||
}
|
||||
}
|
||||
if len(cancelled) != 2 {
|
||||
t.Fatalf("cancel events = %d, want one per step the transaction cancelled", len(cancelled))
|
||||
}
|
||||
for _, e := range cancelled {
|
||||
if e.Kind != events.KindStageFinish || e.Attempt != execution.Attempt {
|
||||
t.Errorf("cancel event = %+v, want a stage_finish row attributed to the attempt", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionLeavesEarlierAttemptsAlone(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
|
||||
firstAttempt := execution.Attempt
|
||||
stepID, _, err := s.StartStep(t.Context(), task.StepStart{
|
||||
ExecutionID: execution.ID, Attempt: firstAttempt, Kind: task.StepKindStage, Name: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("StartStep: %v", err)
|
||||
}
|
||||
if _, err := s.FinishStep(t.Context(), task.StepFinish{
|
||||
StepID: stepID, ExecutionID: execution.ID,
|
||||
From: taskstate.StepRunning, To: taskstate.StepSucceeded,
|
||||
}); err != nil {
|
||||
t.Fatalf("FinishStep: %v", err)
|
||||
}
|
||||
// A retry requeues and reclaims: attempt 2.
|
||||
if err := s.Requeue(t.Context(), execution.ID, taskstate.Running, "implement"); err != nil {
|
||||
t.Fatalf("Requeue: %v", err)
|
||||
}
|
||||
retried, err := s.ClaimNext(t.Context())
|
||||
if err != nil || retried == nil {
|
||||
t.Fatalf("ClaimNext: %+v %v", retried, err)
|
||||
}
|
||||
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "stopped by operator", taskstate.Parked); err != nil {
|
||||
t.Fatalf("CancelExecution: %v", err)
|
||||
}
|
||||
var firstAttemptStatuses []string
|
||||
if err := s.pool.QueryRow(t.Context(),
|
||||
`SELECT jsonb_agg(status) FROM step_executions WHERE execution_id = $1 AND attempt = $2`,
|
||||
execution.ID, firstAttempt).Scan(&firstAttemptStatuses); err != nil {
|
||||
t.Fatalf("read first attempt's steps: %v", err)
|
||||
}
|
||||
for _, status := range firstAttemptStatuses {
|
||||
if status != string(taskstate.StepSucceeded) {
|
||||
t.Errorf("an earlier attempt's step was rewritten to %q; history is never rewritten", status)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionRefusesWhatTheTableForbids(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
target string
|
||||
want error
|
||||
}{
|
||||
{name: "a terminal execution", target: taskstate.Queued, want: storecontract.ErrIllegalTransition},
|
||||
{name: "an unroutable destination", target: "quantum", want: storecontract.ErrIllegalTransition},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if tt.name == "a terminal execution" {
|
||||
// completed is terminal: the table routes nothing out of it.
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Completed, "done"); err != nil {
|
||||
t.Fatalf("seed completed: %v", err)
|
||||
}
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "why", tt.target); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("CancelExecution(to=%q) = %v, want %v", tt.target, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A queued execution cancels fine: the table routes queued -> closed_wont_do.
|
||||
s := storeFor(t)
|
||||
execution := runningExecution(t, s)
|
||||
if err := s.Transition(t.Context(), execution.ID, taskstate.Running, taskstate.Queued, "requeue"); err != nil {
|
||||
t.Fatalf("seed queued: %v", err)
|
||||
}
|
||||
if _, err := s.CancelExecution(t.Context(), execution.ID, "cancelled by operator", taskstate.Declined); err != nil {
|
||||
t.Fatalf("CancelExecution(queued -> closed_wont_do) = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCancelExecutionOnAMissingExecutionIsStale(t *testing.T) {
|
||||
s := storeFor(t)
|
||||
if _, err := s.CancelExecution(t.Context(), 999999, "why", taskstate.Parked); !errors.Is(err, storecontract.ErrStaleTransition) {
|
||||
t.Fatalf("CancelExecution on a missing execution = %v, want ErrStaleTransition", err)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,47 @@ import (
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const cancelAttemptSteps = `-- name: CancelAttemptSteps :many
|
||||
UPDATE step_executions
|
||||
SET status = 'cancelled', finished_at = now()
|
||||
WHERE execution_id = $1 AND attempt = $2 AND status IN ('pending', 'running')
|
||||
RETURNING id, name
|
||||
`
|
||||
|
||||
type CancelAttemptStepsParams struct {
|
||||
ExecutionID int64
|
||||
Attempt int64
|
||||
}
|
||||
|
||||
type CancelAttemptStepsRow struct {
|
||||
ID int64
|
||||
Name string
|
||||
}
|
||||
|
||||
// The half of CancelExecution that cancels the current attempt's
|
||||
// non-terminal steps, returning them so the store writes one event row per
|
||||
// transition in the same transaction. Earlier attempts' rows never match:
|
||||
// history is never rewritten.
|
||||
func (q *Queries) CancelAttemptSteps(ctx context.Context, arg CancelAttemptStepsParams) ([]CancelAttemptStepsRow, error) {
|
||||
rows, err := q.db.Query(ctx, cancelAttemptSteps, arg.ExecutionID, arg.Attempt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []CancelAttemptStepsRow
|
||||
for rows.Next() {
|
||||
var i CancelAttemptStepsRow
|
||||
if err := rows.Scan(&i.ID, &i.Name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const finishStepExecution = `-- name: FinishStepExecution :execrows
|
||||
UPDATE step_executions
|
||||
SET status = $1, detail = $2, tokens_used = $3, finished_at = now()
|
||||
|
||||
@@ -33,4 +33,13 @@ 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;
|
||||
WHERE id = $4 AND status = $5;
|
||||
-- name: CancelAttemptSteps :many
|
||||
-- The half of CancelExecution that cancels the current attempt's
|
||||
-- non-terminal steps, returning them so the store writes one event row per
|
||||
-- transition in the same transaction. Earlier attempts' rows never match:
|
||||
-- history is never rewritten.
|
||||
UPDATE step_executions
|
||||
SET status = 'cancelled', finished_at = now()
|
||||
WHERE execution_id = $1 AND attempt = $2 AND status IN ('pending', 'running')
|
||||
RETURNING id, name;
|
||||
@@ -230,3 +230,70 @@ func stepEventData(to taskstate.StepStatus, durationMS int64, detail string) map
|
||||
func stepParentID(parentID int64) pgtype.Int8 {
|
||||
return pgtype.Int8{Int64: parentID, Valid: parentID != 0}
|
||||
}
|
||||
|
||||
// CancelExecution is the one cancel path (docs/prds/execution-tree-state-machine.md,
|
||||
// "Cancellation"): one transaction moves every non-terminal StepExecution of
|
||||
// the execution's current attempt to cancelled -- one event row each -- and
|
||||
// the execution itself to the status the operator action names, under the
|
||||
// shared execution transition table. Staleness is decided before legality, as
|
||||
// guardTransition decides it, and the audit row lands in the same write. The
|
||||
// caller cancels the in-memory context after this commits; the worker's next
|
||||
// step write then fails ErrStaleTransition and stops.
|
||||
func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to string) ([]int64, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
q := postgresdb.New(tx)
|
||||
|
||||
execution, err := q.LockExecutionForStep(ctx, taskID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !taskstate.CanTransition(execution.Status, to) {
|
||||
return nil, fmt.Errorf("%w: %s -> %s is not a transition",
|
||||
storecontract.ErrIllegalTransition, execution.Status, to)
|
||||
}
|
||||
|
||||
steps, err := q.CancelAttemptSteps(ctx, postgresdb.CancelAttemptStepsParams{
|
||||
ExecutionID: taskID, Attempt: execution.Attempt,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, step := range steps {
|
||||
if _, err := insertEventQ(ctx, q, stepEvent(events.KindStageFinish, execution.ID,
|
||||
execution.Owner, execution.Repo, execution.IssueNumber, execution.Workflow,
|
||||
int(execution.Attempt), step.Name, map[string]any{"cancelled": true})); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
n, err := q.TransitionTask(ctx, postgresdb.TransitionTaskParams{
|
||||
ID: taskID, Status: to, ParkReason: clip(reason, 4000),
|
||||
ParkClass: taskstate.ParkNeedsHuman, Status_2: execution.Status,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if n == 0 {
|
||||
return nil, storecontract.ErrStaleTransition
|
||||
}
|
||||
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
|
||||
TaskID: taskID, FromStatus: execution.Status, ToStatus: to, Detail: clip(reason, 4000),
|
||||
}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := make([]int64, 0, len(steps))
|
||||
for _, step := range steps {
|
||||
ids = append(ids, step.ID)
|
||||
}
|
||||
return ids, nil
|
||||
}
|
||||
@@ -125,6 +125,7 @@ func taskFromRow(t postgresdb.Task) *workflow.Task {
|
||||
var (
|
||||
_ storecontract.TaskStore = (*Store)(nil)
|
||||
_ storecontract.StepRecorder = (*Store)(nil)
|
||||
_ storecontract.ExecutionCanceller = (*Store)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Store)(nil)
|
||||
_ storecontract.ConfigSnapshotStore = (*Store)(nil)
|
||||
_ storecontract.ChannelStatusStore = (*Store)(nil)
|
||||
|
||||
Reference in new issue
Block a user