Skip to content

Commit 6673de7

Browse files
committed
feat[models]: Add terminal-state predicates for all four entities
An embedding application had no supported way to ask whether a Task, TaskExecution, Workflow, or WorkflowStep is done and can no longer move; it had to hardcode a state list. Internally the same question was answered by several private predicates, each independently restating sets owned by the state machines in `models`. Adds `IsTerminal()` on the four state ENUMs and `HasReachedTerminalState()` on the four structs. Both derive from the transition graph - a state is terminal iff it has no outgoing transition - so they cannot drift from the state machine they describe. To make that possible the transition maps that were rebuilt as locals inside Task/Workflow/WorkflowStep ValidNextState are hoisted to package level, matching taskExecutionStateTransitions. ValidNextState is unchanged. Candidates come from each ENUM's Values(), so an unrecognized state reads as non-terminal rather than silently terminal. Five internal duplicates now defer to it, none changing behavior: db.isTerminalTaskState and db.isTerminalWorkflowState are deleted, workflow.nonTerminalWorkflowStates and db/workflow.go's inline step list use the new NonTerminalWorkflow{,Step}States accessors, and the cancellable-state switch in processCancelTask becomes !HasReachedTerminalState(). Left alone on purpose: workflow's isTerminalWorkflowStepState is the weaker settle/dispatch reading (it counts FAILED / TIMED_OUT, which a revive moves), as are the scheduler's hard-stop policy sets and TaskExecution.HasEnded. Each now carries a doc note on which reading applies when.
1 parent 8c60640 commit 6673de7

11 files changed

Lines changed: 646 additions & 124 deletions

‎db/task.go‎

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -353,15 +353,6 @@ func (c *databaseImpl) ListTasks(
353353
return result, nil
354354
}
355355

356-
// isTerminalTaskState reports whether a task state admits no further transition, i.e.
357-
// COMPLETE, FAILED, TIMED_OUT or CANCELLED (see models.Task.ValidNextState).
358-
func isTerminalTaskState(state models.TaskStateENUM) bool {
359-
return state == models.TaskStateComplete ||
360-
state == models.TaskStateFailed ||
361-
state == models.TaskStateTimeout ||
362-
state == models.TaskStateCancelled
363-
}
364-
365356
/*
366357
DeleteTask delete task entry
367358
@@ -377,7 +368,7 @@ func (c *databaseImpl) DeleteTask(ctx context.Context, taskID string) error {
377368
// Terminal gate: a live task may still have execution instances in flight and racing
378369
// scheduler activity, and deleting it cascades that history away underneath them. Require
379370
// it be cancelled (or otherwise ended) before teardown.
380-
if !isTerminalTaskState(entry.TaskState) {
371+
if !entry.TaskState.IsTerminal() {
381372
return goutils.NewConsistencyError(
382373
fmt.Sprintf(
383374
"task %s in state %s is not terminal; cancel it before deleting", taskID, entry.TaskState,

‎db/workflow.go‎

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -406,12 +406,6 @@ func (c *databaseImpl) ListWorkflows(
406406
return result, nil
407407
}
408408

409-
// isTerminalWorkflowState reports whether a workflow state admits no further transition,
410-
// i.e. COMPLETE or CANCELLED (see models.Workflow.ValidNextState).
411-
func isTerminalWorkflowState(state models.WorkflowStateENUM) bool {
412-
return state == models.WorkflowStateComplete || state == models.WorkflowStateCancelled
413-
}
414-
415409
/*
416410
DeleteWorkflow delete a workflow and reap the tasks that executed its steps.
417411
@@ -441,7 +435,7 @@ func (c *databaseImpl) DeleteWorkflow(ctx context.Context, workflowID string) er
441435

442436
// Terminal gate: a live workflow may still have in-flight step tasks and racing scheduler
443437
// activity; require it be cancelled (or complete) before teardown.
444-
if !isTerminalWorkflowState(entry.State) {
438+
if !entry.State.IsTerminal() {
445439
return goutils.NewConsistencyError(
446440
fmt.Sprintf(
447441
"workflow %s in state %s is not terminal; cancel it before deleting",
@@ -549,10 +543,7 @@ func (c *databaseImpl) UpdateWorkflowDeadline(
549543
// Re-sync the deadline onto every non-terminal step of the workflow
550544
if tmp := c.db.
551545
Model(&WorkflowStepEntry{}).
552-
Where("workflow_id = ? and state not in ?", workflowID, []models.WorkflowStepStateENUM{
553-
models.WorkflowStepStateComplete,
554-
models.WorkflowStepStateCancelled,
555-
}).
546+
Where("workflow_id = ? and state in ?", workflowID, models.NonTerminalWorkflowStepStates()).
556547
UpdateColumn("deadline", &deadline); tmp.Error != nil {
557548
return goutils.NewSQLError(
558549
fmt.Sprintf("failed to update workflow %s step deadlines", workflowID), tmp.Error, true,

‎models/state.go‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
package models
2+
3+
/*
4+
Terminal states
5+
6+
Every entity `tasking` tracks - Task, TaskExecution, Workflow, WorkflowStep - is governed by a
7+
state machine declared in this package as a `map[state]map[state]bool`: for each state, the set
8+
of states it may transition to directly. A state which is absent from that map (or maps to an
9+
empty set) has no outgoing transition: once an entity reaches it, it can never move again,
10+
whatever happens. That is what "terminal" means here.
11+
12+
Each state ENUM exposes `IsTerminal`, and each entity exposes `HasReachedTerminalState`, so an
13+
embedding application can ask "is this done - can it still move?" without hardcoding a state
14+
list. Both are derived from the transition graph rather than restating it, so they cannot drift
15+
from the state machine they describe:
16+
17+
- Task - COMPLETE, FAILED, TIMED_OUT, CANCELLED
18+
- TaskExecution - CANCELLED, FINALIZED
19+
- Workflow - COMPLETE, CANCELLED
20+
- WorkflowStep - COMPLETE, CANCELLED
21+
22+
Note what terminal is NOT. A Workflow or WorkflowStep in FAILED or TIMED_OUT takes no further
23+
step on its own, but it is not terminal: a user revive moves it back into the DAG (see
24+
workflow/DESIGN.md "Terminal vs. non-terminal"). Nor is terminal the same as
25+
TaskExecution.HasEnded, which reports that an instance reached an outcome - a PROCESSED or
26+
FAILED instance has ended but still transitions to FINALIZED.
27+
*/
28+
29+
/*
30+
deriveTerminalStates compute the terminal states of a state machine: the states which have no
31+
outgoing transition.
32+
33+
Candidates come from the ENUM's own `Values()` rather than from the transition map, so a state
34+
string this package does not recognize is reported non-terminal instead of silently terminal
35+
(an unknown state is absent from the map, which would otherwise read as "no way out").
36+
37+
@param all []T - every valid state of the ENUM
38+
@param transitions map[T]map[T]bool - the state machine
39+
@returns the set of terminal states
40+
*/
41+
func deriveTerminalStates[T comparable](all []T, transitions map[T]map[T]bool) map[T]bool {
42+
terminal := map[T]bool{}
43+
for _, state := range all {
44+
if len(transitions[state]) == 0 {
45+
terminal[state] = true
46+
}
47+
}
48+
return terminal
49+
}
50+
51+
/*
52+
statesExcept the ENUM's values minus the given set. Used to publish the non-terminal state
53+
lists the persistence layer needs as query conditions.
54+
55+
@param all []T - every valid state of the ENUM
56+
@param exclude map[T]bool - the states to leave out
57+
@returns the remaining states, in `Values()` order
58+
*/
59+
func statesExcept[T comparable](all []T, exclude map[T]bool) []T {
60+
kept := make([]T, 0, len(all))
61+
for _, state := range all {
62+
if !exclude[state] {
63+
kept = append(kept, state)
64+
}
65+
}
66+
return kept
67+
}

0 commit comments

Comments
 (0)